diff --git a/.claude/settings.json b/.claude/settings.json index 3f8cf8aede89..c90b3b1578db 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -11,8 +11,8 @@ }, { "type": "command", - "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -qE '(from\\s+@mui|import.*@mui|@emotion)'; then echo '{\"decision\": \"block\", \"reason\": \"Do not use MUI or @emotion. Use components from openmetadata-ui-core-components instead. See CLAUDE.md for details.\"}'; exit 2; fi", - "description": "Block new MUI/emotion imports" + "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -qE '(from\\s+.antd|import.*antd)'; then echo '{\"decision\": \"block\", \"reason\": \"Do not use Ant Design. Use components from openmetadata-ui-core-components instead. See CLAUDE.md for details.\"}'; exit 2; fi", + "description": "Block Ant Design imports" } ] } @@ -63,8 +63,8 @@ }, { "type": "command", - "command": "FILE=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.file_path // empty' 2>/dev/null); CONTENT=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.content // empty' 2>/dev/null); if [ -n \"$FILE\" ] && echo \"$FILE\" | grep -qE '\\.(ts|tsx)$' && echo \"$CONTENT\" | grep -qE 'import.*from.*@mui|import.*from.*@emotion'; then echo 'Warning: MUI/@emotion import detected. Use components from openmetadata-ui-core-components instead. See CLAUDE.md.'; fi", - "description": "Warn about MUI imports in new files" + "command": "FILE=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.file_path // empty' 2>/dev/null); CONTENT=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r '.content // empty' 2>/dev/null); if [ -n \"$FILE\" ] && echo \"$FILE\" | grep -qE '\\.(ts|tsx)$' && echo \"$CONTENT\" | grep -qE 'import.*from.*antd'; then echo 'Warning: Ant Design import detected (use openmetadata-ui-core-components instead). See CLAUDE.md.'; fi", + "description": "Warn about Ant Design imports in new files" }, { "type": "command", diff --git a/.claude/skills/ui-core-components/SKILL.md b/.claude/skills/ui-core-components/SKILL.md index 756cf983f149..feeae0818982 100644 --- a/.claude/skills/ui-core-components/SKILL.md +++ b/.claude/skills/ui-core-components/SKILL.md @@ -22,7 +22,7 @@ these exist — check this table before writing layout markup. Only **layout container** divs (the ones whose `className` is mostly `flex`/`grid`/`gap`/`items-*`/`justify-*`/border-as-separator) go through a primitive. Leave alone: single non-layout divs, text wrappers, spans, icon -wrappers, and anything built from antd/MUI form components — this is not a +wrappers, and anything built from antd/other external library form components — this is not a "replace every div" rule. ## Quick reference diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 6ed5e7a7d9ce..5cb1039b99da 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -580,9 +580,9 @@ make unit_ingestion_dev_env # For Python changes - ✅ **REQUIRE**: All user-facing text uses `useTranslation` hook: `const { t } = useTranslation()` - ✅ **REQUIRE**: Translation keys like `t('label.key')` from locale files -#### MUI Migration (Preferred) -- ⚠️ **FLAG**: New features using Ant Design components (should use MUI v7.3.1) -- ✅ **PREFER**: MUI components and theme tokens from `openmetadata-ui-core-components` +#### Component Library (Preferred) +- ⚠️ **FLAG**: New features using Ant Design components (should use `openmetadata-ui-core-components`) +- ✅ **PREFER**: Components and theme tokens from `openmetadata-ui-core-components` - ❌ **REJECT**: Hardcoded colors instead of theme tokens #### Code Quality (Must Pass) @@ -617,7 +617,7 @@ When reviewing a UI PR, verify ALL of these: 2. **Type Safety**: Search for `any` type usage - must be zero occurrences 3. **i18n Compliance**: Search for hardcoded strings - must use translation keys 4. **Import Organization**: Check import order follows standard -5. **MUI Usage**: New components prefer MUI over Ant Design +5. **Component Library Usage**: New components prefer `openmetadata-ui-core-components` over Ant Design 6. **No Debug Code**: No console.log, commented code, or debug statements 7. **Performance**: Proper memoization, no unnecessary re-renders 8. **Accessibility**: Semantic HTML, ARIA labels, keyboard navigation @@ -656,7 +656,7 @@ Use this template when reviewing UI PRs: - [ ] `yarn build` succeeds - [ ] No `any` types - [ ] No hardcoded strings -- [ ] Proper MUI usage +- [ ] Proper `openmetadata-ui-core-components` usage - [ ] Screenshots provided See [UI_PR_REVIEW_GUIDELINES.md](../openmetadata-ui/UI_PR_REVIEW_GUIDELINES.md) for complete checklist. diff --git a/.github/workflows/integration-tests-mysql-elasticsearch.yml b/.github/workflows/integration-tests-mysql-elasticsearch.yml index 69fa7c1ba7a9..cb506484d587 100644 --- a/.github/workflows/integration-tests-mysql-elasticsearch.yml +++ b/.github/workflows/integration-tests-mysql-elasticsearch.yml @@ -42,13 +42,17 @@ jobs: changes: name: Detect Changes runs-on: ubuntu-latest + timeout-minutes: 10 if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} + # pull_request_target uses the GitHub API and does not require a checkout. Pushes are + # already scoped by the trigger paths above; merge queue and manual runs exercise the + # full suite. Keep the trigger paths and filter list in sync. outputs: - backend: ${{ github.event_name == 'workflow_dispatch' && 'true' || steps.filter.outputs.backend }} + backend: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.backend }} steps: - uses: dorny/paths-filter@v3 id: filter - if: ${{ github.event_name != 'workflow_dispatch' }} + if: ${{ github.event_name == 'pull_request_target' }} with: filters: | backend: @@ -63,6 +67,7 @@ jobs: integration-tests-mysql-elasticsearch: needs: changes runs-on: ubuntu-latest + timeout-minutes: 90 if: ${{ needs.changes.outputs.backend == 'true' }} steps: - name: Free Disk Space (Ubuntu) @@ -108,15 +113,17 @@ jobs: restore-keys: | ${{ runner.os }}-maven- + # Run unconditionally. The previous `if: steps.cache-output.outputs.exit-code == 0` was a + # bug — `actions/cache@v4` exposes `cache-hit` (boolean) and `cache-primary-key`, never + # `exit-code`. The expression always evaluated to false and the steps never ran. Maven + # then ran against whatever JDK the runner happened to ship with, masking the issue. - name: Set up JDK 21 - if: steps.cache-output.outputs.exit-code == 0 uses: actions/setup-java@v4 with: java-version: '21' distribution: 'temurin' - name: Install Ubuntu dependencies - if: steps.cache-output.outputs.exit-code == 0 run: | sudo apt-get update sudo apt-get install -y unixodbc-dev python3-venv librdkafka-dev gcc libsasl2-dev build-essential libssl-dev libffi-dev \ diff --git a/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml b/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml index 69b133b46ebc..3973e12a33d5 100644 --- a/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml +++ b/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml @@ -57,13 +57,17 @@ jobs: changes: name: Detect Changes runs-on: ubuntu-latest + timeout-minutes: 10 if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} + # pull_request_target uses the GitHub API and does not require a checkout. Pushes are + # already scoped by the trigger paths above; merge queue and manual runs exercise the + # full suite. Keep the trigger paths and filter list in sync. outputs: - backend: ${{ github.event_name == 'workflow_dispatch' && 'true' || steps.filter.outputs.backend }} + backend: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.backend }} steps: - uses: dorny/paths-filter@v3 id: filter - if: ${{ github.event_name != 'workflow_dispatch' }} + if: ${{ github.event_name == 'pull_request_target' }} with: filters: | backend: @@ -78,6 +82,7 @@ jobs: integration-tests-postgres-elasticsearch-redis: needs: changes runs-on: ubuntu-latest + timeout-minutes: 90 if: ${{ needs.changes.outputs.backend == 'true' }} steps: - name: Free Disk Space (Ubuntu) diff --git a/.github/workflows/integration-tests-postgres-opensearch.yml b/.github/workflows/integration-tests-postgres-opensearch.yml index b59b2f579370..98d632efe96a 100644 --- a/.github/workflows/integration-tests-postgres-opensearch.yml +++ b/.github/workflows/integration-tests-postgres-opensearch.yml @@ -42,13 +42,17 @@ jobs: changes: name: Detect Changes runs-on: ubuntu-latest + timeout-minutes: 10 if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} + # pull_request_target uses the GitHub API and does not require a checkout. Pushes are + # already scoped by the trigger paths above; merge queue and manual runs exercise the + # full suite. Keep the trigger paths and filter list in sync. outputs: - backend: ${{ github.event_name == 'workflow_dispatch' && 'true' || steps.filter.outputs.backend }} + backend: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.backend }} steps: - uses: dorny/paths-filter@v3 id: filter - if: ${{ github.event_name != 'workflow_dispatch' }} + if: ${{ github.event_name == 'pull_request_target' }} with: filters: | backend: @@ -63,6 +67,7 @@ jobs: integration-tests-postgres-opensearch: needs: changes runs-on: ubuntu-latest + timeout-minutes: 90 if: ${{ needs.changes.outputs.backend == 'true' }} steps: - name: Free Disk Space (Ubuntu) @@ -108,15 +113,17 @@ jobs: restore-keys: | ${{ runner.os }}-maven- + # Run unconditionally. The previous `if: steps.cache-output.outputs.exit-code == 0` was a + # bug — `actions/cache@v4` exposes `cache-hit` (boolean) and `cache-primary-key`, never + # `exit-code`. The expression always evaluated to false and the steps never ran. Maven + # then ran against whatever JDK the runner happened to ship with, masking the issue. - name: Set up JDK 21 - if: steps.cache-output.outputs.exit-code == 0 uses: actions/setup-java@v4 with: java-version: '21' distribution: 'temurin' - name: Install Ubuntu dependencies - if: steps.cache-output.outputs.exit-code == 0 run: | sudo apt-get update sudo apt-get install -y unixodbc-dev python3-venv librdkafka-dev gcc libsasl2-dev build-essential libssl-dev libffi-dev \ diff --git a/.github/workflows/java-playwright-external.yml b/.github/workflows/java-playwright-external.yml index 7c7aaad86b5e..9179e240823f 100644 --- a/.github/workflows/java-playwright-external.yml +++ b/.github/workflows/java-playwright-external.yml @@ -165,7 +165,9 @@ jobs: fi # OM basic-auth login expects a base64-encoded password (BasicAuthServletHandler). PW_B64=$(printf '%s' "$OM_EXTERNAL_PASSWORD" | base64 | tr -d '\n') - TOKEN=$(curl -fsS -X POST "${OM_EXTERNAL_URL%/}/api/v1/users/login" \ + # The login endpoint sits behind a gateway that intermittently 504s; retry transient + # failures so a single blip doesn't fail the whole job before any test runs. + TOKEN=$(curl -fsS --retry 5 --retry-delay 5 --retry-connrefused --connect-timeout 30 -X POST "${OM_EXTERNAL_URL%/}/api/v1/users/login" \ -H 'Content-Type: application/json' \ -d "{\"email\":\"${OM_EXTERNAL_USERNAME}\",\"password\":\"${PW_B64}\"}" \ | jq -r '.accessToken') @@ -324,7 +326,9 @@ jobs: exit 1 fi PW_B64=$(printf '%s' "$OM_EXTERNAL_PASSWORD" | base64 | tr -d '\n') - TOKEN=$(curl -fsS -X POST "${OM_EXTERNAL_URL%/}/api/v1/users/login" \ + # The login endpoint sits behind a gateway that intermittently 504s; retry transient + # failures so a single blip doesn't fail the whole job before any test runs. + TOKEN=$(curl -fsS --retry 5 --retry-delay 5 --retry-connrefused --connect-timeout 30 -X POST "${OM_EXTERNAL_URL%/}/api/v1/users/login" \ -H 'Content-Type: application/json' \ -d "{\"email\":\"${OM_EXTERNAL_USERNAME}\",\"password\":\"${PW_B64}\"}" \ | jq -r '.accessToken') @@ -457,7 +461,9 @@ jobs: exit 1 fi PW_B64=$(printf '%s' "$OM_EXTERNAL_PASSWORD" | base64 | tr -d '\n') - TOKEN=$(curl -fsS -X POST "${OM_EXTERNAL_URL%/}/api/v1/users/login" \ + # The login endpoint sits behind a gateway that intermittently 504s; retry transient + # failures so a single blip doesn't fail the whole job before any test runs. + TOKEN=$(curl -fsS --retry 5 --retry-delay 5 --retry-connrefused --connect-timeout 30 -X POST "${OM_EXTERNAL_URL%/}/api/v1/users/login" \ -H 'Content-Type: application/json' \ -d "{\"email\":\"${OM_EXTERNAL_USERNAME}\",\"password\":\"${PW_B64}\"}" \ | jq -r '.accessToken') diff --git a/.github/workflows/mysql-nightly-e2e.yml b/.github/workflows/mysql-nightly-e2e.yml index c7a88991516a..8770442b39cb 100644 --- a/.github/workflows/mysql-nightly-e2e.yml +++ b/.github/workflows/mysql-nightly-e2e.yml @@ -21,6 +21,11 @@ on: required: true type: string default: "main" + send_slack_notification: + description: "Send Slack notification with test results" + required: false + type: boolean + default: false permissions: contents: read @@ -42,8 +47,8 @@ jobs: strategy: fail-fast: false matrix: - shardIndex: [1, 2, 3, 4, 5, 6] - shardTotal: [6] + shardIndex: [1, 2, 3, 4, 5, 6, 7] + shardTotal: [7] steps: - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main @@ -94,9 +99,17 @@ jobs: --project=DataAssetRulesEnabled \ --project=DataAssetRulesDisabled + elif [ "${{ matrix.shardIndex }}" -eq "2" ]; then + echo "🔹 Running search relevance tests on shard 2" + + npx playwright test \ + --project=search-nightly \ + playwright/e2e/Search/SearchRelevance.spec.ts \ + --workers=1 + else - # Shards 2-6 handle chromium tests (5 shards total) - CHROMIUM_SHARD=$(( ${{ matrix.shardIndex }} - 1 )) + # Shards 3-7 handle chromium tests (5 shards total) + CHROMIUM_SHARD=$(( ${{ matrix.shardIndex }} - 2 )) echo "🔹 Running all tests (excluding DataAssetRules) on chromium shard ${CHROMIUM_SHARD}/5" npx playwright test \ --project=chromium \ @@ -205,12 +218,17 @@ jobs: pattern: blob-report-* merge-multiple: true - - name: Merge Reports and Generate Slack Notification + - name: Merge Reports + working-directory: openmetadata-ui/src/main/resources/ui/ + run: | + npx playwright merge-reports --reporter json ./blob-reports > merged_tests_results.json + + - name: Generate Slack Notification + if: ${{ inputs.send_slack_notification }} working-directory: openmetadata-ui/src/main/resources/ui/ env: RUN_TITLE: "MySQL Test for OSS Release: ${{ inputs.branch }}" RUN_URL: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" SLACK_BOT_USER_OAUTH_TOKEN: ${{ secrets.E2E_SLACK_BOT_OAUTH_TOKEN }} run: | - npx playwright merge-reports --reporter json ./blob-reports > merged_tests_results.json npx playwright-slack-report -c playwright/slack-cli.config.json -j merged_tests_results.json > slack_report.json diff --git a/.github/workflows/playwright-postgresql-e2e.yml b/.github/workflows/playwright-postgresql-e2e.yml index 908916407016..49c0a48924cc 100644 --- a/.github/workflows/playwright-postgresql-e2e.yml +++ b/.github/workflows/playwright-postgresql-e2e.yml @@ -173,7 +173,7 @@ jobs: ALL_FILES: ${{ steps.all-changes.outputs.all_changed_files }} SPEC_FILES: ${{ steps.changed-specs.outputs.all_changed_files }} run: | - FULL_MATRIX='{"shardIndex":[1,2,3,4,5,6],"shardTotal":[6]}' + FULL_MATRIX='{"shardIndex":[1,2,3,4,5,6,7],"shardTotal":[7]}' SPEC_MATRIX='{"shardIndex":[1],"shardTotal":[1]}' ALL_COUNT=$(echo "$ALL_FILES" | wc -w) @@ -273,10 +273,14 @@ jobs: if echo "$CHANGED_SPECS" | tr ' ' '\n' | grep -q "DomainIsolation/"; then PROJECT_ARGS="$PROJECT_ARGS --project=DomainIsolation" fi + # Search relevance specs use the dedicated search-nightly project. + if echo "$CHANGED_SPECS" | tr ' ' '\n' | grep -q "playwright/e2e/Search/"; then + PROJECT_ARGS="$PROJECT_ARGS --project=search-nightly" + fi # Regular chromium specs: anything not in a special-project category. # Also add Basic because chromium has grepInvert:[@basic], so @basic-tagged tests # in the changed files would be silently skipped without it. - if echo "$CHANGED_SPECS" | tr ' ' '\n' | grep -qvE "(DataAssetRulesEnabled\.spec\.ts|DataAssetRulesDisabled\.spec\.ts|SearchRBAC\.spec\.ts|DomainIsolation/)"; then + if echo "$CHANGED_SPECS" | tr ' ' '\n' | grep -qvE "(DataAssetRulesEnabled\.spec\.ts|DataAssetRulesDisabled\.spec\.ts|SearchRBAC\.spec\.ts|DomainIsolation/|playwright/e2e/Search/)"; then PROJECT_ARGS="$PROJECT_ARGS --project=chromium --project=Basic" fi @@ -296,9 +300,17 @@ jobs: --project=SearchRBAC \ --project=DomainIsolation \ + elif [ "${{ matrix.shardIndex }}" -eq "2" ]; then + echo "🔹 Running search relevance tests on shard 2" + + npx playwright test \ + --project=search-nightly \ + playwright/e2e/Search/SearchRelevance.spec.ts \ + --workers=1 + else - # Shards 2-6 run common chromium tests equally distributed (5-way sharding) - CHROMIUM_SHARD=$(( ${{ matrix.shardIndex }} - 1 )) + # Shards 3-7 run common chromium tests equally distributed (5-way sharding) + CHROMIUM_SHARD=$(( ${{ matrix.shardIndex }} - 2 )) echo "🔹 Running common chromium tests on shard ${CHROMIUM_SHARD}/5" npx playwright test \ --project=chromium \ diff --git a/.github/workflows/playwright-sso-login-nightly.yml b/.github/workflows/playwright-sso-login-nightly.yml index 4336e14d272f..e6a21f4f0136 100644 --- a/.github/workflows/playwright-sso-login-nightly.yml +++ b/.github/workflows/playwright-sso-login-nightly.yml @@ -26,6 +26,11 @@ on: - keycloak-azure-saml - keycloak-azure-saml-crosssite - all + send_slack_notification: + description: "Send Slack notification with test results" + required: false + type: boolean + default: false permissions: contents: read @@ -132,7 +137,7 @@ jobs: retention-days: 5 - name: Send Slack Notification - if: always() + if: ${{ always() && (github.event_name == 'schedule' || inputs.send_slack_notification == true) }} working-directory: openmetadata-ui/src/main/resources/ui env: RUN_TITLE: "SSO Login Nightly: ${{ matrix.provider.name }} (${{ github.ref_name }})" diff --git a/.github/workflows/postgresql-nightly-e2e.yml b/.github/workflows/postgresql-nightly-e2e.yml index 0fe147188ebd..62275f4b1624 100644 --- a/.github/workflows/postgresql-nightly-e2e.yml +++ b/.github/workflows/postgresql-nightly-e2e.yml @@ -21,6 +21,11 @@ on: required: true type: string default: "main" + send_slack_notification: + description: "Send Slack notification with test results" + required: false + type: boolean + default: false permissions: contents: read @@ -42,8 +47,8 @@ jobs: strategy: fail-fast: false matrix: - shardIndex: [1, 2, 3, 4, 5, 6] - shardTotal: [6] + shardIndex: [1, 2, 3, 4, 5, 6, 7] + shardTotal: [7] steps: - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main @@ -94,9 +99,17 @@ jobs: --project=DataAssetRulesEnabled \ --project=DataAssetRulesDisabled + elif [ "${{ matrix.shardIndex }}" -eq "2" ]; then + echo "🔹 Running search relevance tests on shard 2" + + npx playwright test \ + --project=search-nightly \ + playwright/e2e/Search/SearchRelevance.spec.ts \ + --workers=1 + else - # Shards 2-5 handle chromium tests (5 shards total) - CHROMIUM_SHARD=$(( ${{ matrix.shardIndex }} - 1 )) + # Shards 3-7 handle chromium tests (5 shards total) + CHROMIUM_SHARD=$(( ${{ matrix.shardIndex }} - 2 )) echo "🔹 Running all tests (excluding DataAssetRules) on chromium shard ${CHROMIUM_SHARD}/5" npx playwright test \ --project=chromium \ @@ -205,12 +218,17 @@ jobs: pattern: blob-report-* merge-multiple: true - - name: Merge Reports and Generate Slack Notification + - name: Merge Reports + working-directory: openmetadata-ui/src/main/resources/ui/ + run: | + npx playwright merge-reports --reporter json ./blob-reports > merged_tests_results.json + + - name: Generate Slack Notification + if: ${{ inputs.send_slack_notification }} working-directory: openmetadata-ui/src/main/resources/ui/ env: RUN_TITLE: "PostgreSQL Test for OSS Release: ${{ inputs.branch }}" RUN_URL: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" SLACK_BOT_USER_OAUTH_TOKEN: ${{ secrets.E2E_SLACK_BOT_OAUTH_TOKEN }} run: | - npx playwright merge-reports --reporter json ./blob-reports > merged_tests_results.json npx playwright-slack-report -c playwright/slack-cli.config.json -j merged_tests_results.json > slack_report.json diff --git a/.gitignore b/.gitignore index ebef9c33dab4..330e0115e974 100644 --- a/.gitignore +++ b/.gitignore @@ -188,7 +188,7 @@ claude-flow.bat claude-flow.ps1 hive-mind-prompt-*.txt .claude-flow/ -/memory/ +memory .claude/agents .claude/hooks/ ingestion/.claude/agents diff --git a/AGENTS.md b/AGENTS.md index 0219b1f3d56c..e212ebd636a3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -114,7 +114,7 @@ yarn parse-schema # Parse JSON schemas for frontend (connection and - **Side Effects**: Use `useEffect` with proper dependency arrays - **Performance**: Use `useCallback` for event handlers, `useMemo` for expensive computations - **Custom Hooks**: Prefix with `use`, place in `src/hooks/`, return typed objects -- **Internationalization**: Use `useTranslation` hook from react-i18next, access with `t('key')` +- **Internationalization**: Use `useTranslation` hook from react-i18next, access with `t('key')`. When you add new keys to `src/locale/languages/en-us.json`, run `yarn i18n` to propagate them into every other locale file, then **replace the English placeholders that `yarn i18n` inserts with real translations for each language** (`ar-sa`, `de-de`, `es-es`, `fr-fr`, `gl-es`, `he-he`, `ja-jp`, `ko-kr`, `mr-in`, `nl-nl`, `pr-pr`, `pt-br`, `pt-pt`, `ru-ru`, `sv-se`, `th-th`, `tr-tr`, `zh-cn`, `zh-tw`). Shipping English text under a non-English locale key is a reviewable defect; leave a term in English only when it's an intentional translation decision (a widely-borrowed acronym, a product name). - **Component Structure**: Functional components only, no class components - **Props**: Define interfaces for all component props, place in `.interface.ts` files - **Loading States**: Use object state for multiple loading states: `useState>({})` @@ -129,11 +129,10 @@ yarn parse-schema # Parse JSON schemas for frontend (connection and ### Styling -- **MUI Migration**: The project is gradually migrating from Ant Design to Material-UI (MUI) v7.3.1 -- **Preferred Approach**: Use MUI components v7.3.1 and styles wherever possible for new features -- **Theme and Styles**: MUI theme data and styles are defined in `openmetadata-ui-core-components` -- **Colors and Design Tokens**: Always reference theme colors and design tokens from the MUI theme, not hardcoded values -- **Legacy Components**: Ant Design components remain in existing code but should be replaced with MUI equivalents when refactoring +- **Component Library**: The project is gradually migrating from Ant Design to `openmetadata-ui-core-components` as the canonical component library +- **Preferred Approach**: Use `openmetadata-ui-core-components` components and styles wherever possible for new features, do not use Ant Design +- **Colors and Design Tokens**: Always reference design tokens from `openmetadata-ui-core-components`, not hardcoded values. Full token reference, dark mode guide, and anti-pattern cheat sheet: [`openmetadata-ui/src/main/resources/ui/docs/colors.md`](openmetadata-ui/src/main/resources/ui/docs/colors.md). Always consult this before choosing any color class. +- **Legacy Components**: Ant Design components remain in existing code but should be replaced with `openmetadata-ui-core-components` equivalents when refactoring - Do not add unnecessary spacing between logs and code. - In Java, avoid wildcards imports (e.g., use `import java.util.List;` instead of `import java.util.*;`) - Custom styles in `.less` files with component-specific naming (legacy pattern) diff --git a/CLAUDE.md b/CLAUDE.md index e217bed0fe8a..eef307b6c1eb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -217,7 +217,7 @@ yarn parse-schema # Parse JSON schemas for frontend (connection and ### Styling -- **Component Library**: Use components from `openmetadata-ui-core-components` for all new UI work. This is the canonical component library — do not use MUI or introduce new MUI dependencies. +- **Component Library**: Use components from `openmetadata-ui-core-components` for all new UI work. This is the canonical component library — do not use Ant Design or introduce new UI component library dependencies. - **Available Components**: Button, Input, Select, Modal, Table, Tabs, Pagination, Badge, Avatar, Checkbox, Dropdown, Form, Card, Tooltip, Toggle, Slider, Textarea, Tags, and more — all in `openmetadata-ui-core-components/src/main/resources/ui/src/components/` - **Tailwind Classes**: All Tailwind utility classes must use the `tw:` prefix (e.g., `tw:flex`, `tw:text-sm`, `tw:bg-blue-500`) to avoid conflicts with existing Ant Design/Less styles - **Design Tokens**: Use CSS custom properties defined in `openmetadata-ui-core-components/src/main/resources/ui/src/styles/globals.css`. Never use hardcoded color or spacing values. Semantic tokens include: @@ -227,7 +227,6 @@ yarn parse-schema # Parse JSON schemas for frontend (connection and - Shadows: `--shadow-xs` through `--shadow-3xl` - Border radius: `--radius-none` through `--radius-full` - **Color Usage**: Full token reference, dark mode guide, and anti-pattern cheat sheet: [`openmetadata-ui/src/main/resources/ui/docs/colors.md`](openmetadata-ui/src/main/resources/ui/docs/colors.md). Always consult this before choosing any color class. -- **MUI**: Do not use MUI — we are actively removing MUI from the codebase. Do not import from `@mui/*` or `@emotion/*` - **Legacy**: Ant Design components remain in existing code but should be replaced with `openmetadata-ui-core-components` equivalents when refactoring - Do not add unnecessary spacing between logs and code. - In Java, avoid wildcards imports (e.g., use `import java.util.List;` instead of `import java.util.*;`) @@ -510,7 +509,7 @@ These checks run automatically in CI. Code that violates them **will not merge** - **Blank lines around `describe`, `it`, `beforeEach`** in test files - **JSON keys sorted alphabetically** in locale files (`src/locale/**/*.json`) - **Apache 2.0 license header** on every new source file — run `yarn license-header-fix` -- **i18n keys synced** — after adding keys to `en-us.json`, run `yarn i18n` to sync all 17 locales +- **i18n keys synced AND translated** — after adding keys to `en-us.json`, run `yarn i18n` to propagate them into every locale file. `yarn i18n` copies the English string verbatim into each locale as a placeholder — **you MUST then replace those placeholders with real translations in every non-en-us file**. Shipping English text under a non-English locale key is a defect (reviewers will flag it). If a term is intentionally left in English (e.g. an acronym like "AI" in Chinese, or a product name), keep it — but that has to be a translation decision, not a "yarn i18n did it" default. - **Prettier formatting** — 2-space indent, single quotes, strict HTML whitespace #### Playwright Test Rules (lint-playwright) diff --git a/DEVELOPER.md b/DEVELOPER.md index 3d53a322a34d..c7c881309f78 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -60,7 +60,7 @@ For connector-specific development, see [skills/README.md](skills/README.md). ``` **Key rules:** -- Use components from `openmetadata-ui-core-components`, never MUI +- Use components from `openmetadata-ui-core-components`, never Ant Design - All Tailwind classes use `tw:` prefix, all colors use CSS custom properties - No string literals in JSX — use `t('label.key-name')` from `useTranslation()` - No `any` type — use generated types from `generated/` or define proper interfaces diff --git a/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql index a4ef546d9ed2..9ae0da0bca66 100644 --- a/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql @@ -121,28 +121,6 @@ UPDATE ingestion_pipeline_entity SET json = JSON_REMOVE(json, '$.pipelineStatuses') WHERE JSON_CONTAINS_PATH(json, 'one', '$.pipelineStatuses'); --- MCP Server and MCP Chat are no longer internal Applications; their enablement now lives in --- platform settings (mcpConfiguration). The MCP Chat app was never shipped to customers, so --- aiSettings.mcpChat keeps its seeded default shape (no config carry-over). - --- MCP Server: keep it disabled if the server app was not installed (mcpConfiguration defaults --- to enabled=true, which would otherwise turn it on). -UPDATE openmetadata_settings -SET json = JSON_SET(json, '$.enabled', false) -WHERE configType = 'mcpConfiguration' - AND NOT EXISTS (SELECT 1 FROM installed_apps ia WHERE ia.name = 'McpApplication'); - --- Retire the MCP apps (their Java classes and marketplace seeds are removed). Keep the bot users --- so the MCP server keeps its principal. -DELETE er FROM entity_relationship er - JOIN installed_apps ia ON er.fromId = ia.id OR er.toId = ia.id - WHERE ia.name IN ('McpApplication', 'McpChatApplication'); -DELETE er FROM entity_relationship er - JOIN apps_marketplace ia ON er.fromId = ia.id OR er.toId = ia.id - WHERE ia.name IN ('McpApplication', 'McpChatApplication'); -DELETE FROM installed_apps WHERE name IN ('McpApplication', 'McpChatApplication'); -DELETE FROM apps_marketplace WHERE name IN ('McpApplication', 'McpChatApplication'); - -- Post data migration script for Task workflow cutover - OpenMetadata 2.0.0 (moved from 2.0.1) -- RdfIndexApp: switch to weekly Saturday cron and full-rebuild every run. @@ -261,3 +239,24 @@ SET json = JSON_REMOVE(json, '$.openMetadataServerConnection', '$.privateConfigu WHERE extension LIKE 'app.version.%' AND (JSON_EXTRACT(json, '$.openMetadataServerConnection') IS NOT NULL OR JSON_EXTRACT(json, '$.privateConfiguration') IS NOT NULL); + +-- Data Insights no longer runs a Data Quality workflow: testCaseResult and +-- testCaseResolutionStatus are read straight from their live search indexes via the +-- di-data-assets-* aliases, which search indexing now owns. moduleConfiguration is +-- additionalProperties:false, so the retired dataQuality key must be stripped from every +-- persisted config or DataInsightsApp fails to deserialize it on startup. +UPDATE installed_apps +SET json = JSON_REMOVE(json, '$.appConfiguration.moduleConfiguration.dataQuality') +WHERE name = 'DataInsightsApplication' + AND JSON_EXTRACT(json, '$.appConfiguration.moduleConfiguration.dataQuality') IS NOT NULL; + +UPDATE apps_marketplace +SET json = JSON_REMOVE(json, '$.appConfiguration.moduleConfiguration.dataQuality') +WHERE name = 'DataInsightsApplication' + AND JSON_EXTRACT(json, '$.appConfiguration.moduleConfiguration.dataQuality') IS NOT NULL; + +UPDATE entity_extension +SET json = JSON_REMOVE(json, '$.appConfiguration.moduleConfiguration.dataQuality') +WHERE extension LIKE 'app.version.%' + AND json->>'$.name' = 'DataInsightsApplication' + AND JSON_EXTRACT(json, '$.appConfiguration.moduleConfiguration.dataQuality') IS NOT NULL; diff --git a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql index d7cd09646873..09c6ff7fa685 100644 --- a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql @@ -427,11 +427,13 @@ CREATE TABLE IF NOT EXISTS audit_report_entity ( impersonatedBy VARCHAR(256) GENERATED ALWAYS AS (json ->> '$.impersonatedBy') VIRTUAL, deleted BOOLEAN GENERATED ALWAYS AS (JSON_EXTRACT(json, '$.deleted')), status VARCHAR(32) GENERATED ALWAYS AS (json ->> '$.status') VIRTUAL, + requestSignature VARCHAR(512) GENERATED ALWAYS AS (json ->> '$.requestSignature') STORED, PRIMARY KEY (id), UNIQUE KEY unique_name (fqnHash), INDEX name_index (name), INDEX status_index (status), - INDEX deleted_index (deleted) + INDEX deleted_index (deleted), + INDEX request_signature_index (requestSignature) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='AI Audit Report entities'; -- Database-backed user session store for multi-pod session management (issue #21971). CREATE TABLE IF NOT EXISTS `user_session` ( @@ -468,35 +470,6 @@ CREATE INDEX asset_entity_name_index ON asset_entity (name); CREATE INDEX context_file_name_index ON context_file (name); CREATE INDEX context_memory_name_index ON context_memory (name); --- MCP conversation table for MCP Client message tracking -CREATE TABLE IF NOT EXISTS mcp_conversation ( - id VARCHAR(36) GENERATED ALWAYS AS (json ->> '$.id') STORED NOT NULL, - json JSON NOT NULL, - userId VARCHAR(256) GENERATED ALWAYS AS (json ->> '$.user.id') NOT NULL, - createdAt BIGINT UNSIGNED GENERATED ALWAYS AS (json ->> '$.createdAt') NOT NULL, - updatedAt BIGINT UNSIGNED GENERATED ALWAYS AS (json ->> '$.updatedAt') NOT NULL, - createdBy VARCHAR(50) GENERATED ALWAYS AS (json ->> '$.createdBy') NOT NULL, - updatedBy VARCHAR(50) GENERATED ALWAYS AS (json ->> '$.updatedBy') NOT NULL, - messageCount INT GENERATED ALWAYS AS (json ->> '$.messageCount') STORED, - - PRIMARY KEY (id), - INDEX idx_mcp_conversation_user_updated (userId, updatedAt DESC) -); - --- MCP message table for MCP Client message tracking -CREATE TABLE IF NOT EXISTS mcp_message ( - id VARCHAR(36) GENERATED ALWAYS AS (json ->> '$.id') STORED NOT NULL, - json JSON NOT NULL, - conversationId VARCHAR(36) GENERATED ALWAYS AS (json ->> '$.conversationId') STORED NOT NULL, - sender VARCHAR(10) GENERATED ALWAYS AS (json ->> '$.sender') STORED NOT NULL, - messageIndex INT GENERATED ALWAYS AS (json ->> '$.index') STORED, - timestamp BIGINT UNSIGNED GENERATED ALWAYS AS (json ->> '$.timestamp') NOT NULL, - - PRIMARY KEY (id), - CONSTRAINT fk_mcp_message_conversation FOREIGN KEY (conversationId) REFERENCES mcp_conversation(id) ON DELETE CASCADE, - INDEX idx_mcp_message_conversation_index (conversationId, messageIndex), - INDEX idx_mcp_message_conversation_created (conversationId, timestamp) -); -- Task workflow cutover support - OpenMetadata 2.0.0 (moved from 2.0.1) -- Maps legacy thread task IDs to new task entity IDs for migration traceability and redirects. diff --git a/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql index de341e6e742b..57d135529ed3 100644 --- a/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql @@ -90,26 +90,6 @@ UPDATE ingestion_pipeline_entity SET json = (json::jsonb #- '{pipelineStatuses}')::json WHERE json::jsonb #> '{pipelineStatuses}' IS NOT NULL; --- MCP Server and MCP Chat are no longer internal Applications; their enablement now lives in --- platform settings (mcpConfiguration). The MCP Chat app was never shipped to customers, so --- aiSettings.mcpChat keeps its seeded default shape (no config carry-over). - --- MCP Server: keep it disabled if the server app was not installed (mcpConfiguration defaults --- to enabled=true, which would otherwise turn it on). -UPDATE openmetadata_settings -SET json = jsonb_set(json, '{enabled}', 'false'::jsonb) -WHERE configtype = 'mcpConfiguration' - AND NOT EXISTS (SELECT 1 FROM installed_apps ia WHERE ia.name = 'McpApplication'); - --- Retire the MCP apps (their Java classes and marketplace seeds are removed). Keep the bot users --- so the MCP server keeps its principal. -DELETE FROM entity_relationship er USING installed_apps ia - WHERE (er.fromId = ia.id OR er.toId = ia.id) AND ia.name IN ('McpApplication', 'McpChatApplication'); -DELETE FROM entity_relationship er USING apps_marketplace ia - WHERE (er.fromId = ia.id OR er.toId = ia.id) AND ia.name IN ('McpApplication', 'McpChatApplication'); -DELETE FROM installed_apps WHERE name IN ('McpApplication', 'McpChatApplication'); -DELETE FROM apps_marketplace WHERE name IN ('McpApplication', 'McpChatApplication'); - -- Post data migration script for Task workflow cutover - OpenMetadata 2.0.0 (moved from 2.0.1) -- RdfIndexApp: switch to weekly Saturday cron and full-rebuild every run. @@ -246,3 +226,33 @@ SET json = (json::jsonb - 'openMetadataServerConnection' - 'privateConfiguration WHERE extension LIKE 'app.version.%' AND (jsonb_exists(json::jsonb, 'openMetadataServerConnection') OR jsonb_exists(json::jsonb, 'privateConfiguration')); + +-- Data Insights no longer runs a Data Quality workflow: testCaseResult and +-- testCaseResolutionStatus are read straight from their live search indexes via the +-- di-data-assets-* aliases, which search indexing now owns. moduleConfiguration is +-- additionalProperties:false, so the retired dataQuality key must be stripped from every +-- persisted config or DataInsightsApp fails to deserialize it on startup. +UPDATE installed_apps +SET json = jsonb_set( + json::jsonb, + '{appConfiguration,moduleConfiguration}', + (json::jsonb #> '{appConfiguration,moduleConfiguration}') - 'dataQuality') +WHERE name = 'DataInsightsApplication' + AND jsonb_exists(json::jsonb #> '{appConfiguration,moduleConfiguration}', 'dataQuality'); + +UPDATE apps_marketplace +SET json = jsonb_set( + json::jsonb, + '{appConfiguration,moduleConfiguration}', + (json::jsonb #> '{appConfiguration,moduleConfiguration}') - 'dataQuality') +WHERE name = 'DataInsightsApplication' + AND jsonb_exists(json::jsonb #> '{appConfiguration,moduleConfiguration}', 'dataQuality'); + +UPDATE entity_extension +SET json = jsonb_set( + json::jsonb, + '{appConfiguration,moduleConfiguration}', + (json::jsonb #> '{appConfiguration,moduleConfiguration}') - 'dataQuality') +WHERE extension LIKE 'app.version.%' + AND json::jsonb ->> 'name' = 'DataInsightsApplication' + AND jsonb_exists(json::jsonb #> '{appConfiguration,moduleConfiguration}', 'dataQuality'); diff --git a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql index 3a388fe0ab84..00f087e260c9 100644 --- a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql @@ -382,12 +382,14 @@ CREATE TABLE IF NOT EXISTS audit_report_entity ( impersonatedBy VARCHAR(256) GENERATED ALWAYS AS (json->>'impersonatedBy') STORED, deleted BOOLEAN GENERATED ALWAYS AS ((json->>'deleted')::boolean) STORED, status VARCHAR(32) GENERATED ALWAYS AS (json->>'status') STORED, + requestSignature VARCHAR(512) GENERATED ALWAYS AS (json->>'requestSignature') STORED, PRIMARY KEY (id), UNIQUE (fqnHash) ); CREATE INDEX IF NOT EXISTS audit_report_name_index ON audit_report_entity(name); CREATE INDEX IF NOT EXISTS audit_report_status_index ON audit_report_entity(status); CREATE INDEX IF NOT EXISTS audit_report_deleted_index ON audit_report_entity(deleted); +CREATE INDEX IF NOT EXISTS audit_report_request_signature_index ON audit_report_entity(requestSignature); COMMENT ON TABLE audit_report_entity IS 'AI Audit Report entities'; -- Database-backed user session store for multi-pod session management (issue #21971). CREATE TABLE IF NOT EXISTS user_session ( @@ -425,35 +427,6 @@ CREATE INDEX IF NOT EXISTS asset_entity_name_index ON asset_entity (name); CREATE INDEX IF NOT EXISTS context_file_name_index ON context_file (name); CREATE INDEX IF NOT EXISTS context_memory_name_index ON context_memory (name); --- MCP conversation table for MCP Client message tracking -CREATE TABLE IF NOT EXISTS mcp_conversation ( - id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, - json JSONB NOT NULL, - userId VARCHAR(256) GENERATED ALWAYS AS ((json -> 'user') ->> 'id') STORED NOT NULL, - createdAt BIGINT GENERATED ALWAYS AS ((json ->> 'createdAt')::bigint) STORED NOT NULL, - updatedAt BIGINT GENERATED ALWAYS AS ((json ->> 'updatedAt')::bigint) STORED NOT NULL, - createdBy VARCHAR(50) GENERATED ALWAYS AS (json ->> 'createdBy') STORED NOT NULL, - updatedBy VARCHAR(50) GENERATED ALWAYS AS (json ->> 'updatedBy') STORED NOT NULL, - messageCount INT GENERATED ALWAYS AS ((json ->> 'messageCount')::int) STORED, - - PRIMARY KEY (id) -); -CREATE INDEX IF NOT EXISTS idx_mcp_conversation_user_updated ON mcp_conversation (userId, updatedAt DESC); - --- MCP message table for MCP Client message tracking -CREATE TABLE IF NOT EXISTS mcp_message ( - id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, - json JSONB NOT NULL, - conversationId VARCHAR(36) GENERATED ALWAYS AS (json ->> 'conversationId') STORED NOT NULL, - sender VARCHAR(10) GENERATED ALWAYS AS (json ->> 'sender') STORED NOT NULL, - messageIndex INT GENERATED ALWAYS AS ((json ->> 'index')::int) STORED, - timestamp BIGINT GENERATED ALWAYS AS ((json ->> 'timestamp')::bigint) STORED NOT NULL, - - PRIMARY KEY (id), - CONSTRAINT fk_mcp_message_conversation FOREIGN KEY (conversationId) REFERENCES mcp_conversation(id) ON DELETE CASCADE -); -CREATE INDEX IF NOT EXISTS idx_mcp_message_conversation_index ON mcp_message (conversationId, messageIndex); -CREATE INDEX IF NOT EXISTS idx_mcp_message_conversation_created ON mcp_message (conversationId, timestamp); -- Task workflow cutover support - OpenMetadata 2.0.0 (moved from 2.0.1) -- Maps legacy thread task IDs to new task entity IDs for migration traceability and redirects. diff --git a/conf/openmetadata.yaml b/conf/openmetadata.yaml index 87a3d0d13a75..f43f6635d20e 100644 --- a/conf/openmetadata.yaml +++ b/conf/openmetadata.yaml @@ -594,9 +594,9 @@ elasticsearch: # Embedding provider/model/credentials now live under llmConfiguration.embeddings (single LLM config home). # Platform-wide LLM provider configuration. Generic - consumed by any feature that needs LLM -# completions (e.g. Context Center knowledge-pill extraction and the MCP Chat application). The -# file content of uploaded documents is sent to the configured provider when enabled. Disabled by -# default; set provider + credentials (or the matching env vars) to enable. +# completions or embeddings (currently the semantic-search embeddings under +# llmConfiguration.embeddings). Disabled by default; set provider + credentials (or the matching +# env vars) to enable. llmConfiguration: enabled: ${LLM_ENABLED:-false} provider: ${LLM_PROVIDER:-noop} # noop | openai | azureOpenAI | bedrock | google | anthropic diff --git a/docs/company-context-knowledge-pills.md b/docs/company-context-knowledge-pills.md deleted file mode 100644 index 3f0650cda21f..000000000000 --- a/docs/company-context-knowledge-pills.md +++ /dev/null @@ -1,620 +0,0 @@ -# Company Context — File-Extracted Knowledge Pills - -- **Date:** 2026-06-12 -- **Status:** Implemented (as-built spec for branch `pmbrull/companycontext-entity`) -- **Author:** pmbrull (with Claude) -- **Scope:** 72 files, ~+2818/−81. Backend (Java), schema (JSON), ingestion of - file content into reusable memories, embedding/search, MCP tools, UI badge. - -This document describes the feature **as shipped**, not the earlier -pre-implementation design. Where the implementation diverged from that design, -the as-built behavior is recorded here and flagged in -[§13 Known limitations](#13-known-limitations--follow-ups). - ---- - -## 1. Summary - -The Context Center ("Drive") lets users upload documents. Previously an upload -was stored, its raw text extracted into `ContextFile.extractedText`, and that was -the end. This feature turns that raw text into structured, retrievable -**knowledge pills** — short question/answer facts about the company — that are -embedded, indexed, linked back to the originating file, and reachable by any -MCP-connected agent. - -Pills are **not a new entity**. They are `ContextMemory` rows tagged -`sourceType=FileExtraction` with a `sourceFile` back-reference, riding the -entity's existing embedding + search plumbing. - -End-to-end: - -``` -upload ──▶ store blob (object storage / AssetService) - ──▶ extract text (status: Analyzing) - ──▶ LLM extracts knowledge pills (status: ExtractingContext) - ──▶ pills stored as ContextMemory rows, linked to the file - ──▶ pills auto-embedded + indexed on create - ──▶ pills retrievable via MCP + searchable by source filename - file carries a processing status surfaced in the UI (status: Processed) -``` - -## 2. Motivation - -`ContextMemory` already existed — "Reusable context memory for Context Center -and AI-assisted retrieval", a question/answer pill that is already -vector-embedded (`contextMemory` is in `AvailableEntityTypes`, has -`ContextMemoryBodyTextContributor` + `ContextMemoryIndex`, and its index carries -parent aliases `["all", "dataAssetEmbeddings"]`). It needed only a new source -type and a file back-reference to become the backing store for file-extracted -knowledge, avoiding a second overlapping "knowledge" concept and a full new -entity stack. - -The real new infrastructure is a **generic LLM completion layer** — there was no -chat/completion client before (only `EmbeddingClient` and a NoOp `NLQService`). -It is built decoupled from Context Center so other features (e.g. MCP Chat) can -reuse it. - -## 3. Architecture & data flow - -``` -POST /v1/contextCenter/drive/files (ContextFileResource:208) - └─ store asset (AssetServiceFactory.getService().upload), persist ContextFile + content - └─ extractionService.submit(fileId, contentId) (ContextFileResource:287) - -ContextFileProcessingService.process(fileId, contentId) (drive/ContextFileProcessingService.java) - guard: contentId == file.headContentId (else abandon — stale re-upload) - 1. markAnalyzing() → status Analyzing (file + content) - 2. extractText() [DEFAULT_EXECUTOR, CPU] → read blob via AssetService, text-extract - ├─ failure → status Failed (+ processingError on content), extractedText cleared - └─ success → text status (Processed / Unsupported) - 3. if text Processed AND LLMClientHolder.isEnabled(): - status ExtractingContext (file) [content snapshot stays Processed] - submitMemoryExtraction() [LLM_EXECUTOR, network] - runMemoryExtraction(): - deleteExtractedMemories(file, hardDelete=true) ← wholesale replace - ContextMemoryExtractor.extract(file, canonicalText) - chunk → per-chunk LLM call → dedupe → create ContextMemory rows - {sourceType:FileExtraction, sourceFile:, status:Active, - visibility:Shared} └─ VectorEmbeddingHandler auto-embeds - status Processed (file) - ├─ LLM failure → status Failed (+ processingError), extractedText RETAINED - └─ LLM queue full → status Failed ("…queue is full. Please retry later.") - else (LLM disabled): text Processed is terminal; LLM stage never enqueued -``` - -Two **separate** thread pools by design (`ContextFileProcessingService`): - -| Pool | Thread-name prefix | Work | Sizing | -|------|--------------------|------|--------| -| `DEFAULT_EXECUTOR` | `context-file-extraction-` | CPU-bound text extraction | `threads = max(2, cores/2)`, `ArrayBlockingQueue(max(64, threads*8))`, `AbortPolicy`, daemon | -| `LLM_EXECUTOR` | `context-memory-extraction-` | network-bound LLM calls | identical sizing | - -Mixing seconds-long LLM calls into the text pool would starve text extraction; -the pools are kept separate (the class javadoc spells this out). They are -currently sized identically — the only difference is the thread-name prefix. - -## 4. Key design decisions - -| Decision | Choice | -|----------|--------| -| Entity | **Reuse `ContextMemory`** (new `sourceType=FileExtraction` + `sourceFile`); no new entity, no DDL migration | -| LLM layer | New **generic** `LLMCompletionClient` abstraction + per-provider concretes + factory + process-wide holder, modeled on `EmbeddingClient` | -| LLM→entity boundary | A narrow `KnowledgePill` DTO is the anti-corruption layer between untrusted model JSON and the entity (see [§9](#9-the-knowledgepill-dto-boundary)) | -| File↔pill link | `Relationship.MENTIONED_IN` edge, `ContextFile → ContextMemory`; `memoryCount` surfaced on the file | -| Reprocess | **Wholesale hard-delete + recreate** of a file's pills on every extraction run (no versioning, no checksum skip) | -| Async | Reuse + rename the live `ContextFileExtractionService` → `ContextFileProcessingService`; LLM step on its own executor | -| Status | Extend the single `ProcessingStatus` enum: insert `ExtractingContext` between `Analyzing` and `Processed` | -| Embedding | Free — `ContextMemory` already auto-embeds on create; this PR only threads `sourceFile` through the index/body-text | -| MCP | Two purpose-built tools `search_company_context` + `get_company_context` | -| Storage guardrail | New `/system/validate` "Object Storage" step + startup warn — uploads are useless if object storage is NoOp/broken | - -## 5. Generic LLM completion layer - -Package `org.openmetadata.service.llm` (all new). - -### 5.1 Config schema - -`openmetadata-spec/.../json/schema/configuration/llmConfiguration.json` → -`org.openmetadata.schema.configuration.LLMConfiguration`. - -- `enabled` — boolean, default `false`. -- `provider` — enum `["bedrock", "openai", "azureOpenAI", "google", "anthropic", "noop"]`, default `noop` (Java enum `LLMProvider`). -- `maxConcurrentRequests` — integer, default `5`, minimum `1`. -- Per-provider objects (each `additionalProperties:false`): - - | Object | Java type | Auth (masked?) | Notable fields / defaults | - |--------|-----------|----------------|---------------------------| - | `bedrock` | `LLMBedrockConfig` | `awsConfig` → `awsBaseConfig.json` | `modelId` `anthropic.claude-3-5-sonnet-20240620-v1:0`, temp 0.0, maxTokens 4096, timeout 60s | - | `openai` | `LLMOpenAIConfig` | `apiKey` **`mask:true`** | `modelId` `gpt-4o-mini`, `endpoint`, `deploymentName`, `apiVersion` `2024-02-01` (Azure), temp 0.0, maxTokens 4096, timeout 60s | - | `google` | `LLMGoogleConfig` | `apiKey` **`mask:true`** | `modelId` `gemini-2.5-flash`, `endpoint`, temp 0.0, maxTokens 4096, timeout 60s | - | `anthropic` | `LLMAnthropicConfig` | `apiKey` **`mask:true`** | `modelId` `claude-3-5-sonnet-20240620`, `baseUrl` `https://api.anthropic.com`, temp 0.0, maxTokens 4096, timeout 60s | - - Masked API keys round-trip through the Secrets Manager. Bedrock delegates - secrecy to `awsBaseConfig.json`. - -`conf/openmetadata.yaml` carries an `llmConfiguration` block, fully env-var -overridable (`LLM_ENABLED`, `LLM_PROVIDER`, `LLM_MAX_CONCURRENT_REQUESTS`, and -per-provider `LLM__*` keys — see [§12](#12-configuration-reference)). -Its header comment states plainly that **uploaded document content is sent to the -configured provider when enabled**. - -### 5.2 Client hierarchy - -- **`LLMCompletionClient`** (abstract, `@Slf4j`): owns a `Semaphore` - (`maxConcurrentRequests` permits; ctor rejects `< 1`), the `complete()` / - `completeStructured()` template methods, JSON-array parsing, and code-fence - stripping. Abstract surface: `doComplete(systemPrompt, userPrompt)` and - `getModelId()`. `DEFAULT_MAX_CONCURRENT_REQUESTS = 5`. -- **Concretes** — `OpenAICompletionClient` (OpenAI + Azure OpenAI), - `AnthropicCompletionClient`, `BedrockCompletionClient` (AWS SDK v2, - `AutoCloseable`), `GoogleCompletionClient`, and `NoopCompletionClient` - (returns `"[]"`, model id `"noop"`). -- **`LLMCompletionClientFactory.create(LLMConfiguration)`** — switch on - `provider` → concrete; null config/provider → Noop. Note: the factory keys off - `provider` only; it does **not** check `enabled` (the holder does). -- **`LLMClientHolder`** — process-wide holder of the single shared client. - `initialize(config)`: `enabled = config != null && Boolean.TRUE.equals(getEnabled())`; - `instance = enabled ? factory.create(config) : new NoopCompletionClient()`. So - a real client is built **only** when `enabled == true`. `get()` never returns - null; `isEnabled()` gates the pipeline; `setForTesting()` is the test seam. - `volatile` fields + `synchronized` mutators. - -### 5.3 `completeStructured` contract - -```java - List completeStructured(String systemPrompt, String userPrompt, Class elementType) -``` - -- Acquires a permit, calls `doComplete`, releases in `finally`. -- Strips a leading/trailing ` ``` ` code fence (drops the language tag line). -- Parses with a default `new ObjectMapper()` (so `FAIL_ON_UNKNOWN_PROPERTIES` - is **on**) into `List`. Parse failure → `LLMCompletionException`. -- **One retry** on `LLMCompletionException` (logged `warn`), then propagates. The - retry catches `LLMCompletionException` broadly, so transport errors that surface - as `LLMCompletionException` also get one retry. - -### 5.4 Providers - -All providers use plain chat/messages JSON mode (**no tool/function calling**); -non-200 → `LLMCompletionException(" API returned status …")`. - -- **OpenAI / Azure**: JDK `HttpClient`. Azure detected when `endpoint` **and** - `deploymentName` are set → `.../openai/deployments//chat/completions?api-version=` - with `api-key` header; else `Authorization: Bearer`. Reads `choices[0].message.content`. -- **Anthropic**: JDK `HttpClient`, `/v1/messages`, headers `x-api-key` + - `anthropic-version: 2023-06-01`. Reads `content[0].text`. -- **Bedrock**: AWS SDK v2 `BedrockRuntimeClient` (credentials via - `AwsCredentialsUtil.buildCredentialsProvider`, region required). Body uses - `anthropic_version: bedrock-2023-05-31`. Reads `content[0].text`. `close()` - exists but the holder never calls it. -- **Google Gemini**: JDK `HttpClient`, - `.../models/:generateContent?key=` (**API key in the URL - query string**). Reads `candidates[0].content.parts[0].text`. - -### 5.5 Startup wiring - -`OpenMetadataApplicationConfig` gains -`@JsonProperty("llmConfiguration") private LLMConfiguration llmConfiguration`. -`OpenMetadataApplication` startup calls -`LLMClientHolder.initialize(catalogConfig.getLlmConfiguration())` (new), then the -pre-existing `LlmConfigHolder.initialize(...)` (publishes raw config for MCP -Chat). Two holders, same config source. - -## 6. Schema & persistence changes - -No DDL / Flyway migration — `ContextMemory` and `ContextFile` use the generic -JSON-column entity tables, and the file↔pill link lives in the generic -`entity_relationship` table. - -### 6.1 Schemas - -- **`contextMemory.json`** — `sourceType` enum gains `FileExtraction` - (`FILE_EXTRACTION`); new property `sourceFile` (`entityReference`, not required). -- **`createContextMemory.json`** — new create-time `sourceFile` (`entityReference`). -- **`contextFile.json`** — `ProcessingStatus` enum gains `ExtractingContext` (3rd, - between `Analyzing` and `Processed`); new derived property `memoryCount` - (integer, default 0). - -### 6.2 Repositories - -- **`ContextMemoryRepository`** — `FIELD_SOURCE_FILE = "sourceFile"` added to - `PATCH_FIELDS`/`UPDATE_FIELDS`. `storeRelationships` adds an - `addRelationship(sourceFile.id /*from*/, memory.id /*to*/, CONTEXT_FILE, - CONTEXT_MEMORY, Relationship.MENTIONED_IN)` edge. `setFields` resolves it with - `findFrom(memory.id, CONTEXT_MEMORY, MENTIONED_IN, CONTEXT_FILE)` (bulk path via - `findFromBatch`). Patch handled via `updateFromRelationship(...)`. - - **Collision-free by construction:** each relationship hierarchy uses a - distinct `Relationship` — `rootMemory`→`CONTAINS`, `parentMemory`→`PARENT_OF`, - `domains`→`HAS`, `sourceFile`→**`MENTIONED_IN`** — so the four resolvers query - disjoint `(relation, fromType)` tuples. -- **`ContextFileRepository`** — `memoryCount` computed in `setFields` as - `findTo(file.id, CONTEXT_FILE, MENTIONED_IN, CONTEXT_MEMORY).size()`. New - `postDelete` cascades: `deleteExtractedMemories(file, hardDelete)` deletes each - linked pill, propagating the file delete's `hardDelete` flag (soft→soft, - hard→hard). The same method is reused by the reprocess path with `hardDelete=true`. -- **`ContextMemoryMapper`** — passthrough of `create.getSourceFile()`. - -## 7. Processing pipeline & status - -### 7.1 Status state machine (`ProcessingStatus`) - -``` -Uploaded ─▶ Analyzing ─▶ (text result) ─▶ Processed ─▶ ExtractingContext ─▶ Processed - │ ▲ (LLM enabled) (final) - ├─▶ Failed └─ if LLM disabled: terminal here - └─▶ Unsupported (passthrough from text extractor) - any stage failure ─▶ Failed -``` - -- The file and its content snapshot carry status independently. When the file - advances to `ExtractingContext`, the **content snapshot keeps `Processed`** (it - received the raw text status). -- `Unsupported` exists in the enum but the service never writes it — it is passed - through verbatim from `ContextFileTextExtractor`. - -### 7.2 Service (`ContextFileProcessingService`, was `ContextFileExtractionService`) - -- Only call site: `ContextFileResource` upload path → - `extractionService.submit(fileId, contentId)`. -- `submit` wraps `executor.execute(() -> process(...))` and catches - `RejectedExecutionException` (queue full → `Failed`, "Processing queue is full"). -- Every stage re-reads from the repo and re-checks `headContentId`; a newer - upload silently abandons the stale content's writes (concurrent re-upload guard). -- `canonicalText` feeds the LLM the **content snapshot's** extracted text - (capped ~1M chars) in preference to the file's indexed text (capped ~200K). - -### 7.3 Error handling - -- `applyFailure` sets both file and content to `Failed`; `processingError` is - written to the **content snapshot only**, not the file entity. -- **Text-stage** failures clear `extractedText` (+ `pageCount`). **LLM-stage** - failures **retain** `extractedText` (so the file stays indexed and is retriable - by re-upload). -- `extractText` catches `Throwable` but re-throws `VirtualMachineError`. -- No automatic retry anywhere; "retry later" means re-POST the file. - -## 8. Knowledge-pill extraction (`ContextMemoryExtractor`) - -- `extract(file, text)`: `chunkText` → per-chunk `completeStructured(SYSTEM_PROMPT, - chunk, KnowledgePill.class)` → `dedupe` → `memoryRepository.create(toMemory(pill, fileRef))`. -- **Chunking:** `MAX_PROMPT_CHARS = 60_000`, `MAX_CHUNKS = 8`. Chunk ends snap - back to the last `\n\n` / `\n` / ` ` boundary in the second half of the budget, - else hard-cut at the char cap. **Text past 8 chunks (~480K chars) is dropped - with a warning** — even though `canonicalText` may supply up to ~1M chars. -- **Dedupe:** `LinkedHashMap` keyed by `question.trim().toLowerCase(ROOT)`, - first-wins, insertion order preserved. -- **`isValid`:** `question` and `answer` both non-blank (title/summary/memoryType - optional). -- **`toMemory`** sets the full server-owned envelope: `id` (random UUID), `name` - (`-`), `fullyQualifiedName`, `title`, `question`, `answer`, - `summary`, `memoryType` (via `parseType`), `status=ACTIVE`, - `sourceType=FILE_EXTRACTION`, `sourceFile=`, - `shareConfig.visibility=SHARED`, `updatedBy=admin`, `updatedAt=now`. -- **`parseType`:** case-insensitive match against `ContextMemoryType` - (`Preference | UseCase | Note | Runbook | Faq`); default `NOTE`. -- **`SYSTEM_PROMPT`:** *"You extract reusable company knowledge from a document as - a JSON array. Each element is an object with keys: title, question, answer, - summary, memoryType (one of Faq, Note, Runbook, UseCase, Preference). Capture - durable facts, definitions, policies, and how-to guidance. Return ONLY the JSON - array, no prose."* - -### Reprocess / idempotency - -Every LLM run first calls `deleteExtractedMemories(file, hardDelete=true)`, -**hard-deleting all of the file's existing pills**, then recreates from scratch -with fresh random IDs/FQNs. There is **no supersede/versioning** and **no -checksum short-circuit** — re-uploading identical bytes re-runs text extraction -and the LLM and regenerates pills. (Rationale in code: machine-generated pills -are replaced wholesale, so soft-deleted rows would only accumulate with no -restore path.) - -## 9. The `KnowledgePill` DTO boundary - -`KnowledgePill` (`service/llm/KnowledgePill.java`) is a 5-field record -(`title, question, answer, summary, memoryType`) used **only** as the LLM -deserialization target — deliberately not the `ContextMemory` entity. It is the -anti-corruption boundary between untrusted model JSON and the trusted entity -model. Parsing model output straight into `ContextMemory` is avoided because: - -1. **Strict unknown fields.** `completeStructured` uses a default `ObjectMapper` - (`FAIL_ON_UNKNOWN_PROPERTIES` on) and `contextMemory.json` is - `additionalProperties:false` — one stray model key would fail the whole array - parse. `KnowledgePill` carries `@JsonIgnoreProperties(ignoreUnknown = true)`. -2. **Enum leniency.** `ContextMemory.memoryType` is the `ContextMemoryType` enum - (Jackson throws on a non-exact value); `KnowledgePill.memoryType` is a raw - String, so casing/variant forms degrade to `NOTE` in `parseType`. -3. **Server-owned identity.** `contextMemory.json` requires `id`/`name`, and the - whole envelope (FQN, status, sourceType, sourceFile, shareConfig, - updatedBy/At) is set server-side in `toMemory` — the model neither produces - nor should influence these. -4. **Minimal prompt contract.** The DTO is exactly the five fields the prompt - asks for; targeting the entity would expose its nested schema to the model. - -`toMemory` + `parseType` is the single mapping layer; validation and dedupe -operate on the DTO before any entity is built. - -## 10. Embedding & search - -`contextMemory` was already vector-indexable and auto-embedded on create -(`AvailableEntityTypes`, `VectorEmbeddingHandler`, parent aliases -`["all", "dataAssetEmbeddings"]`) — **unchanged here**. This PR threads the new -`sourceFile` reference through three layers so file-derived pills are searchable -by their origin filename: - -- `ContextMemoryIndex` — `doc.put("sourceFile", getEntityWithDisplayName(...))`. -- ES/OS mapping — a new `sourceFile` object (id/type/name/displayName/fqn/deleted - as keywords) added identically to all four - `elasticsearch/{en,jp,ru,zh}/context_memory_search_index.json` files (the - per-language copies are byte-identical; no language-specific analyzers). -- `ContextMemoryBodyTextContributor` — appends `source file: ` to the - embedding body text. - -## 11. Object-storage validation (guardrail) - -Uploaded file content lives in object storage (S3 / Azure / in-memory) via -`AssetService`. If that backend is disabled or NoOp, uploads silently "succeed" -but their bytes are discarded and extraction fails with **"Unable to read file -content from object storage"** — producing zero pills. To surface this *before* -users hit it: - -- **`SystemRepository.getObjectStorageValidation(config)`** adds an **"Object - Storage"** step to the existing `GET /api/v1/system/status` validation. It fails - fast when object storage is disabled/missing or the factory holds a - `NoOpAssetService`; otherwise it runs a **live write→read→delete round-trip - probe** (tiny `text/plain` asset, 10s per-op timeout, asserts the bytes match, - cleans up in `finally`). -- **`AssetServiceFactory.init`** logs a `warn` when storage is disabled, - naming Context Center Drive and the exact failure string. -- Test (`SystemRepositoryObjectStorageValidationTest`) exercises the real - `AssetServiceFactory` + `InMemoryAssetService`: disabled, missing config, - NoOp-after-config-drift, and a passing live in-memory round-trip. - -This reuses the existing `/system/status` framework (no new endpoint) but exists -solely for the Drive → object-storage → extraction pipeline. - -## 12. MCP tools - -Two tools in `openmetadata-mcp/.../tools/`, registered in `tools.json` and -dispatched by new `DefaultToolContext` switch cases (via the 3-arg, no-limits -`execute` — neither tool records usage or enforces limits). - -### `search_company_context` -- **Input:** `query` (string, required); `size` (integer, default 10, clamped 1..50). -- **Query:** `OpenSearchVectorService.search(query, filters, size, from=0, k=100, - threshold=0.0)` with filters pinned to `entityType=contextMemory`, - `sourceType=FileExtraction`, **and `visibility=Shared`**. -- **Output:** `{query, results:[{fullyQualifiedName, name, title, question, - answer, summary, sourceFile, similarityScore}], returnedCount}`. -- **Auth:** global `authorize(CONTEXT_MEMORY, VIEW_ALL)`. Requires vector - embedding enabled, else returns an error payload. - -### `get_company_context` -- **Input:** `fqn` (string, required — the `fullyQualifiedName` from a search hit). -- **Lookup:** `Entity.getEntityByName(CONTEXT_MEMORY, fqn, - "sourceFile,owners,tags,domains", null)`. -- **Exposability gate:** returns the pill only if `sourceType=FILE_EXTRACTION` - **and** `shareConfig.visibility=SHARED`, else an error. -- **Output:** `{fullyQualifiedName, name, title, question, answer, summary, - memoryType, sourceFile (as FQN)}`. -- **Auth:** same global `VIEW_ALL`. - -Both gate on a single global `VIEW_ALL` plus the `Shared`-visibility scope; there -is no per-pill owner re-check beyond that. - -## 13. UI - -- **`DocumentStatusBadge`** (new) renders a `ui-core-components` `Badge` (size - `sm`, no icon) from a `ProcessingStatus`, returning `null` when status is - absent. Mapping: - - | Status | Color | Label key | - |--------|-------|-----------| - | `Uploaded` | gray | `label.uploaded` | - | `Analyzing` | blue | `label.analyzing` | - | `ExtractingContext` | indigo | `label.extracting-context` | - | `Processed` | success | `label.processed` | - | `Failed` | error | `label.failed` | - | `Unsupported` | warning | `label.unsupported` | - -- **`DocumentsView`** renders the badge inline next to each document's filename, - driven by `file.processingStatus`. -- **i18n:** 4 new `en-us` keys (`label.analyzing`, `label.extracting-context`, - `label.unsupported`, `label.uploaded`); `label.processed`/`label.failed` - pre-existed. Synced across all locales. - -## 14. Security & privacy - -- LLM provider API keys are `mask:true` config through the Secrets Manager — - never logged, never returned in API responses. -- **File content is sent to the configured LLM provider** during extraction. This - is an explicit, admin-enabled action (`llmConfiguration.enabled`), and the - provider is the admin's configured choice — documented in the yaml header. -- Generated pills default to `visibility=Shared` (org-readable). MCP retrieval - enforces the `Shared` scope and a `VIEW_ALL` authorize on every call. -- No new unauthenticated surface; MCP tools ride existing OAuth/JWT auth. - -## 15. Testing - -**Java unit (`openmetadata-service`)** -- `drive/ContextFileProcessingServiceTest` — status machine: analyzing→processed, - LLM-enabled extraction, LLM-rejection/failure keeps text, storage-unavailable & - null-stream failures, executor rejection, head-content skip, VME rethrow. -- `drive/ContextMemoryExtractorTest` — one-memory-per-pill, dedupe + skip-invalid, - skip-when-no-text, multi-chunk dedupe, chunk cap. -- `jdbi3/SystemRepositoryObjectStorageValidationTest` — the four storage-validation - scenarios. -- `llm/LLMClientHolderTest`, `llm/LLMCompletionClientFactoryTest`, - `llm/LLMCompletionClientTest` — holder stability + disabled-builds-no-client, - factory dispatch, structured parsing / code-fence / concurrency guard. - -**MCP (`openmetadata-mcp`)** -- `tools/GetCompanyContextToolTest` — missing/blank fqn, auth-denied, shared-pill - projection, non-file & private rejection. -- `tools/SearchCompanyContextToolTest` — missing/blank query, auth-denied (input - guards; does not exercise the vector path). - -**Integration (`openmetadata-integration-tests`)** -- `it/drive/CompanyContextPipelineIT` — end-to-end: upload `.txt`, poll - (Awaitility, ≤45s) to `Processed`, `assumeTrue(memoryCount > 0)` to skip - gracefully when no LLM provider is configured; otherwise asserts - `memoryCount == pills.size()` and per-pill `sourceType=FILE_EXTRACTION`, non-null - `sourceFile` matching the file id, non-blank question/answer. - -**UI** — `DocumentStatusBadge.test.tsx` (renders nothing without status; `it.each` -over the six status→label→color rows). No new Playwright spec. - -## 16. Configuration reference - -```yaml -llmConfiguration: - enabled: ${LLM_ENABLED:-false} - provider: ${LLM_PROVIDER:-noop} # noop | openai | azureOpenAI | bedrock | google | anthropic - maxConcurrentRequests: ${LLM_MAX_CONCURRENT_REQUESTS:-5} - openai: - apiKey: ${LLM_OPENAI_API_KEY:-""} - modelId: ${LLM_OPENAI_MODEL_ID:-"gpt-4o-mini"} - endpoint: ${LLM_OPENAI_ENDPOINT:-""} - deploymentName:${LLM_OPENAI_DEPLOYMENT:-""} - apiVersion: ${LLM_OPENAI_API_VERSION:-"2024-02-01"} - maxTokens: ${LLM_OPENAI_MAX_TOKENS:-4096} - bedrock: - awsConfig: - awsRegion: ${AWS_DEFAULT_REGION:-""} - # IAM or static keys via AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN - modelId: ${LLM_BEDROCK_MODEL_ID:-"eu.anthropic.claude-haiku-4-5-20251001-v1:0"} - maxTokens: ${LLM_BEDROCK_MAX_TOKENS:-4096} - google: - apiKey: ${LLM_GOOGLE_API_KEY:-""} - modelId: ${LLM_GOOGLE_MODEL_ID:-"gemini-2.5-flash"} - maxTokens: ${LLM_GOOGLE_MAX_TOKENS:-4096} - anthropic: - apiKey: ${LLM_ANTHROPIC_API_KEY:-""} - modelId: ${LLM_ANTHROPIC_MODEL_ID:-"claude-3-5-sonnet-20240620"} - baseUrl: ${LLM_ANTHROPIC_BASE_URL:-"https://api.anthropic.com"} - maxTokens: ${LLM_ANTHROPIC_MAX_TOKENS:-4096} -``` - -## 17. Known limitations & follow-ups - -1. **Chunk tail dropped.** Documents over ~480K chars (8 × 60K) lose their tail to - the LLM, even though `canonicalText` supplies up to ~1M chars. Consider raising - `MAX_CHUNKS` or summarizing the remainder. -2. **`memoryCount` not in bulk path.** It is populated only in single-entity - `setFields`, not `setFieldsInBulk` — list endpoints requesting `memoryCount` - may return it unset. -3. **`processingError` is content-only.** The file entity flips to `Failed` with - no error string; clients must read the content snapshot for the reason. -4. **No checksum short-circuit.** Identical re-uploads pay the full text + LLM - cost; the captured checksum is stored but never compared. -5. **Wholesale reprocess.** Pills are hard-deleted and regenerated with new - UUIDs/FQNs each run — no continuity/versioning for an unchanged pill. -6. **Bedrock client never closed.** `BedrockCompletionClient` is `AutoCloseable` - but `LLMClientHolder` never calls `close()`; a re-`initialize` would leak the - prior SDK client. Low impact (single startup init). -7. **Factory ignores `enabled`.** Only the holder gates on it; calling the factory - directly with `enabled=false` + a real provider would still build a live client. -8. **MCP authorization is coarse.** A single global `VIEW_ALL` + ES - `visibility=Shared` filter, with no per-pill owner re-check. -9. **`Unsupported` status** is in the enum but never written by the service - (passthrough from the text extractor only). -10. **Per-language ES index files are byte-identical** — the jp/ru/zh - `sourceFile` mappings carry no CJK/Russian-specific analyzers. - -## 18. File touch-list - -**New — backend** -- `openmetadata-spec/.../json/schema/configuration/llmConfiguration.json` -- `openmetadata-service/.../service/llm/` — `LLMCompletionClient`, - `LLMCompletionClientFactory`, `LLMClientHolder`, `LLMCompletionException`, - `KnowledgePill`, `NoopCompletionClient`, `OpenAICompletionClient`, - `AnthropicCompletionClient`, `BedrockCompletionClient`, `GoogleCompletionClient` -- `openmetadata-service/.../service/drive/ContextMemoryExtractor.java` -- `openmetadata-mcp/.../tools/SearchCompanyContextTool.java`, `GetCompanyContextTool.java` - -**New — frontend** -- `.../components/.../ContextCenter/DocumentStatusBadge/` (component, interface, test) - -**Modified — schema** -- `entity/context/contextMemory.json`, `api/context/createContextMemory.json`, - `entity/data/contextFile.json` (+ generated TS mirrors) - -**Modified — backend** -- `OpenMetadataApplication.java`, `OpenMetadataApplicationConfig.java`, - `conf/openmetadata.yaml` -- `service/drive/ContextFileExtractionService.java` → **renamed** - `ContextFileProcessingService.java` -- `resources/drive/ContextFileResource.java` -- `jdbi3/ContextMemoryRepository.java`, `jdbi3/ContextFileRepository.java`, - `jdbi3/SystemRepository.java`, `attachments/AssetServiceFactory.java` -- `resources/context/ContextMemoryMapper.java` -- `search/indexes/ContextMemoryIndex.java`, - `search/vector/ContextMemoryBodyTextContributor.java`, - `elasticsearch/{en,jp,ru,zh}/context_memory_search_index.json` -- `openmetadata-mcp/.../tools/DefaultToolContext.java`, - `openmetadata-mcp/.../resources/json/data/mcp/tools.json` - -**Modified — frontend** -- `.../DocumentsView/DocumentsView.component.tsx`, locale files (17), generated TS - -**Tests** — across `openmetadata-service`, `openmetadata-mcp`, -`openmetadata-integration-tests`, and UI (see [§15](#15-testing)). - -**Codegen after schema edits:** `make generate`, `mvn spotless:apply`, UI -checkstyle for generated TS, `npx tsc --noEmit`. - ---- - -## 19. Follow-on: AISettings + Memory Agent (designed) - -**Status:** Designed, not yet built. Full design: -`docs/superpowers/specs/2026-06-18-ai-settings-memory-agent-design.md`. Built on -branch `pmbrull/ottawa`. Two capabilities layered on top of the pill pipeline above. - -### 19.1 AISettings (config plane) - -A SearchSettings-style settings entity (`configuration/aiSettings.json`, -`SettingsType.AI_SETTINGS`, seeded + merged via `SettingsCache` / a new -`AISettingsHandler`, read/written through the generic `SystemResource` -GET/PUT/reset, UI page under Preferences → AI). Shape: - -- master `enabled` kill-switch (gates extraction **and** the agent) -- `memoryExtraction.{fromFiles, fromPages}` -- `memoryAgent.{enabled, deriveGlossaryTerms, deriveMetrics, deletionPolicy}` - (`deletionPolicy` ∈ `cascade | orphan | deprecate`, default `cascade`) -- `prompts.{memoryExtraction, memoryAgent}.systemPrompt` - -**Deltas to this doc:** -- The hardcoded `ContextMemoryExtractor.SYSTEM_PROMPT` ([§8](#8-knowledge-pill-extraction-contextmemoryextractor)) - moves to `AISettings.prompts.memoryExtraction.systemPrompt` — seed JSON carries - the default, the code constant is kept only as the cache-miss fallback, and the - extractor reads it at run time. This addresses the un-tunable-prompt gap. -- File extraction ([§7.2](#72-service-contextfileprocessingservice-was-contextfileextractionservice) - `submit`) and page extraction now gate **additionally** on AISettings - (`enabled && memoryExtraction.fromFiles` / `fromPages`), not only on - `LLMClientHolder.isEnabled()`. - -### 19.2 Memory Agent (memory → ontology) - -On `ContextMemory` create/update, an async, throttled agent reconciles the memory -against the **existing** instance ontology and derives Glossary Terms / Metrics — -reusing what already covers the memory, creating only what is missing. - -- New **`DERIVED_FROM`** relationship (appended last in `entityRelationship.json`; - `derivedEntity → sourceMemory`). -- `MemoryExtractor` (pure `derive`) + `MemoryReconciler` (owns writes) + - `MemoryProcessingEngine` (orchestrator) in the `drive` package — siblings to - this pill pipeline, same hash-gate / throttle / reconcile idioms — triggered - from new `ContextMemoryRepository.postCreate` / `postUpdate` hooks. -- Per memory, two **independent** axes (Term, Metric), each: - REUSE (`RELATED_TO` edge to an existing entity, not owned) / - CREATE (`provider=automation`, `DERIVED_FROM` edge, agent-owned; mints a - glossary when none fits) / SKIP. Grounding is top-K search over the existing - term/metric indexes (no full-ontology load). -- **Ownership lifecycle:** adopt-on-touch flips `automation→user` on a human PATCH - (mirrors the pills Manual-guard); `deletionPolicy` governs memory-delete cleanup - of owned entities (`cascade` hard-deletes, `orphan` releases, `deprecate` flags). - Agent writes as a dedicated `memory-bot`. -- **Schema:** new `ContextMemory.memoryStats` (hash-gate + derived/reused - counts); new `provider` field on `Metric` ([§6.1](#61-schemas)) for uniform - ownership across Terms/Metrics/Glossaries. -- Renders the full **File → Memory → Term/Metric** provenance chain in the UI. diff --git a/docs/superpowers/plans/2026-06-22-logviewer-modal.md b/docs/superpowers/plans/2026-06-22-logviewer-modal.md index f40f5c362513..d7e2138b4984 100644 --- a/docs/superpowers/plans/2026-06-22-logviewer-modal.md +++ b/docs/superpowers/plans/2026-06-22-logviewer-modal.md @@ -14,7 +14,7 @@ - No string literals in the component — use `useTranslation` (`const { t } = useTranslation()`); reuse existing keys: `label.download`, `label.search-entity`, `label.log-plural`. No new i18n keys are required. - No `any` in production code (`.component.tsx`, `.interface.ts`). Test mocks may use minimal local typing. - Use design tokens only (`bg-primary`, `text-primary`, `border-secondary`, etc.) — never hardcoded colors. -- Component library is `@openmetadata/ui-core-components` — NOT MUI, NOT Ant Design. +- Component library is `@openmetadata/ui-core-components` — NOT any other external UI library, NOT Ant Design. - Apache 2.0 license header on every new source file (run `yarn license-header-fix `). - Run the UI checkstyle sequence (organize-imports → eslint --fix → prettier --write) before finishing (see final task / `ui-checkstyle` skill). - Component does NO data fetching; parent owns `open`, `logs`, `loading`, `follow`. diff --git a/docs/superpowers/specs/2026-06-22-logviewer-modal-design.md b/docs/superpowers/specs/2026-06-22-logviewer-modal-design.md index 879bf1e92933..4b6650aea5cd 100644 --- a/docs/superpowers/specs/2026-06-22-logviewer-modal-design.md +++ b/docs/superpowers/specs/2026-06-22-logviewer-modal-design.md @@ -54,7 +54,7 @@ a `follow` prop (auto-tail) without implementing any streaming itself. (dark surface, light monospace text, line-number gutter, bottom search bar). - Reuse the existing `LazyLog` library — no custom log renderer. - Use Untitled UI / Tailwind (`tw:`) styling and the `ui-core-components` modal - primitives. No MUI. + primitives. No Ant Design. - Be a "pure" presentational component: stateless beyond `LazyLog`'s internals, controlled open/close, no API calls. - Be live-log ready (future scope) through a single `follow` prop. diff --git a/ingestion/examples/sample_data/api_service/api_endpoint.json b/ingestion/examples/sample_data/api_service/api_endpoint.json index bbcb5837de96..b13c947af8b4 100644 --- a/ingestion/examples/sample_data/api_service/api_endpoint.json +++ b/ingestion/examples/sample_data/api_service/api_endpoint.json @@ -266,6 +266,62 @@ "description": "Delete pet by ID", "endpointURL": "https://petstore3.swagger.io/#/pet/deletePet", "requestMethod": "DELETE" + }, + { + "name": "provider_address_texas_endpoint", + "apiCollection": "sample_api_service.pet", + "displayName": "Provider Address Texas Endpoint", + "description": "Search relevancy fixture endpoint for provider address Texas lookups.", + "endpointURL": "https://petstore3.swagger.io/#/pet/providerAddressTexas", + "requestMethod": "GET", + "responseSchema": { + "schemaType": "JSON", + "schemaFields": [ + { + "name": "provider_id", + "dataType": "INT", + "description": "Provider identifier" + }, + { + "name": "provider_address", + "dataType": "STRING", + "description": "Provider address" + }, + { + "name": "texas_region", + "dataType": "STRING", + "description": "Texas region" + } + ] + } + }, + { + "name": "customer_profiles_endpoint", + "apiCollection": "sample_api_service.pet", + "displayName": "Customer Profiles Endpoint", + "description": "Search relevancy fixture endpoint for customer profiles lookups.", + "endpointURL": "https://petstore3.swagger.io/#/pet/customerProfiles", + "requestMethod": "GET", + "responseSchema": { + "schemaType": "JSON", + "schemaFields": [ + { + "name": "customer_id", + "dataType": "INT", + "description": "Customer identifier" + }, + { + "name": "customer_profile_id", + "dataType": "STRING", + "description": "Customer profile identifier" + }, + { + "name": "profile_status", + "dataType": "STRING", + "description": "Customer profile status" + } + ] + } } ] -} \ No newline at end of file +} diff --git a/ingestion/examples/sample_data/dashboards/dashboards.json b/ingestion/examples/sample_data/dashboards/dashboards.json index 4692bb567f53..d5351f20c531 100644 --- a/ingestion/examples/sample_data/dashboards/dashboards.json +++ b/ingestion/examples/sample_data/dashboards/dashboards.json @@ -120,6 +120,26 @@ "sourceUrl": "http://localhost:808/superset/dashboard/forecast_sales_performance/", "charts": ["sample_superset.211"], "href": "http://localhost:8585/api/v1/dashboards/d2b0af00-f419-4905-bb43-036697ce53a5" + }, + { + "name": "provider_address_texas_dashboard", + "displayName": "Provider Address Texas Dashboard", + "fullyQualifiedName": "sample_superset.provider_address_texas_dashboard", + "description": "Search relevancy fixture dashboard for provider address Texas reporting.", + "sourceUrl": "http://localhost:808/superset/dashboard/provider_address_texas_dashboard/", + "charts": ["sample_superset.210"], + "tags": [], + "href": "http://localhost:8585/api/v1/dashboards/provider_address_texas_dashboard" + }, + { + "name": "customer_profiles_dashboard", + "displayName": "Customer Profiles Dashboard", + "fullyQualifiedName": "sample_superset.customer_profiles_dashboard", + "description": "Search relevancy fixture dashboard for customer profiles reporting.", + "sourceUrl": "http://localhost:808/superset/dashboard/customer_profiles_dashboard/", + "charts": ["sample_superset.210"], + "tags": [], + "href": "http://localhost:8585/api/v1/dashboards/customer_profiles_dashboard" } ] } diff --git a/ingestion/examples/sample_data/datasets/query_log b/ingestion/examples/sample_data/datasets/query_log index 67953f5a8414..d610a662e715 100644 --- a/ingestion/examples/sample_data/datasets/query_log +++ b/ingestion/examples/sample_data/datasets/query_log @@ -1403,4 +1403,42 @@ query,cost,user "select * from shopify.raw_customer",12,admin "create table shopify.dim_address_clean as select address_id, shop_id, first_name, last_name, address1 as address, company, city, region, zip, country, phone from shopify.dim_address",0.5,admin "create table shopify.dim_address_clean as select address_id, shop_id, first_name, last_name, address1 as address, company, city, region, zip, country, phone from shopify.dim_address",0.5,admin -"select * from shopify.raw_customer limit 1",12,admin \ No newline at end of file +"select * from shopify.raw_customer limit 1",12,admin +"select provider_id, provider_address from shopify.provider_address",8,admin +"select provider_id, provider_address from shopify.provider_address",7,admin +"select job_id, provider_address from shopify.service_job_registry",6,admin +"select job_id, provider_address from shopify.service_job_registry",5,admin +"select work_id, service_type from shopify.work",160,admin +"select work_id, service_type from shopify.work",159,admin +"select work_id, service_type from shopify.work",158,admin +"select work_id, service_type from shopify.work",157,admin +"select work_id, service_type from shopify.work",156,admin +"select work_id, service_type from shopify.work",155,admin +"select work_id, service_type from shopify.work",154,admin +"select work_id, service_type from shopify.work",153,admin +"select work_id, service_type from shopify.work",152,admin +"select work_id, service_type from shopify.work",151,admin +"select work_id, service_type from shopify.work",150,admin +"select work_id, service_type from shopify.work",149,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",25,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",24,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",23,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",22,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",21,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",20,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",19,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",18,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",17,admin +"select record_id, region_name from shopify.regional_directory_tier1_usage",16,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",190,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",189,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",188,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",187,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",186,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",185,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",184,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",183,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",182,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",181,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",180,admin +"select case_id, support_queue from shopify.support_case_rollup_tier1_usage",179,admin diff --git a/ingestion/examples/sample_data/datasets/tables.json b/ingestion/examples/sample_data/datasets/tables.json index 1fac85a5a84a..01b58b4c246a 100644 --- a/ingestion/examples/sample_data/datasets/tables.json +++ b/ingestion/examples/sample_data/datasets/tables.json @@ -33636,6 +33636,677 @@ "appliedDate": 1767799745051, "expiryDate": 1799335745051 } + }, + { + "name": "provider_address", + "description": "Provider address lookup table used for canonical provider location matching. Search fixture: clear table-name match should rank ahead of popularity-only descriptive matches.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/provider_address", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE provider_address(provider_id NUMERIC PRIMARY KEY, provider_address VARCHAR(500), mailing_address VARCHAR(500), texas_region VARCHAR(100), network_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "provider_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the provider.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "provider_address", + "dataType": "VARCHAR", + "dataLength": 500, + "dataTypeDisplay": "varchar", + "description": "Canonical provider address.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "mailing_address", + "dataType": "VARCHAR", + "dataLength": 500, + "dataTypeDisplay": "varchar", + "description": "Mailing address for the provider.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "texas_region", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Texas operating region for the address.", + "tags": [], + "ordinalPosition": 4 + }, + { + "name": "network_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Operational network status.", + "tags": [], + "ordinalPosition": 5 + } + ], + "tags": [] + }, + { + "name": "provider_address_texas", + "description": "Canonical provider address table for Texas network locations. Search fixture: exact name should rank ahead of descriptive matches.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/provider_address_texas", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE provider_address_texas(provider_id NUMERIC PRIMARY KEY, provider_address VARCHAR(500), texas_region VARCHAR(100), network_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "provider_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the provider.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "provider_address", + "dataType": "VARCHAR", + "dataLength": 500, + "dataTypeDisplay": "varchar", + "description": "Normalized provider street address.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "texas_region", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Texas service region for the provider address.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "network_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Operational network status.", + "tags": [], + "ordinalPosition": 4 + } + ], + "tags": [] + }, + { + "name": "provider_directory", + "description": "Directory used by network operations teams for active healthcare providers.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/provider_directory", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE provider_directory(provider_id NUMERIC PRIMARY KEY, provider_address VARCHAR(500), texas_region VARCHAR(100), directory_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "provider_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the provider.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "provider_address", + "dataType": "VARCHAR", + "dataLength": 500, + "dataTypeDisplay": "varchar", + "description": "Provider address captured from source systems.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "texas_region", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Texas operating region.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "directory_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Status of the provider directory record.", + "tags": [], + "ordinalPosition": 4 + } + ], + "tags": [] + }, + { + "name": "service_job_registry", + "description": "Operational registry for dispatch jobs, billing checkpoints, and lifecycle status.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/service_job_registry", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE service_job_registry(job_id NUMERIC PRIMARY KEY, provider_address VARCHAR(500), texas_region VARCHAR(100), dispatch_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "job_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the service job.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "provider_address", + "dataType": "VARCHAR", + "dataLength": 500, + "dataTypeDisplay": "varchar", + "description": "Address captured on the service job.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "texas_region", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Texas operations region.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "dispatch_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Current dispatch status.", + "tags": [], + "ordinalPosition": 4 + } + ], + "tags": [] + }, + { + "name": "work", + "description": "Work table containing enriched service job attributes, Texas provider details, billing status, and lifecycle tracking. Search fixture: this table is intentionally Tier 1 and very high usage but only has a weak description match for provider and Texas.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/work", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE work(work_id NUMERIC PRIMARY KEY, service_type VARCHAR(100), assignee VARCHAR(100), billing_status VARCHAR(50), lifecycle_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "work_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the work record.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "service_type", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Type of service job.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "assignee", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Person assigned to the work item.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "billing_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Billing status for the work item.", + "tags": [], + "ordinalPosition": 4 + }, + { + "name": "lifecycle_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Lifecycle status of the work item.", + "tags": [], + "ordinalPosition": 5 + } + ], + "tags": [ + { + "tagFQN": "Tier.Tier1", + "description": "Tier 1 data - critical business data", + "source": "Classification", + "labelType": "Manual", + "state": "Confirmed" + } + ] + }, + { + "name": "regional_directory_tier1_usage", + "description": "Stores provider address in Texas and regional notes for data stewards. This fixture is intentionally Tier 1 and high usage but only matches in description.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/regional_directory_tier1_usage", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE regional_directory_tier1_usage(record_id NUMERIC PRIMARY KEY, region_name VARCHAR(100), steward_notes VARCHAR(500))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "record_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the regional record.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "region_name", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Region associated with this directory record.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "steward_notes", + "dataType": "VARCHAR", + "dataLength": 500, + "dataTypeDisplay": "varchar", + "description": "Free-form operational notes.", + "tags": [], + "ordinalPosition": 3 + } + ], + "tags": [ + { + "tagFQN": "Tier.Tier1", + "description": "Tier 1 data - critical business data", + "source": "Classification", + "labelType": "Manual", + "state": "Confirmed" + } + ] + }, + { + "name": "customer", + "displayName": "Customers", + "description": "Search relevancy fixture for singular customer records. The display name intentionally uses customers so singular and plural queries can be compared.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/customer", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE customer(customer_id NUMERIC PRIMARY KEY, customer_name VARCHAR(200), customer_email VARCHAR(200), customer_profile_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "customer_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the customer.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "customer_name", + "dataType": "VARCHAR", + "dataLength": 200, + "dataTypeDisplay": "varchar", + "description": "Customer full name.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "customer_email", + "dataType": "VARCHAR", + "dataLength": 200, + "dataTypeDisplay": "varchar", + "description": "Customer email address.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "customer_profile_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Status of the customer profile.", + "tags": [], + "ordinalPosition": 4 + } + ], + "tags": [] + }, + { + "name": "customers", + "displayName": "Customer", + "description": "Search relevancy fixture for plural customers records. The display name intentionally uses customer so plural and singular queries can be compared.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/customers", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE customers(customer_id NUMERIC PRIMARY KEY, customer_name VARCHAR(200), preferred_channel VARCHAR(100), lifecycle_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "customer_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the customer.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "customer_name", + "dataType": "VARCHAR", + "dataLength": 200, + "dataTypeDisplay": "varchar", + "description": "Customer full name.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "preferred_channel", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Preferred communication channel.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "lifecycle_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Lifecycle status for the customer.", + "tags": [], + "ordinalPosition": 4 + } + ], + "tags": [] + }, + { + "name": "customer_profile", + "displayName": "Customer Profile", + "description": "Search relevancy fixture for customer profile enrichment. Clear name matches should outrank high-signal tables that only mention customer profile in description.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/customer_profile", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE customer_profile(customer_id NUMERIC PRIMARY KEY, customer_profile_id VARCHAR(100), customer_profile_status VARCHAR(50), loyalty_segment VARCHAR(100), account_region VARCHAR(100))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "customer_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the customer.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "customer_profile_id", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Identifier for the customer profile.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "customer_profile_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Status of the customer profile.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "loyalty_segment", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Assigned loyalty segment.", + "tags": [], + "ordinalPosition": 4 + }, + { + "name": "account_region", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Region for the account.", + "tags": [], + "ordinalPosition": 5 + } + ], + "tags": [] + }, + { + "name": "customer_profiles", + "displayName": "Customer Profiles", + "description": "Search relevancy fixture for customers profile records. Close singular/plural name matches should rank before Tier 1 usage-only description matches.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/customer_profiles", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE customer_profiles(customer_id NUMERIC PRIMARY KEY, customer_profile_id VARCHAR(100), customer_profile_status VARCHAR(50), profile_score NUMERIC, loyalty_segment VARCHAR(100))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "customer_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the customer.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "customer_profile_id", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Identifier for the customer profile.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "customer_profile_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Status of the customer profile.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "profile_score", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Profile completeness score.", + "tags": [], + "ordinalPosition": 4 + }, + { + "name": "loyalty_segment", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Assigned loyalty segment.", + "tags": [], + "ordinalPosition": 5 + } + ], + "tags": [] + }, + { + "name": "identity_resolution_registry", + "description": "Registry used for identity resolution workflows. Search fixture: table name does not contain customer profile, but column names do.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/identity_resolution_registry", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE identity_resolution_registry(identity_id NUMERIC PRIMARY KEY, customer_profile_id VARCHAR(100), customer_profile_status VARCHAR(50), customers_matched_count NUMERIC, resolution_status VARCHAR(50))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "identity_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the identity record.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "customer_profile_id", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Matched customer profile identifier.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "customer_profile_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Status copied from the matched customer profile.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "customers_matched_count", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Number of customers matched into this identity.", + "tags": [], + "ordinalPosition": 4 + }, + { + "name": "resolution_status", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Current identity resolution status.", + "tags": [], + "ordinalPosition": 5 + } + ], + "tags": [] + }, + { + "name": "support_case_rollup_tier1_usage", + "description": "Support rollup used by executives. Search fixture: intentionally Tier 1 and very high usage while only mentioning customer profile status and customers in description.", + "version": 0.1, + "updatedAt": 1638354087391, + "updatedBy": "anonymous", + "href": "http://localhost:8585/api/v1/tables/support_case_rollup_tier1_usage", + "tableType": "Regular", + "schemaDefinition": "CREATE TABLE support_case_rollup_tier1_usage(case_id NUMERIC PRIMARY KEY, support_queue VARCHAR(100), case_priority VARCHAR(50), resolution_state VARCHAR(50), agent_team VARCHAR(100))", + "retentionPeriod": "30D", + "columns": [ + { + "name": "case_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the support case.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "support_queue", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Support queue for the case.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "case_priority", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Priority assigned to the support case.", + "tags": [], + "ordinalPosition": 3 + }, + { + "name": "resolution_state", + "dataType": "VARCHAR", + "dataLength": 50, + "dataTypeDisplay": "varchar", + "description": "Resolution state for the support case.", + "tags": [], + "ordinalPosition": 4 + }, + { + "name": "agent_team", + "dataType": "VARCHAR", + "dataLength": 100, + "dataTypeDisplay": "varchar", + "description": "Team assigned to resolve the support case.", + "tags": [], + "ordinalPosition": 5 + } + ], + "tags": [ + { + "tagFQN": "Tier.Tier1", + "description": "Tier 1 data - critical business data", + "source": "Classification", + "labelType": "Manual", + "state": "Confirmed" + } + ] } ] -} \ No newline at end of file +} diff --git a/ingestion/examples/sample_data/models/models.json b/ingestion/examples/sample_data/models/models.json index 1ecc79f98a29..24dbb63a44fc 100644 --- a/ingestion/examples/sample_data/models/models.json +++ b/ingestion/examples/sample_data/models/models.json @@ -135,5 +135,75 @@ "value": "42" } ] + }, + { + "name": "provider_address_texas_model", + "displayName": "Provider Address Texas Model", + "description": "Search relevancy fixture model for scoring provider address Texas coverage.", + "algorithm": "mlmodel", + "dashboard": "sample_superset.provider_address_texas_dashboard", + "mlStore": { + "storage": "mlflow-artifacts:/4/provider-address-texas/artifacts/model" + }, + "sourceUrl": "http://localhost:8088/#/models/provider_address_texas_model", + "mlFeatures": [ + { + "name": "provider_address_quality", + "dataType": "numerical" + }, + { + "name": "texas_region", + "dataType": "categorical" + }, + { + "name": "network_status", + "dataType": "categorical" + } + ], + "mlHyperParameters": [ + { + "name": "max_depth", + "value": "6" + }, + { + "name": "learning_rate", + "value": "0.05" + } + ] + }, + { + "name": "customer_profiles_model", + "displayName": "Customer Profiles Model", + "description": "Search relevancy fixture model for scoring customer profiles quality.", + "algorithm": "mlmodel", + "dashboard": "sample_superset.customer_profiles_dashboard", + "mlStore": { + "storage": "mlflow-artifacts:/5/customer-profiles/artifacts/model" + }, + "sourceUrl": "http://localhost:8088/#/models/customer_profiles_model", + "mlFeatures": [ + { + "name": "customer_profile_score", + "dataType": "numerical" + }, + { + "name": "profile_status", + "dataType": "categorical" + }, + { + "name": "loyalty_segment", + "dataType": "categorical" + } + ], + "mlHyperParameters": [ + { + "name": "max_depth", + "value": "6" + }, + { + "name": "learning_rate", + "value": "0.05" + } + ] } ] diff --git a/ingestion/examples/sample_data/pipelines/pipelines.json b/ingestion/examples/sample_data/pipelines/pipelines.json index 1df17887310c..e6a01ad8884e 100644 --- a/ingestion/examples/sample_data/pipelines/pipelines.json +++ b/ingestion/examples/sample_data/pipelines/pipelines.json @@ -351,6 +351,38 @@ "downstreamTasks": [], "taskType": "dbtTestTask" }] + }, + { + "name": "provider_address_texas_pipeline", + "displayName": "Provider Address Texas Pipeline", + "description": "Search relevancy fixture pipeline for loading provider address Texas reference data.", + "sourceUrl": "https://airflow.example.com/dags/provider_address_texas_pipeline", + "scheduleInterval": "0 3 * * *", + "service": "sample_airflow", + "tasks": [{ + "name": "load_provider_address_texas", + "displayName": "Load Provider Address Texas", + "description": "Load the provider address Texas fixture table.", + "sourceUrl": "https://airflow.example.com/dags/provider_address_texas_pipeline/tasks/load_provider_address_texas", + "downstreamTasks": [], + "taskType": "PythonOperator" + }] + }, + { + "name": "customer_profiles_pipeline", + "displayName": "Customer Profiles Pipeline", + "description": "Search relevancy fixture pipeline for loading customer profiles reference data.", + "sourceUrl": "https://airflow.example.com/dags/customer_profiles_pipeline", + "scheduleInterval": "0 3 * * *", + "service": "sample_airflow", + "tasks": [{ + "name": "load_customer_profiles", + "displayName": "Load Customer Profiles", + "description": "Load the customer profiles fixture table.", + "sourceUrl": "https://airflow.example.com/dags/customer_profiles_pipeline/tasks/load_customer_profiles", + "downstreamTasks": [], + "taskType": "PythonOperator" + }] } ] -} \ No newline at end of file +} diff --git a/ingestion/examples/sample_data/searchIndexes/searchIndexes.json b/ingestion/examples/sample_data/searchIndexes/searchIndexes.json index 9c496d38ed6f..2672f0082bcb 100644 --- a/ingestion/examples/sample_data/searchIndexes/searchIndexes.json +++ b/ingestion/examples/sample_data/searchIndexes/searchIndexes.json @@ -71,6 +71,74 @@ ], "tags": [], "followers": [] + }, + { + "name": "provider_address_texas_index", + "displayName": "Provider Address Texas Index", + "fullyQualifiedName": "elasticsearch_sample.provider_address_texas_index", + "description": "Search relevancy fixture index for provider address Texas documents.", + "version": 0.1, + "updatedAt": 1638354087591, + "serviceType": "ElasticSearch", + "fields": [ + { + "name": "provider_id", + "dataType": "TEXT", + "dataTypeDisplay": "text", + "description": "Provider identifier.", + "tags": [] + }, + { + "name": "provider_address", + "dataType": "TEXT", + "dataTypeDisplay": "text", + "description": "Provider address search field.", + "tags": [] + }, + { + "name": "texas_region", + "dataType": "TEXT", + "dataTypeDisplay": "text", + "description": "Texas region search field.", + "tags": [] + } + ], + "tags": [], + "followers": [] + }, + { + "name": "customer_profiles_index", + "displayName": "Customer Profiles Index", + "fullyQualifiedName": "elasticsearch_sample.customer_profiles_index", + "description": "Search relevancy fixture index for customer profiles documents.", + "version": 0.1, + "updatedAt": 1638354087591, + "serviceType": "ElasticSearch", + "fields": [ + { + "name": "customer_id", + "dataType": "TEXT", + "dataTypeDisplay": "text", + "description": "Customer identifier.", + "tags": [] + }, + { + "name": "customer_profile_id", + "dataType": "TEXT", + "dataTypeDisplay": "text", + "description": "Customer profile search field.", + "tags": [] + }, + { + "name": "profile_status", + "dataType": "TEXT", + "dataTypeDisplay": "text", + "description": "Customer profile status search field.", + "tags": [] + } + ], + "tags": [], + "followers": [] } ] -} \ No newline at end of file +} diff --git a/ingestion/examples/sample_data/storage/containers.json b/ingestion/examples/sample_data/storage/containers.json index e5aa17235744..bb83167756fa 100644 --- a/ingestion/examples/sample_data/storage/containers.json +++ b/ingestion/examples/sample_data/storage/containers.json @@ -194,5 +194,91 @@ "zstd", "tsv" ] + }, + { + "name": "provider_address_texas_exports", + "displayName": "Provider Address Texas Exports", + "description": "Search relevancy fixture container for provider address Texas export files.", + "parent": "s3_storage_sample.departments", + "prefix": "/departments/provider-address-texas/", + "dataModel": { + "isPartitioned": false, + "columns": [ + { + "name": "provider_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the provider.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "provider_address", + "dataType": "VARCHAR", + "dataTypeDisplay": "varchar", + "description": "Provider address exported for downstream systems.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "texas_region", + "dataType": "VARCHAR", + "dataTypeDisplay": "varchar", + "description": "Texas region partition.", + "tags": [], + "ordinalPosition": 3 + } + ] + }, + "numberOfObjects": "12", + "size": "98304", + "fileFormats": [ + "csv", + "parquet" + ] + }, + { + "name": "customer_profiles_exports", + "displayName": "Customer Profiles Exports", + "description": "Search relevancy fixture container for customer profiles export files.", + "parent": "s3_storage_sample.departments", + "prefix": "/departments/customer-profiles/", + "dataModel": { + "isPartitioned": false, + "columns": [ + { + "name": "customer_id", + "dataType": "NUMERIC", + "dataTypeDisplay": "numeric", + "description": "Unique identifier for the customer.", + "tags": [], + "constraint": "PRIMARY_KEY", + "ordinalPosition": 1 + }, + { + "name": "customer_profile_id", + "dataType": "VARCHAR", + "dataTypeDisplay": "varchar", + "description": "Customer profile identifier exported for downstream systems.", + "tags": [], + "ordinalPosition": 2 + }, + { + "name": "profile_status", + "dataType": "VARCHAR", + "dataTypeDisplay": "varchar", + "description": "Customer profile status.", + "tags": [], + "ordinalPosition": 3 + } + ] + }, + "numberOfObjects": "12", + "size": "98304", + "fileFormats": [ + "csv", + "parquet" + ] } ] diff --git a/ingestion/examples/sample_data/topics/topics.json b/ingestion/examples/sample_data/topics/topics.json index cdb7287bd8bf..614172c876e0 100644 --- a/ingestion/examples/sample_data/topics/topics.json +++ b/ingestion/examples/sample_data/topics/topics.json @@ -111,6 +111,24 @@ "replicationFactor":2, "maximumMessageSize":167, "cleanupPolicies": ["delete"] + }, + { + "name": "provider_address_texas_events", + "description": "Search relevancy fixture topic for provider address Texas events.", + "partitions": 24, + "retentionSize": 455858109, + "replicationFactor":2, + "maximumMessageSize":167, + "cleanupPolicies": ["delete"] + }, + { + "name": "customer_profiles_events", + "description": "Search relevancy fixture topic for customer profiles events.", + "partitions": 24, + "retentionSize": 455858109, + "replicationFactor":2, + "maximumMessageSize":167, + "cleanupPolicies": ["delete"] } ] -} \ No newline at end of file +} diff --git a/ingestion/src/metadata/automations/runner.py b/ingestion/src/metadata/automations/runner.py index 964d08548eb9..e3b16856c8c2 100644 --- a/ingestion/src/metadata/automations/runner.py +++ b/ingestion/src/metadata/automations/runner.py @@ -25,7 +25,11 @@ raise_test_connection_exception, ) from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection, get_test_connection_fn +from metadata.ingestion.source.connections import ( + create_connection, + get_connection, + get_test_connection_fn, +) from metadata.utils.ssl_manager import SSLManager, check_ssl_and_init @@ -74,9 +78,13 @@ def _test_connection( """ Test the connection """ + owned = create_connection(config) + if owned is not None: + with owned: + return owned.test_connection(metadata, automation_workflow=automation_workflow) + # Non-migrated / custom connector: legacy module-level test_connection. + # Migrated connectors go through create_connection above, so this always + # resolves to the legacy (metadata, connection, config) signature. test_connection_fn = get_test_connection_fn(config) - try: - return test_connection_fn(metadata, automation_workflow=automation_workflow) - except TypeError: - connection = get_connection(config) - return test_connection_fn(metadata, connection, config, automation_workflow=automation_workflow) + connection = get_connection(config) + return test_connection_fn(metadata, connection, config, automation_workflow=automation_workflow) diff --git a/ingestion/src/metadata/core/connections/lifetime.py b/ingestion/src/metadata/core/connections/lifetime.py new file mode 100644 index 000000000000..84fa372aecd7 --- /dev/null +++ b/ingestion/src/metadata/core/connections/lifetime.py @@ -0,0 +1,44 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The reference a collaborator holds to a client it does not own. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +if TYPE_CHECKING: + from collections.abc import Callable + +C = TypeVar("C") + + +class Borrowed(Generic[C]): + """A client someone else owns: read it, never build it, never close it. + + Reading ``client`` delegates to the owner, which builds it once on first read. + Carries no config and no teardown, so a holder can do neither. + """ + + __slots__ = ("_read",) + + def __init__(self, read: Callable[[], C]) -> None: + self._read = read + + @property + def client(self) -> C: + return self._read() + + @classmethod + def of(cls, client: C) -> Borrowed[C]: + """A handle over an already-built client. For tests and fakes.""" + return cls(lambda: client) diff --git a/ingestion/src/metadata/core/connections/test_connection/aws.py b/ingestion/src/metadata/core/connections/test_connection/aws.py new file mode 100644 index 000000000000..8182c5c2ad5b --- /dev/null +++ b/ingestion/src/metadata/core/connections/test_connection/aws.py @@ -0,0 +1,115 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Shared authentication diagnoses for the AWS-backed connectors (boto3 / botocore). + +Fold in with ``ErrorPack.including(AWS_ERRORS)``; the connector's own rules still +match first, and it keeps its authorization diagnosis (an ``AccessDenied`` fix must +name that service's IAM actions). ``NETWORK_ERRORS`` is already folded in here. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from botocore.exceptions import ( + ClientError, + EndpointConnectionError, + NoCredentialsError, + NoRegionError, +) + +from metadata.core.connections.test_connection.classifier import ( + ErrorPack, + Matchers, + exception_chain, + when, +) +from metadata.core.connections.test_connection.network import NETWORK_ERRORS + +if TYPE_CHECKING: + from metadata.core.connections.test_connection.classifier import Matcher + + +def aws_error_code(error: BaseException) -> str | None: + """The botocore ``ClientError`` code anywhere in the cause chain, if any.""" + code = None + for current in exception_chain(error): + if isinstance(current, ClientError): + code = current.response.get("Error", {}).get("Code") + break + return code + + +def aws_code(*codes: str) -> Matcher: + """Match a botocore ``ClientError`` by its structured AWS error code.""" + wanted = frozenset(codes) + return lambda error: aws_error_code(error) in wanted + + +# Each cause below has one code per wire protocol: rest-xml (S3), json (Glue, +# Athena), query (STS). An assume-role config hits the STS leg first, so every +# code stays reachable from every connector. +# InvalidClientTokenId reads "security token" but means the key ID is unknown. +_UNKNOWN_KEY = ("InvalidAccessKeyId", "UnrecognizedClientException", "InvalidClientTokenId") +_BAD_SIGNATURE = ("SignatureDoesNotMatch", "InvalidSignatureException") +_EXPIRED_TOKEN = ("ExpiredToken", "ExpiredTokenException") + +_SKEW_MESSAGES = ("signature expired", "signature not yet current") + +# For connectors that also match authorization failures by message text. +AWS_AUTHENTICATION_CODES = frozenset(_UNKNOWN_KEY + _BAD_SIGNATURE + _EXPIRED_TOKEN) + + +def _clock_skew(error: BaseException) -> bool: + """Skew fails signature verification, so it shares the wrong-secret codes and + is told apart only by message.""" + if aws_error_code(error) not in _BAD_SIGNATURE: + return False + text = " ".join(str(current) for current in exception_chain(error)).lower() + return any(message in text for message in _SKEW_MESSAGES) + + +# Split by cause: each one sends the user somewhere different. Skew first - it +# shares the codes of the wrong-secret rule below. +AWS_ERRORS = ErrorPack( + when(_clock_skew).diagnose( + "Request signature expired", + fix="The clock where ingestion runs is too far from AWS's (tolerance is about 5 minutes); sync it with NTP.", + ), + when(aws_code(*_UNKNOWN_KEY)).diagnose( + "AWS access key not recognized", + fix="AWS does not know this awsAccessKeyId - it may be deleted, inactive, or from another " + "account or partition. With temporary credentials, the awsSessionToken may also be invalid.", + ), + when(aws_code(*_BAD_SIGNATURE)).diagnose( + "AWS secret key does not match", + fix="The awsSecretAccessKey is wrong for this awsAccessKeyId; re-enter the credential pair.", + ), + when(aws_code(*_EXPIRED_TOKEN)).diagnose( + "AWS session token expired", + fix="Temporary credentials have expired; refresh the awsSessionToken.", + ), + when(Matchers.exception(NoCredentialsError)).diagnose( + "No AWS credentials found", + fix="No credentials were configured or resolvable; set awsAccessKeyId/awsSecretAccessKey " + "or make an IAM role available where ingestion runs.", + ), + when(Matchers.exception(NoRegionError)).diagnose( + "No AWS region configured", + fix="Set awsRegion; the client cannot resolve a service endpoint without it.", + ), + when(Matchers.exception(EndpointConnectionError)).diagnose( + "Cannot reach the AWS endpoint", + fix="Check awsRegion (and endPointURL when overridden), and that the network allows " + "access to the service endpoint from where ingestion runs.", + ), +).including(NETWORK_ERRORS) diff --git a/ingestion/src/metadata/core/connections/test_connection/checks/dashboard.py b/ingestion/src/metadata/core/connections/test_connection/checks/dashboard.py index fac8e5494e0c..fb46ded550a6 100644 --- a/ingestion/src/metadata/core/connections/test_connection/checks/dashboard.py +++ b/ingestion/src/metadata/core/connections/test_connection/checks/dashboard.py @@ -22,7 +22,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, TypeVar from metadata.core.connections.test_connection.check import CheckError, StepName from metadata.core.connections.test_connection.records import Diagnosis, Evidence @@ -30,6 +30,8 @@ if TYPE_CHECKING: from collections.abc import Callable, Sized +_T = TypeVar("_T") + # A check only needs to prove the list endpoint is reachable and returns items, # not enumerate every one, so ``fetch_list`` counts at most this many and renders @@ -43,6 +45,16 @@ class DashboardStep(StepName): CheckAccess = "CheckAccess" GetDashboards = "GetDashboards" + ServerInfo = "ServerInfo" + ValidateApiVersion = "ValidateApiVersion" + ValidateVersion = "ValidateVersion" + ValidateSiteUrl = "ValidateSiteUrl" + GetWorkbooks = "GetWorkbooks" + GetViews = "GetViews" + GetOwners = "GetOwners" + GetDataModels = "GetDataModels" + ListDashboards = "ListDashboards" + ListLookMLModels = "ListLookMLModels" def _count(number: int, noun: str, cap: int | None = None) -> str: @@ -72,6 +84,20 @@ def verify_access(authenticate: Callable[[], object], command: str) -> Evidence: return Evidence(summary="authenticated", command=command) +def call_endpoint(call: Callable[[], _T], command: str) -> _T: + """Call a REST endpoint and hand its result back to the check. + + For steps whose evidence is not a count: the check summarizes the returned + value itself (an API version, a resolved owner). On failure, re-raise as + ``CheckError`` carrying the attempted command so the failed step still + reports what it ran. + """ + try: + return call() + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + + def fetch_list( fetch: Callable[[], Sized | None], noun: str, diff --git a/ingestion/src/metadata/core/connections/test_connection/checks/database.py b/ingestion/src/metadata/core/connections/test_connection/checks/database.py index 6792d9efbeb2..342d5a2d3a69 100644 --- a/ingestion/src/metadata/core/connections/test_connection/checks/database.py +++ b/ingestion/src/metadata/core/connections/test_connection/checks/database.py @@ -59,6 +59,13 @@ class DatabaseStep(StepName): GetColumnMetadata = "GetColumnMetadata" GetTableComments = "GetTableComments" GetInformationSchemaColumns = "GetInformationSchemaColumns" + GetViewDefinitions = "GetViewDefinitions" + GetCatalogTags = "GetCatalogTags" + GetSchemaTags = "GetSchemaTags" + GetTableTags = "GetTableTags" + GetColumnTags = "GetColumnTags" + GetTableLineage = "GetTableLineage" + GetColumnLineage = "GetColumnLineage" @contextmanager diff --git a/ingestion/src/metadata/core/connections/test_connection/checks/pipeline.py b/ingestion/src/metadata/core/connections/test_connection/checks/pipeline.py new file mode 100644 index 000000000000..3246ef050457 --- /dev/null +++ b/ingestion/src/metadata/core/connections/test_connection/checks/pipeline.py @@ -0,0 +1,98 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Pipeline service step identity and shared check helpers. + +Pipeline connectors (dbt Cloud, Airflow, Fivetran) reach their orchestrator over +a REST API with token auth, not a SQLAlchemy engine, so these helpers stay +HTTP-generic: they call a connector-supplied callable and summarize what it +returned, and on failure raise ``CheckError`` carrying the label of the call they +attempted, so a failed step still reports its ``Evidence`` to the backend. The +runner and the rest of the package stay engine- and protocol-agnostic; connectors +reuse these helpers from their ``@check`` methods. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from metadata.core.connections.test_connection.check import CheckError, StepName +from metadata.core.connections.test_connection.records import Diagnosis, Evidence + +if TYPE_CHECKING: + from collections.abc import Callable, Sized + + +# A check only needs to prove the list endpoint is reachable and returns items, +# not enumerate every one, so ``fetch_list`` counts at most this many and renders +# ``+`` when the count meets or exceeds it, keeping the summary bounded on +# huge accounts. +DEFAULT_LIST_CAP = 100 + + +class PipelineStep(StepName): + """The steps a pipeline connector can be asked to verify.""" + + CheckAccess = "CheckAccess" + GetJobs = "GetJobs" + GetRuns = "GetRuns" + PipelineDetailsAccess = "PipelineDetailsAccess" + TaskDetailAccess = "TaskDetailAccess" + GetPipelines = "GetPipelines" + + +def _count(number: int, noun: str, cap: int | None = None) -> str: + """``3 jobs`` / ``1 job`` - pluralize the noun to match the count. + + When ``cap`` is given and the count meets or exceeds it, the figure is + rendered ``+`` so a capped sample is not read as an exact total. The + caller caps ``number`` at ``cap`` first, so this only ever renders ``+`` + at the boundary, never a larger bare number. + """ + plural = noun if number == 1 else noun + "s" + shown = f"{cap}+" if cap is not None and number >= cap else str(number) + return f"{shown} {plural}" + + +def verify_access(authenticate: Callable[[], object], command: str) -> Evidence: + """Prove the connector can authenticate against the REST API. + + On failure, re-raise as ``CheckError`` carrying the attempted command, so the + gate step still reports what it tried. + """ + try: + authenticate() + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + return Evidence(summary="authenticated", command=command) + + +def fetch_list( + fetch: Callable[[], Sized | None], + noun: str, + command: str, + cap: int = DEFAULT_LIST_CAP, + empty_caveat: Diagnosis | None = None, +) -> Evidence: + """Call a REST list endpoint and report how many items it returned. + + The count is capped at ``cap`` and rendered ``+`` at the boundary. When the + endpoint returns nothing and ``empty_caveat`` is given, the step passes but + carries the caveat as a non-blocking Warning. On failure, re-raise as + ``CheckError`` carrying the command, so the failed step still reports what it ran. + """ + try: + items = fetch() + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + count = min(len(items) if items else 0, cap) + caveat = empty_caveat if count == 0 else None + return Evidence(summary=f"{_count(count, noun, cap)} enumerated", command=command, caveat=caveat) diff --git a/ingestion/src/metadata/core/connections/test_connection/network.py b/ingestion/src/metadata/core/connections/test_connection/network.py index 54852a55afc5..713bd8635477 100644 --- a/ingestion/src/metadata/core/connections/test_connection/network.py +++ b/ingestion/src/metadata/core/connections/test_connection/network.py @@ -39,10 +39,12 @@ class NetworkUnreachableError(OSError): def tcp_probe(host: str, port: int, timeout: float = NETWORK_PROBE_TIMEOUT_SECONDS) -> None: - """Prove a host:port is reachable by opening and immediately closing a TCP connection. + """Prove host:port is reachable by opening a TCP connection to it. - Raises ``NetworkUnreachableError`` - chaining the underlying socket error so - the classifier can still match its type - when the connect fails or times out. + ``create_connection`` resolves the host and tries each address it returns, + IPv4 and IPv6, until one connects: an IPv6-only host is reached and a + dual-stack host falls back to IPv4. Raises ``NetworkUnreachableError``, + chaining the socket error so the classifier can match its type. """ try: with socket.create_connection((host, port), timeout=timeout): diff --git a/ingestion/src/metadata/data_quality/interface/test_suite_interface.py b/ingestion/src/metadata/data_quality/interface/test_suite_interface.py index 908463585479..8f2ca06816c2 100644 --- a/ingestion/src/metadata/data_quality/interface/test_suite_interface.py +++ b/ingestion/src/metadata/data_quality/interface/test_suite_interface.py @@ -26,6 +26,9 @@ from metadata.data_quality.validations.runtime_param_setter.param_setter_factory import ( RuntimeParameterSetterFactory, ) +from metadata.generated.schema.configuration.profilerConfiguration import ( + SampleDataIngestionConfig, +) from metadata.generated.schema.entity.data.table import Table from metadata.generated.schema.entity.services.databaseService import DatabaseConnection from metadata.generated.schema.tests.basic import TestCaseStatus @@ -51,6 +54,7 @@ def __init__( sampler: SamplerInterface, table_entity: Table, validator_builder: Type[ValidatorBuilder], # noqa: UP006 + sample_data_config: Optional[SampleDataIngestionConfig] = None, # noqa: UP045 ): """Required attribute for the interface""" self.ometa_client = ometa_client @@ -58,6 +62,7 @@ def __init__( self.table_entity = table_entity self.sampler = sampler self.validator_builder_class = validator_builder + self.sample_data_config = sample_data_config @classmethod def create( @@ -106,6 +111,11 @@ def _set_runtime_params_setter_fact(cls, class_fact: Type[RuntimeParameterSetter """ cls.runtime_params_setter_fact = class_fact + def _should_collect_failed_rows_sample(self) -> bool: + """Failed row samples are persisted sample data. Skip collecting them + when the global profiler configuration disables storing sample data.""" + return self.sample_data_config is None or bool(self.sample_data_config.storeSampleData) + def run_test_case(self, test_case: TestCase) -> Optional[TestCaseResultResponse]: # noqa: UP045 """run column data quality tests""" runtime_params_setter_fact: RuntimeParameterSetterFactory = self._get_runtime_params_setter_fact() # type: ignore @@ -133,7 +143,14 @@ def run_test_case(self, test_case: TestCase) -> Optional[TestCaseResultResponse] try: test_result = validator.run_validation() response = TestCaseResultResponse(testCaseResult=test_result, testCase=test_case) - validator.result_with_failed_samples(response) + if self._should_collect_failed_rows_sample(): + validator.result_with_failed_samples(response) + else: + logger.debug( + "Global profiler configuration disables storing sample data. " + "Skipping failed rows sample collection for %s.", + test_case.name.root, + ) return response # noqa: TRY300 except Exception as err: message = f"Error executing {test_case.testDefinition.fullyQualifiedName} - {err}" diff --git a/ingestion/src/metadata/data_quality/runner/base_test_suite_source.py b/ingestion/src/metadata/data_quality/runner/base_test_suite_source.py index 9039a16eb69b..d648aa893029 100644 --- a/ingestion/src/metadata/data_quality/runner/base_test_suite_source.py +++ b/ingestion/src/metadata/data_quality/runner/base_test_suite_source.py @@ -19,6 +19,10 @@ from metadata.data_quality.builders.validator_builder import ValidatorBuilder from metadata.data_quality.interface.test_suite_interface import TestSuiteInterface from metadata.data_quality.runner.core import DataTestsRunner +from metadata.generated.schema.configuration.profilerConfiguration import ( + ProfilerConfiguration, + SampleDataIngestionConfig, +) from metadata.generated.schema.entity.data.table import Table from metadata.generated.schema.entity.services.connections.database.bigQueryConnection import ( BigQueryConnection, @@ -46,12 +50,15 @@ from metadata.sampler.sampler_interface import SamplerInterface # noqa: TC001 from metadata.utils.bigquery_utils import copy_service_config from metadata.utils.constants import SAMPLE_DATA_DEFAULT_COUNT +from metadata.utils.logger import test_suite_logger from metadata.utils.profiler_utils import get_context_entities from metadata.utils.service_spec.service_spec import ( import_sampler_class, import_test_suite_class, ) +logger = test_suite_logger() + class BaseTestSuiteRunner: """Base class for the data quality runner""" @@ -160,9 +167,22 @@ def create_data_quality_interface(self) -> TestSuiteInterface: sampler=sampler_interface, table_entity=self.entity, validator_builder=self.validator_builder_class, + sample_data_config=self._get_sample_data_config(), ) return self.interface + def _get_sample_data_config(self) -> SampleDataIngestionConfig | None: + """Fetch the global sample data ingestion config from the profiler settings.""" + sample_data_config = None + try: + settings = self.ometa_client.get_profiler_config_settings() + if settings and settings.config_value: + profiler_config = cast("ProfilerConfiguration", settings.config_value) + sample_data_config = profiler_config.sampleDataConfig + except Exception as exc: + logger.debug(f"Could not fetch global profiler config: {exc}") + return sample_data_config + def get_data_quality_runner(self) -> DataTestsRunner: """Get a data quality runner diff --git a/ingestion/src/metadata/ingestion/api/step.py b/ingestion/src/metadata/ingestion/api/step.py index 4069fcd482e6..e7fc3f05d7d4 100644 --- a/ingestion/src/metadata/ingestion/api/step.py +++ b/ingestion/src/metadata/ingestion/api/step.py @@ -43,6 +43,10 @@ class Step(ABC, Closeable): """All Workflow steps must inherit this base class.""" status: Status + # Opt out of the 10-failure display cap in Summary.from_step: set True on a subclass when + # downstream logic needs the complete failure list (e.g. the Policy Agent coordinator, which + # decides per-policy grant vs manual from exactly which policy ids failed). + report_all_failures: bool = False def __init__(self): self.status = Status() @@ -111,6 +115,14 @@ def from_step(cls, step: Step) -> "Summary": # Stage time = time spent processing entities stage_time_ms = workflow_timing.get("stage", {}).get("total_ms", 0) + # Failures are capped to 10 for display payload size. A step may opt out + # (report_all_failures=True) when downstream logic needs the COMPLETE list — e.g. the Policy + # Agent, whose coordinator decides per-policy grant vs manual from exactly which policy ids + # failed; a truncated list would silently (and unsafely) grant the rest. + display_failures = step.status.failures or None + if display_failures and not step.report_all_failures: + display_failures = display_failures[0:10] + return Summary( name=step.name, records=step.status.record_count if step.status.record_count > 0 else len(step.status.records), @@ -118,7 +130,9 @@ def from_step(cls, step: Step) -> "Summary": warnings=len(step.status.warnings), errors=len(step.status.failures), filtered=len(step.status.filtered), - failures=step.status.failures[0:10] if step.status.failures else None, + # Status stores TruncatedStackTraceError; StepSummary.failures is typed as + # StackTraceError (pre-existing invariance) — safe, the truncated form is a display drop-in. + failures=display_failures, # pyright: ignore[reportArgumentType] progress=progress_tracker.get_progress_as_dict() or None, operationMetrics=operation_metrics.get_summary() or None, sourceTimeMs=source_time_ms if source_time_ms else None, diff --git a/ingestion/src/metadata/ingestion/api/topology_runner.py b/ingestion/src/metadata/ingestion/api/topology_runner.py index 70e88df96adb..7d6bc6e3c0b1 100644 --- a/ingestion/src/metadata/ingestion/api/topology_runner.py +++ b/ingestion/src/metadata/ingestion/api/topology_runner.py @@ -38,15 +38,19 @@ TopologyContextManager, TopologyNode, get_topology_node, - get_topology_nodes, get_topology_root, ) from metadata.ingestion.ometa.ometa_api import OpenMetadata from metadata.ingestion.ometa.utils import model_str +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.ingestion.progress.runner_tracker import TopologyProgressTracker +from metadata.ingestion.progress.tracking import ( + ProgressTracking, + attach_progress_tracking, +) from metadata.utils.custom_thread_pool import CustomThreadPoolExecutor from metadata.utils.logger import ingestion_logger from metadata.utils.operation_metrics import OperationMetricsState -from metadata.utils.progress_tracking import ProgressTrackingMixin from metadata.utils.source_hash import generate_source_hash logger = ingestion_logger() @@ -61,7 +65,7 @@ class MissingExpectedEntityAckException(Exception): # noqa: N818 """ -class TopologyRunnerMixin(ProgressTrackingMixin, Generic[C]): +class TopologyRunnerMixin(Generic[C]): """ Prepares the _run function dynamically based on the source topology @@ -73,17 +77,27 @@ class TopologyRunnerMixin(ProgressTrackingMixin, Generic[C]): queue = Queue() + progress_mode: ClassVar[ProgressMode] = ProgressMode.AUTO + """AUTO (default): the topology runner counts processed entities. + MANUAL: the runner makes zero progress calls; the source drives + ``progress_tracking.manual`` itself. OFF: no progress at all.""" + _SIDE_OUTPUT_STAGE_TYPES: ClassVar[set[str]] = { "OMetaTagAndClassification", "OMetaLifeCycleData", "AddLineageRequest", } - progress_tracking_enabled: ClassVar[bool] = False - """Master gate for hierarchical progress tracking. Off for every connector - by default: when False the runner makes zero progress calls, the registry - is never created, and there is no per-entity overhead. A connector opts in - by setting this True on its source class.""" + @property + def progress_tracking(self) -> ProgressTracking: + """Composed per-source progress state (registry, mode, manual facade). + Lazy: a source that never tracks progress never builds a registry.""" + return attach_progress_tracking(self) + + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Optional connector hook: declare denominators (totals) so the run + renders % and ETA. Called exactly once by the topology runner, just + before the first non-root node is processed. Default: no totals.""" def _node_primary_stage(self, node: TopologyNode) -> Optional[NodeStage]: # noqa: UP045 """The node's primary, non-side-output stage — the stage whose entity is @@ -119,95 +133,22 @@ def _run_node_producer(self, node: TopologyNode) -> Iterable[Entity]: ) ) - def _root_context_keys(self) -> set[str]: - """Context keys owned by root topology nodes (the service level). Root - nodes are those with no consumers — the existing definition of a - topology root — so the exclusion is derived, never a string literal. - Cached per source; the topology is static.""" - cached = self.__dict__.get("_root_ctx_keys") - if cached is None: - cached = { - stage.context for node in get_topology_root(self.topology) for stage in node.stages if stage.context - } - self.__dict__["_root_ctx_keys"] = cached - return cached - - def _primary_stage_index(self) -> "dict[str, NodeStage]": - """Map of entity type name → that node's primary stage, built once from - the static topology. Entity types are unique per node, so the first - match wins on the rare collision.""" - cached = self.__dict__.get("_primary_stage_idx") - if cached is None: - cached = {} - for node in get_topology_nodes(self.topology): - stage = self._node_primary_stage(node) - if stage is not None: - cached.setdefault(stage.type_.__name__, stage) - self.__dict__["_primary_stage_idx"] = cached - return cached - - def _primary_entity_stage(self, entity_type_name: Optional[str]) -> Optional[NodeStage]: # noqa: UP045 - """The primary stage whose entity type is the node's progress key — the - same stage ``_get_entity_type_for_node`` selects. ``None`` when no node - produces ``entity_type_name`` (or it is ``None``), so callers can skip - topology access entirely for the run-grain default.""" - result = None - if entity_type_name is not None: - result = self._primary_stage_index().get(entity_type_name) - return result - - def current_progress_path(self, entity_type_name: Optional[str] = None) -> List[str]: # noqa: UP006,UP045 - """Ancestor container labels from the node's primary-stage ``consumer`` - chain minus the service-root key, each remaining key resolved to its - current context value. - - ``consumer`` lists only *ancestors*; a node's own context key is never - in its own consumer list. In the depth-first walk every ancestor - container is mid-iteration, so its value is fresh — this is why the - ``database_schema``-not-cleared-between-siblings bug cannot occur here. - Returns ``[]`` for the run-grain default (no ``entity_type_name``) or a - root-level entity (empty consumer).""" - path: List[str] = [] # noqa: UP006 - stage = self._primary_entity_stage(entity_type_name) - if stage is not None: - root_keys = self._root_context_keys() - ctx = self.context.get() - for key in stage.consumer or []: - if key not in root_keys: - value = getattr(ctx, key, None) - if value is not None: - path.append(model_str(value)) - return path - - def _is_root_node(self, node: TopologyNode) -> bool: - """The topology root (the Service node) is a structural wrapper, not a - progress level: it always holds a single entity and would otherwise - collide with the first real level (databases) at the registry root.""" - return id(node) in self.__dict__.get("_root_node_ids", set()) - - def _should_track_progress(self, node: TopologyNode, entity_type_name: Optional[str]) -> bool: # noqa: UP045 - """Progress is recorded only for opted-in sources, for real entity - nodes, and never for the structural service root.""" - return self.progress_tracking_enabled and bool(entity_type_name) and not self._is_root_node(node) - - def _scope_path_for_node(self, node: TopologyNode, parent_path: List[str]) -> Optional[List[str]]: # noqa: UP006,UP045 - """The path of the container entity currently in context: its parent - ancestors plus this node's own context value. Used to prune a scope - from the progress tree once its children finish. ``None`` when the - node's context value is not set.""" - result = None - stage = self._node_primary_stage(node) - if stage is not None and stage.context and parent_path is not None: - value = getattr(self.context.get(), stage.context, None) - if value is not None: - result = [*parent_path, model_str(value)] - return result + @property + def progress_tracker(self) -> TopologyProgressTracker: + """Per-source topology progress policy. Lazy: first access is in + ``_iter`` before worker threads spawn.""" + tracker = self.__dict__.get("_topology_progress_tracker") + if tracker is None: + tracker = TopologyProgressTracker(self) + self.__dict__["_topology_progress_tracker"] = tracker + return tracker def _multithread_process_node(self, node: TopologyNode, threads: int) -> Iterable[Entity]: """Multithread Processing of a Node with progress tracking""" child_nodes = self._get_child_nodes(node) entity_type_name = self._get_entity_type_for_node(node) operation_metrics = OperationMetricsState() + node_progress = self.progress_tracker.for_node(node, is_leaf=not child_nodes) # Track SOURCE time - fetching entities from producer source_start = perf_counter() @@ -223,12 +164,7 @@ def _multithread_process_node(self, node: TopologyNode, threads: int) -> Iterabl entity_type=entity_type_name, ) - track_progress = self._should_track_progress(node, entity_type_name) - parent_path = self.current_progress_path(entity_type_name) if track_progress else None - if track_progress and parent_path is not None: - self.progress.open(parent_path, entity_type_name, node_entities_length) - if self.progress.is_reconcilable(entity_type_name) and parent_path: - self.progress.reconcile_scope_total(entity_type_name, parent_path[-1], node_entities_length) + node_progress.open(node_entities_length) if node_entities_length == 0: return @@ -246,8 +182,7 @@ def _multithread_process_node(self, node: TopologyNode, threads: int) -> Iterabl chunk, child_nodes, self.context.get_current_thread_id(), - entity_type_name, - parent_path, + node_progress, ) for chunk in chunks ] @@ -270,31 +205,27 @@ def _multithread_process_node(self, node: TopologyNode, threads: int) -> Iterabl def _process_node(self, node: TopologyNode) -> Iterable[Entity]: """Single-threaded processing of a Node. - Container producers (database, schema) are iterated lazily so connectors - can set up per-yield inspector/session state before each child is - processed. Leaf producers (table, stored procedure) are materialized - eagerly ONLY when progress tracking is enabled — to record an exact child - count via ``progress.open``; otherwise they are iterated lazily so - connectors whose stages depend on per-yield producer state (e.g. PowerBI's - per-workspace ``state.enter`` / ``finally: state.exit``) are not torn down - before their stages run. + Producers are iterated lazily by default so connectors can set up + per-yield inspector/session state — and read context a stage of the + just-yielded entity populated (e.g. S3 storage's ``get_containers``) — + before the next child is produced. A producer is materialized eagerly + only when its node's progress handle wants an exact upfront child count, + which today is limited to reconcilable container counters (schema totals + nudged toward the observed count). Leaf producers are never drained + eagerly: their per-leaf ``advance`` already yields an accurate processed + count. """ child_nodes = self._get_child_nodes(node) - entity_type_name = self._get_entity_type_for_node(node) - is_leaf = not child_nodes - track_progress = self._should_track_progress(node, entity_type_name) - parent_path = self.current_progress_path(entity_type_name) if track_progress else [] + node_progress = self.progress_tracker.for_node(node, is_leaf=not child_nodes) - reconcilable = track_progress and not is_leaf and self.progress.is_reconcilable(entity_type_name) - if track_progress and (is_leaf or reconcilable): + if node_progress.wants_eager_count: + # Holds the node's whole producer output in memory — safe only for + # bounded container nodes; see NodeProgress.wants_eager_count. node_entities = list(self._run_node_producer(node) or []) - self.progress.open(parent_path, entity_type_name, len(node_entities)) - if reconcilable and parent_path: - self.progress.reconcile_scope_total(entity_type_name, parent_path[-1], len(node_entities)) + node_progress.open(len(node_entities)) else: node_entities = self._run_node_producer(node) or [] - if track_progress: - self.progress.open(parent_path, entity_type_name, None) + node_progress.open(None) for node_entity in node_entities: for stage in node.stages: @@ -304,14 +235,10 @@ def _process_node(self, node: TopologyNode) -> Iterable[Entity]: if stage.clear_context: self.context.get().clear_stage(stage=stage) - if track_progress and is_leaf: - self.progress.advance(parent_path, entity_type_name) + node_progress.advance_leaf() - scope_path = self._scope_path_for_node(node, parent_path) if track_progress and not is_leaf else None - yield from self.process_nodes(child_nodes) - if scope_path is not None: - self.progress.close(scope_path) - self.progress.track(entity_type_name) + with node_progress.enter_scope(): + yield from self.process_nodes(child_nodes) def process_nodes(self, nodes: List[TopologyNode]) -> Iterable[Entity]: # noqa: UP006 """ @@ -358,8 +285,7 @@ def _multithread_process_entity( node_entities: List[Any], # noqa: UP006 child_nodes: List[TopologyNode], # noqa: UP006 parent_thread_id: int, - entity_type_name: Optional[str] = None, # noqa: UP045 - parent_path: Optional[List[str]] = None, # noqa: UP006,UP045 + node_progress, ): """Multithread processing of a Node Entity with progress tracking""" # Generates a new context based on the parent thread. @@ -378,17 +304,11 @@ def _multithread_process_entity( if stage.clear_context: self.context.get().clear_stage(stage=stage) - if parent_path is not None and entity_type_name and not child_nodes: - self.progress.advance(parent_path, entity_type_name) + node_progress.advance_leaf() - scope_path = ( - self._scope_path_for_node(node, parent_path) if parent_path is not None and child_nodes else None - ) - for child_result in self.process_nodes(child_nodes): - self.queue.put(child_result) - if scope_path is not None: - self.progress.close(scope_path) - self.progress.track(entity_type_name) + with node_progress.enter_scope(): + for child_result in self.process_nodes(child_nodes): + self.queue.put(child_result) # Merge thread-local metrics into global state before thread exits operation_metrics.merge_thread_metrics() @@ -471,7 +391,7 @@ def _iter(self) -> Iterable[Either]: :return: Iterable of the Entities yielded by all nodes in the topology """ root_nodes = get_topology_root(self.topology) - self.__dict__["_root_node_ids"] = {id(node) for node in root_nodes} # pyright: ignore[reportIndexIssue] + self.progress_tracker.on_walk_start(root_nodes) yield from self.process_nodes(root_nodes) # pyright: ignore[reportReturnType] def create_patch_request(self, original_entity: Entity, create_request: C) -> PatchRequest: diff --git a/ingestion/src/metadata/ingestion/connections/builders.py b/ingestion/src/metadata/ingestion/connections/builders.py index c1be5868e238..6ccec567e951 100644 --- a/ingestion/src/metadata/ingestion/connections/builders.py +++ b/ingestion/src/metadata/ingestion/connections/builders.py @@ -19,7 +19,7 @@ from pydantic import SecretStr from sqlalchemy import create_engine -from sqlalchemy.engine import Engine +from sqlalchemy.engine import Dialect, Engine from sqlalchemy.event import listen from sqlalchemy.pool import QueuePool @@ -56,6 +56,24 @@ def get_connection_args_common(connection) -> Dict[str, Any]: # noqa: UP006 ) +def _dialect_supports_autocommit(dialect: Dialect) -> bool: + """ + Return True when the SQLAlchemy dialect accepts isolation_level='AUTOCOMMIT'. + Uses get_isolation_level_values(None), which the transactional dialects + evaluate without a live connection. Non-transactional dialects (Hive, Impala, + Druid, Pinot) may not implement it, in which case we treat it as unsupported. + """ + supported = False + # Transactional dialects report their isolation levels without reading the + # connection, so None is safe here; others raise and are handled below. + no_connection: Any = None + try: + supported = "AUTOCOMMIT" in dialect.get_isolation_level_values(no_connection) + except Exception: # pylint: disable=broad-except + supported = False + return supported + + def create_generic_db_connection( connection, get_connection_url_fn: Callable, @@ -82,6 +100,14 @@ def create_generic_db_connection( **kwargs, ) + # Read-only metadata/profiler ingestion must not hold a transaction open for + # the whole run. On Redshift/Postgres that pins AccessShareLock on every + # crawled table and blocks other users' DDL for hours (issue #29092). + # AUTOCOMMIT releases locks after each statement. Skip dialects that do not + # support it (non-transactional engines do not hold these locks anyway). + if "isolation_level" not in kwargs and _dialect_supports_autocommit(engine.dialect): + engine.update_execution_options(isolation_level="AUTOCOMMIT") + attach_query_tracker(engine) if hasattr(connection, "supportsQueryComment"): diff --git a/ingestion/src/metadata/ingestion/connections/connection.py b/ingestion/src/metadata/ingestion/connections/connection.py index 7ebdfdeeb169..997ad9114a83 100644 --- a/ingestion/src/metadata/ingestion/connections/connection.py +++ b/ingestion/src/metadata/ingestion/connections/connection.py @@ -26,6 +26,7 @@ from contextlib import ExitStack from typing import TYPE_CHECKING, Generic, Optional, TypeVar +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection.constants import STEP_TIMEOUT_SECONDS from metadata.core.connections.test_connection.runner import TestConnectionRunner from metadata.generated.schema.entity.automations.workflow import ( @@ -35,6 +36,9 @@ TestConnectionResult, ) from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.utils.logger import ingestion_logger + +logger = ingestion_logger() if TYPE_CHECKING: from metadata.core.connections.test_connection.check import ChecksProvider @@ -60,14 +64,30 @@ def __init__(self, service_connection: S) -> None: self.service_connection = service_connection self._client = None self._closing = ExitStack() + self._was_closed = False @property def client(self) -> C: - """The service client, built once on first access and cached.""" + """The service client, built once on first access and cached. Rebuilt if + requested after ``close()``.""" if self._client is None: - self._client = self._get_client() + self._client = self._build_client() return self._client + def borrow(self) -> Borrowed[C]: + """A read-only reference to this connection's client: readable, not + buildable, not closable. The first read is what builds the client.""" + return Borrowed(lambda: self.client) + + def _build_client(self) -> C: + if self._was_closed: + logger.info( + "Connection client for %s was closed; opening a new client.", + type(self).__name__, + ) + self._was_closed = False + return self._get_client() + @abstractmethod def _get_client(self) -> C: """Build the client (engine, REST client, ...). Called once by ``client``.""" @@ -88,18 +108,14 @@ def test_connection( """ Test the connection through the runner. The timeout is applied per step, defaulting to the connector's ``step_timeout_seconds`` when not passed. + Does not close the connection; the owner controls lifecycle (as a context + manager or via ``close()``). """ # Every service connection config carries a `type` enum, but `S` is an # unbound TypeVar so the access can't be proven statically. service_type = self.service_connection.type.value # pyright: ignore[reportAttributeAccessIssue] effective_timeout = timeout_seconds if timeout_seconds is not None else self.step_timeout_seconds - try: - result = TestConnectionRunner(self.checks(), service_type, effective_timeout).run( - metadata, automation_workflow - ) - finally: - self.close() - return result + return TestConnectionRunner(self.checks(), service_type, effective_timeout).run(metadata, automation_workflow) def _on_close(self, teardown: Callable[[], None]) -> None: """Register a teardown to run on ``close()``. ``_get_client`` calls this @@ -115,6 +131,7 @@ def close(self) -> None: self._closing.close() self._closing = ExitStack() self._client = None + self._was_closed = True def __enter__(self) -> "BaseConnection[S, C]": return self diff --git a/ingestion/src/metadata/ingestion/ometa/client.py b/ingestion/src/metadata/ingestion/ometa/client.py index 8d01d7f7c532..714c288493af 100644 --- a/ingestion/src/metadata/ingestion/ometa/client.py +++ b/ingestion/src/metadata/ingestion/ometa/client.py @@ -16,7 +16,7 @@ import traceback from contextlib import nullcontext from datetime import datetime, timezone -from typing import Any, Callable, Dict, List, Optional, Union # noqa: UP035 +from typing import Any, Callable, Dict, List, Optional, Union, cast # noqa: UP035 import requests from requests.exceptions import HTTPError, JSONDecodeError @@ -185,6 +185,8 @@ def _request( # noqa: C901, pylint: disable=too-many-arguments,too-many-branche headers: Optional[dict] = None, # noqa: UP045 timeout: Optional[Union[float, tuple[float, float]]] = None, # noqa: UP007, UP045 retries: Optional[int] = None, # noqa: UP045 + retry_wait: Optional[int] = None, # noqa: UP045 + raw: bool = False, ): # pylint: disable=too-many-locals if path in self._limits_reached: @@ -250,23 +252,23 @@ def _request( # noqa: C901, pylint: disable=too-many-arguments,too-many-branche if effective_timeout: opts["timeout"] = effective_timeout - # Per-call `retries` override takes precedence over the client - # config. `_retry` / `_retry_wait` are Optional in ClientConfig; - # narrow to plain ints here so the loop body type-checks cleanly. + # Per-call `retries` / `retry_wait` override the client config. `_retry` / + # `_retry_wait` are Optional in ClientConfig; narrow to plain ints here so + # the loop body type-checks cleanly. total_retries: int if retries is not None: total_retries = retries if retries > 0 else 0 else: total_retries = self._retry if self._retry and self._retry > 0 else 0 retry: int = total_retries - retry_wait_base: int = self._retry_wait or 0 + retry_wait_base: int = retry_wait if retry_wait is not None else (self._retry_wait or 0) http_tracker = get_global_tracker() http_cm = http_tracker.request(method, url) if http_tracker is not None else nullcontext() op_cm = diagnostics.operation("ometa.http", method=method, url=str(url)) with http_cm, op_cm: while retry >= 0: try: - return self._one_request(method, url, opts, retry) + return self._one_request(method, url, opts, retry, raw) except LimitsException as exc: logger.error(f"Feature limit exceeded for {url}") self._limits_reached.add(path) @@ -286,12 +288,16 @@ def _request( # noqa: C901, pylint: disable=too-many-arguments,too-many-branche traceback.format_exc() return None - def _one_request(self, method: str, url: URL, opts: dict, retry: int): + def _one_request(self, method: str, url: URL, opts: dict, retry: int, raw: bool = False): """ Perform one request, possibly raising RetryException in the case the response is 429. Otherwise, if error text contain "code" string, then it decodes to json object and returns APIError. Returns the body json in the 200 status. + + When ``raw`` is set, returns the ``Response`` after the same retry/limit + decisions (504/429 still retry) instead of the decoded body, so the caller + can read a status the error handling below would otherwise drop. """ retry_codes = self._retry_codes limit_codes = self._limit_codes @@ -299,6 +305,8 @@ def _one_request(self, method: str, url: URL, opts: dict, retry: int): try: resp = self._session.request(method, url, **opts) resp.raise_for_status() + if raw: + return resp if resp.text != "": try: @@ -320,6 +328,8 @@ def _one_request(self, method: str, url: URL, opts: dict, retry: int): raise RetryException() from http_error if resp.status_code in limit_codes: raise LimitsException() from http_error + if raw: + return http_error.response if "code" in resp.text: error = resp.json() if "code" in error: @@ -354,6 +364,24 @@ def get(self, path, data=None, headers=None): """ return self._request("GET", path, data, headers=headers) + def get_raw( + self, + path: str, + data: Any = None, + headers: Optional[dict] = None, # noqa: UP045 + retry_wait: Optional[int] = None, # noqa: UP045 + ) -> requests.Response: + """GET returning the raw ``Response`` so the caller can read its status. + + ``get`` drops the status and returns ``None`` for an error body it cannot + classify; a caller that needs the status uses this instead. Same pipeline as + ``get`` (auth, retries); ``retry_wait`` overrides the between-retry sleep. + """ + return cast( + "requests.Response", + self._request("GET", path, data, headers=headers, retry_wait=retry_wait, raw=True), + ) + def post( self, path: str, diff --git a/ingestion/src/metadata/ingestion/ometa/mixins/lineage_mixin.py b/ingestion/src/metadata/ingestion/ometa/mixins/lineage_mixin.py index d0d0d97b6a40..ccb0e22de7e2 100644 --- a/ingestion/src/metadata/ingestion/ometa/mixins/lineage_mixin.py +++ b/ingestion/src/metadata/ingestion/ometa/mixins/lineage_mixin.py @@ -62,6 +62,17 @@ class OMetaLineageMixin(Generic[T]): def _lineage_reference_cache_key(entity_reference: EntityReference) -> str: return f"{entity_reference.type}:id:{model_str(entity_reference.id)}" + @staticmethod + def _entity_ref_summary(reference: EntityReference) -> Dict[str, Any]: # noqa: UP006 + """Minimal ``{"entity": ...}`` payload the sink reads (fullyQualifiedName), rebuilt + from a reference we already hold so we can skip the post-write lineage-graph GET. + fullyQualifiedName degrades to None if the reference does not carry one.""" + return { + "fullyQualifiedName": (model_str(reference.fullyQualifiedName) if reference.fullyQualifiedName else None), + "id": model_str(reference.id), + "type": reference.type, + } + @classmethod def _lineage_edge_cache_key(cls, from_entity: EntityReference, to_entity: EntityReference) -> str: return f"{cls._lineage_reference_cache_key(from_entity)}->{cls._lineage_reference_cache_key(to_entity)}" @@ -227,10 +238,16 @@ def _is_matching_lineage_target( ) -> bool: return model_str(to_entity.id) == downstream_edge_to_id - def add_lineage(self, data: AddLineageRequest, check_patch: bool = False) -> Dict[str, Any]: # noqa: UP006 + def add_lineage( + self, data: AddLineageRequest, check_patch: bool = False, return_lineage: bool = True + ) -> Dict[str, Any]: # noqa: UP006 """ Add lineage relationship between two entities and returns - the entity information of the origin node + the entity information of the origin node. + + When ``return_lineage`` is False, the expensive post-write GET that fetches the + source entity's full lineage graph is skipped; callers that only need the source + FQN (e.g. the metadata sink) get it rebuilt from the request they already hold. """ data = deepcopy(data) try: @@ -284,6 +301,12 @@ def add_lineage(self, data: AddLineageRequest, check_patch: bool = False) -> Dic logger.error(error) return {"error": error} + if not return_lineage: + # Skip the full-graph fetch below. This also skips _update_cache seeding, which is + # only an optimization: the edge cache refills via the patch-check GET on the next + # write of the same edge, and that lookup is independently LRU-cached. + return {"entity": self._entity_ref_summary(data.edge.fromEntity)} + from_entity_lineage = self.get_lineage_by_id(data.edge.fromEntity.type, model_str(data.edge.fromEntity.id)) if from_entity_lineage: @@ -298,6 +321,7 @@ def add_lineage_by_name( to_entity_type: str, lineage_details: Optional[LineageDetails] = None, # noqa: UP045 check_patch: bool = False, + return_lineage: bool = True, ) -> Dict[str, Any]: # noqa: UP006 lineage_details = deepcopy(lineage_details) if lineage_details else LineageDetails.model_validate({}) try: @@ -366,6 +390,11 @@ def add_lineage_by_name( logger.error(error) return {"error": error} + if not return_lineage: + # See add_lineage: skip the full-graph GET when the caller only needs the source + # FQN, which we already have. Mirrors the fallback shape used below. + return {"entity": {"fullyQualifiedName": from_entity_fqn}} + return self.get_lineage_by_name(from_entity_type, from_entity_fqn) or { "entity": {"fullyQualifiedName": from_entity_fqn} } diff --git a/ingestion/src/metadata/ingestion/progress/__init__.py b/ingestion/src/metadata/ingestion/progress/__init__.py new file mode 100644 index 000000000000..790bdb828e75 --- /dev/null +++ b/ingestion/src/metadata/ingestion/progress/__init__.py @@ -0,0 +1,69 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Ingestion progress capturing — the single home for all progress code. + +Ownership contract: + +* The **connector** knows how to query the source and how to calculate totals + (denominators). It never counts processed items. +* The **topology runner** counts processed entities for every connector by + default. +* The **ProgressRegistry** stores the state, calculates the ETA, and reports + it (CLI tree + SSE payload). +""" + +from metadata.ingestion.progress._render import ( + format_eta, + render_progress_tree, + snapshot_to_progress_payload, +) +from metadata.ingestion.progress.modes import ( + ManualProgress, + ProgressMode, + ProgressModeError, + TotalsDeclarer, +) +from metadata.ingestion.progress.registry import ( + DEFAULT_ACTIVE_LEAF_CAP, + GlobalCounter, + ProgressNode, + ProgressNodeSnapshot, + ProgressRegistry, +) +from metadata.ingestion.progress.runner_tracker import ( + NO_OP_NODE_PROGRESS, + NodeProgress, + TopologyProgressTracker, +) +from metadata.ingestion.progress.tracking import ( + ProgressTracking, + attach_progress_tracking, +) + +__all__ = [ + "DEFAULT_ACTIVE_LEAF_CAP", + "GlobalCounter", + "ManualProgress", + "NO_OP_NODE_PROGRESS", + "NodeProgress", + "ProgressMode", + "ProgressModeError", + "ProgressNode", + "ProgressNodeSnapshot", + "ProgressRegistry", + "ProgressTracking", + "TopologyProgressTracker", + "TotalsDeclarer", + "attach_progress_tracking", + "format_eta", + "render_progress_tree", + "snapshot_to_progress_payload", +] diff --git a/ingestion/src/metadata/ingestion/progress/_render.py b/ingestion/src/metadata/ingestion/progress/_render.py new file mode 100644 index 000000000000..fef77c273f6a --- /dev/null +++ b/ingestion/src/metadata/ingestion/progress/_render.py @@ -0,0 +1,92 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Render a ProgressRegistry snapshot tree for humans (CLI) and for the server +(nested progressNode payload). + +Dependency-free on purpose (stdlib only) so both the workflow base and the +status mixin can import it without a circular dependency. +""" + +from typing import TYPE_CHECKING, List, Optional # noqa: UP035 + +if TYPE_CHECKING: + from metadata.ingestion.progress.registry import ProgressNodeSnapshot + + +def render_progress_tree(root: "Optional[ProgressNodeSnapshot]") -> str: # noqa: UP045 + """Active-scope tree: the run rollup, then one indented line per in-flight + branch. Known counts render ``processed/expected``; lazy counts render a + bare ``processed``.""" + lines: List[str] = [] # noqa: UP006 + if root is not None: + _render_node(root, 0, lines) + return "\n".join(lines) + + +def _render_node(node: "ProgressNodeSnapshot", depth: int, lines: List[str]) -> None: # noqa: UP006 + prefix = " " * depth + ("└ " if depth else "") + label = f"{node.label} " if node.label else "" + type_ = f"{node.child_type} " if node.child_type else "" + if node.child_type is None: + count = "" + else: + count = f"{node.processed}/{node.expected}" if node.expected is not None else str(node.processed) + overflow = f" (+{node.overflow} more)" if node.overflow else "" + lines.append(f"{prefix}{label}{type_}{count}{overflow}".rstrip()) + for child in node.children: + _render_node(child, depth + 1, lines) + + +def snapshot_to_progress_payload(root: "Optional[ProgressNodeSnapshot]") -> Optional[dict]: # noqa: UP045 + """Map a snapshot tree to the ProgressUpdate.progress (progressNode) shape.""" + return _node_to_payload(root) if root is not None else None + + +def format_eta(seconds: int) -> str: + """Human ``~45s`` / ``~6m`` / ``~1h 20m`` from a rounded seconds count.""" + if seconds < 60: + result = f"~{seconds}s" + elif seconds < 3600: + result = f"~{seconds // 60}m" + else: + result = f"~{seconds // 3600}h {(seconds % 3600) // 60}m" + return result + + +def _render_joined(node: "ProgressNodeSnapshot", ancestors: "List[str]", lines: "List[str]") -> None: # noqa: UP006 + """Render active nodes with ancestor labels joined by '.' so sibling-level + hierarchy collapses into a single readable label, e.g. ``sales.public Table 45/310``.""" + path = [*ancestors, node.label] if node.label else list(ancestors) + if node.children: + for child in node.children: + _render_joined(child, path, lines) + else: + joined_label = ".".join(path) if path else "" + type_ = f"{node.child_type} " if node.child_type else "" + if node.child_type is None: + count = "" + else: + count = f"{node.processed}/{node.expected}" if node.expected is not None else str(node.processed) + overflow = f" (+{node.overflow} more)" if node.overflow else "" + lines.append(f"{joined_label} {type_}{count}{overflow}".strip()) + + +def _node_to_payload(node: "ProgressNodeSnapshot") -> dict: + return { + "label": node.label, + "entityType": node.child_type, + "processed": node.processed, + "expected": node.expected, + "active": node.active, + "overflow": node.overflow, + "children": [_node_to_payload(child) for child in node.children], + } diff --git a/ingestion/src/metadata/ingestion/progress/modes.py b/ingestion/src/metadata/ingestion/progress/modes.py new file mode 100644 index 000000000000..56536e96f190 --- /dev/null +++ b/ingestion/src/metadata/ingestion/progress/modes.py @@ -0,0 +1,101 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Progress modes and the two connector-facing facades. + +``TotalsDeclarer`` is denominator-only: an AUTO connector's +``declare_progress_totals`` hook receives it and structurally cannot increment +processed counts. ``ManualProgress`` is the MANUAL-mode escape hatch: the +runner makes zero progress calls and the connector drives counting itself — +auto XOR manual, never both. +""" + +from enum import Enum +from typing import TYPE_CHECKING, Dict, Optional # noqa: UP035 + +if TYPE_CHECKING: + from metadata.ingestion.progress.registry import ProgressRegistry + + +class ProgressMode(Enum): + AUTO = "auto" + MANUAL = "manual" + OFF = "off" + + +class ProgressModeError(RuntimeError): + """A source used a progress API its declared ``progress_mode`` forbids.""" + + +class TotalsDeclarer: + """Denominator-only view of the registry, handed to + ``declare_progress_totals``. Declarations feed % and ETA; they never + increment ``processed``.""" + + def __init__(self, registry: "ProgressRegistry") -> None: + self._registry = registry + + def set_total(self, entity_type: str, total: Optional[int]) -> None: # noqa: UP045 + self._registry.set_total(entity_type, total) + + def seed_scope_total(self, entity_type: str, scope: str, n: int) -> None: + self._registry.seed_scope_total(entity_type, scope, n) + + def mark_reconcilable(self, entity_type: str) -> None: + """Declare that the connector cannot pre-count ``entity_type``; the + runner will build the total from observed scope counts instead.""" + self._registry.set_reconcilable(entity_type) + + +class ManualProgress(TotalsDeclarer): + """Counting facade for ``ProgressMode.MANUAL`` sources — connectors whose + enumeration the topology runner cannot count (grouped dashboard walks, + custom ``_iter`` query sources). Extends the denominator-only declarer + with the counting side; AUTO hooks still receive a plain + ``TotalsDeclarer``, never this subclass.""" + + def __init__(self, registry: "ProgressRegistry") -> None: + super().__init__(registry) + self._group_label: Optional[str] = None # noqa: UP045 + + def track(self, entity_type: Optional[str], n: int = 1) -> None: # noqa: UP045 + self._registry.track(entity_type, n) + + def track_asset(self, entity_type: Optional[str], n: int = 1) -> None: # noqa: UP045 + """Track ``n`` completed units of ``entity_type`` that are also catalog + assets, so they count toward both the type's progress bar and the run's + ``assets_ingested`` total (the flat-source equivalent of a topology + ``advance()``).""" + self._registry.track(entity_type, n) + self._registry.record_asset(n) + + def reconcile_scope_total(self, entity_type: Optional[str], scope: str, observed: int) -> None: # noqa: UP045 + self._registry.reconcile_scope_total(entity_type, scope, observed) + + def declare_groups(self, label: str, total: Optional[int]) -> None: # noqa: UP045 + """Declare the grouping axis (e.g. workspaces) as a global counter and + remember its label so ``close_group`` can count completions on it.""" + self._group_label = label + self._registry.set_total(label, total) + + def open_group(self, group: str, expected_by_type: Dict[str, Optional[int]]) -> None: # noqa: UP006,UP045 + """Open one child node per asset type under ``group``; ``expected`` may + be None for lazy (running) counts.""" + for asset_type, expected in expected_by_type.items(): + self._registry.open([group, asset_type], asset_type, expected) + + def advance(self, group: str, asset_type: str) -> None: + self._registry.advance([group, asset_type], asset_type) + + def close_group(self, group: str) -> None: + """Count the finished group on its global counter and prune its subtree.""" + if self._group_label is not None: + self._registry.track(self._group_label) + self._registry.close([group]) diff --git a/ingestion/src/metadata/utils/progress_registry.py b/ingestion/src/metadata/ingestion/progress/registry.py similarity index 80% rename from ingestion/src/metadata/utils/progress_registry.py rename to ingestion/src/metadata/ingestion/progress/registry.py index 96cbbc9086ac..f98af3607088 100644 --- a/ingestion/src/metadata/utils/progress_registry.py +++ b/ingestion/src/metadata/ingestion/progress/registry.py @@ -31,6 +31,12 @@ from dataclasses import dataclass, field from typing import Dict, List, Mapping, Optional, Tuple # noqa: UP035 +from metadata.ingestion.progress._render import ( + _render_joined, + format_eta, + snapshot_to_progress_payload, +) + DEFAULT_ACTIVE_LEAF_CAP = 20 @@ -108,6 +114,14 @@ def advance(self, path: List[str], child_type: Optional[str] = None) -> None: # node.processed_by_type[key] = node.processed_by_type.get(key, 0) + 1 self._total_ingested += 1 + def record_asset(self, n: int = 1) -> None: + """Count ``n`` leaf entities toward the run-total assets ingested, for + flat MANUAL sources that have no topology tree to ``advance()``. Keeps + ``assets_ingested`` in step with the connector's own completion count.""" + with self._lock: + self._mark_started() + self._total_ingested += n + def assets_ingested(self) -> int: """Monotonic run-total of leaf entities processed. Independent of the tree — pruning a completed scope never decreases it.""" @@ -186,6 +200,75 @@ def global_counters(self) -> "List[Tuple[str, int, Optional[int]]]": # noqa: UP with self._lock: return [(type_, c.done, c.total) for type_, c in self._global.items()] + def eta_seconds(self) -> Optional[int]: # noqa: UP045 + """Overall run ETA in seconds from the driver counter's cumulative rate: + ``elapsed * (total - done) / done``. ``None`` during warm-up (``done == + 0``), when there is no driver, when the driver is complete (``done >= + total``), or before elapsed time is available.""" + driver = self._driver_counter() + result = None + if driver is not None: + _, done, total = driver + elapsed = self.elapsed_seconds() + if done > 0 and total is not None and done < total and elapsed is not None and elapsed > 0: + result = round(elapsed * (total - done) / done) + return result + + def _driver_counter( + self, + counters: "Optional[List[Tuple[str, int, Optional[int]]]]" = None, # noqa: UP006,UP045 + ) -> "Optional[Tuple[str, int, Optional[int]]]": # noqa: UP006,UP045 + """The ETA driver: the last-declared global counter that has a known + total (finest-grained real unit of work), or ``None`` when no counter + declares a total.""" + pool = self.global_counters() if counters is None else counters + driver = None + for counter in pool: + if counter[2] is not None: + driver = counter + return driver + + def render_cli(self) -> str: + """Human progress report: global-counter header (with ETA on the driver + line) plus the active-scope tree.""" + snapshot = self.snapshot() + counters = self.global_counters() + header = self._render_header(counters) + if snapshot is None: + return header if counters else "" + lines: List[str] = [] # noqa: UP006 + _render_joined(snapshot, [], lines) + tree = "\n".join(lines) + return f"{header}\n{tree}" if tree else header + + def _render_header(self, counters: "List[Tuple[str, int, Optional[int]]]") -> str: # noqa: UP006,UP045 + lines: List[str] = [] # noqa: UP006 + driver = self._driver_counter(counters) + eta = self.eta_seconds() + for type_, done, total in counters: + line = f"{type_} {done}/{total}" if total is not None else f"{type_} {done}" + if eta is not None and driver is not None and type_ == driver[0]: + line = f"{line} {format_eta(eta)}" + lines.append(line) + assets = self.assets_ingested() + if assets > 0: + lines.append(f"Ingested: {assets:,} assets") + return "\n".join(lines) + + def sse_payload(self) -> Optional[dict]: # noqa: UP045 + """Bare ``progressNode`` tree (validates against ``ProgressUpdate``, + which is ``extra='forbid'``). The run-root ``processed`` carries the + monotonic asset total; ``expected`` is unknown (no global count).""" + snapshot = self.snapshot() + result = None + if snapshot is not None: + tree = snapshot_to_progress_payload(snapshot) + if tree is not None: + tree["processed"] = self.assets_ingested() + tree["expected"] = None + result = tree + return result + def close(self, path: List[str]) -> None: # noqa: UP006 """Remove the node at ``path`` from its parent's children once its work is complete, so the tree retains only active scopes. No-op on an empty diff --git a/ingestion/src/metadata/ingestion/progress/runner_tracker.py b/ingestion/src/metadata/ingestion/progress/runner_tracker.py new file mode 100644 index 000000000000..b76ff7bfd0c8 --- /dev/null +++ b/ingestion/src/metadata/ingestion/progress/runner_tracker.py @@ -0,0 +1,285 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Topology-walk progress policy, extracted from the runner. + +The runner asks ``for_node`` for a per-node handle and calls it +unconditionally. When the source is not in AUTO mode, the node is the +structural service root, or the node has no typed stage, the handle is a +shared no-op — the walk code carries zero progress conditionals. +""" + +import traceback +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set # noqa: UP035 + +from metadata.ingestion.models.topology import ( + NodeStage, + TopologyNode, + get_topology_nodes, + get_topology_root, +) +from metadata.ingestion.ometa.utils import model_str +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.utils.logger import ingestion_logger + +logger = ingestion_logger() + +if TYPE_CHECKING: + from metadata.ingestion.progress.registry import ProgressRegistry + + +class _NoOpScope: + """No container scope to retire.""" + + def __enter__(self) -> "_NoOpScope": + return self + + def __exit__(self, exc_type: object, exc: object, tb: object) -> None: + """Nothing to close.""" + + +NO_OP_SCOPE = _NoOpScope() + + +class _Scope: + """An open container scope: exiting prunes the subtree from the tree. + The finished container is counted on its global counter only on a clean + exit — a failure (or early generator close) mid-subtree prunes without + claiming the container completed.""" + + def __init__(self, registry: "ProgressRegistry", path: List[str], entity_type_name: str) -> None: # noqa: UP006 + self._registry = registry + self._path = path + self._entity_type_name = entity_type_name + + def __enter__(self) -> "_Scope": + return self + + def __exit__(self, exc_type: object, exc: object, tb: object) -> None: + self._registry.close(self._path) + if exc_type is None: + self._registry.track(self._entity_type_name) + + +class _NoOpNodeProgress: + """Shared do-nothing handle: zero registry calls, zero per-entity overhead.""" + + wants_eager_count = False + + def open(self, count: Optional[int]) -> None: # noqa: UP045 + """No-op.""" + + def advance_leaf(self) -> None: + """No-op.""" + + def enter_scope(self) -> _NoOpScope: + return NO_OP_SCOPE + + +NO_OP_NODE_PROGRESS = _NoOpNodeProgress() + + +class NodeProgress: + """Progress recording for one topology node. The parent path is resolved at + creation time — before worker threads spawn — so the handle can be shared + across a node's worker threads; ``enter_scope`` reads the *current thread's* + context at call time.""" + + def __init__( + self, + tracker: "TopologyProgressTracker", + node: TopologyNode, + entity_type_name: str, + parent_path: List[str], # noqa: UP006 + is_leaf: bool, + ) -> None: + self._tracker = tracker + self._node = node + self._registry = tracker.registry + self._entity_type_name = entity_type_name + self._parent_path = parent_path + self._is_leaf = is_leaf + self._reconcilable = self._registry.is_reconcilable(entity_type_name) + + @property + def wants_eager_count(self) -> bool: + """Whether the runner should drain this node's producer into a ``list()`` + up front to learn its exact child count. + + MEMORY WARNING: returning ``True`` makes the topology runner hold the + node's ENTIRE producer output in memory at once (see + ``TopologyRunnerMixin._process_node``). For a high-cardinality node — + tables in a large schema, dashboards in a big tenant — that is a real + OOM risk. Keep this ``True`` ONLY for low-cardinality *container* nodes + whose count is bounded (e.g. schemas per database, typically tens), and + NEVER for leaf entity nodes, which can number in the hundreds of + thousands. Any new reconcilable declaration must respect that bound; if + a container can itself be huge, add a cap or count it lazily instead. + + So: eager only when the node's counter is reconcilable — a bounded + container whose scope total is nudged toward the observed child count. + Leaf producers are always iterated lazily: their per-leaf ``advance`` + already yields an accurate processed count without materializing + anything, and an eager ``list()``-drain would additionally run the + producer to completion before any stage sinks an entity — breaking + connectors (e.g. S3 storage's ``get_containers``) whose producer reads + context a stage of the just-yielded entity populated.""" + return self._reconcilable + + def open(self, count: Optional[int]) -> None: # noqa: UP045 + """Open this node's counter under its parent scope. An exact ``count`` + (the runner materialized the producer) additionally reconciles a + reconcilable container's scope total toward the observed child count; + a lazy open (``None``) has nothing to reconcile with.""" + self._registry.open(self._parent_path, self._entity_type_name, count) + if count is not None and self._reconcilable and self._parent_path: + self._registry.reconcile_scope_total(self._entity_type_name, self._parent_path[-1], count) + + def advance_leaf(self) -> None: + if self._is_leaf: + self._registry.advance(self._parent_path, self._entity_type_name) + # A leaf has no container scope to advance its global counter's done + # on exit, so a leaf-declared total (e.g. Pipeline) only moves here. + # No-op for leaf types with no declared counter (Table, etc.). + self._registry.track(self._entity_type_name) + + def enter_scope(self): + """Scope handle for the container entity currently in this thread's + context; NO_OP for a leaf node or when the context value is unset.""" + result = NO_OP_SCOPE + if not self._is_leaf: + scope_path = self._tracker.scope_path_for_node(self._node, self._parent_path) + if scope_path is not None: + result = _Scope(self._registry, scope_path, self._entity_type_name) + return result + + +class TopologyProgressTracker: + """All topology-walk progress policy for one source: mode gating, ancestor + path resolution, once-only totals declaration, and handle creation. + + ``source`` is the TopologyRunnerMixin instance; the tracker reads its + ``topology``, ``context``, ``progress``, ``progress_mode``, + ``declare_progress_totals`` and primary-stage helpers.""" + + def __init__(self, source: Any) -> None: + self._source = source + self._root_node_ids: Set[int] = set() # noqa: UP006 + self._root_ctx_keys: Optional[Set[str]] = None # noqa: UP006,UP045 + self._primary_stage_idx: Optional[Dict[str, NodeStage]] = None # noqa: UP006,UP045 + self._totals_declared = False + + @property + def registry(self) -> "ProgressRegistry": + return self._source.progress_tracking.registry + + def on_walk_start(self, root_nodes) -> None: + self._root_node_ids = {id(node) for node in root_nodes} + + def is_root_node(self, node: TopologyNode) -> bool: + """The topology root (the Service node) is a structural wrapper, not a + progress level: it always holds a single entity and would otherwise + collide with the first real level (databases) at the registry root.""" + return id(node) in self._root_node_ids + + def for_node(self, node: TopologyNode, is_leaf: bool): + """A NodeProgress for AUTO sources on real entity nodes; the shared + no-op otherwise. Declares connector totals on the first real node — + after the service root has populated the context the totals code may + need.""" + result = NO_OP_NODE_PROGRESS + if self._source.progress_mode is ProgressMode.AUTO and not self.is_root_node(node): + entity_type_name = self._source._get_entity_type_for_node(node) + if entity_type_name: + self._declare_totals_once() + parent_path = self.current_path(entity_type_name) + result = NodeProgress(self, node, entity_type_name, parent_path, is_leaf) + return result + + def _declare_totals_once(self) -> None: + """Run the connector's totals hook once. Totals are a progress-only + enhancement (they drive % and ETA), so a failure here — e.g. a totals + query raising — must not abort the ingestion walk: warn and continue + with denominator-less progress.""" + if not self._totals_declared: + self._totals_declared = True + try: + self._source.declare_progress_totals(TotalsDeclarer(self.registry)) + except Exception as exc: + logger.warning("Progress totals declaration failed; continuing without totals: %s", exc) + logger.debug(traceback.format_exc()) + + def current_path(self, entity_type_name: Optional[str] = None) -> List[str]: # noqa: UP006,UP045 + """Ancestor container labels from the node's primary-stage ``consumer`` + chain minus the service-root key, each remaining key resolved to its + current context value. + + ``consumer`` lists only *ancestors*; a node's own context key is never + in its own consumer list. In the depth-first walk every ancestor + container is mid-iteration, so its value is fresh — this is why the + ``database_schema``-not-cleared-between-siblings bug cannot occur here. + Returns ``[]`` for the run-grain default (no ``entity_type_name``) or a + root-level entity (empty consumer).""" + path: List[str] = [] # noqa: UP006 + stage = self._primary_entity_stage(entity_type_name) + if stage is not None: + root_keys = self._root_context_keys() + ctx = self._source.context.get() + for key in stage.consumer or []: + if key not in root_keys: + value = getattr(ctx, key, None) + if value is not None: + path.append(model_str(value)) + return path + + def scope_path_for_node(self, node: TopologyNode, parent_path: List[str]) -> Optional[List[str]]: # noqa: UP006,UP045 + """The path of the container entity currently in context: its parent + ancestors plus this node's own context value. Used to prune a scope + from the progress tree once its children finish. ``None`` when the + node's context value is not set.""" + result = None + stage = self._source._node_primary_stage(node) + if stage is not None and stage.context and parent_path is not None: + value = getattr(self._source.context.get(), stage.context, None) + if value is not None: + result = [*parent_path, model_str(value)] + return result + + def _root_context_keys(self) -> Set[str]: # noqa: UP006 + """Context keys owned by root topology nodes (the service level), + derived from the topology — never a string literal. Cached; the + topology is static.""" + if self._root_ctx_keys is None: + self._root_ctx_keys = { + stage.context + for node in get_topology_root(self._source.topology) + for stage in node.stages + if stage.context + } + return self._root_ctx_keys + + def _primary_stage_index(self) -> Dict[str, NodeStage]: # noqa: UP006 + """Map of entity type name → that node's primary stage, built once from + the static topology. Entity types are unique per node, so the first + match wins on the rare collision.""" + if self._primary_stage_idx is None: + index: Dict[str, NodeStage] = {} # noqa: UP006 + for node in get_topology_nodes(self._source.topology): + stage = self._source._node_primary_stage(node) + if stage is not None: + index.setdefault(stage.type_.__name__, stage) + self._primary_stage_idx = index + return self._primary_stage_idx + + def _primary_entity_stage(self, entity_type_name: Optional[str]) -> Optional[NodeStage]: # noqa: UP045 + result = None + if entity_type_name is not None: + result = self._primary_stage_index().get(entity_type_name) + return result diff --git a/ingestion/src/metadata/ingestion/progress/tracking.py b/ingestion/src/metadata/ingestion/progress/tracking.py new file mode 100644 index 000000000000..c41b822efe86 --- /dev/null +++ b/ingestion/src/metadata/ingestion/progress/tracking.py @@ -0,0 +1,74 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Per-source progress state, composed into a source rather than mixed in. + +A source *has a* ``ProgressTracking`` object (reached through the +``progress_tracking`` property its base defines) instead of *being* a progress +mixin. The object owns the registry, the declared mode, and the guarded manual +facade; ``attach_progress_tracking`` builds it lazily so a step that never +tracks progress has no registry and the workflow reporter (which scans steps +for the ``_progress_tracking`` attribute) skips it. +""" + +from typing import Any, Optional + +from metadata.ingestion.progress.modes import ( + ManualProgress, + ProgressMode, + ProgressModeError, +) +from metadata.ingestion.progress.registry import ProgressRegistry + + +class ProgressTracking: + """One source's progress state: the registry, the declared mode, and the + guarded manual facade. Composed into a source, not inherited.""" + + def __init__(self, mode: ProgressMode, source_name: str) -> None: + self._mode = mode + self._source_name = source_name + self._registry = ProgressRegistry() + self._manual: Optional[ManualProgress] = None # noqa: UP045 + + @property + def mode(self) -> ProgressMode: + return self._mode + + @property + def registry(self) -> ProgressRegistry: + return self._registry + + @property + def manual(self) -> ManualProgress: + """MANUAL-mode counting facade. Raises for AUTO/OFF sources — the + runner counts AUTO sources, so a manual increment would double-count.""" + if self._mode is not ProgressMode.MANUAL: + raise ProgressModeError( + f"progress_tracking.manual requires progress_mode=MANUAL, but {self._source_name} " + f"declares {self._mode.name}. AUTO sources are counted by the topology runner " + "and may only declare totals via declare_progress_totals()." + ) + if self._manual is None: + self._manual = ManualProgress(self._registry) + return self._manual + + +def attach_progress_tracking(source: Any) -> ProgressTracking: + """Lazily build and cache the source's ``ProgressTracking``. Kept a + module-level helper (not a base class) so any host composes progress + without inheriting a progress mixin. First access is single-threaded (in + ``_iter``, before worker threads spawn), so the lazy init is safe.""" + tracking = source.__dict__.get("_progress_tracking") + if tracking is None: + mode = getattr(source, "progress_mode", ProgressMode.AUTO) + tracking = ProgressTracking(mode, type(source).__name__) + source.__dict__["_progress_tracking"] = tracking + return tracking diff --git a/ingestion/src/metadata/ingestion/sink/metadata_rest.py b/ingestion/src/metadata/ingestion/sink/metadata_rest.py index 0969e558c54e..de60dd0fc092 100644 --- a/ingestion/src/metadata/ingestion/sink/metadata_rest.py +++ b/ingestion/src/metadata/ingestion/sink/metadata_rest.py @@ -33,6 +33,7 @@ CreateDataContractRequest, ) from metadata.generated.schema.api.data.createGlossary import CreateGlossaryRequest +from metadata.generated.schema.api.data.createMetric import CreateMetricRequest from metadata.generated.schema.api.data.createPipeline import CreatePipelineRequest from metadata.generated.schema.api.data.createQuery import CreateQueryRequest from metadata.generated.schema.api.domains.createDataProduct import ( @@ -255,6 +256,7 @@ def write_create_request(self, entity_request) -> Either[Entity]: CreateTestDefinitionRequest, CreateMcpServerRequest, CreateGlossaryRequest, + CreateMetricRequest, ), ) ): @@ -545,15 +547,25 @@ def write_classification_and_tag(self, record: OMetaTagAndClassification) -> Eit return Either(right=tag) @_run_dispatch.register - def write_lineage(self, add_lineage: AddLineageRequest) -> Either[dict[str, Any]]: - created_lineage = self.metadata.add_lineage(add_lineage, check_patch=True) + def write_lineage(self, add_lineage: AddLineageRequest) -> Either[str]: + # return_lineage=False: we only need a status identifier below, so skip the expensive + # per-edge full-graph GET that otherwise dominates lineage-heavy ingestions. + created_lineage = self.metadata.add_lineage(add_lineage, check_patch=True, return_lineage=False) if created_lineage.get("error"): return Either(left=StackTraceError(name="AddLineageRequestError", error=created_lineage["error"])) - return Either(right=created_lineage["entity"]["fullyQualifiedName"]) + # Producers that build id-only references carry no FQN. Fall back to a "{type}:{uuid}" + # label (e.g. "table:d311bdf2-..."): + # a None right would silently drop the edge from scanned status (ReturnStep.run) and + # stop write_override_lineage from patching the lineage-processed flag. + from_reference = add_lineage.edge.fromEntity + source_label = ( + created_lineage["entity"]["fullyQualifiedName"] or f"{from_reference.type}:{model_str(from_reference.id)}" + ) + return Either(right=source_label) # pyright: ignore[reportCallIssue] @_run_dispatch.register - def write_fqn_lineage(self, add_lineage: OMetaFQNLineageRequest) -> Either[dict[str, Any]]: + def write_fqn_lineage(self, add_lineage: OMetaFQNLineageRequest) -> Either[str]: created_lineage = self.metadata.add_lineage_by_name( from_entity_fqn=add_lineage.from_entity_fqn, from_entity_type=add_lineage.from_entity_type, @@ -561,6 +573,7 @@ def write_fqn_lineage(self, add_lineage: OMetaFQNLineageRequest) -> Either[dict[ to_entity_type=add_lineage.to_entity_type, lineage_details=add_lineage.lineage_details, check_patch=True, + return_lineage=False, ) if not created_lineage or created_lineage.get("error"): error = (created_lineage or {}).get("error", "Failed to add lineage - no response") @@ -592,7 +605,7 @@ def _delete_lineage_by_source_reference(self, entity_reference: EntityReference, ) @_run_dispatch.register - def write_override_lineage(self, add_lineage: OMetaLineageRequest) -> Either[dict[str, Any]]: + def write_override_lineage(self, add_lineage: OMetaLineageRequest) -> Either[str]: """ Writes the override lineage for the given lineage request. @@ -600,7 +613,8 @@ def write_override_lineage(self, add_lineage: OMetaLineageRequest) -> Either[dic add_lineage (OMetaLineageRequest): The lineage request containing the override lineage information. Returns: - Either[Dict[str, Any]]: The result of the dispatch operation. + Either[str]: The dispatched write_lineage / write_fqn_lineage result, carrying the + source status identifier (FQN or "{type}:{uuid}" fallback) on success. """ if add_lineage.override_lineage is True and ( add_lineage.lineage_request.lineage_details diff --git a/ingestion/src/metadata/ingestion/source/connections.py b/ingestion/src/metadata/ingestion/source/connections.py index d1f38da7b5e5..a9f6a03436ec 100644 --- a/ingestion/src/metadata/ingestion/source/connections.py +++ b/ingestion/src/metadata/ingestion/source/connections.py @@ -62,66 +62,58 @@ def _get_connection_class_from_spec( return None -def _get_connection_fn_from_service_spec(connection: BaseModel) -> Optional[Callable]: # noqa: UP045 - """ - Import the get_connection function from the source, or use ServiceSpec connection_class if defined. - """ +def create_connection(connection: BaseModel) -> Optional[BaseConnection]: # noqa: UP045 + """Return the ServiceSpec ``BaseConnection`` owner, or ``None`` if the + connection has no ``connection_class``.""" connection_class = _get_connection_class_from_spec(connection) - if connection_class: + return connection_class(connection) if connection_class else None - def _get_client(conn): - return connection_class(conn).client - return _get_client - return None +def run_test_connection(metadata: OpenMetadata, connection: BaseConnection) -> None: + """Test an already-built connection owner, reusing its live client, and raise + on failure. Does not close it; the source owns and closes the connection.""" + raise_test_connection_exception(connection.test_connection(metadata)) -def _get_test_fn_from_service_spec(connection: BaseModel) -> Optional[Callable]: # noqa: UP045 +def get_test_connection_fn(connection: BaseModel) -> Callable: """ - Import the get_connection function from the source, or use ServiceSpec connection_class if defined. + Build the test-connection function: the ServiceSpec ``connection_class`` when + defined, else the source's legacy module-level ``test_connection``. """ connection_class = _get_connection_class_from_spec(connection) if connection_class: - return connection_class(connection).test_connection - return None + def _test(metadata: OpenMetadata, *args, **kwargs): + # BaseConnection.test_connection does not self-close; close the + # temporary owner via the context manager once the test is done. + with connection_class(connection) as owned: + return owned.test_connection(metadata, *args, **kwargs) -def get_connection_fn(connection: BaseModel) -> Callable: - """ - Import the get_connection function from the source, or use ServiceSpec connection_class if defined. - """ - # Try ServiceSpec path first - connection_fn = _get_connection_fn_from_service_spec(connection) - if connection_fn: - return connection_fn - # Fallback to default - return import_connection_fn(connection=connection, function_name=GET_CONNECTION_FN_NAME) - - -def get_test_connection_fn(connection: BaseModel) -> Callable: - """ - Import the test_connection function from the source - """ - test_fn = _get_test_fn_from_service_spec(connection) - if test_fn: - return test_fn - # Fallback to default + return _test return import_connection_fn(connection=connection, function_name=TEST_CONNECTION_FN_NAME) def get_connection(connection: BaseModel) -> Any: """ - Main method to prepare a connection from - a service connection pydantic model + Prepare a client from a service connection: the ServiceSpec ``BaseConnection`` + client when defined, else the source's legacy module-level ``get_connection``. """ - return get_connection_fn(connection)(connection) + owned = create_connection(connection) + if owned is not None: + return owned.client + return import_connection_fn(connection=connection, function_name=GET_CONNECTION_FN_NAME)(connection) def test_connection_common(metadata: OpenMetadata, connection_obj, service_connection): - test_connection_fn = get_test_connection_fn(service_connection) - # TODO: Remove this once we migrate all connectors to use the new test connection function - try: - result = test_connection_fn(metadata) - except TypeError: - result = test_connection_fn(metadata, connection_obj, service_connection) + owned = create_connection(service_connection) + if owned is not None: + with owned: + result = owned.test_connection(metadata) + else: + # Non-migrated / custom connector: legacy module-level test_connection. + # Migrated connectors go through create_connection above, so the function + # resolved here always takes the legacy (metadata, client, connection) args. + test_connection_fn = get_test_connection_fn(service_connection) + client = connection_obj if connection_obj is not None else get_connection(service_connection) + result = test_connection_fn(metadata, client, service_connection) raise_test_connection_exception(result) diff --git a/ingestion/src/metadata/ingestion/source/dashboard/dashboard_service.py b/ingestion/src/metadata/ingestion/source/dashboard/dashboard_service.py index 031e4678d80a..48f4dc996a32 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/dashboard_service.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/dashboard_service.py @@ -72,7 +72,13 @@ TopologyNode, ) from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection, test_connection_common +from metadata.ingestion.ometa.utils import model_str +from metadata.ingestion.source.connections import ( + create_connection, + get_connection, + run_test_connection, + test_connection_common, +) from metadata.utils import fqn from metadata.utils.filters import filter_by_dashboard, filter_by_project from metadata.utils.logger import ingestion_logger @@ -216,27 +222,26 @@ class DashboardServiceSource(TopologyRunnerMixin, Source, ABC): chart_source_state: Set = set() # noqa: RUF012, UP006 def _declare_progress_groups(self, label: str, total: Optional[int]) -> None: # noqa: UP045 - """Declare the grouping axis (e.g. workspaces) as a global counter and - remember its label so completion can target it at scope close.""" - self.__dict__["_progress_counter_label"] = label # pyright: ignore[reportIndexIssue] - self.progress.set_total(label, total) + """Declare the grouping axis (e.g. workspaces) as a global counter. + + These group helpers drive ``self.progress_tracking.manual`` and therefore require + the connector to set ``progress_mode = ProgressMode.MANUAL`` (as PowerBI + does); calling them from a default AUTO source raises ``ProgressModeError`` + and would double-count against the runner's own tracking.""" + self.progress_tracking.manual.declare_groups(label, total) def _open_group_progress(self, group: str, expected_by_type: Dict[str, Optional[int]]) -> None: # noqa: UP006, UP045 """Open one child node per asset type under ``group`` so each type renders as its own line; ``expected`` may be None for lazy (running) counts.""" - for asset_type, expected in expected_by_type.items(): - self.progress.open([group, asset_type], asset_type, expected) + self.progress_tracking.manual.open_group(group, expected_by_type) def _advance_group_progress(self, group: str, asset_type: str) -> None: """Record one processed asset of ``asset_type`` under ``group``.""" - self.progress.advance([group, asset_type], asset_type) + self.progress_tracking.manual.advance(group, asset_type) def _close_group_progress(self, group: str) -> None: """Count the finished group on its global counter and prune its subtree.""" - label = self.__dict__.get("_progress_counter_label") - if label is not None: - self.progress.track(label) - self.progress.close([group]) + self.progress_tracking.manual.close_group(group) @retry_with_docker_host() def __init__( @@ -249,11 +254,13 @@ def __init__( self.metadata = metadata self.service_connection = self.config.serviceConnection.root.config self.source_config: DashboardServiceMetadataPipeline = self.config.sourceConfig.config - self.client = get_connection(self.service_connection) - - # Flag the connection for the test connection - self.connection_obj = self.client - self.test_connection() + self._connection = create_connection(self.service_connection) + self.client = self._connection.client if self._connection else get_connection(self.service_connection) + try: + self.test_connection() + except Exception: + self.close() + raise @property def name(self) -> str: @@ -441,6 +448,8 @@ def yield_dashboard_usage(self, *args, **kwargs) -> Iterable[DashboardUsage]: return def close(self): + if self._connection is not None: + self._connection.close() self.metadata.close() def get_services(self) -> Iterable[WorkflowSource]: @@ -549,16 +558,24 @@ def _get_add_lineage_request( sql: Optional[str] = None, # noqa: UP045 ) -> Optional[Either[AddLineageRequest]]: # noqa: UP045 if from_entity and to_entity: - return Either( + return Either( # pyright: ignore[reportCallIssue] right=AddLineageRequest( edge=EntitiesEdge( - fromEntity=EntityReference( + # Carry the FQN on both references so the sink can return the source FQN + # without a follow-up lineage GET (see add_lineage return_lineage flag). + fromEntity=EntityReference( # pyright: ignore[reportCallIssue] id=Uuid(from_entity.id.root), type=LINEAGE_MAP[type(from_entity)], + fullyQualifiedName=( + model_str(from_entity.fullyQualifiedName) if from_entity.fullyQualifiedName else None + ), ), - toEntity=EntityReference( + toEntity=EntityReference( # pyright: ignore[reportCallIssue] id=Uuid(to_entity.id.root), type=LINEAGE_MAP[type(to_entity)], + fullyQualifiedName=( + model_str(to_entity.fullyQualifiedName) if to_entity.fullyQualifiedName else None + ), ), lineageDetails=LineageDetails( source=LineageSource.DashboardLineage, @@ -631,7 +648,10 @@ def get_dashboard(self) -> Any: yield dashboard_details def test_connection(self) -> None: - test_connection_common(self.metadata, self.connection_obj, self.service_connection) + if self._connection is not None: + run_test_connection(self.metadata, self._connection) + else: + test_connection_common(self.metadata, self.client, self.service_connection) def prepare(self): """By default, nothing to prepare""" diff --git a/ingestion/src/metadata/ingestion/source/dashboard/grafana/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/grafana/connection.py index bc38f161bb5b..b94ef29f1414 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/grafana/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/grafana/connection.py @@ -30,21 +30,17 @@ from metadata.utils.constants import THREE_MIN -def get_connection(connection: GrafanaConnectionConfig) -> GrafanaApiClient: - """ - Create connection to Grafana - """ - return GrafanaApiClient( - host_port=connection.hostPort, - api_key=connection.apiKey.get_secret_value(), - verify_ssl=connection.verifySSL or True, - page_size=connection.pageSize or 100, - ) - - class GrafanaConnection(BaseConnection[GrafanaConnectionConfig, GrafanaApiClient]): def _get_client(self) -> GrafanaApiClient: - return get_connection(self.service_connection) + """ + Create connection to Grafana + """ + return GrafanaApiClient( + host_port=str(self.service_connection.hostPort), + api_key=self.service_connection.apiKey.get_secret_value(), + verify_ssl=(self.service_connection.verifySSL if self.service_connection.verifySSL is not None else True), + page_size=self.service_connection.pageSize or 100, + ) def test_connection( self, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/grafana/metadata.py b/ingestion/src/metadata/ingestion/source/dashboard/grafana/metadata.py index 3d4ef6f8071a..8ff5fc57be28 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/grafana/metadata.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/grafana/metadata.py @@ -13,7 +13,7 @@ """ import traceback -from typing import Dict, Iterable, List, Optional, Set # noqa: UP035 +from typing import Dict, Iterable, List, Optional, Set, cast # noqa: UP035 from metadata.generated.schema.api.data.createChart import CreateChartRequest from metadata.generated.schema.api.data.createDashboard import CreateDashboardRequest @@ -46,7 +46,9 @@ from metadata.ingestion.lineage.parser import LineageParser from metadata.ingestion.ometa.ometa_api import OpenMetadata from metadata.ingestion.source.dashboard.dashboard_service import DashboardServiceSource -from metadata.ingestion.source.dashboard.grafana.client import GrafanaApiClient # noqa: TC001 +from metadata.ingestion.source.dashboard.grafana.client import ( # noqa: TC001 + GrafanaApiClient, +) from metadata.ingestion.source.dashboard.grafana.models import ( GrafanaDashboardResponse, GrafanaDatasource, @@ -78,7 +80,7 @@ def __init__( metadata: OpenMetadata, ): super().__init__(config, metadata) - self.client: GrafanaApiClient = self.connection_obj + self.client: GrafanaApiClient = cast("GrafanaApiClient", self.client) self.folders: List[GrafanaFolder] = [] # noqa: UP006 self.datasources: Dict[str, GrafanaDatasource] = {} # noqa: UP006 self.dashboards: List[GrafanaSearchResult] = [] # noqa: UP006 diff --git a/ingestion/src/metadata/ingestion/source/dashboard/hex/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/hex/connection.py index 29687584ff21..1e97ee3c4d44 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/hex/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/hex/connection.py @@ -33,16 +33,12 @@ logger = ingestion_logger() -def get_connection(connection: HexConnectionConfig) -> HexApiClient: - """ - Create connection - """ - return HexApiClient(connection) - - class HexConnection(BaseConnection[HexConnectionConfig, HexApiClient]): def _get_client(self) -> HexApiClient: - return get_connection(self.service_connection) + """ + Create connection + """ + return HexApiClient(self.service_connection) def test_connection( self, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/hex/metadata.py b/ingestion/src/metadata/ingestion/source/dashboard/hex/metadata.py index 651c064452d7..d6c794181958 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/hex/metadata.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/hex/metadata.py @@ -43,7 +43,6 @@ from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata from metadata.ingestion.source.dashboard.dashboard_service import DashboardServiceSource -from metadata.ingestion.source.dashboard.hex.connection import get_connection from metadata.ingestion.source.dashboard.hex.models import Project from metadata.ingestion.source.dashboard.hex.query_fetcher import ( HexProjectLineage, @@ -69,7 +68,6 @@ def __init__( metadata: OpenMetadata, ): super().__init__(config, metadata) - self.client = get_connection(self.service_connection) self.projects = [] # We will populate this in `prepare` # Initialize lineage components diff --git a/ingestion/src/metadata/ingestion/source/dashboard/looker/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/looker/connection.py index 14c8c0b9f2d5..291ac8030412 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/looker/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/looker/connection.py @@ -13,75 +13,285 @@ Source connection handler """ -import os -from typing import Optional +from __future__ import annotations + +import re +from typing import TYPE_CHECKING import looker_sdk +from looker_sdk.rtl.api_settings import ApiSettings, SettingsConfig from looker_sdk.sdk.api40.methods import Looker40SDK -from metadata.generated.schema.entity.automations.workflow import ( - Workflow as AutomationWorkflow, +from metadata.core.connections.test_connection import ( + Diagnosis, + ErrorPack, + Evidence, + Matchers, + check, + when, +) +from metadata.core.connections.test_connection.check import CheckError +from metadata.core.connections.test_connection.checks.dashboard import ( + DashboardStep, + call_endpoint, + fetch_list, + verify_access, ) +from metadata.core.connections.test_connection.classifier import exception_chain +from metadata.core.connections.test_connection.network import NETWORK_ERRORS from metadata.generated.schema.entity.services.connections.dashboard.lookerConnection import ( LookerConnection as LookerConnectionConfig, ) -from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - TestConnectionResult, -) from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.connections.test_connections import test_connection_steps -from metadata.ingestion.ometa.ometa_api import OpenMetadata from metadata.utils.constants import THREE_MIN +if TYPE_CHECKING: + from metadata.core.connections.lifetime import Borrowed + from metadata.core.connections.test_connection import ChecksProvider + from metadata.core.connections.test_connection.classifier import Matcher + +SDK_API_VERSION = "4.0" + +API_SDK_DOC = "https://cloud.google.com/looker/docs/api-sdk" + +# Looker encodes the HTTP status of a failed call in the documentation URL it +# returns with the error body, e.g. +# https://cloud.google.com/looker/docs/r/err/4.0/404/post/api/4.0/login +_ERROR_DOC_URL = re.compile(r"/r/err/[^/]+/(?P\d{3})/(?P\S*)", re.IGNORECASE) + +# A 404 from a server that is not Looker. Word-bounded so a port or byte count +# containing 404 does not match. +_FOREIGN_404 = re.compile(r"\b404\b|not found", re.IGNORECASE) + + +class UnsupportedApiVersionError(Exception): + """The Looker instance does not list the API version the SDK speaks.""" + + +def _error_doc(error: BaseException) -> re.Match[str] | None: + """Parse the status and endpoint from the documentation URL the error carries. + + Searches the message and the attribute: an API call deserializes the URL onto + ``documentation_url``, a failed login raises the raw body as the message, and + only newer ``looker-sdk`` renders the attribute in ``__str__``. + """ + doc_url = getattr(error, "documentation_url", "") or "" + return _ERROR_DOC_URL.search(f"{error} {doc_url}") + + +def _http_status(*codes: int) -> Matcher: + """Match a Looker REST error by the HTTP status of the call that failed.""" + wanted = frozenset(str(code) for code in codes) + return lambda error: any( + (match := _error_doc(current)) is not None and match["status"] in wanted for current in exception_chain(error) + ) + + +def _login_rejected(error: BaseException) -> bool: + """Match Looker rejecting the credentials: a 404 on ``/login``, so the endpoint - + not the status - is what separates it from a wrong host.""" + return any( + (match := _error_doc(current)) is not None and match["status"] == "404" and "login" in match["path"].lower() + for current in exception_chain(error) + ) + + +def _has_error_doc(error: BaseException) -> bool: + """Whether any error in the chain carries a Looker error document. + + A real transport failure is flattened into a message with no such document, so + its presence marks a structured Looker answer that must keep its raw errorLog + rather than be diagnosed from incidental text. + """ + return any(_error_doc(current) is not None for current in exception_chain(error)) + + +def _foreign_404(error: BaseException) -> bool: + """Match a 404 from a server that is not Looker: a 404 token, but no Looker + error document (a Looker 404 carries one and is matched above).""" + return not _has_error_doc(error) and any(_FOREIGN_404.search(str(current)) for current in exception_chain(error)) + + +def _transport_text(*tokens: str) -> Matcher: + """Match a flattened transport error by text: the SDK re-raises every + ``IOError`` as an ``SDKError`` whose message is the stringified original, so + DNS, refused, TLS and timeout errors lose their type. + + Guarded by the absence of a Looker error document, so a structured Looker + error whose message happens to contain a transport token (e.g. a 400 reading + "timeout") keeps its raw errorLog instead of being blamed on the network. + """ + lowered = tuple(token.lower() for token in tokens) + + def match(error: BaseException) -> bool: + if _has_error_doc(error): + return False + chain = " ".join(str(current) for current in exception_chain(error)).lower() + return any(token in chain for token in lowered) + + return match + + +# The API spec documents 400, 404 and 429 for the endpoints these checks call - no +# 401 anywhere, no 403 on any of them. An unmatched status keeps its raw errorLog. +LOOKER_ERRORS = ErrorPack( + # Before the generic 404: a rejected login is itself a 404, on /login. + when(_login_rejected).diagnose( + "Authentication failed", + fix="Looker rejected the credentials. Check the Client ID and Client Secret.", + doc=API_SDK_DOC, + ), + when(Matchers.contains("Required auth credentials not found")).diagnose( + "Missing credentials", + fix="Provide both the Client ID and the Client Secret.", + doc=API_SDK_DOC, + ), + when(_http_status(404)).diagnose( + "Resource not found", + fix="Looker could not find the requested resource. Check that Host Port is the instance URL.", + ), + when(_http_status(429)).diagnose( + "Rate limited by Looker", + fix="Looker is throttling the requests. Retry once the instance is under less load.", + ), + when(Matchers.exception(UnsupportedApiVersionError)).diagnose( + f"API {SDK_API_VERSION} is not supported by this instance", + fix=f"This connector uses API {SDK_API_VERSION}, which the instance does not list as supported.", + doc=API_SDK_DOC, + ), + # Matched on text: the transport flattens these into an SDKError message. Guarded + # so a structured Looker error is not read as a transport failure; the type-based + # NETWORK_ERRORS below only fires outside the transport. + when( + _transport_text("failed to resolve", "name or service not known", "nodename nor servname", "getaddrinfo failed") + ).diagnose( + "Host could not be resolved", + fix="Check Host Port and that DNS resolves it from where ingestion runs.", + ), + when(_transport_text("connection refused")).diagnose( + "Connection refused", + fix="Nothing is listening on that port. Check the host and port in Host Port.", + ), + when(_transport_text("timed out", "timeout")).diagnose( + "Connection timed out", + fix="The host did not answer in time. Check that the network allows access to this host and port.", + ), + when(_transport_text("certificate verify failed", "sslerror", "ssl: ")).diagnose( + "TLS verification failed", + fix="The instance's certificate could not be verified from where ingestion runs.", + ), + when(_transport_text("max retries exceeded", "connection aborted", "connection error")).diagnose( + "Cannot reach the host", + fix="Check Host Port and that the instance is reachable from where ingestion runs.", + ), + # Looker serves this page, with no error document, both for a rejected sign-in + # and for a host that is not a live instance; the two cannot be told apart. + when(_transport_text("looker is unavailable", "looker not found")).diagnose( + "Authentication failed", + fix="Looker returns this same page for wrong credentials and for a host that is not a live " + "instance. Check the Client ID and Client Secret, then Host Port.", + doc=API_SDK_DOC, + ), + # Last: a 404 from something that is not Looker - any Looker error carries an + # error document, whether or not this pack diagnoses its status. + when(_foreign_404).diagnose( + "The host is not serving the Looker API", + fix="A server answered but did not return a Looker error. Check that Host Port points at the Looker instance.", + ), +).including(NETWORK_ERRORS) + + +class LookerChecks: + """Test-connection checks for Looker. + + ``CheckAccess`` is the gate: reading the borrowed client logs in on its first + call, so bad credentials and an unreachable host fail there. + """ + + errors = LOOKER_ERRORS + + def __init__(self, looker: Borrowed[Looker40SDK]) -> None: + self._looker = looker + + def _client(self) -> Looker40SDK: + return self._looker.client + + @check(DashboardStep.CheckAccess) + def check_access(self) -> Evidence: + return verify_access( + lambda: self._client().me(), + command="log in and read the authenticated user", + ) + + @check(DashboardStep.ValidateVersion) + def validate_version(self) -> Evidence: + command = "list the API versions the instance supports" + versions = call_endpoint(lambda: self._client().versions(), command=command) + supported = [version.version for version in versions.supported_versions or []] + if SDK_API_VERSION not in supported: + raise CheckError( + UnsupportedApiVersionError( + f"API {SDK_API_VERSION} is not listed among the supported versions: " + f"{', '.join(version for version in supported if version) or 'none'}" + ), + Evidence(command=command), + ) + return Evidence(summary=f"API {SDK_API_VERSION} is supported", command=command) + + @check(DashboardStep.ListDashboards) + def list_dashboards(self) -> Evidence: + return fetch_list( + lambda: self._client().all_dashboards(fields="id,title"), + noun="dashboard", + command="list dashboards", + empty_caveat=Diagnosis( + title="No dashboards visible", + remediation="The connection works but returned no dashboards. Confirm the user can see " + "the dashboards to ingest.", + ), + ) + + @check(DashboardStep.ListLookMLModels) + def list_lookml_models(self) -> Evidence: + return fetch_list( + lambda: self._client().all_lookml_models(limit=1), + noun="LookML model", + command="list LookML models", + empty_caveat=Diagnosis( + title="No LookML models visible", + remediation="The connection works but returned no LookML model. Grant the user access " + "to the models to ingest; without them, lineage will not be present.", + ), + ) + + +class LookerSettings(ApiSettings): + """Configure the SDK from this service's connection. + + Without it the SDK reads host and credentials from the process environment, + which a long-lived worker populates once: later connections in that process + would reuse the first one's. + """ + + def __init__(self, connection: LookerConnectionConfig) -> None: + self._config: SettingsConfig = { + "base_url": str(connection.hostPort), + "client_id": connection.clientId, + "client_secret": connection.clientSecret.get_secret_value(), + } + super().__init__() + + def read_config(self) -> SettingsConfig: + return self._config + class LookerConnection(BaseConnection[LookerConnectionConfig, Looker40SDK]): + # Listing dashboards and LookML models can be slow on large instances; keep the + # legacy 3-minute budget the imperative handler used, now applied per step. + step_timeout_seconds = THREE_MIN + def _get_client(self) -> Looker40SDK: - connection = self.service_connection - if not os.environ.get("LOOKERSDK_CLIENT_ID"): - os.environ["LOOKERSDK_CLIENT_ID"] = connection.clientId - if not os.environ.get("LOOKERSDK_CLIENT_SECRET"): - os.environ["LOOKERSDK_CLIENT_SECRET"] = connection.clientSecret.get_secret_value() - if not os.environ.get("LOOKERSDK_BASE_URL"): - os.environ["LOOKERSDK_BASE_URL"] = str(connection.hostPort) - - return looker_sdk.init40() - - def test_connection( - self, - metadata: OpenMetadata, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 - ) -> TestConnectionResult: - """ - Test connection. This can be executed either as part - of a metadata workflow or during an Automation Workflow - """ - client = self.client - service_connection = self.service_connection - - def list_datamodels_test(): - """ - Make sure that we get a non-empty result - """ - assert client.all_lookml_models(limit=1) - - def validate_api_version(): - """ - Make sure we get a True - """ - assert "4.0" in (api_version.version for api_version in client.versions().supported_versions) # pyright: ignore[reportOptionalIterable] - - test_fn = { - "CheckAccess": client.me, - "ValidateVersion": validate_api_version, - "ListDashboards": lambda: client.all_dashboards(fields="id,title"), - "ListLookMLModels": list_datamodels_test, - } + return looker_sdk.init40(config_settings=LookerSettings(self.service_connection)) - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=service_connection.type.value, # pyright: ignore[reportOptionalMemberAccess] - automation_workflow=automation_workflow, - timeout_seconds=timeout_seconds, - ) + def checks(self) -> ChecksProvider: + return LookerChecks(looker=self.borrow()) diff --git a/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py b/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py index ac92fdcad2d5..0a8974eeb430 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/looker/metadata.py @@ -109,6 +109,7 @@ from metadata.ingestion.lineage.sql_lineage import get_column_fqn from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import ProgressMode from metadata.ingestion.source.dashboard.dashboard_service import ( DashboardServiceSource, DashboardUsage, @@ -129,7 +130,12 @@ from metadata.readers.file.credentials import get_credentials_from_url from metadata.readers.file.local import LocalReader from metadata.utils import fqn -from metadata.utils.filters import filter_by_chart, filter_by_datamodel +from metadata.utils.filters import ( + filter_by_chart, + filter_by_dashboard, + filter_by_datamodel, + filter_pattern_enabled, +) from metadata.utils.helpers import clean_uri, get_standard_chart_type from metadata.utils.logger import ingestion_logger from metadata.utils.tag_utils import get_ometa_tag_and_classification, get_tag_labels @@ -194,6 +200,7 @@ class LookerSource(DashboardServiceSource): config: WorkflowSource metadata: OpenMetadata client: Looker40SDK + progress_mode = ProgressMode.MANUAL def __init__( self, @@ -425,6 +432,13 @@ def list_datamodels(self) -> Iterable[LookmlModelExplore]: # Store the models for later processing of standalone views self._all_lookml_models = all_lookml_models + manual = self.progress_tracking.manual + manual.set_total( + DashboardDataModel.__name__, + self._reconcilable_explore_total(all_lookml_models), + ) + manual.mark_reconcilable(DashboardDataModel.__name__) + # Finally, iterate through them to ingest Explores and Views yield from self.fetch_lookml_explores(all_lookml_models) @@ -432,6 +446,27 @@ def list_datamodels(self) -> Iterable[LookmlModelExplore]: logger.debug(traceback.format_exc()) logger.error(f"Unexpected error fetching LookML models - {err}") + def _reconcilable_explore_total(self, all_lookml_models: Sequence[LookmlModel]) -> int: + """Count the explores that ``fetch_lookml_explores`` would actually + yield, i.e. those whose model and composite datamodel name survive the + dataModelFilterPattern. This is the DashboardDataModel progress total.""" + total = 0 + for model in all_lookml_models: + model_name = model.name + explores = model.explores + if not model_name or not explores: + continue + if filter_by_datamodel(self.source_config.dataModelFilterPattern, model_name): + continue + for explore in explores: + explore_name = explore.name + if explore_name and not filter_by_datamodel( + self.source_config.dataModelFilterPattern, + build_datamodel_name(model_name, explore_name), + ): + total += 1 + return total + def fetch_lookml_explores(self, all_lookml_models: Sequence[LookmlModel]) -> Iterable[LookmlModelExplore]: """ Based on the LookML models, iterate over the explores @@ -531,6 +566,7 @@ def yield_standalone_datamodels( ) yield Either(right=data_model_request) + self.progress_tracking.manual.track(DashboardDataModel.__name__) self.register_record_datamodel(datamodel_request=data_model_request) # Build and cache the view model @@ -626,6 +662,7 @@ def yield_bulk_datamodel(self, model: LookmlModelExplore) -> Iterable[Either[Cre ), ) yield Either(right=explore_datamodel) + self.progress_tracking.manual.track(DashboardDataModel.__name__) self.register_record_datamodel(datamodel_request=explore_datamodel) # build datamodel by our hand since ack_sink=False @@ -1177,12 +1214,31 @@ def get_dashboards_list(self) -> List[DashboardBase]: # noqa: UP006 if not self.source_config.includeOwners: logger.debug("Skipping owner information as includeOwners is False") try: - return list(self.client.all_dashboards(fields=",".join(LIST_DASHBOARD_FIELDS))) + dashboards = list(self.client.all_dashboards(fields=",".join(LIST_DASHBOARD_FIELDS))) + kept = [ + dashboard + for dashboard in dashboards + if not filter_by_dashboard( + self.source_config.dashboardFilterPattern, + self.get_dashboard_name(dashboard), + ) + ] + manual = self.progress_tracking.manual + if filter_pattern_enabled(self.source_config.projectFilterPattern): + # projectFilterPattern is applied downstream in the base + # get_dashboard (needs per-dashboard project detail), so the + # kept count over-counts — show a running count instead of a + # bar stuck below 100%. + manual.mark_reconcilable(Dashboard.__name__) + else: + manual.set_total(Dashboard.__name__, len(kept)) except Exception as err: logger.debug(traceback.format_exc()) logger.error(f"Wild error trying to obtain dashboard list {err}") # If we cannot list the dashboards, let's blow up raise err # noqa: TRY201 + else: + return dashboards def get_dashboard_name(self, dashboard: DashboardBase) -> str: """ @@ -1253,6 +1309,7 @@ def yield_dashboard(self, dashboard_details: LookerDashboard) -> Iterable[Either owners=self.get_owner_ref(dashboard_details=dashboard_details), ) yield Either(right=dashboard_request) + self.progress_tracking.manual.track(Dashboard.__name__) self.register_record(dashboard_request=dashboard_request) def get_project_name(self, dashboard_details: LookerDashboard) -> Optional[str]: # noqa: UP045 diff --git a/ingestion/src/metadata/ingestion/source/dashboard/metabase/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/metabase/connection.py index 0e19efec8c4c..5c117be339b0 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/metabase/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/metabase/connection.py @@ -31,16 +31,9 @@ from metadata.utils.constants import THREE_MIN -def get_connection(connection: MetabaseConnectionConfig) -> MetabaseClient: - """ - Create connection - """ - return MetabaseClient(connection) - - class MetabaseConnection(BaseConnection[MetabaseConnectionConfig, MetabaseClient]): def _get_client(self) -> MetabaseClient: - return get_connection(self.service_connection) + return MetabaseClient(self.service_connection) def test_connection( self, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/microstrategy/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/microstrategy/connection.py index 244d61554402..2958db04c2ba 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/microstrategy/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/microstrategy/connection.py @@ -31,16 +31,9 @@ from metadata.utils.constants import THREE_MIN -def get_connection(connection: MicroStrategyConnectionConfig) -> MicroStrategyClient: - """ - Create connection - """ - return MicroStrategyClient(connection) - - class MicroStrategyConnection(BaseConnection[MicroStrategyConnectionConfig, MicroStrategyClient]): def _get_client(self) -> MicroStrategyClient: - return get_connection(self.service_connection) + return MicroStrategyClient(self.service_connection) def test_connection( self, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/powerbi/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/powerbi/connection.py index 61baea96d824..43147f6cb9ca 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/powerbi/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/powerbi/connection.py @@ -44,6 +44,7 @@ from metadata.ingestion.source.dashboard.powerbi.file_client import PowerBiFileClient if TYPE_CHECKING: + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.classifier import Matcher @@ -129,16 +130,6 @@ def match(error: BaseException) -> bool: ).including(NETWORK_ERRORS) -def get_connection(connection: PowerBIConnectionConfig) -> PowerBiClient: - """ - Create connection - """ - file_client = None - if connection.pbitFilesSource: - file_client = PowerBiFileClient(connection) - return PowerBiClient(api_client=PowerBiApiClient(connection), file_client=file_client) - - class PowerBIChecks: """Test-connection checks for PowerBI. @@ -146,28 +137,17 @@ class PowerBIChecks: principal fails fast before any list endpoint is dialled. ``GetDashboards`` then exercises list access. - The REST client is built lazily inside the first check, never at - construction: the underlying MSAL client performs authority/instance - discovery over the network in its constructor, so building it eagerly would - run before the runner's gate and surface as a raw workflow error instead of a - classified ``CheckAccess`` failure. + ``CheckAccess`` is the gate: reading the borrowed client does MSAL discovery + and acquires the token, so a bad service principal fails there. """ errors = POWERBI_ERRORS - def __init__(self, connection: PowerBIConnectionConfig) -> None: - self._connection = connection - self._api_client: PowerBiApiClient | None = None + def __init__(self, powerbi: Borrowed[PowerBiClient]) -> None: + self._powerbi = powerbi def _client(self) -> PowerBiApiClient: - """Build (once) and return the REST client. Built directly rather than via - ``get_connection`` so the file client (unused by the checks) is never - constructed. The MSAL client it wraps does authority/instance discovery - over the network in its constructor, so this is only ever called from - inside a check - never at construction.""" - if self._api_client is None: - self._api_client = PowerBiApiClient(self._connection) - return self._api_client + return self._powerbi.client.api_client @check(DashboardStep.CheckAccess) def check_access(self) -> Evidence: @@ -193,7 +173,16 @@ def get_dashboards(self) -> Evidence: class PowerBIConnection(BaseConnection[PowerBIConnectionConfig, PowerBiClient]): def _get_client(self) -> PowerBiClient: - return get_connection(self.service_connection) + """ + Create connection + """ + file_client = None + if self.service_connection.pbitFilesSource: + file_client = PowerBiFileClient(self.service_connection) + return PowerBiClient( + api_client=PowerBiApiClient(self.service_connection), + file_client=file_client, + ) def checks(self) -> ChecksProvider: - return PowerBIChecks(connection=self.service_connection) + return PowerBIChecks(powerbi=self.borrow()) diff --git a/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py b/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py index c659c0d5b499..a91ab36e99c2 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/powerbi/metadata.py @@ -65,6 +65,7 @@ from metadata.ingestion.models.barrier import Barrier from metadata.ingestion.ometa.ometa_api import OpenMetadata from metadata.ingestion.ometa.utils import model_str +from metadata.ingestion.progress.modes import ProgressMode from metadata.ingestion.source.dashboard.dashboard_service import DashboardServiceSource from metadata.ingestion.source.dashboard.powerbi.constants import ( BIGQUERY_QUERY_EXPRESSION_KW, @@ -133,6 +134,8 @@ class LineageTargetSpec: class PowerbiSource(DashboardServiceSource): """PowerBi Source Class""" + progress_mode = ProgressMode.MANUAL + config: WorkflowSource metadata_config: OpenMetadataConnection @@ -167,7 +170,7 @@ def get_org_workspace_data(self) -> Iterable[Optional[Group]]: # noqa: UP045 workspaces = self.client.api_client.fetch_all_workspaces(filter_pattern) if workspaces: workspace_total += len(workspaces) - self.progress.set_total("Workspaces", workspace_total) + self.progress_tracking.manual.set_total("Workspaces", workspace_total) for workspace in workspaces: # add the dashboards to the workspace workspace.dashboards.extend( @@ -307,7 +310,7 @@ def get_admin_workspace_data(self) -> Iterable[Optional[Group]]: # noqa: UP045 missing_workspaces, ) active_workspace_total += len(active_workspaces) - self.progress.set_total("Workspaces", active_workspace_total) + self.progress_tracking.manual.set_total("Workspaces", active_workspace_total) yield from active_workspaces count += 1 else: diff --git a/ingestion/src/metadata/ingestion/source/dashboard/sigma/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/sigma/connection.py index c5a69aac1989..36a5ffd0a6c7 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/sigma/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/sigma/connection.py @@ -34,20 +34,13 @@ from metadata.utils.constants import THREE_MIN -def get_connection(connection: SigmaConnectionConfig) -> SigmaApiClient: - """ - Create connection - """ - try: - return SigmaApiClient(connection) - except Exception as exc: - msg = f"Unknown error connecting with {connection}: {exc}." - raise SourceConnectionException(msg) from exc - - class SigmaConnection(BaseConnection[SigmaConnectionConfig, SigmaApiClient]): def _get_client(self) -> SigmaApiClient: - return get_connection(self.service_connection) + try: + return SigmaApiClient(self.service_connection) + except Exception as exc: + msg = f"Unknown error connecting with {self.service_connection}: {exc}." + raise SourceConnectionException(msg) from exc def test_connection( self, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/ssrs/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/ssrs/connection.py index e24afa239c83..2b152f82ebb1 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/ssrs/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/ssrs/connection.py @@ -31,17 +31,13 @@ from metadata.utils.ssl_registry import get_verify_ssl_fn -def get_connection(connection: SsrsConnectionConfig) -> SsrsClient: - verify_ssl = None - if connection.verifySSL: - verify_ssl_fn = get_verify_ssl_fn(connection.verifySSL) - verify_ssl = verify_ssl_fn(connection.sslConfig) - return SsrsClient(connection, verify_ssl=verify_ssl) - - class SsrsConnection(BaseConnection[SsrsConnectionConfig, SsrsClient]): def _get_client(self) -> SsrsClient: - return get_connection(self.service_connection) + verify_ssl = None + if self.service_connection.verifySSL: + verify_ssl_fn = get_verify_ssl_fn(self.service_connection.verifySSL) + verify_ssl = verify_ssl_fn(self.service_connection.sslConfig) + return SsrsClient(self.service_connection, verify_ssl=verify_ssl) def test_connection( self, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/superset/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/superset/connection.py index 2c5ad4e25cd0..55d430746619 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/superset/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/superset/connection.py @@ -14,9 +14,7 @@ """ from functools import partial -from typing import Any, Optional, Union - -from sqlalchemy.engine import Engine +from typing import Any, Optional from metadata.generated.schema.entity.automations.workflow import ( Workflow as AutomationWorkflow, @@ -53,24 +51,19 @@ from metadata.utils.constants import THREE_MIN -def get_connection( - connection: SupersetConnectionConfig, -) -> Union[SupersetAPIClient, Engine, None]: # noqa: UP007 - """ - Create connection - """ - if isinstance(connection.connection, SupersetApiConnection): - return SupersetAPIClient(connection) - if isinstance(connection.connection, PostgresConnectionConfig): - return PostgresConnection(connection.connection).client - if isinstance(connection.connection, MysqlConnectionConfig): - return MySQLConnection(connection.connection).client - return None - - class SupersetConnection(BaseConnection[SupersetConnectionConfig, Any]): def _get_client(self) -> Any: - return get_connection(self.service_connection) + """ + Create connection + """ + connection = self.service_connection + if isinstance(connection.connection, SupersetApiConnection): + return SupersetAPIClient(connection) + if isinstance(connection.connection, PostgresConnectionConfig): + return PostgresConnection(connection.connection).client + if isinstance(connection.connection, MysqlConnectionConfig): + return MySQLConnection(connection.connection).client + return None def test_connection( self, diff --git a/ingestion/src/metadata/ingestion/source/dashboard/tableau/client.py b/ingestion/src/metadata/ingestion/source/dashboard/tableau/client.py index e52e51012e0f..5ff9c3d09698 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/tableau/client.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/tableau/client.py @@ -14,14 +14,14 @@ import math import traceback -from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union # noqa: UP035 +from typing import Dict, Iterable, List, Optional, Tuple, Union # noqa: UP035 import validators -from cached_property import cached_property from tableauserverclient import ( Pager, PersonalAccessTokenAuth, ProjectItem, + RequestOptions, Server, TableauAuth, ViewItem, @@ -96,9 +96,8 @@ def __init__( self.all_projects: List[ProjectItem] = [] # noqa: UP006 self.ssl_manager = ssl_manager - @cached_property - def server_info(self) -> Callable: - return self.tableau_server.server_info.get + def server_info(self): + return self.tableau_server.server_info.get() def server_api_version(self) -> str: return self.tableau_server.version @@ -200,6 +199,13 @@ def get_project_parents_by_id(self, project_id: str) -> Optional[str]: # noqa: logger.debug(f"Failed to get project parents by id: {str(e)}") # noqa: RUF010 return None + def get_workbook_count(self) -> int: + """Total workbooks available server-side via the pagination summary — a + single page-size-1 request, no full workbook materialization. This is the + pre-filter denominator for Dashboard progress.""" + _, pagination_item = self.tableau_server.workbooks.get(RequestOptions(pagesize=1)) + return pagination_item.total_available + def get_workbooks(self, include_owners: bool = True) -> Iterable[TableauDashboard]: """ Fetch all tableau workbooks diff --git a/ingestion/src/metadata/ingestion/source/dashboard/tableau/connection.py b/ingestion/src/metadata/ingestion/source/dashboard/tableau/connection.py index 51697b2d62e9..437874ef038b 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/tableau/connection.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/tableau/connection.py @@ -8,42 +8,151 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - """ Source connection handler """ +from __future__ import annotations + import traceback -from typing import Any, Dict, Optional, Union # noqa: UP035 +from typing import TYPE_CHECKING, Any, Dict, Optional, Union # noqa: UP035 import tableauserverclient as TSC # noqa: N812 +from requests.exceptions import SSLError +from tableauserverclient.server.endpoint.exceptions import ( + InternalServerError, + ServerResponseError, +) -from metadata.generated.schema.entity.automations.workflow import ( - Workflow as AutomationWorkflow, +from metadata.core.connections.test_connection import ( + ErrorPack, + Evidence, + Matchers, + check, + when, ) +from metadata.core.connections.test_connection.checks.dashboard import ( + DashboardStep, + call_endpoint, + verify_access, +) +from metadata.core.connections.test_connection.classifier import exception_chain +from metadata.core.connections.test_connection.network import NETWORK_ERRORS from metadata.generated.schema.entity.services.connections.dashboard.tableauConnection import ( TableauConnection as TableauConnectionConfig, ) -from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - TestConnectionResult, -) from metadata.generated.schema.security.credentials.accessTokenAuth import ( AccessTokenAuth, ) from metadata.generated.schema.security.credentials.basicAuth import BasicAuth from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.connections.test_connections import ( - SourceConnectionException, - test_connection_steps, +from metadata.ingestion.connections.test_connections import SourceConnectionException +from metadata.ingestion.source.dashboard.tableau.client import ( + TableauChartsException, + TableauClient, + TableauDataModelsException, + TableauOwnersNotFound, + TableauWorkBookException, ) -from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.dashboard.tableau.client import TableauClient from metadata.utils.constants import THREE_MIN from metadata.utils.logger import ingestion_logger from metadata.utils.ssl_manager import SSLManager +if TYPE_CHECKING: + from metadata.core.connections.lifetime import Borrowed + from metadata.core.connections.test_connection import ChecksProvider + from metadata.core.connections.test_connection.classifier import Matcher + logger = ingestion_logger() +METADATA_API_DOC = ( + "https://help.tableau.com/current/api/metadata_api/en-us/docs/meta_api_start.html" + "#enable-the-tableau-metadata-api-for-tableau-server" +) + + +def _status_of(error: BaseException) -> int | None: + """Return the HTTP status a Tableau error carries, if any. + + Only the two Tableau error types whose ``.code`` is HTTP-ish are trusted - + ``ServerResponseError.code`` is a string whose first three digits are the + status (e.g. ``401002``), ``InternalServerError.code`` is the status itself - + plus a raw ``requests`` error's ``.response.status_code``. Reading ``.code`` + off any exception would misclassify an unrelated app code the chain happens + to carry. + """ + if isinstance(error, ServerResponseError) and error.code[:3].isdigit(): + status = int(error.code[:3]) + elif isinstance(error, InternalServerError) and isinstance(error.code, int): + status = error.code + else: + response = getattr(error, "response", None) + status = getattr(response, "status_code", None) + return status if isinstance(status, int) else None + + +def _http_status(*codes: int) -> Matcher: + """Match a Tableau REST error by HTTP status, across the cause chain. + + The status is the stable signal - the summary and detail of a Tableau error + vary by endpoint and server version. + """ + wanted = frozenset(codes) + return lambda error: any(_status_of(current) in wanted for current in exception_chain(error)) + + +TABLEAU_ERRORS = ErrorPack( + when(_http_status(401)).diagnose( + "Authentication failed", + fix="Tableau rejected the credentials (401). Check the Personal Access Token name and " + "secret (or the username and password) and that it has not expired, and that the Site " + "Name matches the site those credentials belong to.", + ), + when(_http_status(403)).diagnose( + "Insufficient permissions", + fix="The credentials are valid but not authorized for this resource (403). Grant the user " + "at least the Viewer site role and read access to the projects to ingest.", + ), + when(_http_status(404)).diagnose( + "Resource not found", + fix="Tableau could not find the requested resource (404). Check that Host Port points at " + "the Tableau server or Tableau Cloud pod, and that the Site Name exists - for " + "https:///#/site/MarketingTeam/home the Site Name is 'MarketingTeam'.", + ), + when(Matchers.exception(SSLError)).diagnose( + "TLS verification failed", + fix="The server's certificate could not be verified. Provide the CA certificate under SSL " + "Config with Verify SSL set to 'validate', or set Verify SSL to 'ignore' for a " + "self-signed certificate.", + ), + when(Matchers.exception(TableauWorkBookException)).diagnose( + "No workbooks visible", + fix="The user is authenticated but no workbook could be read. Grant it access to at least " + "one project containing workbooks.", + ), + when(Matchers.exception(TableauChartsException)).diagnose( + "No views visible", + fix="Workbooks are readable but their views are not. Grant the user the View permission on " + "the workbooks to ingest; charts are ingested from workbook views.", + ), + when(Matchers.exception(TableauOwnersNotFound)).diagnose( + "Owner information not available", + fix="Owners could not be resolved. Grant the user permission to read users on the site, or " + "disable owner ingestion in the service configuration.", + ), + when(Matchers.exception(TableauDataModelsException)).diagnose( + "Data sources could not be read", + fix="The Tableau Metadata API returned no data sources for the workbook. Enable the " + "Metadata API on the Tableau instance.", + doc=METADATA_API_DOC, + ), + when(Matchers.contains("in incorrect format")).diagnose( + "Invalid Site Name", + fix="The Site Name must be the site identifier, not a URL - for " + "https:///#/site/MarketingTeam/home enter 'MarketingTeam'.", + ), +).including(NETWORK_ERRORS) + def get_connection(connection: TableauConnectionConfig) -> TableauClient: """ @@ -78,26 +187,21 @@ def set_verify_ssl( return False, None if connection.verifySSL.value == "validate": - # Use SSLManager to create temporary certificate files if not connection.sslConfig: raise ValueError( "SSL Config is required when verifySSL is set to 'validate'. " "Please provide CA certificate, SSL certificate, or SSL key." ) - # Create SSLManager to handle certificate files ssl_manager = SSLManager( ca=connection.sslConfig.root.caCertificate, cert=connection.sslConfig.root.sslCertificate, key=connection.sslConfig.root.sslKey, ) - # Return the CA certificate file path for verification - # If no CA certificate is provided, use default verification if ssl_manager.ca_file_path: return ssl_manager.ca_file_path, ssl_manager else: # noqa: RET505 - # If no CA certificate is provided but SSL is enabled, use default verification return True, ssl_manager raise ValueError( @@ -105,37 +209,6 @@ def set_verify_ssl( ) -def test_connection( - metadata: OpenMetadata, - client: TableauClient, - service_connection: TableauConnectionConfig, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 -) -> TestConnectionResult: - """ - Test connection. This can be executed either as part - of a metadata workflow or during an Automation Workflow - """ - - test_fn = { - "ServerInfo": client.server_info, - "ValidateApiVersion": client.server_api_version, - "ValidateSiteUrl": client.test_site_url, - "GetWorkbooks": client.test_get_workbooks, - "GetViews": client.test_get_workbook_views, - "GetOwners": client.test_get_owners, - "GetDataModels": client.test_get_datamodels, - } - - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=service_connection.type.value, - automation_workflow=automation_workflow, - timeout_seconds=timeout_seconds, - ) - - def build_server_config(connection: TableauConnectionConfig) -> Dict[str, Dict[str, Any]]: # noqa: UP006 """ Build client configuration @@ -163,20 +236,83 @@ def build_server_config(connection: TableauConnectionConfig) -> Dict[str, Dict[s return tableau_auth +class TableauChecks: + """Test-connection checks for Tableau. + + ``ServerInfo`` is the gate: reading the borrowed client signs in, so bad + credentials or an unreachable server fail there and the rest are skipped. + """ + + errors = TABLEAU_ERRORS + + def __init__(self, server: Borrowed[TableauClient]) -> None: + self._server = server + + @check(DashboardStep.ServerInfo) + def server_info(self) -> Evidence: + # Lambda, not a bound method: the sign-in must happen inside verify_access's + # try, or a bad credential escapes unclassified. + return verify_access( + lambda: self._server.client.server_info(), # noqa: PLW0108 + command="sign in and read server info", + ) + + @check(DashboardStep.ValidateApiVersion) + def validate_api_version(self) -> Evidence: + command = "read the server REST API version" + version = call_endpoint(lambda: self._server.client.server_api_version(), command=command) # noqa: PLW0108 + return Evidence(summary=f"REST API version {version}", command=command) + + @check(DashboardStep.ValidateSiteUrl) + def validate_site_url(self) -> Evidence: + command = "validate the configured site name" + call_endpoint(lambda: self._server.client.test_site_url(), command=command) # noqa: PLW0108 + return Evidence(summary="site name is well formed", command=command) + + @check(DashboardStep.GetWorkbooks) + def get_workbooks(self) -> Evidence: + command = "fetch workbooks" + call_endpoint(lambda: self._server.client.test_get_workbooks(), command=command) # noqa: PLW0108 + return Evidence(summary="workbooks are readable", command=command) + + @check(DashboardStep.GetViews) + def get_views(self) -> Evidence: + command = "fetch the views of a workbook" + call_endpoint(lambda: self._server.client.test_get_workbook_views(), command=command) # noqa: PLW0108 + return Evidence(summary="workbook views are readable", command=command) + + @check(DashboardStep.GetOwners) + def get_owners(self) -> Evidence: + command = "fetch the owner of a workbook" + call_endpoint(lambda: self._server.client.test_get_owners(), command=command) # noqa: PLW0108 + return Evidence(summary="workbook owners are resolvable", command=command) + + @check(DashboardStep.GetDataModels) + def get_data_models(self) -> Evidence: + command = "query the Metadata API for the data sources of a workbook" + call_endpoint(lambda: self._server.client.test_get_datamodels(), command=command) # noqa: PLW0108 + return Evidence(summary="data sources are readable", command=command) + + +def _sign_out(client: TableauClient) -> None: + """Best-effort: close() unwinds teardowns without catching, so a failed sign-out + must not replace the error being unwound.""" + try: + client.sign_out() + except Exception: + logger.warning("Tableau sign-out failed while closing the connection", exc_info=True) + + class TableauConnection(BaseConnection[TableauConnectionConfig, TableauClient]): + # The workbook and Metadata API steps can be slow on large servers; keep the + # legacy 3-minute budget the imperative handler used, now applied per step. + step_timeout_seconds = THREE_MIN + def _get_client(self) -> TableauClient: - return get_connection(self.service_connection) - - def test_connection( - self, - metadata: OpenMetadata, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 - ) -> TestConnectionResult: - return test_connection( - metadata, - self.client, - self.service_connection, - automation_workflow, - timeout_seconds, - ) + client = get_connection(self.service_connection) + # sign_out releases the server session and clears the SSL temp files. + self._on_close(lambda: _sign_out(client)) + return client + + def checks(self) -> ChecksProvider: + return TableauChecks(server=self.borrow()) diff --git a/ingestion/src/metadata/ingestion/source/dashboard/tableau/metadata.py b/ingestion/src/metadata/ingestion/source/dashboard/tableau/metadata.py index d7b4984089fe..c3242395d1ff 100644 --- a/ingestion/src/metadata/ingestion/source/dashboard/tableau/metadata.py +++ b/ingestion/src/metadata/ingestion/source/dashboard/tableau/metadata.py @@ -70,6 +70,7 @@ ) from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import ProgressMode from metadata.ingestion.source.dashboard.dashboard_service import ( DashboardServiceSource, DashboardUsage, @@ -86,7 +87,11 @@ from metadata.ingestion.source.database.column_helpers import truncate_column_name from metadata.ingestion.source.database.column_type_parser import ColumnTypeParser from metadata.utils import fqn -from metadata.utils.filters import filter_by_chart, filter_by_datamodel +from metadata.utils.filters import ( + filter_by_chart, + filter_by_datamodel, + filter_pattern_enabled, +) from metadata.utils.fqn import build_es_fqn_search_string from metadata.utils.helpers import ( clean_uri, @@ -109,6 +114,7 @@ class TableauSource(DashboardServiceSource): config: WorkflowSource metadata_config: OpenMetadataConnection client: TableauClient + progress_mode = ProgressMode.MANUAL def __init__( self, @@ -134,8 +140,28 @@ def create( def get_dashboards_list(self) -> Iterable[TableauDashboard]: if not self.source_config.includeOwners: logger.debug("Skipping owner information as includeOwners is False") + self._declare_dashboard_progress_total() yield from self.client.get_workbooks(include_owners=self.source_config.includeOwners) + def _declare_dashboard_progress_total(self) -> None: + """Declare the Dashboard progress total. ``get_workbook_count`` is a + server-side pre-filter count, so when a dashboard or project filter is + active the tracked (post-filter) count can never reach it — fall back to + a reconcilable running count instead of a bar stuck below 100%.""" + manual = self.progress_tracking.manual + patterns = ( + self.source_config.dashboardFilterPattern, + self.source_config.projectFilterPattern, + ) + if any(filter_pattern_enabled(pattern) for pattern in patterns): + manual.mark_reconcilable(Dashboard.__name__) + else: + try: + manual.set_total(Dashboard.__name__, self.client.get_workbook_count()) + except Exception as exc: + logger.warning("Could not prefetch Tableau workbook count for progress: %s", exc) + manual.mark_reconcilable(Dashboard.__name__) + def get_dashboard_name(self, dashboard: TableauDashboard) -> str: return dashboard.name @@ -332,6 +358,7 @@ def yield_dashboard(self, dashboard_details: TableauDashboard) -> Iterable[Eithe owners=self.get_owner_ref(dashboard_details=dashboard_details), ) yield Either(right=dashboard_request) + self.progress_tracking.manual.track(Dashboard.__name__) self.register_record(dashboard_request=dashboard_request) except Exception as exc: yield Either( diff --git a/ingestion/src/metadata/ingestion/source/database/athena/connection.py b/ingestion/src/metadata/ingestion/source/database/athena/connection.py index 4e41091a53da..8b2cae98dd41 100644 --- a/ingestion/src/metadata/ingestion/source/database/athena/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/athena/connection.py @@ -15,10 +15,10 @@ from __future__ import annotations +from dataclasses import replace from typing import TYPE_CHECKING from urllib.parse import quote_plus -from botocore.exceptions import ClientError from sqlalchemy.engine import Engine from sqlalchemy.inspection import inspect @@ -29,13 +29,17 @@ check, when, ) +from metadata.core.connections.test_connection.aws import ( + AWS_AUTHENTICATION_CODES, + AWS_ERRORS, + aws_error_code, +) from metadata.core.connections.test_connection.checks.database import ( DatabaseStep, list_schemas, run_sql, ) from metadata.core.connections.test_connection.classifier import exception_chain -from metadata.core.connections.test_connection.network import NETWORK_ERRORS from metadata.core.connections.test_connection.records import Diagnosis, Evidence from metadata.generated.schema.entity.services.connections.database.athenaConnection import ( AthenaConnection as AthenaConnectionConfig, @@ -48,8 +52,7 @@ from metadata.utils.filters import filter_by_schema if TYPE_CHECKING: - from collections.abc import Callable - + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.classifier import Matcher from metadata.generated.schema.type.filterPattern import FilterPattern @@ -58,70 +61,41 @@ # databases cannot exhaust the test-connection timeout. MAX_SCHEMAS_TO_PROBE = 100 +DEFAULT_CATALOG = "AwsDataCatalog" + +# pyathena reflects through the Athena metadata API rather than SQL, so the shared +# statement capture records nothing; the reported command is the API operation. +LIST_DATABASES = "athena:ListDatabases" +LIST_TABLE_METADATA = "athena:ListTableMetadata" + def _message(error: BaseException) -> str: """The lower-cased text of the error and its cause chain.""" return " ".join(str(current) for current in exception_chain(error)).lower() -def _aws_error_code(error: BaseException) -> str | None: - """The botocore ``ClientError`` code anywhere in the cause chain. - - pyathena wraps a botocore ``ClientError`` raised by the underlying AWS call; - SQLAlchemy then wraps that, so the actionable code (``AccessDeniedException`` - and friends) only survives by walking the chain.""" - code = None - for current in exception_chain(error): - if isinstance(current, ClientError): - code = current.response.get("Error", {}).get("Code") - break - return code - - -def _aws_code(*codes: str) -> Matcher: - """Match a botocore ``ClientError`` code - the stable signal for an AWS-side - rejection, where the rendered message text varies.""" - wanted = frozenset(codes) - return lambda error: _aws_error_code(error) in wanted - - def _all_of(*tokens: str) -> Matcher: """Match when every token is present in the error's cause-chain text.""" return lambda error: all(token in _message(error) for token in tokens) +_AUTHORIZATION_CODES = frozenset({"AccessDeniedException", "AccessDenied"}) + + def _authorization_error(error: BaseException) -> bool: """An IAM authorization failure - valid credentials, missing permission. - Athena/Glue raise ``AccessDeniedException`` and STS (assume-role) raises the - suffix-less ``AccessDenied``; both are authorization codes distinct from the - authentication ones, and AWS usually renders them "... is not authorized to - perform: ...". Match either the codes or the message so a missing-privilege - error is never read as a credential problem, whatever the wording.""" - return _aws_error_code(error) in {"AccessDeniedException", "AccessDenied"} or "not authorized" in _message(error) + Athena/Glue raise ``AccessDeniedException``, STS raises ``AccessDenied``, and + AWS renders both as "... is not authorized to perform: ...". The message + fallback stands down for an authentication code, which AWS_ERRORS owns.""" + code = aws_error_code(error) + return code in _AUTHORIZATION_CODES or ( + code not in AWS_AUTHENTICATION_CODES and "not authorized" in _message(error) + ) -# Athena's transport is HTTPS to the regional AWS endpoint over botocore, so auth -# and permission failures surface as botocore ``ClientError``s matched by -# code/message, not driver errnos. The credential codes cover both the STS -# assume-role handshake (which the checks run inside CheckAccess) and the Athena -# query itself. NETWORK_ERRORS is folded in so a genuine DNS/socket failure to the -# endpoint is typed rather than left raw. +# Only what is specific to Athena; the rest comes from AWS_ERRORS. ATHENA_ERRORS = ErrorPack( - when( - _aws_code( - "UnrecognizedClientException", - "InvalidClientTokenId", - "InvalidSignatureException", - "SignatureDoesNotMatch", - "AuthFailure", - "ExpiredToken", - "ExpiredTokenException", - ) - ).diagnose( - "Authentication failed", - fix="Check the AWS credentials (access key, secret, session token, or assume-role ARN).", - ), when(_authorization_error).diagnose( "Not authorized", fix="Grant the IAM principal the required Athena and Glue permissions " @@ -136,17 +110,25 @@ def _authorization_error(error: BaseException) -> bool: fix="Set s3StagingDir to an S3 path the principal can write to, or configure a query " "result location on the workgroup.", ), + # Athena raises this before the query runs, when it cannot even reach the bucket. + when(Matchers.contains("unable to verify/create output bucket")).diagnose( + "Query result bucket not usable", + fix="Athena cannot reach the bucket in s3StagingDir. Check that it exists in awsRegion " + "and that the identity has s3:ListBucket and s3:GetBucketLocation on it.", + ), when(Matchers.contains("writing to location")).diagnose( "Cannot write query results", fix="Athena could not write results to the staging location. Grant s3:PutObject on " "s3StagingDir, and if the bucket requires encryption, use a workgroup that sets " "server-side encryption on query results.", ), + # By message, not by type: pyathena renders EndpointConnectionError into the + # SQLAlchemy error it raises, so the original type does not survive the chain. when(Matchers.contains("could not connect to the endpoint")).diagnose( "Cannot reach the AWS Athena endpoint", fix="Check that awsRegion is correct and that the Athena endpoint is reachable from where ingestion runs.", ), -).including(NETWORK_ERRORS) +).including(AWS_ERRORS) class AthenaChecks: @@ -156,31 +138,23 @@ class AthenaChecks: def __init__( self, - client_factory: Callable[[], Engine], + db: Borrowed[Engine], schema_filter_pattern: FilterPattern | None = None, catalog_id: str | None = None, ) -> None: - self._client_factory = client_factory - self._client: Engine | None = None + self._db = db self.schema_filter_pattern = schema_filter_pattern self.catalog_id = catalog_id self._targeted: list[str] | None = None - @property - def client(self) -> Engine: - """The Athena engine, built on first use - which is inside CheckAccess, the - gate. Building it runs the STS assume-role handshake (when an assumeRoleArn - is configured), so a bad credential or assume-role denial fails the gate and - is classified like any other access error, instead of raising eagerly at - provider construction - before the runner - and bypassing the gate.""" - if self._client is None: - self._client = self._client_factory() - return self._client - @property def _catalog_label(self) -> str: return f"catalog '{self.catalog_id}'" if self.catalog_id else "the default catalog (AwsDataCatalog)" + @property + def _catalog_name(self) -> str: + return self.catalog_id or DEFAULT_CATALOG + def _targeted_schemas(self) -> list[str]: """The schemas the configured schemaFilterPattern would target, mirroring what the ingestion run will read. @@ -191,7 +165,7 @@ def _targeted_schemas(self) -> list[str]: MAX_SCHEMAS_TO_PROBE so a catalog with very many databases cannot exhaust the test-connection timeout.""" if self._targeted is None: - inspector = inspect(self.client) + inspector = inspect(self._db.client) targeted: list[str] = [] for schema in inspector.get_schema_names() or []: if filter_by_schema(self.schema_filter_pattern, schema): @@ -207,11 +181,12 @@ def check_access(self) -> Evidence: # run_sql, not ping: the URL carries the AWS endpoint host:port but the # transport is HTTPS over botocore, so a raw TCP preflight to it would be # meaningless. A real reachability failure still surfaces via NETWORK_ERRORS. - return run_sql(self.client, "SELECT 1", lambda _: "connection established") + return run_sql(self._db.client, "SELECT 1", lambda _: "connection established") @check(DatabaseStep.GetSchemas) def get_schemas(self) -> Evidence: - return list_schemas(self.client) + command = f"{LIST_DATABASES} (CatalogName={self._catalog_name})" + return replace(list_schemas(self._db.client), command=command) @check(DatabaseStep.GetTables) def get_tables(self) -> Evidence: @@ -225,6 +200,7 @@ def get_tables(self) -> Evidence: if not targeted: return Evidence( summary=f"no schemas visible in {self._catalog_label}", + command=f"{LIST_DATABASES} (CatalogName={self._catalog_name})", caveat=Diagnosis( title="No schemas visible", remediation=f"No databases were listable in {self._catalog_label}. Check the login's " @@ -232,12 +208,17 @@ def get_tables(self) -> Evidence: "catalog and schemaFilterPattern are not excluding everything.", ), ) - inspector = inspect(self.client) + inspector = inspect(self._db.client) + command = f"{LIST_TABLE_METADATA} (CatalogName={self._catalog_name})" readable = any(inspector.get_table_names(schema) for schema in targeted) - result = Evidence(summary=f"tables readable across {len(targeted)} targeted schema(s) of {self._catalog_label}") + result = Evidence( + summary=f"tables readable across {len(targeted)} targeted schema(s) of {self._catalog_label}", + command=command, + ) if not readable: result = Evidence( summary=f"no readable tables across {len(targeted)} targeted schema(s) of {self._catalog_label}", + command=command, caveat=Diagnosis( title="No readable tables", remediation="No tables were readable in any targeted schema. AWS Lake Formation returns " @@ -253,10 +234,13 @@ def get_views(self) -> Evidence: # Views are frequently absent and GetViews is non-mandatory, so we probe # for visibility but never raise on an empty result. targeted = self._targeted_schemas() - inspector = inspect(self.client) + inspector = inspect(self._db.client) visible = any(inspector.get_view_names(schema) for schema in targeted) summary = "views visible" if visible else "no views visible (not required)" - return Evidence(summary=f"{summary} across {len(targeted)} targeted schema(s)") + return Evidence( + summary=f"{summary} across {len(targeted)} targeted schema(s)", + command=f"{LIST_TABLE_METADATA} (CatalogName={self._catalog_name})", + ) class AthenaConnection(BaseConnection[AthenaConnectionConfig, Engine]): @@ -304,10 +288,9 @@ def _get_client(self) -> Engine: return engine def checks(self) -> ChecksProvider: - # Pass a thunk, not self.client: deferring the build keeps the STS - # assume-role handshake out of provider construction and inside the gate. + # The borrow defers the build, keeping the STS handshake behind the gate. return AthenaChecks( - client_factory=lambda: self.client, + db=self.borrow(), schema_filter_pattern=self.service_connection.schemaFilterPattern, catalog_id=self.service_connection.catalogId, ) diff --git a/ingestion/src/metadata/ingestion/source/database/bigquery/connection.py b/ingestion/src/metadata/ingestion/source/database/bigquery/connection.py index d7db1a954636..dc72c11ce655 100644 --- a/ingestion/src/metadata/ingestion/source/database/bigquery/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/bigquery/connection.py @@ -69,8 +69,7 @@ from metadata.utils.logger import ingestion_logger if TYPE_CHECKING: - from collections.abc import Callable - + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider logger = ingestion_logger() @@ -283,44 +282,35 @@ class BigQueryChecks: happens a layer up (``BigquerySource._test_connection`` clones the connection per project and drives this provider once per clone). - The engine is built lazily on first use inside ``CheckAccess`` (never at - construction), so credential parsing - which happens while building the engine - (e.g. a malformed private key) - fails *inside the gate step* and is classified - by the error pack, instead of escaping before the runner starts. + Reading the borrowed engine is what builds it, so credential parsing (e.g. a + malformed private key) fails inside the gate step and is classified. """ errors = BIGQUERY_ERRORS def __init__( self, - get_client: Callable[[], Engine], + db: Borrowed[Engine], service_connection: BigQueryConnectionConfig, ) -> None: - self._get_client = get_client - self._client: Engine | None = None + self._db = db self.service_connection = service_connection - @property - def client(self) -> Engine: - if self._client is None: - self._client = self._get_client() - return self._client - @check(DatabaseStep.CheckAccess) def check_access(self) -> Evidence: - return ping(self.client) + return ping(self._db.client) @check(DatabaseStep.GetSchemas) def get_schemas(self) -> Evidence: - return list_schemas(self.client) + return list_schemas(self._db.client) @check(DatabaseStep.GetTables) def get_tables(self) -> Evidence: - return probe_table_view_enumeration(self.client) + return probe_table_view_enumeration(self._db.client) @check(DatabaseStep.GetViews) def get_views(self) -> Evidence: - return probe_table_view_enumeration(self.client) + return probe_table_view_enumeration(self._db.client) @check(DatabaseStep.GetTags) def get_tags(self) -> Evidence | None: @@ -332,12 +322,12 @@ def get_queries(self) -> Evidence: region=self.service_connection.usageLocation, creation_date=datetime.now().strftime("%Y-%m-%d"), ) - return run_sql(self.client, statement, lambda _: "query history accessible") + return run_sql(self._db.client, statement, lambda _: "query history accessible") def _taxonomy_project_ids(self) -> list[str]: project_ids: list[str] = [] - if self.client.url.host: - project_ids.append(self.client.url.host) + if self._db.client.url.host: + project_ids.append(self._db.client.url.host) if self.service_connection.taxonomyProjectID: project_ids.extend(self.service_connection.taxonomyProjectID) return project_ids @@ -389,6 +379,6 @@ def _get_client(self) -> Engine: def checks(self) -> ChecksProvider: return BigQueryChecks( - get_client=lambda: self.client, + db=self.borrow(), service_connection=self.service_connection, ) diff --git a/ingestion/src/metadata/ingestion/source/database/bigquery/helper.py b/ingestion/src/metadata/ingestion/source/database/bigquery/helper.py index 7199e4d77e4f..92e9457c3b36 100644 --- a/ingestion/src/metadata/ingestion/source/database/bigquery/helper.py +++ b/ingestion/src/metadata/ingestion/source/database/bigquery/helper.py @@ -92,6 +92,16 @@ def get_impersonate_client_kwargs(service_connection: BigQueryConnection) -> dic return kwargs +def get_bigquery_client_for_project(database_name: str, service_connection: BigQueryConnection): + """Build a project-scoped ``bigquery.Client`` (no engine/inspector), shared by + the inspector setup and the progress-totals dataset listing.""" + new_service_connection = clone_connection_for_project(database_name, service_connection) + kwargs = get_impersonate_client_kwargs(new_service_connection) + if new_service_connection.usageLocation: + kwargs["location"] = new_service_connection.usageLocation + return get_bigquery_client(project_id=new_service_connection.billingProjectId or database_name, **kwargs) + + def get_inspector_details(database_name: str, service_connection: BigQueryConnection) -> InspectorWrapper: """ Method to get the bigquery inspector details @@ -99,12 +109,7 @@ def get_inspector_details(database_name: str, service_connection: BigQueryConnec # TODO support location property in JSON Schema # TODO support OAuth 2.0 scopes new_service_connection = clone_connection_for_project(database_name, service_connection) - kwargs = get_impersonate_client_kwargs(new_service_connection) - - if new_service_connection.usageLocation: - kwargs["location"] = new_service_connection.usageLocation - - client = get_bigquery_client(project_id=new_service_connection.billingProjectId or database_name, **kwargs) + client = get_bigquery_client_for_project(database_name, service_connection) engine = get_connection(new_service_connection) inspector = inspect(engine) diff --git a/ingestion/src/metadata/ingestion/source/database/bigquery/metadata.py b/ingestion/src/metadata/ingestion/source/database/bigquery/metadata.py index f21a096808c0..b38e5bd3076a 100644 --- a/ingestion/src/metadata/ingestion/source/database/bigquery/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/bigquery/metadata.py @@ -71,11 +71,13 @@ from metadata.ingestion.models.life_cycle import OMetaLifeCycleData from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.connections import get_test_connection_fn from metadata.ingestion.source.database.bigquery.helper import ( clear_constraint_cache, clear_constraint_cache_for_schema, clone_connection_for_project, + get_bigquery_client_for_project, get_foreign_keys, get_inspector_details, get_pk_constraint, @@ -108,7 +110,6 @@ from metadata.ingestion.source.database.multi_db_source import MultiDBSource from metadata.utils import fqn from metadata.utils.credentials import GOOGLE_CREDENTIALS -from metadata.utils.filters import filter_by_database, filter_by_schema from metadata.utils.helpers import retry_with_docker_host from metadata.utils.logger import ingestion_logger from metadata.utils.sqlalchemy_utils import is_complex_type @@ -645,35 +646,20 @@ def _get_filtered_datasets(self, project_id: str) -> List[str]: # noqa: UP006 return [ schema_name for schema_name in self.get_raw_database_schema_names() - if not filter_by_schema( - self.source_config.schemaFilterPattern, - ( - fqn.build( - self.metadata, - entity_type=DatabaseSchema, - service_name=self.context.get().database_service, - database_name=project_id, - schema_name=schema_name, - ) - if self.source_config.useFqnForFiltering - else schema_name - ), - ) + if not self._is_schema_filtered(project_id, schema_name) ] def _get_filtered_schema_names(self, return_fqn: bool = False, add_to_status: bool = True) -> Iterable[str]: + project_id = self.context.get().database # pyright: ignore[reportAttributeAccessIssue] for schema_name in self.get_raw_database_schema_names(): schema_fqn = fqn.build( self.metadata, entity_type=DatabaseSchema, service_name=self.context.get().database_service, - database_name=self.context.get().database, + database_name=project_id, schema_name=schema_name, ) - if filter_by_schema( - self.source_config.schemaFilterPattern, - schema_fqn if self.source_config.useFqnForFiltering else schema_name, - ): + if self._is_schema_filtered(project_id, schema_name): if add_to_status: self.status.filter(schema_fqn, "Schema Filtered Out") continue @@ -821,21 +807,67 @@ def set_inspector(self, database_name: str): def get_configured_database(self) -> Optional[str]: # noqa: UP045 return None + def _raw_dataset_names(self, project_id: str) -> Iterable[str]: + """Dataset IDs for ``project_id``, context-free (does not read the walk's + current database). Honors a single configured ``databaseSchema``. Reuses the + walk's client when set, else builds a lightweight project-scoped client so + the totals hook (which runs before ``set_inspector``) can still list.""" + configured_schema = getattr(self.service_connection, "databaseSchema", None) + if configured_schema: + yield configured_schema + else: + client = self.client or get_bigquery_client_for_project(project_id, self.service_connection) + for dataset in client.list_datasets(project_id): # pyright: ignore[reportAttributeAccessIssue] + yield dataset.dataset_id + + def _kept_schema_counts(self, project_ids: List[str]) -> Optional[Dict[str, int]]: # noqa: UP006,UP045 + """Post-filter dataset count per project from ``list_datasets``. Returns + ``None`` when any project's listing fails, so the caller reconciles the + schema total instead of seeding partial scopes.""" + counts: Dict[str, int] = {} # noqa: UP006 + try: + for project_id in project_ids: + counts[project_id] = sum( + 1 + for dataset in self._raw_dataset_names(project_id) + if not self._is_schema_filtered(project_id, dataset) + ) + except Exception as exc: # pylint: disable=broad-except + logger.warning( + "BigQuery dataset listing failed (%s); progress schema total will reconcile during the walk.", + exc, + ) + return None + return counts + + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Seed the run-level ``Database`` (filtered project count) and per-project + ``DatabaseSchema`` (filtered dataset count) counters upfront. When dataset + listing fails for any project, mark the schema counter reconcilable so the + walk fills its total instead.""" + filtered_projects = [ + project_id for project_id in self.project_ids if not self._is_database_filtered(project_id) + ] + totals.set_total(Database.__name__, len(filtered_projects)) + kept_by_project = self._kept_schema_counts(filtered_projects) + if kept_by_project is None: + totals.mark_reconcilable(DatabaseSchema.__name__) + else: + for project_id, count in kept_by_project.items(): + totals.seed_scope_total(DatabaseSchema.__name__, project_id, count) + def get_database_names_raw(self) -> Iterable[str]: yield from self.project_ids def get_database_names(self) -> Iterable[str]: for project_id in self.project_ids: - database_fqn = fqn.build( - self.metadata, - entity_type=Database, - service_name=self.context.get().database_service, - database_name=project_id, - ) - if filter_by_database( - self.source_config.databaseFilterPattern, - database_fqn if self.source_config.useFqnForFiltering else project_id, - ): + if self._is_database_filtered(project_id): + database_fqn = fqn.build( + self.metadata, + entity_type=Database, + service_name=self.context.get().database_service, # pyright: ignore[reportAttributeAccessIssue] + database_name=project_id, + ) self.status.filter(database_fqn, "Database Filtered out") else: try: diff --git a/ingestion/src/metadata/ingestion/source/database/burstiq/connection.py b/ingestion/src/metadata/ingestion/source/database/burstiq/connection.py index 777f29d2b4ef..3faba94c9262 100644 --- a/ingestion/src/metadata/ingestion/source/database/burstiq/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/burstiq/connection.py @@ -13,7 +13,9 @@ """ import hashlib -from typing import Dict, Optional # noqa: UP035 +from typing import Optional + +from cachetools import LRUCache from metadata.generated.schema.entity.automations.workflow import ( Workflow as AutomationWorkflow, @@ -33,29 +35,21 @@ logger = ingestion_logger() -_CLIENT_CACHE: Dict[str, BurstIQClient] = {} # noqa: UP006 - - -def get_connection(connection: BurstIQConnectionConfig) -> BurstIQClient: - """ - Create or return a cached BurstIQ client connection. +CLIENT_CACHE_SIZE = 100 - Caching avoids re-authentication on every table during profiler ingestion, - where SamplerInterface.__init__ calls get_ssl_connection once per table. - Using id(connection) was unreliable because each table deserialization - produces a new object with a different id. A SHA-256 digest of the - serialised config is used as the key: collision-resistant but never - stores plaintext credentials in the cache keys. - """ - key = hashlib.sha256(connection.model_dump_json().encode()).hexdigest() - if key not in _CLIENT_CACHE: - _CLIENT_CACHE[key] = BurstIQClient(config=connection) - return _CLIENT_CACHE[key] +_CLIENT_CACHE: "LRUCache[str, BurstIQClient]" = LRUCache(maxsize=CLIENT_CACHE_SIZE) class BurstIQConnection(BaseConnection[BurstIQConnectionConfig, BurstIQClient]): def _get_client(self) -> BurstIQClient: - return get_connection(self.service_connection) + """Return a BurstIQ client, cached by a digest of the serialised config.""" + connection = self.service_connection + key = hashlib.sha256(connection.model_dump_json().encode()).hexdigest() + client = _CLIENT_CACHE.get(key) + if client is None: + client = BurstIQClient(config=connection) + _CLIENT_CACHE[key] = client + return client def test_connection( self, @@ -63,20 +57,7 @@ def test_connection( automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 ) -> TestConnectionResult: - """ - Test connection to BurstIQ. This can be executed either as part - of a metadata workflow or during an Automation Workflow - - Args: - metadata: OpenMetadata client - client: BurstIQClient instance - service_connection: BurstIQConnection configuration - automation_workflow: Optional automation workflow - timeout_seconds: Timeout for connection test - - Returns: - TestConnectionResult - """ + """Test connection to BurstIQ, as a metadata workflow or an Automation Workflow.""" client = self.client service_connection = self.service_connection diff --git a/ingestion/src/metadata/ingestion/source/database/burstiq/metadata.py b/ingestion/src/metadata/ingestion/source/database/burstiq/metadata.py index e76580f6b2a1..343f1742e2fa 100644 --- a/ingestion/src/metadata/ingestion/source/database/burstiq/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/burstiq/metadata.py @@ -13,7 +13,7 @@ """ import traceback -from typing import Any, Iterable, List, Optional, Tuple # noqa: UP035 +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, cast # noqa: UP035 from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createDatabaseSchema import ( @@ -57,14 +57,17 @@ from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.database.burstiq.client import BurstIQClient -from metadata.ingestion.source.database.burstiq.connection import get_connection +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.burstiq.models import BurstIQDictionary from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.utils import fqn from metadata.utils.filters import filter_by_table from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from metadata.ingestion.connections.connection import BaseConnection + from metadata.ingestion.source.database.burstiq.client import BurstIQClient + logger = ingestion_logger() @@ -80,12 +83,15 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata): self.metadata = metadata self.source_config: DatabaseServiceMetadataPipeline = self.config.sourceConfig.config self.service_connection: BurstIQConnection = self.config.serviceConnection.root.config - self.client: Optional[BurstIQClient] = None # noqa: UP045 self._current_dictionary: Optional[BurstIQDictionary] = None # noqa: UP045 - # Initialize connection and test it - self.connection_obj = self._get_client() - self.test_connection() + self._connection = create_connection(self.service_connection) + self.client: BurstIQClient = cast("BaseConnection", self._connection).client + try: + self.test_connection() + except Exception: + self.close() + raise @classmethod def create( @@ -100,12 +106,6 @@ def create( raise InvalidSourceException(f"Expected BurstIQConnection, but got {connection}") return cls(config, metadata) - def _get_client(self) -> BurstIQClient: - """Get or create BurstIQ client""" - if self.client is None: - self.client = get_connection(self.service_connection) - return self.client - def _get_current_dictionary(self, table_name: str) -> Optional[BurstIQDictionary]: # noqa: UP045 """ Get the currently cached dictionary for the given table name @@ -121,7 +121,7 @@ def _get_current_dictionary(self, table_name: str) -> Optional[BurstIQDictionary # If not cached or doesn't match, fetch from API logger.warning(f"Dictionary for table '{table_name}' not in cache, fetching from API...") - client = self._get_client() + client = self.client return client.get_dictionary_by_name(table_name) def get_database_names(self) -> Iterable[str]: @@ -188,8 +188,7 @@ def get_tables_name_and_type(self) -> Optional[Iterable[Tuple[str, str]]]: # no schema_name = self.context.get().database_schema try: if self.source_config.includeTables: - # Get BurstIQ client - client = self._get_client() + client = self.client # Fetch and iterate dictionaries directly logger.info("Fetching dictionaries from BurstIQ LifeGraph...") @@ -499,11 +498,5 @@ def yield_tag(self, schema_name: str) -> Iterable[Either[OMetaTagAndClassificati return [] def close(self): - """ - Clean up resources - """ - # Clear cached dictionary self._current_dictionary = None - # Close client if needed (currently no cleanup required for requests.Session) - if self.client: - self.client = None + super().close() diff --git a/ingestion/src/metadata/ingestion/source/database/common_db_source.py b/ingestion/src/metadata/ingestion/source/database/common_db_source.py index 69f670c338b7..b72683b192b9 100644 --- a/ingestion/src/metadata/ingestion/source/database/common_db_source.py +++ b/ingestion/src/metadata/ingestion/source/database/common_db_source.py @@ -62,7 +62,7 @@ from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.models.patch_request import PatchedEntity, PatchRequest from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection +from metadata.ingestion.source.connections import create_connection, get_connection from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.ingestion.source.database.sql_column_handler import SqlColumnHandlerMixin from metadata.ingestion.source.database.sqlalchemy_source import SqlAlchemySource @@ -119,15 +119,21 @@ def __init__( if self.ssl_manager: self.service_connection = self.ssl_manager.setup_ssl(self.service_connection) - self.engine: Engine = get_connection(self.service_connection) + self._connection_map = {} # Lazy init as well + self._inspector_map = {} + + self._connection = create_connection(self.service_connection) + self.engine: Engine = self._connection.client if self._connection else get_connection(self.service_connection) self.session = create_and_bind_thread_safe_session(self.engine) # Flag the connection for the test connection self.connection_obj = self.engine - self.test_connection() + try: + self.test_connection() + except Exception: + self.close() + raise - self._connection_map = {} # Lazy init as well - self._inspector_map = {} self.table_constraints = None self.database_source_state = set() self.context.get_global().table_constrains = [] @@ -147,7 +153,8 @@ def set_inspector(self, database_name: str) -> None: new_service_connection = deepcopy(self.service_connection) new_service_connection.database = database_name - self.engine = get_connection(new_service_connection) + self._connection = create_connection(new_service_connection) + self.engine = self._connection.client if self._connection else get_connection(new_service_connection) self.session = create_and_bind_thread_safe_session(self.engine) self.connection_obj = self.engine @@ -178,6 +185,9 @@ def _release_engine(self) -> None: logger.error(f"Failed to dispose engine: {exc}") self.engine = None self.connection_obj = None + if self._connection is not None: + self._connection.close() + self._connection = None def get_database_names(self) -> Iterable[str]: """ diff --git a/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py b/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py index b5fb1945405d..24596c0b9c42 100644 --- a/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py +++ b/ingestion/src/metadata/ingestion/source/database/common_nosql_source.py @@ -47,7 +47,7 @@ from metadata.ingestion.api.models import Either from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection +from metadata.ingestion.source.connections import create_connection, get_connection from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.ingestion.source.database.stored_procedures_mixin import QueryByProcedure from metadata.utils import fqn @@ -90,9 +90,14 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata): self.ssl_manager = check_ssl_and_init(self.service_connection) if self.ssl_manager: self.service_connection = self.ssl_manager.setup_ssl(self.service_connection) - self.connection_obj = get_connection(self.service_connection) + self._connection = create_connection(self.service_connection) + self.connection_obj = self._connection.client if self._connection else get_connection(self.service_connection) - self.test_connection() + try: + self.test_connection() + except Exception: + self.close() + raise def prepare(self): """ @@ -332,6 +337,5 @@ def get_source_url( """ def close(self): - """ - By default there is nothing to close - """ + if self._connection is not None: + self._connection.close() diff --git a/ingestion/src/metadata/ingestion/source/database/database_service.py b/ingestion/src/metadata/ingestion/source/database/database_service.py index d0eca676d247..09bfa47d4e8d 100644 --- a/ingestion/src/metadata/ingestion/source/database/database_service.py +++ b/ingestion/src/metadata/ingestion/source/database/database_service.py @@ -59,6 +59,7 @@ from metadata.ingestion.api.models import Either from metadata.ingestion.api.steps import Source from metadata.ingestion.api.topology_runner import TopologyRunnerMixin +from metadata.ingestion.connections.connection import BaseConnection from metadata.ingestion.models.life_cycle import OMetaLifeCycleData from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.models.topology import ( @@ -68,9 +69,9 @@ TopologyNode, ) from metadata.ingestion.ometa.utils import model_str -from metadata.ingestion.source.connections import test_connection_common +from metadata.ingestion.source.connections import run_test_connection, test_connection_common from metadata.utils import fqn -from metadata.utils.filters import filter_by_schema, filter_by_stored_procedure +from metadata.utils.filters import filter_by_database, filter_by_schema, filter_by_stored_procedure from metadata.utils.logger import ingestion_logger from metadata.utils.owner_utils import get_owner_from_config from metadata.utils.tag_utils import get_tag_label @@ -216,6 +217,10 @@ class DatabaseServiceSource(TopologyRunnerMixin, Source, ABC): # pylint: disabl # When processing the database, the source will update the inspector if needed inspector: Inspector + # Set by sources that own their connection lifecycle; `None` keeps the + # legacy `connection_obj` test path for non-migrated sources. + _connection: Optional[BaseConnection] = None # noqa: UP045 + topology = DatabaseServiceTopology() context = TopologyContextManager(topology) @@ -572,6 +577,32 @@ def _get_filtered_schema_names(self, return_fqn: bool = False, add_to_status: bo continue yield schema_fqn if return_fqn else schema_name + def _is_database_filtered(self, database_name: str) -> bool: + """Whether a database fails ``databaseFilterPattern``. Pure predicate — no + status side effects — so the totals hook and the walk can share it.""" + database_fqn = fqn.build( + self.metadata, + entity_type=Database, + service_name=self.context.get().database_service, + database_name=database_name, + ) + filter_name = database_fqn if self.source_config.useFqnForFiltering and database_fqn else database_name + return filter_by_database(self.source_config.databaseFilterPattern, filter_name) + + def _is_schema_filtered(self, database_name: str, schema_name: str) -> bool: + """Whether a schema fails ``schemaFilterPattern``, matched the same way as the + walk (FQN or bare name per ``useFqnForFiltering``). Context-free: the FQN is + built from the explicit database name.""" + schema_fqn = fqn.build( + self.metadata, + entity_type=DatabaseSchema, + service_name=self.context.get().database_service, # pyright: ignore[reportAttributeAccessIssue] + database_name=database_name, + schema_name=schema_name, + ) + filter_name = schema_fqn if self.source_config.useFqnForFiltering and schema_fqn else schema_name + return filter_by_schema(self.source_config.schemaFilterPattern, filter_name) + def is_stored_procedure_filtered(self, stored_procedure_name: str) -> bool: """ Check if a stored procedure should be filtered based on the filter pattern. @@ -579,7 +610,7 @@ def is_stored_procedure_filtered(self, stored_procedure_name: str) -> bool: stored_procedure_fqn = fqn.build( self.metadata, entity_type=StoredProcedure, - service_name=self.context.get().database_service, + service_name=self.context.get().database_service, # pyright: ignore[reportAttributeAccessIssue] database_name=self.context.get().database, schema_name=self.context.get().database_schema, procedure_name=stored_procedure_name, @@ -867,4 +898,12 @@ def yield_table_constraints(self) -> Iterable[Either[AddLineageRequest]]: """ def test_connection(self) -> None: - test_connection_common(self.metadata, self.connection_obj, self.service_connection) + if self._connection is not None: + run_test_connection(self.metadata, self._connection) + else: + test_connection_common(self.metadata, self.connection_obj, self.service_connection) + + def close(self) -> None: + if self._connection is not None: + self._connection.close() + self._connection = None diff --git a/ingestion/src/metadata/ingestion/source/database/databricks/auth.py b/ingestion/src/metadata/ingestion/source/database/databricks/auth.py index fcef05baa107..d3d0c10bf1c5 100644 --- a/ingestion/src/metadata/ingestion/source/database/databricks/auth.py +++ b/ingestion/src/metadata/ingestion/source/database/databricks/auth.py @@ -34,6 +34,15 @@ ) +def normalize_host_port(host_port: str) -> str: + """Strip a pasted URL scheme and path, leaving ``host:port``.""" + return host_port.split("://", 1)[-1].split("/", 1)[0] + + +def _host(connection: Union[DatabricksConnection, UnityCatalogConnection]) -> str: # noqa: UP007 + return normalize_host_port(connection.hostPort).split(":")[0] + + def get_personal_access_token_auth( connection: Union[DatabricksConnection, UnityCatalogConnection], # noqa: UP007 ) -> dict: @@ -51,7 +60,7 @@ def get_databricks_oauth_auth( """ def credential_provider(): - hostname = connection.hostPort.split(":")[0] + hostname = _host(connection) config = Config( host=f"https://{hostname}", client_id=connection.authType.clientId, @@ -68,7 +77,7 @@ def get_azure_ad_auth(connection: Union[DatabricksConnection, UnityCatalogConnec """ def credential_provider(): - hostname = connection.hostPort.split(":")[0] + hostname = _host(connection) config = Config( host=f"https://{hostname}", azure_client_secret=connection.authType.azureClientSecret.get_secret_value(), diff --git a/ingestion/src/metadata/ingestion/source/database/databricks/connection.py b/ingestion/src/metadata/ingestion/source/database/databricks/connection.py index 3264f98f85ea..929e49081272 100644 --- a/ingestion/src/metadata/ingestion/source/database/databricks/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/databricks/connection.py @@ -13,24 +13,40 @@ Source connection handler """ +from __future__ import annotations + from copy import deepcopy -from functools import partial -from typing import Optional +from typing import TYPE_CHECKING, Optional from urllib.parse import quote_plus from sqlalchemy import text from sqlalchemy.engine import Engine -from sqlalchemy.exc import DatabaseError from sqlalchemy.inspection import inspect -from metadata.generated.schema.entity.automations.workflow import ( - Workflow as AutomationWorkflow, +from metadata.core.connections.test_connection import ( + ErrorPack, + Evidence, + Matchers, + check, + when, +) +from metadata.core.connections.test_connection.check import CheckError +from metadata.core.connections.test_connection.checks.database import ( + DEFAULT_SAMPLE_ROWS, + DatabaseStep, + run_sql, +) +from metadata.core.connections.test_connection.constants import STEP_TIMEOUT_SECONDS +from metadata.core.connections.test_connection.network import ( + NETWORK_ERRORS, + NetworkUnreachableError, + tcp_probe, ) from metadata.generated.schema.entity.services.connections.database.databricksConnection import ( DatabricksConnection as DatabricksConnectionConfig, ) -from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - TestConnectionResult, +from metadata.generated.schema.entity.services.connections.database.unityCatalogConnection import ( + UnityCatalogConnection as UnityCatalogConnectionConfig, ) from metadata.ingestion.connections.builders import ( create_generic_db_connection, @@ -38,12 +54,11 @@ init_empty_connection_arguments, ) from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.connections.test_connections import ( - test_connection_engine_step, - test_connection_steps, +from metadata.ingestion.source.database.databricks.auth import ( + get_auth_config, + normalize_host_port, ) -from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.database.databricks.auth import get_auth_config +from metadata.ingestion.source.database.databricks.client import DatabricksClient from metadata.ingestion.source.database.databricks.log_filters import ( suppress_user_agent_entry_deprecation_log, ) @@ -58,44 +73,137 @@ TEST_TABLE_TAGS, TEST_VIEW_DEFINITIONS, ) -from metadata.utils.constants import THREE_MIN from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from metadata.core.connections.lifetime import Borrowed + from metadata.core.connections.test_connection import ChecksProvider + logger = ingestion_logger() suppress_user_agent_entry_deprecation_log() +# Databricks dials the workspace over HTTPS; the gate TCP-probes this port. +DEFAULT_DATABRICKS_PORT = 443 + +DEFAULT_CATALOG = "main" + +SYSTEM_SCHEMAS = frozenset({"information_schema", "performance_schema", "sys"}) + + +# databricks-sql/thrift reports failures as message tokens, not numeric codes, so +# rules key on tokens; specific ones precede broad ones (first match wins). +DATABRICKS_ERRORS = ErrorPack( + when(Matchers.contains("invalid access token")).diagnose( + "Authentication failed", + fix="Check the access token - the workspace rejected it. Verify the token is valid, " + "not expired, and belongs to a user with access to this workspace.", + ), + when(Matchers.contains("token is expired")).diagnose( + "Access token expired", + fix="The access token has expired. Generate a new token and update the connection.", + ), + when(Matchers.contains("forbidden")).diagnose( + "Access denied", + fix="The workspace returned 403 Forbidden. Verify the token's user is entitled to the " + "workspace and the configured HTTP path / SQL warehouse.", + ), + when(Matchers.contains("malformed_request")).diagnose( + "Invalid HTTP path", + fix="The HTTP Path is malformed. Copy it from the SQL warehouse (or cluster) Connection " + "Details in Databricks - it must look like /sql/1.0/warehouses/ or " + "/sql/1.0/endpoints/.", + ), + when(Matchers.contains("no_such_catalog")).diagnose( + "Catalog not found", + fix="The configured catalog does not exist or is not visible to the token's user. Verify " + "the catalog name and that the user has USE CATALOG on it.", + ), + when(Matchers.contains("no_such_schema")).diagnose( + "Schema not found", + fix="The configured schema does not exist or is not visible. Verify the schema name and " + "that the user has USE SCHEMA on it.", + ), + when(Matchers.contains("table_or_view_not_found")).diagnose( + "Table or view not found", + fix="The referenced table or view does not exist or is not visible to the token's user. " + "Verify the object exists and the user has SELECT on it.", + ), + when(Matchers.contains("schema_not_found")).diagnose( + "Schema not found", + fix="The referenced schema does not exist or is not visible. Verify the schema name and " + "that the user has USAGE on it.", + ), + when(Matchers.contains("permission_denied")).diagnose( + "Insufficient privileges", + fix="Grant the token's user the privileges the failing step needs (USAGE on the catalog / " + "schema and SELECT on the system or information_schema tables it reads).", + ), + when(Matchers.contains("insufficient_permissions")).diagnose( + "Insufficient privileges", + fix="Grant the token's user the privileges the failing step needs (USAGE on the catalog / " + "schema and SELECT on the system or information_schema tables it reads).", + ), + when(Matchers.contains("does not exist")).diagnose( + "Object not found", + fix="Verify the configured catalog, schema, and HTTP path exist and the token's user is " + "authorized to use them.", + ), +).including(NETWORK_ERRORS) + + +def _summarize(rows: Sequence[object], noun: str) -> str: + """``N s enumerated`` (``N+`` at the cap) or ``no s enumerated``.""" + count = len(rows) + if not count: + return f"no {noun}s enumerated" + suffix = "+" if count >= DEFAULT_SAMPLE_ROWS else "" + plural = noun if count == 1 else f"{noun}s" + return f"{count}{suffix} {plural} enumerated" + class DatabricksEngineWrapper: - """Wrapper to store engine and schemas to avoid multiple calls""" + """Wraps the borrowed engine, caching the resolved catalog and schema. Lookups + are lazy, so constructing it touches no network and stays behind the gate.""" - def __init__(self, engine: Engine): - self.engine = engine - self.inspector = inspect(engine) + def __init__(self, db: Borrowed[Engine]): + self._db = db + self._inspector = None self.schemas = None self.first_schema = None self.first_catalog = None + @property + def engine(self) -> Engine: + return self._db.client + + @property + def inspector(self): + # Lazy, never at construction: inspect(engine) connects eagerly (the + # dialect's _init_engine runs engine.connect().close()), which would + # bypass the CheckAccess gate. + if self._inspector is None: + self._inspector = inspect(self.engine) + return self._inspector + def get_schemas(self, schema_name: Optional[str] = None): # noqa: UP045 """Get schemas and cache them""" if schema_name is not None: - with self.engine.connect() as connection: - connection.execute(text(f"USE CATALOG `{self.first_catalog}`")) + if self.first_catalog: + with self.engine.connect() as connection: + connection.execute(text(f"USE CATALOG `{self.first_catalog}`")) self.first_schema = schema_name return [schema_name] if self.schemas is None: - self.schemas = self.inspector.get_schema_names(database=self.first_catalog) + # Bound the reflected list (no driver-side cap) to the sample size. + self.schemas = self.inspector.get_schema_names(database=self.first_catalog)[:DEFAULT_SAMPLE_ROWS] if self.schemas: - # Find the first schema that's not a system schema for schema in self.schemas: - if schema.lower() not in ( - "information_schema", - "performance_schema", - "sys", - ): + if schema.lower() not in SYSTEM_SCHEMAS: self.first_schema = schema break - # If no non-system schema found, use the first one if self.first_schema is None and self.schemas: self.first_schema = self.schemas[0] return self.schemas @@ -103,41 +211,40 @@ def get_schemas(self, schema_name: Optional[str] = None): # noqa: UP045 def get_tables(self): """Get tables using the cached first schema""" if self.first_schema is None: - self.get_schemas() # This will set first_schema - if self.first_schema: + self.get_schemas() + if self.first_catalog and self.first_schema: with self.engine.connect() as connection: tables = connection.execute(text(f"SHOW TABLES IN `{self.first_catalog}`.`{self.first_schema}`")) - return tables # noqa: RET504 + return tables.fetchmany(DEFAULT_SAMPLE_ROWS) return [] def get_views(self): """Get views using the cached first schema""" if self.first_schema is None: - self.get_schemas() # This will set first_schema - if self.first_schema: + self.get_schemas() + if self.first_catalog and self.first_schema: with self.engine.connect() as connection: views = connection.execute(text(f"SHOW VIEWS IN `{self.first_catalog}`.`{self.first_schema}`")) - return views # noqa: RET504 + return views.fetchmany(DEFAULT_SAMPLE_ROWS) return [] def get_catalogs(self, catalog_name: Optional[str] = None): # noqa: UP045 """Get catalogs""" - catalogs = [] if catalog_name is not None: self.first_catalog = catalog_name return [catalog_name] with self.engine.connect() as connection: - catalogs = connection.execute(text(DATABRICKS_GET_CATALOGS)).fetchall() - for catalog in catalogs: - if catalog[0] != "__databricks_internal": - self.first_catalog = catalog[0] - break + catalogs = connection.execute(text(DATABRICKS_GET_CATALOGS)).fetchmany(DEFAULT_SAMPLE_ROWS) + for catalog in catalogs: + if catalog[0] != "__databricks_internal": + self.first_catalog = catalog[0] + break return catalogs def get_connection_url(connection: DatabricksConnectionConfig) -> str: scheme = connection.scheme.value if connection.scheme else "databricks" - url = f"{scheme}://{connection.hostPort}" + url = f"{scheme}://{normalize_host_port(connection.hostPort)}" if connection.catalog: url = f"{url}?catalog={quote_plus(connection.catalog)}" return url @@ -170,95 +277,149 @@ def get_connection(connection: DatabricksConnectionConfig) -> Engine: return engine +class DatabricksChecks: + """Test-connection checks for Databricks. Catalog/schema listing goes through + ``DatabricksEngineWrapper``; every statement is built inside its ``@check`` so + nothing connects before the gate.""" + + errors = DATABRICKS_ERRORS + + def __init__(self, db: Borrowed[Engine], service_connection: DatabricksConnectionConfig) -> None: + self._db = db + self.service_connection = service_connection + self._engine_wrapper = DatabricksEngineWrapper(db) + + def _first_catalog(self) -> str: + """Resolve and cache the catalog to scope tag probes to.""" + if self._engine_wrapper.first_catalog is None: + self._engine_wrapper.get_catalogs(catalog_name=self.service_connection.catalog) + return self._engine_wrapper.first_catalog or self.service_connection.catalog or DEFAULT_CATALOG + + def _probe_target(self) -> tuple[str, int]: + host_port = normalize_host_port(self.service_connection.hostPort) + host, _, port = host_port.rpartition(":") + if host and port.isdigit(): + return host, int(port) + return host_port, DEFAULT_DATABRICKS_PORT + + def _list(self, operation: Callable[[], Sequence[object] | None], command: str | None, noun: str) -> Evidence: + """Run a wrapper listing op, reporting the command and a row-count summary; + on failure re-raise as ``CheckError`` carrying the attempted command.""" + try: + rows = operation() + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + rows = list(rows) if rows is not None else [] + return Evidence(summary=_summarize(rows, noun), command=command) + + @check(DatabaseStep.CheckAccess) + def check_access(self) -> Evidence: + host, port = self._probe_target() + try: + tcp_probe(host, port) + except NetworkUnreachableError as error: + raise CheckError(error, Evidence(command=f"TCP connect {host}:{port}")) from error + return run_sql(self._db.client, "SELECT 1", lambda _: "connection established") + + @check(DatabaseStep.GetDatabases) + def get_databases(self) -> Evidence: + # A configured catalog is trusted without querying, so no SHOW CATALOGS runs. + configured = self.service_connection.catalog + command = None if configured else DATABRICKS_GET_CATALOGS + return self._list( + lambda: self._engine_wrapper.get_catalogs(catalog_name=configured), + command, + "catalog", + ) + + @check(DatabaseStep.GetSchemas) + def get_schemas(self) -> Evidence: + return self._list( + lambda: self._engine_wrapper.get_schemas(schema_name=self.service_connection.databaseSchema), + "SHOW SCHEMAS", + "schema", + ) + + @check(DatabaseStep.GetTables) + def get_tables(self) -> Evidence: + return self._list(self._engine_wrapper.get_tables, "SHOW TABLES", "table") + + @check(DatabaseStep.GetViews) + def get_views(self) -> Evidence: + return self._list(self._engine_wrapper.get_views, "SHOW VIEWS", "view") + + @check(DatabaseStep.GetQueries) + def get_queries(self) -> Evidence: + statement = DATABRICKS_SQL_STATEMENT_TEST.format(query_history=self.service_connection.queryHistoryTable) + return run_sql(self._db.client, statement, lambda _: "query history accessible") + + @check(DatabaseStep.GetViewDefinitions) + def get_view_definitions(self) -> Evidence: + return run_sql(self._db.client, TEST_VIEW_DEFINITIONS, lambda _: "view definitions accessible") + + @check(DatabaseStep.GetCatalogTags) + def get_catalog_tags(self) -> Evidence: + statement = TEST_CATALOG_TAGS.format(database_name=self._first_catalog()) + return run_sql(self._db.client, statement, lambda _: "catalog tags accessible") + + @check(DatabaseStep.GetSchemaTags) + def get_schema_tags(self) -> Evidence: + statement = TEST_SCHEMA_TAGS.format(database_name=self._first_catalog()) + return run_sql(self._db.client, statement, lambda _: "schema tags accessible") + + @check(DatabaseStep.GetTableTags) + def get_table_tags(self) -> Evidence: + statement = TEST_TABLE_TAGS.format(database_name=self._first_catalog()) + return run_sql(self._db.client, statement, lambda _: "table tags accessible") + + @check(DatabaseStep.GetColumnTags) + def get_column_tags(self) -> Evidence: + statement = TEST_COLUMN_TAGS.format(database_name=self._first_catalog()) + return run_sql(self._db.client, statement, lambda _: "column tags accessible") + + @check(DatabaseStep.GetTableLineage) + def get_table_lineage(self) -> Evidence: + return run_sql(self._db.client, TEST_TABLE_LINEAGE, lambda _: "table lineage accessible") + + @check(DatabaseStep.GetColumnLineage) + def get_column_lineage(self) -> Evidence: + return run_sql(self._db.client, TEST_COLUMN_LINEAGE, lambda _: "column lineage accessible") + + +class DatabricksApiConnection( + BaseConnection[DatabricksConnectionConfig | UnityCatalogConnectionConfig, DatabricksClient] +): + """Owns the Databricks REST client (Jobs, query-history, and lineage APIs): + a separate lifetime from the SQL engine, shared by the databricks and Unity + Catalog sources.""" + + def _get_client(self) -> DatabricksClient: + # No pooled resource to close: uses the ``requests`` module, not a Session. + return DatabricksClient(self.service_connection) + + class DatabricksConnection(BaseConnection[DatabricksConnectionConfig, Engine]): + def __init__(self, service_connection: DatabricksConnectionConfig) -> None: + super().__init__(service_connection) + # Honor the user-facing connectionTimeout (default 120s) as the per-step + # budget; a cold serverless warehouse can exceed the 60s framework default. + self.step_timeout_seconds = service_connection.connectionTimeout or STEP_TIMEOUT_SECONDS + # A sub-owner, not a client: constructing it opens nothing. + self.api = DatabricksApiConnection(service_connection) + def _get_client(self) -> Engine: - return get_connection(self.service_connection) - - def test_connection( - self, - metadata: OpenMetadata, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 - ) -> TestConnectionResult: - """ - Test connection. This can be executed either as part - of a metadata workflow or during an Automation Workflow - """ - connection = self.client - service_connection = self.service_connection - - def test_database_query(engine: Engine, statement: str): - """ - Method used to execute the given query and fetch a result - to test if user has access to the tables specified - in the sql statement - """ - try: - connection = engine.connect() - connection.execute(text(statement)).fetchone() - except DatabaseError as soe: - logger.debug(f"Failed to fetch catalogs due to: {soe}") - - # Create wrapper to avoid multiple schema calls - engine_wrapper = DatabricksEngineWrapper(connection) - - # Helper function to get first catalog for tag queries - def get_first_catalog(): - catalogs = engine_wrapper.get_catalogs(catalog_name=service_connection.catalog) - return catalogs[0] if catalogs else service_connection.catalog or "main" - - test_fn = { - "CheckAccess": partial(test_connection_engine_step, connection), - "GetSchemas": partial(engine_wrapper.get_schemas, schema_name=service_connection.databaseSchema), - "GetTables": engine_wrapper.get_tables, - "GetViews": engine_wrapper.get_views, - "GetDatabases": partial(engine_wrapper.get_catalogs, catalog_name=service_connection.catalog), - "GetQueries": partial( - test_database_query, - engine=connection, - statement=DATABRICKS_SQL_STATEMENT_TEST.format(query_history=service_connection.queryHistoryTable), - ), - "GetViewDefinitions": partial( - test_database_query, - engine=connection, - statement=TEST_VIEW_DEFINITIONS, - ), - "GetCatalogTags": partial( - test_database_query, - engine=connection, - statement=TEST_CATALOG_TAGS.format(database_name=get_first_catalog()), - ), - "GetSchemaTags": partial( - test_database_query, - engine=connection, - statement=TEST_SCHEMA_TAGS.format(database_name=get_first_catalog()), - ), - "GetTableTags": partial( - test_database_query, - engine=connection, - statement=TEST_TABLE_TAGS.format(database_name=get_first_catalog()), - ), - "GetColumnTags": partial( - test_database_query, - engine=connection, - statement=TEST_COLUMN_TAGS.format(database_name=get_first_catalog()), - ), - "GetTableLineage": partial( - test_database_query, - engine=connection, - statement=TEST_TABLE_LINEAGE, - ), - "GetColumnLineage": partial( - test_database_query, - engine=connection, - statement=TEST_COLUMN_LINEAGE, - ), - } - - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=service_connection.type.value, # pyright: ignore[reportOptionalMemberAccess] - automation_workflow=automation_workflow, - timeout_seconds=service_connection.connectionTimeout or timeout_seconds, + engine = get_connection(self.service_connection) + self._on_close(engine.dispose) + return engine + + def close(self) -> None: + # Not _on_close: that registry is reset by close(), so a sub-owner + # registered once would not be released on a later reuse cycle. + self.api.close() + super().close() + + def checks(self) -> ChecksProvider: + return DatabricksChecks( + db=self.borrow(), + service_connection=self.service_connection, ) diff --git a/ingestion/src/metadata/ingestion/source/database/databricks/metadata.py b/ingestion/src/metadata/ingestion/source/database/databricks/metadata.py index 95997b0ea527..0e90069b7f4a 100644 --- a/ingestion/src/metadata/ingestion/source/database/databricks/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/databricks/metadata.py @@ -14,7 +14,7 @@ import re import traceback from copy import deepcopy -from typing import Any, Iterable, Optional, Tuple, Union # noqa: UP035 +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union, cast # noqa: UP035 from sqlalchemy import exc, text, types, util from sqlalchemy.engine import Connection, reflection @@ -42,13 +42,13 @@ from metadata.ingestion.connections.session import create_and_bind_thread_safe_session from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.connections import get_connection from metadata.ingestion.source.database.column_type_parser import create_sqlalchemy_type from metadata.ingestion.source.database.common_db_source import ( CommonDbSourceService, TableNameAndType, ) -from metadata.ingestion.source.database.databricks.client import DatabricksClient from metadata.ingestion.source.database.databricks.models import ( ColumnDescriptions, DescribeJsonPayload, @@ -61,6 +61,7 @@ ) from metadata.ingestion.source.database.databricks.queries import ( DATABRICKS_DDL, + DATABRICKS_GET_ALL_SCHEMAS, DATABRICKS_GET_CATALOGS, DATABRICKS_GET_CATALOGS_TAGS, DATABRICKS_GET_COLUMN_TAGS, @@ -90,6 +91,12 @@ ) from metadata.utils.tag_utils import get_ometa_tag_and_classification +if TYPE_CHECKING: + from metadata.ingestion.source.database.databricks.connection import ( + DatabricksConnection as DatabricksConnectionHandler, + ) + + logger = ingestion_logger() DATABRICKS_TAG = "DATABRICKS TAG" @@ -846,7 +853,7 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata): self.table_tags = {} self.external_location_map = {} self.column_tags = {} - self.api_client = DatabricksClient(self.service_connection) + self.api_client = cast("DatabricksConnectionHandler", self._connection).api.client self.owner_resolver = DatabricksOwnerResolver( api_client=self.api_client, metadata=self.metadata, @@ -1327,3 +1334,60 @@ def get_owner_ref(self, table_name: str) -> Optional[EntityReferenceList]: # no logger.debug(traceback.format_exc()) logger.warning(f"Error processing owner for table {table_name}: {exc}") return # noqa: RET502 + + def _filtered_database_names_for_totals(self) -> List[str]: # noqa: UP006 + """Filtered database names for the progress denominator. Single configured + catalog when one is set on the connection, else the filtered result of the + catalog enumeration. Emits no status side effects.""" + configured_db = self.get_configured_database() + if configured_db: + result = [configured_db] + else: + result = [db for db in self.get_database_names_raw() if not self._is_database_filtered(db)] + return result + + def _schema_names_by_database(self) -> "Optional[Dict[str, List[str]]]": # noqa: UP006,UP045 + """``{database: [schema_names]}`` for every visible catalog from a single + cross-catalog ``system.information_schema.schemata`` query — one round-trip, + no per-catalog reconnect. Returns ``None`` when the view is unavailable + (missing permissions or the system schema not enabled) so the caller falls + back to reconcile-only.""" + try: + rows = self.connection.execute(text(DATABRICKS_GET_ALL_SCHEMAS)).fetchall() + except Exception as exc: # pylint: disable=broad-except + logger.warning( + "system.information_schema.schemata unavailable (%s); progress schema total will reconcile during the walk.", + exc, + ) + return None + by_database: Dict[str, List[str]] = {} # noqa: UP006 + for row in rows: + database_name = row[0] + schema_name = row[1] + if database_name is not None and schema_name is not None: + by_database.setdefault(str(database_name), []).append(str(schema_name)) + return by_database + + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Seed the run-level ``Database`` and ``DatabaseSchema`` counters upfront. + ``Database`` is the filtered DB count; ``DatabaseSchema`` is the post-filter + schema count per database from the cross-catalog + ``system.information_schema.schemata``. When that view is unavailable the + schema counter is marked reconcilable so the walk fills its total instead.""" + database_names = self._filtered_database_names_for_totals() + totals.set_total(Database.__name__, len(database_names)) + schemas_by_database = self._schema_names_by_database() + if schemas_by_database is None: + totals.mark_reconcilable(DatabaseSchema.__name__) + else: + # Catalog identifiers are case-insensitive: the walk's scope key keeps the + # configured/SHOW CATALOGS casing while the view returns catalog_name in its + # own casing, so match case-insensitively to avoid seeding a spurious 0. + schemas_by_lower = {db.lower(): schemas for db, schemas in schemas_by_database.items()} + for database_name in database_names: + kept = [ + schema_name + for schema_name in schemas_by_lower.get(database_name.lower(), []) + if not self._is_schema_filtered(database_name, schema_name) + ] + totals.seed_scope_total(DatabaseSchema.__name__, database_name, len(kept)) diff --git a/ingestion/src/metadata/ingestion/source/database/databricks/queries.py b/ingestion/src/metadata/ingestion/source/database/databricks/queries.py index c25db62ddae8..5a665f9bf3eb 100644 --- a/ingestion/src/metadata/ingestion/source/database/databricks/queries.py +++ b/ingestion/src/metadata/ingestion/source/database/databricks/queries.py @@ -186,3 +186,7 @@ WHERE 1=0 """ ) + +DATABRICKS_GET_ALL_SCHEMAS = """ +SELECT catalog_name, schema_name FROM system.information_schema.schemata +""" diff --git a/ingestion/src/metadata/ingestion/source/database/datalake/connection.py b/ingestion/src/metadata/ingestion/source/database/datalake/connection.py index e919ae6c50bf..c5cfb024f64e 100644 --- a/ingestion/src/metadata/ingestion/source/database/datalake/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/datalake/connection.py @@ -53,23 +53,26 @@ def _get_client(self) -> DatalakeBaseClient: DatalakeS3Client, ) - return DatalakeS3Client.from_config(connection.configSource) - elif isinstance(connection.configSource, GCSConfig): # noqa: RET505 + client: DatalakeBaseClient = DatalakeS3Client.from_config(connection.configSource) + elif isinstance(connection.configSource, GCSConfig): from metadata.ingestion.source.database.datalake.clients.gcs import ( # noqa: PLC0415 DatalakeGcsClient, ) - return DatalakeGcsClient.from_config(connection.configSource) + client = DatalakeGcsClient.from_config(connection.configSource) elif isinstance(connection.configSource, AzureConfig): from metadata.ingestion.source.database.datalake.clients.azure_blob import ( # noqa: PLC0415 DatalakeAzureBlobClient, ) - return DatalakeAzureBlobClient.from_config(connection.configSource) + client = DatalakeAzureBlobClient.from_config(connection.configSource) else: msg = f"Config not implemented for type {type(connection.configSource)}: {connection.configSource}" raise NotImplementedError(msg) + self._on_close(lambda: client.close(self.service_connection)) + return client + def test_connection( self, metadata: OpenMetadata, diff --git a/ingestion/src/metadata/ingestion/source/database/datalake/metadata.py b/ingestion/src/metadata/ingestion/source/database/datalake/metadata.py index fb29a399179f..350d326170fc 100644 --- a/ingestion/src/metadata/ingestion/source/database/datalake/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/datalake/metadata.py @@ -16,7 +16,7 @@ import json import traceback from hashlib import md5 -from typing import Any, Iterable, Optional, Tuple # noqa: UP035 +from typing import TYPE_CHECKING, Any, Iterable, Optional, Tuple, cast # noqa: UP035 from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createDatabaseSchema import ( @@ -52,7 +52,7 @@ from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.ingestion.source.database.stored_procedures_mixin import QueryByProcedure from metadata.ingestion.source.storage.storage_service import ( @@ -71,6 +71,10 @@ from metadata.utils.filters import filter_by_database, filter_by_schema, filter_by_table from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from metadata.ingestion.connections.connection import BaseConnection + + logger = ingestion_logger() OBJECT_FILTERED_OUT_MESSAGE = "Object Filtered Out" @@ -88,12 +92,16 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata): self.source_config: DatabaseServiceMetadataPipeline = self.config.sourceConfig.config self.metadata = metadata self.service_connection = self.config.serviceConnection.root.config - self.client = get_connection(self.service_connection) + self._connection = create_connection(self.service_connection) + self.client = cast("BaseConnection", self._connection).client self.table_constraints = None self.database_source_state = set() self.config_source = self.service_connection.configSource - self.connection_obj = self.client - self.test_connection() + try: + self.test_connection() + except Exception: + self.close() + raise self.reader = get_reader(config_source=self.config_source, client=self.client.client) @classmethod @@ -350,6 +358,3 @@ def filter_dl_table(self, table_name: str): ) return True return False - - def close(self): - self.client.close(self.service_connection) diff --git a/ingestion/src/metadata/ingestion/source/database/dbt/dbt_service.py b/ingestion/src/metadata/ingestion/source/database/dbt/dbt_service.py index f81ccc2a5cae..d73a0ab0c634 100644 --- a/ingestion/src/metadata/ingestion/source/database/dbt/dbt_service.py +++ b/ingestion/src/metadata/ingestion/source/database/dbt/dbt_service.py @@ -8,6 +8,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# pyright: reportCallIssue=false, reportAttributeAccessIssue=false """ DBT service Topology. """ @@ -19,6 +20,7 @@ from pydantic import Field from typing_extensions import Annotated # noqa: UP035 +from metadata.generated.schema.api.data.createMetric import CreateMetricRequest from metadata.generated.schema.api.lineage.addLineage import AddLineageRequest from metadata.generated.schema.api.tests.createTestCase import CreateTestCaseRequest from metadata.generated.schema.api.tests.createTestDefinition import ( @@ -82,6 +84,7 @@ class DbtServiceTopology(ServiceTopology): "process_dbt_entities", "process_dbt_tests", "process_dbt_exposures", + "process_dbt_metrics", ], ) process_dbt_data_model: Annotated[TopologyNode, Field(description="Process dbt data models")] = TopologyNode( @@ -167,6 +170,24 @@ class DbtServiceTopology(ServiceTopology): ), ], ) + process_dbt_metrics: Annotated[TopologyNode, Field(description="Process dbt semantic layer metrics")] = ( + TopologyNode( + producer="get_dbt_metrics", + stages=[ + NodeStage( + type_=CreateMetricRequest, + processor="yield_dbt_metrics", + consumer=["yield_data_models"], + nullable=True, + ), + NodeStage( + type_=AddLineageRequest, + processor="create_dbt_metric_lineage", + nullable=True, + ), + ], + ) + ) class DbtServiceSource(TopologyRunnerMixin, Source, ABC): @@ -192,7 +213,7 @@ def remove_manifest_non_required_keys(self, manifest_dict: dict): # This step is necessary as the manifest file may not always adhere to the schema definition # and the presence of other nodes can hinder the ingestion process from progressing any further. # Therefore, we are only retaining the essential data for further processing. - required_manifest_keys = {"nodes", "sources", "metadata", "exposures"} + required_manifest_keys = {"nodes", "sources", "metadata", "exposures", "metrics", "semantic_models"} manifest_dict.update( { key: [] if isinstance(manifest_dict[key], list) else {} @@ -349,6 +370,12 @@ def get_dbt_exposures(self) -> Iterable[dict]: for _, exposure in self.context.get().exposures.items(): # noqa: PERF102 yield exposure + def get_dbt_metrics(self) -> Iterable[dict]: + """ + Prepare the DBT metrics + """ + yield from self.context.get().dbt_metrics.values() + @abstractmethod def create_dbt_tests_definition(self, dbt_test: dict) -> CreateTestDefinitionRequest: """ @@ -379,6 +406,18 @@ def process_dbt_custom_properties(self, data_model_link: DataModelLink): Method to process DBT custom properties using patch APIs """ + @abstractmethod + def yield_dbt_metrics(self, metric_entry: dict) -> Iterable[Either[CreateMetricRequest]]: + """ + Yield CreateMetric requests from dbt metric definitions + """ + + @abstractmethod + def create_dbt_metric_lineage(self, metric_entry: dict) -> Iterable[Either[AddLineageRequest]]: + """ + Create lineage from source tables to dbt metrics + """ + def is_filtered(self, database_name: str, schema_name: str, table_name: str) -> DbtFilteredModel: """ Function used to identify the filtered models diff --git a/ingestion/src/metadata/ingestion/source/database/dbt/dbt_utils.py b/ingestion/src/metadata/ingestion/source/database/dbt/dbt_utils.py index aad788fd135a..9f4fbbfa4b1a 100644 --- a/ingestion/src/metadata/ingestion/source/database/dbt/dbt_utils.py +++ b/ingestion/src/metadata/ingestion/source/database/dbt/dbt_utils.py @@ -17,6 +17,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Tuple, Union # noqa: UP035 +from metadata.generated.schema.entity.data.metric import MetricType from metadata.generated.schema.entity.data.table import Table from metadata.generated.schema.entity.domains.domain import Domain from metadata.generated.schema.entity.teams.team import Team @@ -997,6 +998,122 @@ def format_entity_reference(entity: Any, entity_type: Optional[str] = None) -> D } +DBT_METRIC_TYPE_MAP = { + "simple": MetricType.SIMPLE, + "ratio": MetricType.RATIO, + "cumulative": MetricType.CUMULATIVE, + "derived": MetricType.DERIVED, + "conversion": MetricType.CONVERSION, +} + + +def map_dbt_metric_type(dbt_type: str) -> MetricType | None: + return DBT_METRIC_TYPE_MAP.get(dbt_type) + + +def find_semantic_model_by_unique_id(semantic_models: dict[str, Any], unique_id: str) -> Any | None: + return semantic_models.get(unique_id) + + +def find_semantic_models_for_metric(metric, semantic_models: dict[str, Any]) -> list[Any]: + depends_on = getattr(metric, "depends_on", None) + if not depends_on: + return [] + nodes = getattr(depends_on, "nodes", None) or [] + result = [] + for node_id in nodes: + if node_id.startswith("semantic_model."): + sm = find_semantic_model_by_unique_id(semantic_models, node_id) + if sm: + result.append(sm) + return result + + +def find_semantic_models_transitive( + metric, + semantic_models: dict[str, Any], + all_metrics: dict[str, Any], + visited_metrics: Optional[set[str]] = None, # noqa: UP045 +) -> list[Any]: + """Resolve semantic models transitively through sub-metric dependencies. + + ``visited_metrics`` tracks already-traversed metric node ids so a circular + ``depends_on`` chain in a user-supplied manifest cannot cause unbounded + recursion. + """ + direct = find_semantic_models_for_metric(metric, semantic_models) + if direct: + return direct + if visited_metrics is None: + visited_metrics = set() + metric_id = getattr(metric, "unique_id", None) + if metric_id is not None: + if metric_id in visited_metrics: + return [] + visited_metrics.add(metric_id) + depends_on = getattr(metric, "depends_on", None) + if not depends_on: + return [] + nodes = getattr(depends_on, "nodes", None) or [] + seen = set() + result = [] + for node_id in nodes: + if node_id.startswith("metric.") and node_id in all_metrics and node_id not in visited_metrics: + sub_metric = all_metrics[node_id] + for sm in find_semantic_models_transitive(sub_metric, semantic_models, all_metrics, visited_metrics): + sm_id = getattr(sm, "unique_id", id(sm)) + if sm_id not in seen: + seen.add(sm_id) + result.append(sm) + return result + + +def order_metrics_by_dependency(metrics: dict[str, Any]) -> list[str]: + """Order metric node ids so a metric is emitted after the metrics it depends on. + + dbt manifests list metrics in arbitrary dict order, so a derived/ratio metric + can appear before the metric it references. Emitting in dependency order lets + ``relatedMetrics`` resolve against already-created parents. A DFS post-order + with a visited guard keeps the traversal safe against circular dependencies. + """ + name_to_key = {} + for key, node in metrics.items(): + name = getattr(node, "name", None) + if name: + name_to_key[name] = key + ordered: list[str] = [] + visited: set[str] = set() + + def visit(key: str) -> None: + if key in visited: + return + visited.add(key) + for dep_name in find_dependent_metric_names(metrics[key]): + dep_key = name_to_key.get(dep_name) + if dep_key is not None and dep_key != key: + visit(dep_key) + ordered.append(key) + + for key in metrics: + visit(key) + return ordered + + +def find_dependent_metric_names(metric) -> list[str]: + """Get metric names from depends_on.nodes that are metric references.""" + depends_on = getattr(metric, "depends_on", None) + if not depends_on: + return [] + nodes = getattr(depends_on, "nodes", None) or [] + result = [] + for node_id in nodes: + if node_id.startswith("metric."): + parts = node_id.split(".") + if len(parts) >= 3: + result.append(parts[-1]) + return result + + def find_domain_by_name(metadata: OpenMetadata, domain_name: str) -> Optional[Any]: # noqa: UP045 """ Search domain by name diff --git a/ingestion/src/metadata/ingestion/source/database/dbt/metadata.py b/ingestion/src/metadata/ingestion/source/database/dbt/metadata.py index b904c064fe83..4f776f44d438 100644 --- a/ingestion/src/metadata/ingestion/source/database/dbt/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/dbt/metadata.py @@ -9,15 +9,19 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# pyright: reportCallIssue=false, reportAttributeAccessIssue=false """ DBT source methods. """ +import contextlib +import re import traceback from copy import deepcopy from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Union # noqa: UP035 +from metadata.generated.schema.api.data.createMetric import CreateMetricRequest from metadata.generated.schema.api.lineage.addLineage import AddLineageRequest from metadata.generated.schema.api.tests.createTestCase import CreateTestCaseRequest from metadata.generated.schema.api.tests.createTestDefinition import ( @@ -25,6 +29,15 @@ ) from metadata.generated.schema.entity.classification.tag import Tag from metadata.generated.schema.entity.data.glossaryTerm import GlossaryTerm +from metadata.generated.schema.entity.data.metric import ( + Language, + Metric, + MetricDimension, + MetricExpression, + MetricFilter, + MetricGranularity, + MetricMeasure, +) from metadata.generated.schema.entity.data.table import ( Column, DataModel, @@ -54,13 +67,17 @@ Timestamp, Uuid, ) -from metadata.generated.schema.type.entityLineage import EntitiesEdge, LineageDetails +from metadata.generated.schema.type.entityLineage import ( + ColumnLineage, + EntitiesEdge, + LineageDetails, +) from metadata.generated.schema.type.entityLineage import Source as LineageSource from metadata.generated.schema.type.entityReference import EntityReference from metadata.generated.schema.type.entityReferenceList import EntityReferenceList from metadata.ingestion.api.models import Either from metadata.ingestion.lineage.models import ConnectionTypeDialectMapper -from metadata.ingestion.lineage.sql_lineage import get_lineage_by_query +from metadata.ingestion.lineage.sql_lineage import get_column_fqn, get_lineage_by_query from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.models.ometa_lineage import LineageRequest, OMetaLineageRequest from metadata.ingestion.models.patch_request import PatchedEntity, PatchRequest @@ -89,7 +106,10 @@ check_ephemeral_node, create_test_case_parameter_definitions, create_test_case_parameter_values, + find_dependent_metric_names, find_domain_by_name, + find_semantic_models_for_metric, + find_semantic_models_transitive, format_domain_reference, format_validation_error_message, generate_entity_link, @@ -101,6 +121,8 @@ get_dbt_test_definition_name, get_manifest_column_name, get_snapshot_effective_schema_and_database, + map_dbt_metric_type, + order_metrics_by_dependency, validate_custom_property_value, ) from metadata.ingestion.source.database.dbt.models import DbtMeta @@ -743,6 +765,7 @@ def yield_data_models(self, dbt_objects: DbtObjects) -> Iterable[Either[DataMode self.context.get().data_model_links = [] self.context.get().exposures = {} self.context.get().dbt_tests = {} + self.context.get().dbt_metrics = {} self.context.get().table_domains = {} self.context.get().table_custom_properties = {} self.context.get().run_results_generate_time = None @@ -888,6 +911,24 @@ def yield_data_models(self, dbt_objects: DbtObjects) -> Iterable[Either[DataMode ) ) + self._collect_dbt_metrics(dbt_objects) + + def _collect_dbt_metrics(self, dbt_objects: DbtObjects): + if not getattr(self.source_config, "includeMetrics", False): + return + manifest = dbt_objects.dbt_manifest + metrics = getattr(manifest, "metrics", None) or {} + semantic_models = getattr(manifest, "semantic_models", None) or {} + if not metrics: + return + logger.debug(f"Found {len(metrics)} dbt metrics to process") + for key in order_metrics_by_dependency(metrics): + self.context.get().dbt_metrics[key] = { + "metric_node": metrics[key], + "semantic_models": semantic_models, + "all_metrics": metrics, + } + def parse_upstream_nodes(self, manifest_entities, dbt_node): """ Method to fetch the upstream nodes @@ -1244,6 +1285,398 @@ def create_dbt_exposures_lineage(self, exposure_spec: dict) -> Iterable[Either[A logger.debug(traceback.format_exc()) logger.warning(f"Failed to parse the node {upstream_node} to capture lineage: {exc}") + def yield_dbt_metrics(self, metric_entry: dict) -> Iterable[Either[CreateMetricRequest]]: + metric_node = metric_entry["metric_node"] + semantic_models = metric_entry["semantic_models"] + all_metrics = metric_entry.get("all_metrics") or {} + try: + metric_name = metric_node.name + dbt_type = getattr(metric_node.type, "value", str(metric_node.type)) + metric_type = map_dbt_metric_type(dbt_type) + + description = getattr(metric_node, "description", None) or "" + label = getattr(metric_node, "label", None) + + type_params = getattr(metric_node, "type_params", None) + metric_expression, related_metrics = self._build_expression_and_related(dbt_type, type_params, all_metrics) + + dimensions = self._extract_dimensions(metric_node, semantic_models, all_metrics) + measures = self._extract_measures(metric_node, semantic_models, all_metrics) + filters = self._extract_filters(metric_node) + + granularity = None + time_gran = getattr(metric_node, "time_granularity", None) + if time_gran: + gran_value = getattr(time_gran, "value", str(time_gran)).upper() + with contextlib.suppress(ValueError): + granularity = MetricGranularity(gran_value) + + tags = self._extract_metric_tags(metric_node) + + create_metric = CreateMetricRequest( + name=metric_name, + displayName=label or metric_name, + description=description, + metricType=metric_type, + metricExpression=metric_expression, + granularity=granularity, + relatedMetrics=related_metrics, + dimensions=dimensions or None, + measures=measures or None, + filters=filters or None, + tags=tags or None, + ) + + yield Either(right=create_metric) + + except Exception as exc: + yield Either( + left=StackTraceError( + name=getattr(metric_node, "name", "unknown_metric"), + error=f"Failed to process dbt metric: {exc}", + stackTrace=traceback.format_exc(), + ) + ) + + def _build_expression_and_related(self, dbt_type, type_params, all_metrics): + builders = { + "simple": self._simple_metric_expression, + "derived": self._derived_metric_expr_and_related, + "ratio": self._ratio_metric_expr_and_related, + "cumulative": self._cumulative_metric_expression, + "conversion": self._conversion_metric_expression, + } + metric_expression = None + related_metrics = None + builder = builders.get(dbt_type) + if builder and type_params: + metric_expression, related_metrics = builder(type_params) + if related_metrics: + related_metrics = self._filter_known_metrics(related_metrics, all_metrics) + return metric_expression, related_metrics + + @staticmethod + def _simple_metric_expression(type_params): + expression = None + measure_ref = getattr(type_params, "measure", None) + measure_name = getattr(measure_ref, "name", None) if measure_ref else None + if measure_name: + expression = MetricExpression(language=Language.SQL, code=measure_name) + return expression, None + + @staticmethod + def _derived_metric_expr_and_related(type_params): + expression = None + expr = getattr(type_params, "expr", None) + if expr: + expression = MetricExpression(language=Language.SQL, code=expr) + sub_metrics = getattr(type_params, "metrics", None) or [] + related = [getattr(m, "name", str(m)) for m in sub_metrics] or None + return expression, related + + @staticmethod + def _ratio_metric_expr_and_related(type_params): + expression = None + numerator = getattr(type_params, "numerator", None) + denominator = getattr(type_params, "denominator", None) + num_name = getattr(numerator, "name", str(numerator)) if numerator else "" + den_name = getattr(denominator, "name", str(denominator)) if denominator else "" + related = [name for name in (num_name, den_name) if name] or None + if num_name and den_name: + expression = MetricExpression(language=Language.SQL, code=f"{num_name} / {den_name}") + return expression, related + + @staticmethod + def _cumulative_window_str(type_params): + window_str = "" + cum_params = getattr(type_params, "cumulative_type_params", None) + window = getattr(cum_params, "window", None) if cum_params else None + if window: + count = getattr(window, "count", "") + gran = getattr(window, "granularity", None) + gran_val = getattr(gran, "value", str(gran)) if gran else "" + window_str = f" over {count} {gran_val}" if count else "" + return window_str + + @staticmethod + def _cumulative_metric_expression(type_params): + expression = None + measure_ref = getattr(type_params, "measure", None) + measure_name = getattr(measure_ref, "name", None) if measure_ref else None + if measure_name: + window_str = DbtSource._cumulative_window_str(type_params) + expression = MetricExpression(language=Language.SQL, code=f"cumulative({measure_name}{window_str})") + return expression, None + + @staticmethod + def _conversion_metric_expression(type_params): + expression = None + conv = getattr(type_params, "conversion_type_params", None) + if conv: + base = getattr(conv, "base_measure", None) + conversion = getattr(conv, "conversion_measure", None) + base_name = getattr(base, "name", "") if base else "" + conv_name = getattr(conversion, "name", "") if conversion else "" + entity = getattr(conv, "entity", "") + expression = MetricExpression( + language=Language.SQL, + code=f"conversion({base_name} -> {conv_name}, entity={entity})", + ) + return expression, None + + @staticmethod + def _filter_known_metrics(related_metrics, all_metrics): + known = {name for node in all_metrics.values() if (name := getattr(node, "name", None))} + return [name for name in related_metrics if name in known] or None + + def _extract_dimensions(self, metric_node, semantic_models, all_metrics=None) -> list[MetricDimension]: + result = [] + models = ( + find_semantic_models_transitive(metric_node, semantic_models, all_metrics) + if all_metrics + else find_semantic_models_for_metric(metric_node, semantic_models) + ) + seen = set() + for sm in models: + for dim in getattr(sm, "dimensions", None) or []: + if dim.name in seen: + continue + seen.add(dim.name) + dim_type = getattr(dim.type, "value", str(dim.type)).upper() if dim.type else None + result.append( + MetricDimension( + name=dim.name, + type=dim_type, + description=getattr(dim, "description", None), + expression=getattr(dim, "expr", None), + ) + ) + return result + + def _extract_measures(self, metric_node, semantic_models, all_metrics=None) -> list[MetricMeasure]: + result = [] + models = ( + find_semantic_models_transitive(metric_node, semantic_models, all_metrics) + if all_metrics + else find_semantic_models_for_metric(metric_node, semantic_models) + ) + seen = set() + for sm in models: + for measure in getattr(sm, "measures", None) or []: + if measure.name in seen: + continue + seen.add(measure.name) + agg_value = getattr(measure.agg, "value", str(measure.agg)) if measure.agg else None + result.append( + MetricMeasure( + name=measure.name, + aggregation=agg_value, + description=getattr(measure, "description", None), + expression=getattr(measure, "expr", None), + ) + ) + return result + + def _extract_filters(self, metric_node) -> list[MetricFilter]: + result = [] + filter_obj = getattr(metric_node, "filter", None) + if filter_obj: + where_filters = getattr(filter_obj, "where_filters", None) or [] + for wf in where_filters: + sql_template = getattr(wf, "where_sql_template", None) + if sql_template: + result.append(MetricFilter(where=sql_template)) + return result + + def _extract_metric_tags(self, metric_node) -> list: + tags = getattr(metric_node, "tags", None) or [] + if not tags: + return [] + return ( + get_tag_labels( + metadata=self.metadata, + tags=tags, + classification_name=self.tag_classification_name, + include_tags=bool(self.source_config.includeTags), + ) + or [] + ) + + def create_dbt_metric_lineage(self, metric_entry: dict) -> Iterable[Either[AddLineageRequest]]: + metric_node = metric_entry["metric_node"] + semantic_models = metric_entry["semantic_models"] + all_metrics = metric_entry.get("all_metrics") or {} + + metric_name = metric_node.name + metric_entity = self.metadata.get_by_name( + entity=Metric, + fqn=metric_name, + ) + if not metric_entity: + logger.debug(f"Metric entity '{metric_name}' not found, skipping lineage") + return + + # Table → Metric lineage (from semantic models). Resolve transitively so + # derived/ratio/conversion metrics that inherit semantic models through parent + # metrics also get source-table and column lineage, matching dimension/measure extraction. + models = ( + find_semantic_models_transitive(metric_node, semantic_models, all_metrics) + if all_metrics + else find_semantic_models_for_metric(metric_node, semantic_models) + ) + for sm in models: + node_relation = getattr(sm, "node_relation", None) + if not node_relation: + continue + try: + table_fqn = fqn.build( + self.metadata, + entity_type=Table, + service_name=self.config.serviceName, + database_name=getattr(node_relation, "database", None), + schema_name=node_relation.schema_name, + table_name=node_relation.alias, + ) + from_entity = self._get_table_entity(table_fqn) + if not from_entity: + continue + columns_lineage = self._build_table_metric_column_lineage(metric_entity, from_entity, sm) + yield Either( + right=OMetaLineageRequest( + lineage_request=AddLineageRequest( + edge=EntitiesEdge( + fromEntity=EntityReference( + id=Uuid(from_entity.id.root), + type="table", + ), + toEntity=EntityReference( + id=Uuid(metric_entity.id.root), + type="metric", + ), + lineageDetails=LineageDetails( + source=LineageSource.DbtLineage, + columnsLineage=columns_lineage or None, + ), + ) + ), + override_lineage=self.source_config.overrideLineage, + ) + ) + except Exception as exc: + logger.debug(traceback.format_exc()) + logger.warning( + f"Failed to create table lineage for metric '{metric_name}' from semantic model '{sm.name}': {exc}" + ) + + # Metric → Metric lineage (for derived/ratio/conversion metrics) + for parent_name in find_dependent_metric_names(metric_node): + try: + parent_entity = self.metadata.get_by_name(entity=Metric, fqn=parent_name) + if not parent_entity: + continue + columns_lineage = self._build_metric_metric_column_lineage(parent_entity, metric_entity) + yield Either( + right=OMetaLineageRequest( + lineage_request=AddLineageRequest( + edge=EntitiesEdge( + fromEntity=EntityReference( + id=Uuid(parent_entity.id.root), + type="metric", + ), + toEntity=EntityReference( + id=Uuid(metric_entity.id.root), + type="metric", + ), + lineageDetails=LineageDetails( + source=LineageSource.DbtLineage, + columnsLineage=columns_lineage or None, + ), + ) + ), + override_lineage=self.source_config.overrideLineage, + ) + ) + except Exception as exc: + logger.debug(traceback.format_exc()) + logger.warning( + f"Failed to create metric lineage for '{metric_name}' from parent metric '{parent_name}': {exc}" + ) + + _SIMPLE_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + def _candidate_source_column(self, child) -> str | None: + expr = getattr(child, "expr", None) + if expr and self._SIMPLE_IDENTIFIER_RE.match(expr.strip()): + return expr.strip() + return getattr(child, "name", None) + + @staticmethod + def _find_metric_child_fqn(metric_entity: Metric, children_attr: str, name: str) -> str | None: + children = getattr(metric_entity, children_attr, None) or [] + for child in children: + if child.name == name and child.fullyQualifiedName is not None: + return child.fullyQualifiedName.root + return None + + def _build_table_metric_column_lineage( + self, + metric_entity: Metric, + from_table_entity: Table, + semantic_model, + ) -> list[ColumnLineage]: + """Column-level lineage from a source table to a metric's dimensions/measures. + + Matches each dimension/measure by `expr` when it's a simple column identifier, + otherwise falls back to the child's name. + """ + columns_lineage: list[ColumnLineage] = [] + pairs = ( + ("dimensions", "dimensions"), + ("measures", "measures"), + ) + for sm_attr, metric_attr in pairs: + for child in getattr(semantic_model, sm_attr, None) or []: + candidate = self._candidate_source_column(child) + if not candidate: + continue + source_col_fqn = get_column_fqn(from_table_entity, candidate) + if not source_col_fqn: + continue + metric_child_fqn = self._find_metric_child_fqn(metric_entity, metric_attr, child.name) + if not metric_child_fqn: + continue + columns_lineage.append( + ColumnLineage( + fromColumns=[source_col_fqn], + toColumn=metric_child_fqn, + ) + ) + return columns_lineage + + def _build_metric_metric_column_lineage(self, parent_entity: Metric, child_entity: Metric) -> list[ColumnLineage]: + """Column-level lineage between metrics by name-matching their children. + + A derived metric inherits dimensions/measures from its parents; whenever a + child metric has a dimension or measure of the same name as its parent, we + emit a ColumnLineage connecting the two. + """ + columns_lineage: list[ColumnLineage] = [] + for attr in ("dimensions", "measures"): + parent_children = { + c.name: c for c in (getattr(parent_entity, attr, None) or []) if c.fullyQualifiedName is not None + } + for child in getattr(child_entity, attr, None) or []: + parent_child = parent_children.get(child.name) + if not parent_child or child.fullyQualifiedName is None: + continue + columns_lineage.append( + ColumnLineage( + fromColumns=[parent_child.fullyQualifiedName.root], + toColumn=child.fullyQualifiedName.root, + ) + ) + return columns_lineage + def process_dbt_meta(self, manifest_meta, table_fqn): """ Method to process DBT meta for Tags and GlossaryTerms @@ -1539,7 +1972,7 @@ def add_dbt_test_result(self, dbt_test: dict): ) ], sampleData=None, - result=None, + result=(dbt_test_result.message if test_case_status != TestCaseStatus.Success else None), ) # Create the test case fqns and add the results diff --git a/ingestion/src/metadata/ingestion/source/database/deltalake/metadata.py b/ingestion/src/metadata/ingestion/source/database/deltalake/metadata.py index f73f6804a049..deac9928f428 100644 --- a/ingestion/src/metadata/ingestion/source/database/deltalake/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/deltalake/metadata.py @@ -13,7 +13,7 @@ """ import traceback -from typing import Any, Iterable, Optional, Tuple # noqa: UP035 +from typing import TYPE_CHECKING, Any, Iterable, Optional, Tuple, cast # noqa: UP035 from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createDatabaseSchema import ( @@ -43,13 +43,17 @@ from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.ingestion.source.database.stored_procedures_mixin import QueryByProcedure from metadata.utils import fqn from metadata.utils.filters import filter_by_schema, filter_by_table from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from metadata.ingestion.connections.connection import BaseConnection + + logger = ingestion_logger() @@ -77,11 +81,15 @@ def __init__( self.metadata = metadata self.service_connection = self.config.serviceConnection.root.config - self.connection = get_connection(self.service_connection) + self._connection = create_connection(self.service_connection) + self.connection = cast("BaseConnection", self._connection).client self.client = self.connection.client - self.connection_obj = self.connection - self.test_connection() + try: + self.test_connection() + except Exception: + self.close() + raise @classmethod def create(cls, config_dict, metadata: OpenMetadata, pipeline_name: Optional[str] = None): # noqa: UP045 @@ -262,6 +270,3 @@ def yield_stored_procedure(self, stored_procedure: Any) -> Iterable[Either[Creat def get_stored_procedure_queries(self) -> Iterable[QueryByProcedure]: """Not Implemented""" - - def close(self): - """No client to close""" diff --git a/ingestion/src/metadata/ingestion/source/database/domodatabase/metadata.py b/ingestion/src/metadata/ingestion/source/database/domodatabase/metadata.py index 30f3d968c8a9..09dd80314553 100644 --- a/ingestion/src/metadata/ingestion/source/database/domodatabase/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/domodatabase/metadata.py @@ -14,7 +14,7 @@ """ import traceback -from typing import Any, Iterable, Optional, Tuple # noqa: UP035 +from typing import TYPE_CHECKING, Any, Iterable, Optional, Tuple, cast # noqa: UP035 from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createDatabaseSchema import ( @@ -50,7 +50,7 @@ from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.ingestion.source.database.domodatabase.models import ( OutputDataset, @@ -66,6 +66,10 @@ from metadata.utils.helpers import clean_uri from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from metadata.ingestion.connections.connection import BaseConnection + + logger = ingestion_logger() @@ -81,9 +85,13 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata): self.source_config: DatabaseServiceMetadataPipeline = self.config.sourceConfig.config self.metadata = metadata self.service_connection = self.config.serviceConnection.root.config - self.domo_client = get_connection(self.service_connection) - self.connection_obj = self.domo_client - self.test_connection() + self._connection = create_connection(self.service_connection) + self.domo_client = cast("BaseConnection", self._connection).client + try: + self.test_connection() + except Exception: + self.close() + raise @classmethod def create( @@ -289,6 +297,3 @@ def standardize_table_name( # pylint: disable=unused-argument self, schema: str, table: str ) -> str: return table - - def close(self) -> None: - """Nothing to close""" diff --git a/ingestion/src/metadata/ingestion/source/database/exasol/queries.py b/ingestion/src/metadata/ingestion/source/database/exasol/queries.py index 3d2cd51a6066..6bc382e5cb7a 100644 --- a/ingestion/src/metadata/ingestion/source/database/exasol/queries.py +++ b/ingestion/src/metadata/ingestion/source/database/exasol/queries.py @@ -13,8 +13,9 @@ JOIN EXA_STATISTICS.EXA_DBA_AUDIT_SESSIONS se ON s.SESSION_ID = se.SESSION_ID WHERE s.sql_text NOT LIKE '/* {{"app": "OpenMetadata", %%}} */%%' + AND s.success = TRUE AND s.sql_text NOT LIKE '/* {{"app": "dbt", %%}} */%%' - AND start_time between TO_TIMESTAMP('{start_time}') and TO_TIMESTAMP('{end_time}') + AND s.start_time between TO_TIMESTAMP('{start_time}') and TO_TIMESTAMP('{end_time}') {filters} LIMIT {result_limit} """ diff --git a/ingestion/src/metadata/ingestion/source/database/exasol/service_spec.py b/ingestion/src/metadata/ingestion/source/database/exasol/service_spec.py index 23f7f2f4e884..a1844fbd0ffa 100644 --- a/ingestion/src/metadata/ingestion/source/database/exasol/service_spec.py +++ b/ingestion/src/metadata/ingestion/source/database/exasol/service_spec.py @@ -1,6 +1,7 @@ from metadata.ingestion.source.database.exasol.connection import ExasolConnection from metadata.ingestion.source.database.exasol.lineage import ExasolLineageSource from metadata.ingestion.source.database.exasol.metadata import ExasolSource +from metadata.ingestion.source.database.exasol.usage import ExasolUsageSource from metadata.profiler.interface.sqlalchemy.exasol.profiler_interface import ( ExasolProfilerInterface, ) @@ -10,5 +11,6 @@ profiler_class=ExasolProfilerInterface, # pyright: ignore[reportArgumentType] metadata_source_class=ExasolSource, lineage_source_class=ExasolLineageSource, + usage_source_class=ExasolUsageSource, # pyright: ignore[reportArgumentType] connection_class=ExasolConnection, # pyright: ignore[reportArgumentType] ) diff --git a/ingestion/src/metadata/ingestion/source/database/exasol/usage.py b/ingestion/src/metadata/ingestion/source/database/exasol/usage.py new file mode 100644 index 000000000000..c4f8721cccae --- /dev/null +++ b/ingestion/src/metadata/ingestion/source/database/exasol/usage.py @@ -0,0 +1,30 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Exasol usage module +""" + +from metadata.ingestion.lineage.models import Dialect +from metadata.ingestion.source.database.exasol.queries import EXASOL_SQL_STATEMENT +from metadata.ingestion.source.database.exasol.query_parser import ExasolQueryParserSource +from metadata.ingestion.source.database.usage_source import UsageSource + + +class ExasolUsageSource(ExasolQueryParserSource, UsageSource): + """ + Exasol class for Usage + """ + + dialect = Dialect.EXASOL # pyright: ignore[reportAssignmentType] + sql_stmt = EXASOL_SQL_STATEMENT + filters = """ + AND s.command_name = 'SELECT' + """ diff --git a/ingestion/src/metadata/ingestion/source/database/glue/connection.py b/ingestion/src/metadata/ingestion/source/database/glue/connection.py index da41f6d577c2..b582d31bafc0 100644 --- a/ingestion/src/metadata/ingestion/source/database/glue/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/glue/connection.py @@ -8,68 +8,159 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - """ -Source connection handler +Source connection handler for the AWS Glue Data Catalog. + +Glue has no SQL engine and no host:port: a check's reported ``command`` is the +boto3 API operation it exercised, and failures arrive as botocore ``ClientError``s. """ -from typing import Any, Optional +from __future__ import annotations + +from typing import TYPE_CHECKING, Any from metadata.clients.aws_client import AWSClient -from metadata.generated.schema.entity.automations.workflow import ( - Workflow as AutomationWorkflow, -) +from metadata.core.connections.test_connection import ErrorPack, check, when +from metadata.core.connections.test_connection.aws import AWS_ERRORS, aws_code +from metadata.core.connections.test_connection.check import CheckError +from metadata.core.connections.test_connection.checks.database import DatabaseStep +from metadata.core.connections.test_connection.records import Diagnosis, Evidence from metadata.generated.schema.entity.services.connections.database.glueConnection import ( GlueConnection as GlueConnectionConfig, ) -from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - TestConnectionResult, -) from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.connections.test_connections import test_connection_steps -from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.utils.constants import THREE_MIN + +if TYPE_CHECKING: + from metadata.core.connections.lifetime import Borrowed + from metadata.core.connections.test_connection import ChecksProvider + + +# A check only needs to prove the catalog can be listed, not enumerate all of it. +DEFAULT_LIST_LIMIT = 100 + +# Catalogs commonly lead with an empty 'default' database, so the table probe keeps +# looking past it - bounded, since each database costs a GetTables call. +MAX_DATABASES_TO_PROBE = 10 + + +# Only what is specific to Glue: its IAM actions and its not-found code. +# Authentication, region, endpoint and network failures come from AWS_ERRORS. +GLUE_ERRORS = ErrorPack( + when(aws_code("AccessDenied", "AccessDeniedException")).diagnose( + "Not authorized", + fix="Grant glue:GetDatabases and glue:GetTables to the identity used, and check any " + "Lake Formation permissions on the catalog.", + ), + # Only from GetTables; a GetDatabases listing returns an empty list instead. + when(aws_code("EntityNotFoundException")).diagnose( + "Glue database not found", + fix="The database disappeared from the catalog while the connection was being tested; re-run the test.", + ), +).including(AWS_ERRORS) + + +def _count(n: int, noun: str) -> str: + """``3 tables`` / ``1 table`` - pluralize the noun to match the count.""" + return f"{n} {noun if n == 1 else noun + 's'}" + + +def _more_suffix(shown: int, more: bool) -> str: + """Mark a summary as capped when the catalog holds more assets beyond ``shown``.""" + return f" (showing first {shown}; more exist)" if more else "" + + +def _paginate(client: Any, operation: str, key: str, limit: int, **kwargs: Any) -> list[Any]: + """Return at most ``limit + 1`` items - one past the cap, so the caller can + report "more exist" without crawling the whole catalog.""" + paginator = client.get_paginator(operation) + pages = paginator.paginate(PaginationConfig={"MaxItems": limit + 1}, **kwargs) + return [item for page in pages for item in page.get(key, [])] + + +def list_databases(client: Any, limit: int = DEFAULT_LIST_LIMIT) -> Evidence: + """Enumerate the Glue databases the identity can see, reporting at most ``limit``. + + Lake Formation filters the response instead of raising, so zero grants read + exactly like an empty catalog: both surface as a caveat, never a failure.""" + command = "glue:GetDatabases" + try: + databases = _paginate(client, "get_databases", "DatabaseList", limit) + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + caveat = None + if not databases: + caveat = Diagnosis( + title="No databases visible", + remediation="The catalog in awsRegion may be empty, or Lake Formation may be filtering " + "it out: grant the identity DESCRIBE on the databases it should read. Ingestion would " + "collect nothing as configured.", + ) + shown = min(len(databases), limit) + summary = f"{_count(shown, 'database')} enumerated" + _more_suffix(shown, len(databases) > limit) + return Evidence(summary=summary, command=command, caveat=caveat) + + +def list_tables(client: Any, limit: int = DEFAULT_LIST_LIMIT) -> Evidence: + """Prove tables can be listed, probing databases until one exposes a table. + + Stopping at the first database would report zero tables for a healthy catalog + that merely leads with an empty one. Nothing here fails the step: an empty + catalog is already flagged by ``list_databases``, and Lake Formation returns an + empty list rather than an error when grants are missing.""" + command = "glue:GetDatabases" + try: + databases = _paginate(client, "get_databases", "DatabaseList", MAX_DATABASES_TO_PROBE) + if not databases: + return Evidence(summary="no databases available to probe", command=command, caveat=_no_tables_caveat()) + for database in databases[:MAX_DATABASES_TO_PROBE]: + name = database["Name"] + command = f"glue:GetTables (DatabaseName={name})" + tables = _paginate(client, "get_tables", "TableList", limit, DatabaseName=name) + if tables: + shown = min(len(tables), limit) + summary = f"{_count(shown, 'table')} in database '{name}'" + _more_suffix(shown, len(tables) > limit) + return Evidence(summary=summary, command=command) + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + probed = min(len(databases), MAX_DATABASES_TO_PROBE) + return Evidence( + summary=f"no tables in the first {_count(probed, 'database')}", + command=command, + caveat=_no_tables_caveat(), + ) + + +def _no_tables_caveat() -> Diagnosis: + return Diagnosis( + title="No tables visible", + remediation="No database exposed a table. Verify the identity's Glue permissions and any " + "Lake Formation DESCRIBE grants; ingestion would collect nothing as configured.", + ) + + +class GlueChecks: + """Test-connection checks for the Glue Data Catalog. + + Reading the borrowed client is what builds it, so an assume-role config's STS + handshake stays behind the gate.""" + + errors = GLUE_ERRORS + + def __init__(self, catalog: Borrowed[Any]) -> None: + self._catalog = catalog + + @check(DatabaseStep.GetDatabases) + def get_databases(self) -> Evidence: + return list_databases(self._catalog.client) + + @check(DatabaseStep.GetTables) + def get_tables(self) -> Evidence: + return list_tables(self._catalog.client) class GlueConnection(BaseConnection[GlueConnectionConfig, Any]): def _get_client(self) -> Any: return AWSClient(self.service_connection.awsConfig).get_glue_client() - def test_connection( - self, - metadata: OpenMetadata, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 - ) -> TestConnectionResult: - """ - Test connection. This can be executed either as part - of a metadata workflow or during an Automation Workflow - """ - client = self.client - - def custom_executor_for_database(): - paginator = client.get_paginator("get_databases") - list(paginator.paginate()) - - def custom_executor_for_table(): - paginator = client.get_paginator("get_databases") - for page in paginator.paginate(): - for schema in page["DatabaseList"]: - database_name = schema["Name"] - paginator = client.get_paginator("get_tables") - tables = paginator.paginate(DatabaseName=database_name) - return list(tables) - return None - - test_fn = { - "GetDatabases": custom_executor_for_database, - "GetTables": custom_executor_for_table, - } - - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=self.service_connection.type.value, # pyright: ignore[reportOptionalMemberAccess] - automation_workflow=automation_workflow, - timeout_seconds=timeout_seconds, - ) + def checks(self) -> ChecksProvider: + return GlueChecks(catalog=self.borrow()) diff --git a/ingestion/src/metadata/ingestion/source/database/glue/metadata.py b/ingestion/src/metadata/ingestion/source/database/glue/metadata.py index 2aa656c404ca..f05680ea872e 100755 --- a/ingestion/src/metadata/ingestion/source/database/glue/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/glue/metadata.py @@ -13,7 +13,7 @@ """ import traceback -from typing import Any, Iterable, Optional, Tuple # noqa: UP035 +from typing import TYPE_CHECKING, Any, Iterable, Optional, Tuple, cast # noqa: UP035 from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createDatabaseSchema import ( @@ -52,7 +52,7 @@ from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.column_helpers import truncate_column_name from metadata.ingestion.source.database.column_type_parser import ColumnTypeParser from metadata.ingestion.source.database.database_service import DatabaseServiceSource @@ -70,6 +70,10 @@ from metadata.utils.filters import filter_by_database, filter_by_schema, filter_by_table from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from metadata.ingestion.connections.connection import BaseConnection + + logger = ingestion_logger() @@ -85,12 +89,16 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata): self.source_config: DatabaseServiceMetadataPipeline = self.config.sourceConfig.config self.metadata = metadata self.service_connection = self.config.serviceConnection.root.config - self.glue = get_connection(self.service_connection) + self._connection = create_connection(self.service_connection) + self.glue = cast("BaseConnection", self._connection).client - self.connection_obj = self.glue self.schema_description_map = {} self.external_location_map = {} - self.test_connection() + try: + self.test_connection() + except Exception: + self.close() + raise @classmethod def create(cls, config_dict, metadata: OpenMetadata, pipeline_name: Optional[str] = None): # noqa: UP045 @@ -485,6 +493,3 @@ def get_source_url( logger.debug(traceback.format_exc()) logger.error(f"Unable to get source url: {exc}") return None - - def close(self): - """Nothing to close""" diff --git a/ingestion/src/metadata/ingestion/source/database/lineage_source.py b/ingestion/src/metadata/ingestion/source/database/lineage_source.py index 13ae5121338f..b1f032a83866 100644 --- a/ingestion/src/metadata/ingestion/source/database/lineage_source.py +++ b/ingestion/src/metadata/ingestion/source/database/lineage_source.py @@ -335,6 +335,13 @@ def yield_table_query(self) -> Iterator[TableQuery]: logger.debug(traceback.format_exc()) logger.warning(f"Error processing query_dict {query_dict}: {exc}") logger.info(f"Processed {row_count} query log entries for lineage") + result_limit = getattr(self.source_config, "resultLimit", None) + if isinstance(result_limit, int) and row_count >= result_limit: + logger.debug( + f"Reached the configured resultLimit of {result_limit} query log entries; " + f"if more queries exist they were truncated and lineage may be incomplete. " + f"Consider increasing resultLimit." + ) def get_table_query(self) -> Iterator[TableQuery]: """ @@ -367,14 +374,14 @@ def yield_query_lineage( result_limit = self.source_config.resultLimit # pyright: ignore[reportOptionalMemberAccess, reportAttributeAccessIssue] if result_limit is not None: - self.progress.seed_scope_total("Queries", "run", result_limit) + self.progress_tracking.manual.seed_scope_total("Queries", "run", result_limit) produced = 0 def producer_fn(): nonlocal produced for table_query in self.query_lineage_producer(): produced += 1 - self.progress.track("Queries") + self.progress_tracking.manual.track("Queries") yield table_query processor_fn = query_lineage_processor @@ -394,7 +401,7 @@ def producer_fn(): args, max_threads=self.source_config.threads, # pyright: ignore[reportAttributeAccessIssue] ) - self.progress.reconcile_scope_total("Queries", "run", produced) + self.progress_tracking.manual.reconcile_scope_total("Queries", "run", produced) def view_lineage_producer(self) -> Iterable[TableView]: """ diff --git a/ingestion/src/metadata/ingestion/source/database/mssql/connection.py b/ingestion/src/metadata/ingestion/source/database/mssql/connection.py index b8447e15226c..facd2567fc18 100644 --- a/ingestion/src/metadata/ingestion/source/database/mssql/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/mssql/connection.py @@ -53,6 +53,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.records import Evidence @@ -149,39 +150,39 @@ class MssqlChecks: } ) - def __init__(self, client: Engine, get_databases_statement: str) -> None: - self.client = client + def __init__(self, db: Borrowed[Engine], get_databases_statement: str) -> None: + self._db = db self.get_databases_statement = get_databases_statement @check(DatabaseStep.CheckAccess) def check_access(self) -> Evidence: - return ping(self.client) + return ping(self._db.client) @check(DatabaseStep.GetDatabases) def get_databases(self) -> Evidence: - return run_sql(self.client, self.get_databases_statement, _databases_enumerated) + return run_sql(self._db.client, self.get_databases_statement, _databases_enumerated) @check(DatabaseStep.GetSchemas) def get_schemas(self) -> Evidence: - return list_schemas(self.client) + return list_schemas(self._db.client) @check(DatabaseStep.GetTables) def get_tables(self) -> Evidence: - return list_tables(self.client, None, self.SYSTEM_SCHEMAS) + return list_tables(self._db.client, None, self.SYSTEM_SCHEMAS) @check(DatabaseStep.GetViews) def get_views(self) -> Evidence: - return list_views(self.client, None, self.SYSTEM_SCHEMAS) + return list_views(self._db.client, None, self.SYSTEM_SCHEMAS) @check(DatabaseStep.GetQueries) def get_queries(self) -> Evidence: - if is_query_store_enabled(self.client): + if is_query_store_enabled(self._db.client): query = MSSQL_TEST_GET_QUERIES_FROM_QUERY_STORE summary = "query history accessible via Query Store" else: query = MSSQL_TEST_GET_QUERIES summary = "query history accessible via plan-cache DMVs" - return run_sql(self.client, query, lambda _: summary) + return run_sql(self._db.client, query, lambda _: summary) class MssqlConnection(BaseConnection[MssqlConnectionConfig, Engine]): @@ -201,6 +202,6 @@ def _get_databases_statement(self) -> str: def checks(self) -> ChecksProvider: return MssqlChecks( - client=self.client, + db=self.borrow(), get_databases_statement=self._get_databases_statement(), ) diff --git a/ingestion/src/metadata/ingestion/source/database/mssql/metadata.py b/ingestion/src/metadata/ingestion/source/database/mssql/metadata.py index c4ebafe619fc..522833987953 100644 --- a/ingestion/src/metadata/ingestion/source/database/mssql/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/mssql/metadata.py @@ -169,7 +169,11 @@ def _get_encrypted_procedures(self, database_name: str, schema_name: str) -> set ).all() self.encrypted_procedures_cache[cache_key] = {row.procedure_name for row in results} except Exception as exc: - logger.debug(f"Could not fetch encrypted procedures for {database_name}.{schema_name}: {exc}") + logger.debug(traceback.format_exc()) + logger.warning( + f"Could not detect encrypted stored procedures for {database_name}.{schema_name}; " + f"any encrypted procedures may be treated as non-encrypted: {exc}" + ) self.encrypted_procedures_cache[cache_key] = set() return self.encrypted_procedures_cache[cache_key] @@ -189,12 +193,29 @@ def get_stored_procedure_description(self, stored_procedure: str) -> Optional[st def get_database_names_raw(self) -> Iterable[str]: yield from self._execute_database_query(MSSQL_GET_DATABASE) + def _load_description_maps(self) -> None: + """ + Reset the per-database encrypted-procedure cache and load the description + maps. Descriptions are optional metadata, so a failure here must not + abort the run: it is logged and ingestion continues without them. + """ + self.encrypted_procedures_cache.clear() + description_loaders = { + "schema": self.set_schema_description_map, + "database": self.set_database_description_map, + "stored procedure": self.set_stored_procedure_description_map, + } + for description_type, load_description_map in description_loaders.items(): + try: + load_description_map() + except Exception as exc: + logger.debug(traceback.format_exc()) + logger.debug(f"Could not load MSSQL {description_type} descriptions, continuing without them: {exc}") + def get_database_names(self) -> Iterable[str]: if not self.config.serviceConnection.root.config.ingestAllDatabases: # pyright: ignore[reportAttributeAccessIssue] configured_db = self.config.serviceConnection.root.config.database # pyright: ignore[reportAttributeAccessIssue] - self.set_schema_description_map() - self.set_database_description_map() - self.set_stored_procedure_description_map() + self._load_description_maps() self.set_inspector(database_name=configured_db) yield configured_db else: @@ -214,14 +235,19 @@ def get_database_names(self) -> Iterable[str]: continue try: - self.set_schema_description_map() - self.set_database_description_map() - self.set_stored_procedure_description_map() + self._load_description_maps() self.set_inspector(database_name=new_database) yield new_database except Exception as exc: logger.debug(traceback.format_exc()) logger.error(f"Error trying to connect to database {new_database}: {exc}") + self.status.failed( + error=StackTraceError( + name=new_database, + error=f"Error trying to connect to database {new_database}: {exc}", + stackTrace=traceback.format_exc(), + ) + ) def get_stored_procedures(self) -> Iterable[MssqlStoredProcedure]: """List Snowflake stored procedures""" diff --git a/ingestion/src/metadata/ingestion/source/database/mysql/connection.py b/ingestion/src/metadata/ingestion/source/database/mysql/connection.py index 17440d38cd4d..5dc3e7b21158 100644 --- a/ingestion/src/metadata/ingestion/source/database/mysql/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/mysql/connection.py @@ -64,6 +64,7 @@ from metadata.utils.credentials import get_azure_access_token, set_google_credentials if TYPE_CHECKING: + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.records import Evidence @@ -129,30 +130,30 @@ class MySQLChecks: # MySQL 8 system databases - skipped when auto-selecting a schema to probe. SYSTEM_SCHEMAS = frozenset({"information_schema", "performance_schema", "mysql", "sys"}) - def __init__(self, client: Engine, schema: str | None, queries_statement: str) -> None: - self.client = client + def __init__(self, db: Borrowed[Engine], schema: str | None, queries_statement: str) -> None: + self._db = db self.schema = schema self.queries_statement = queries_statement @check(DatabaseStep.CheckAccess) def check_access(self) -> Evidence: - return ping(self.client) + return ping(self._db.client) @check(DatabaseStep.GetSchemas) def get_schemas(self) -> Evidence: - return list_schemas(self.client) + return list_schemas(self._db.client) @check(DatabaseStep.GetTables) def get_tables(self) -> Evidence: - return list_tables(self.client, self.schema, self.SYSTEM_SCHEMAS) + return list_tables(self._db.client, self.schema, self.SYSTEM_SCHEMAS) @check(DatabaseStep.GetViews) def get_views(self) -> Evidence: - return list_views(self.client, self.schema, self.SYSTEM_SCHEMAS) + return list_views(self._db.client, self.schema, self.SYSTEM_SCHEMAS) @check(DatabaseStep.GetQueries) def get_queries(self) -> Evidence: - return run_sql(self.client, self.queries_statement, lambda _: "query history accessible") + return run_sql(self._db.client, self.queries_statement, lambda _: "query history accessible") def _basic_engine(connection: MySQLConnectionConfig) -> Engine: @@ -328,7 +329,7 @@ def _test_queries_statement(self) -> str: def checks(self) -> ChecksProvider: return MySQLChecks( - client=self.client, + db=self.borrow(), schema=self.service_connection.databaseSchema, queries_statement=self._test_queries_statement(), ) diff --git a/ingestion/src/metadata/ingestion/source/database/mysql/metadata.py b/ingestion/src/metadata/ingestion/source/database/mysql/metadata.py index cfc2eaef3289..467ac9e2983b 100644 --- a/ingestion/src/metadata/ingestion/source/database/mysql/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/mysql/metadata.py @@ -21,6 +21,7 @@ from metadata.generated.schema.api.data.createStoredProcedure import ( CreateStoredProcedureRequest, ) +from metadata.generated.schema.entity.data.database import Database from metadata.generated.schema.entity.data.databaseSchema import DatabaseSchema from metadata.generated.schema.entity.data.storedProcedure import StoredProcedureCode from metadata.generated.schema.entity.services.connections.database.mysqlConnection import ( @@ -36,6 +37,7 @@ from metadata.ingestion.api.models import Either from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.database.common_db_source import CommonDbSourceService from metadata.ingestion.source.database.mysql.models import ( DEFAULT_STORED_PROC_LANGUAGE, @@ -76,6 +78,15 @@ def create(cls, config_dict, metadata: OpenMetadata, pipeline_name: Optional[str raise InvalidSourceException(f"Expected MysqlConnection, but got {connection}") return cls(config, metadata) + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Seed the run-level ``Database`` counter with MySQL's single database and + let the runner reconcile the ``DatabaseSchema`` total from the schemas it + observes. MySQL exposes schemas only through the live inspector, which the + walk queries anyway, so pre-counting them here would just duplicate that + query for no gain.""" + totals.set_total(Database.__name__, len(list(self.get_database_names()))) + totals.mark_reconcilable(DatabaseSchema.__name__) + def get_stored_procedures(self) -> Iterable[MysqlRoutine]: """List stored procedures and functions""" if self.source_config.includeStoredProcedures: diff --git a/ingestion/src/metadata/ingestion/source/database/postgres/connection.py b/ingestion/src/metadata/ingestion/source/database/postgres/connection.py index c645f4506597..c110dc600bc7 100644 --- a/ingestion/src/metadata/ingestion/source/database/postgres/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/postgres/connection.py @@ -54,6 +54,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.classifier import Matcher from metadata.core.connections.test_connection.records import Evidence @@ -153,17 +154,17 @@ class PostgresChecks: # System schemas - skipped when auto-selecting a schema to probe. SYSTEM_SCHEMAS = frozenset({"information_schema", "pg_catalog", "pg_toast"}) - def __init__(self, client: Engine, query_statement_source: str | None) -> None: - self.client = client + def __init__(self, db: Borrowed[Engine], query_statement_source: str | None) -> None: + self._db = db self.query_statement_source = query_statement_source @check(DatabaseStep.CheckAccess) def check_access(self) -> Evidence: - return ping(self.client) + return ping(self._db.client) @check(DatabaseStep.GetDatabases) def get_databases(self) -> Evidence: - return run_sql(self.client, POSTGRES_GET_DATABASE, self._summarize_databases) + return run_sql(self._db.client, POSTGRES_GET_DATABASE, self._summarize_databases) @staticmethod def _summarize_databases(rows: Sequence[object]) -> str: @@ -175,41 +176,43 @@ def _summarize_databases(rows: Sequence[object]) -> str: @check(DatabaseStep.GetSchemas) def get_schemas(self) -> Evidence: - return list_schemas(self.client) + return list_schemas(self._db.client) @check(DatabaseStep.GetTables) def get_tables(self) -> Evidence: - return list_tables(self.client, None, self.SYSTEM_SCHEMAS) + return list_tables(self._db.client, None, self.SYSTEM_SCHEMAS) @check(DatabaseStep.GetViews) def get_views(self) -> Evidence: - return list_views(self.client, None, self.SYSTEM_SCHEMAS) + return list_views(self._db.client, None, self.SYSTEM_SCHEMAS) @check(DatabaseStep.GetTags) def get_tags(self) -> Evidence: - return run_sql(self.client, POSTGRES_TEST_GET_TAGS, lambda _: "policy tags accessible") + return run_sql(self._db.client, POSTGRES_TEST_GET_TAGS, lambda _: "policy tags accessible") @check(DatabaseStep.GetQueries) def get_queries(self) -> Evidence: # Built here, not at construction, so the version-probe query runs only # after CheckAccess has confirmed reachability - never ahead of the gate. statement = POSTGRES_TEST_GET_QUERIES.format( - time_column_name=get_postgres_time_column_name(engine=self.client), + time_column_name=get_postgres_time_column_name(engine=self._db.client), query_statement_source=self.query_statement_source or "pg_stat_statements", ) - return run_sql(self.client, statement, lambda _: "query history accessible") + return run_sql(self._db.client, statement, lambda _: "query history accessible") @check(DatabaseStep.GetColumnMetadata) def get_column_metadata(self) -> Evidence: - return run_sql(self.client, TEST_COLUMN_METADATA, lambda _: "column metadata accessible") + return run_sql(self._db.client, TEST_COLUMN_METADATA, lambda _: "column metadata accessible") @check(DatabaseStep.GetTableComments) def get_table_comments(self) -> Evidence: - return run_sql(self.client, TEST_TABLE_COMMENTS, lambda _: "table comments accessible") + return run_sql(self._db.client, TEST_TABLE_COMMENTS, lambda _: "table comments accessible") @check(DatabaseStep.GetInformationSchemaColumns) def get_information_schema_columns(self) -> Evidence: - return run_sql(self.client, TEST_INFORMATION_SCHEMA_COLUMNS, lambda _: "information_schema.columns accessible") + return run_sql( + self._db.client, TEST_INFORMATION_SCHEMA_COLUMNS, lambda _: "information_schema.columns accessible" + ) class PostgresConnection(BaseConnection[PostgresConnectionConfig, Engine]): @@ -224,6 +227,6 @@ def _get_client(self) -> Engine: def checks(self) -> ChecksProvider: return PostgresChecks( - client=self.client, + db=self.borrow(), query_statement_source=self.service_connection.queryStatementSource, ) diff --git a/ingestion/src/metadata/ingestion/source/database/query_parser_source.py b/ingestion/src/metadata/ingestion/source/database/query_parser_source.py index 599ad4407e9d..20585d7be5ff 100644 --- a/ingestion/src/metadata/ingestion/source/database/query_parser_source.py +++ b/ingestion/src/metadata/ingestion/source/database/query_parser_source.py @@ -27,16 +27,20 @@ from metadata.ingestion.lineage.masker import masked_query_cache from metadata.ingestion.lineage.models import ConnectionTypeDialectMapper from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import ProgressMode +from metadata.ingestion.progress.tracking import ( + ProgressTracking, + attach_progress_tracking, +) from metadata.ingestion.source.connections import test_connection_common from metadata.utils.helpers import get_start_and_end, retry_with_docker_host from metadata.utils.logger import ingestion_logger -from metadata.utils.progress_tracking import ProgressTrackingMixin from metadata.utils.ssl_manager import get_ssl_connection logger = ingestion_logger() -class QueryParserSource(ProgressTrackingMixin, Source, ABC): +class QueryParserSource(Source, ABC): """ Core class to be inherited for sources that parse query logs, be it for usage or lineage. @@ -46,6 +50,14 @@ class QueryParserSource(ProgressTrackingMixin, Source, ABC): some utilities to be overwritten when necessary """ + progress_mode = ProgressMode.MANUAL + + @property + def progress_tracking(self) -> ProgressTracking: + """Composed per-source progress state; these query sources are MANUAL, + so they drive ``progress_tracking.manual`` directly.""" + return attach_progress_tracking(self) + sql_stmt: str dialect: str filters: str diff --git a/ingestion/src/metadata/ingestion/source/database/redshift/connection.py b/ingestion/src/metadata/ingestion/source/database/redshift/connection.py index 999a467a077b..a8bdb4ad195b 100644 --- a/ingestion/src/metadata/ingestion/source/database/redshift/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/redshift/connection.py @@ -67,6 +67,7 @@ from sqlalchemy.engine import Row + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.classifier import Matcher @@ -318,37 +319,37 @@ class RedshiftChecks: # keeps it cheap since the step only proves the read is permitted. _RELATIONS_PROBE = REDSHIFT_GET_ALL_RELATIONS.format(schema_clause="", table_clause="", limit_clause="LIMIT 1") - def __init__(self, client: Engine) -> None: - self.client = client + def __init__(self, db: Borrowed[Engine]) -> None: + self._db = db @check(DatabaseStep.CheckAccess) def check_access(self) -> Evidence: - return ping(self.client) + return ping(self._db.client) @check(DatabaseStep.GetDatabases) def get_databases(self) -> Evidence: - return run_sql(self.client, REDSHIFT_GET_DATABASE_NAMES, _summarize_databases) + return run_sql(self._db.client, REDSHIFT_GET_DATABASE_NAMES, _summarize_databases) @check(DatabaseStep.GetSchemas) def get_schemas(self) -> Evidence: - return list_schemas(self.client) + return list_schemas(self._db.client) @check(DatabaseStep.GetTables) def get_tables(self) -> Evidence: - return run_sql(self.client, self._RELATIONS_PROBE, lambda rows: f"{len(rows)} relations accessible") + return run_sql(self._db.client, self._RELATIONS_PROBE, lambda rows: f"{len(rows)} relations accessible") @check(DatabaseStep.GetViews) def get_views(self) -> Evidence: - return run_sql(self.client, self._RELATIONS_PROBE, lambda rows: f"{len(rows)} relations accessible") + return run_sql(self._db.client, self._RELATIONS_PROBE, lambda rows: f"{len(rows)} relations accessible") @check(DatabaseStep.GetQueries) def get_queries(self) -> Evidence: # Resolved here, not at construction, so the instance-type probe and the # privilege query run only after CheckAccess - never ahead of the gate. - instance_type = get_redshift_instance_type(self.client) + instance_type = get_redshift_instance_type(self._db.client) statement = REDSHIFT_TEST_GET_QUERIES_MAP[instance_type] try: - evidence = run_sql(self.client, statement, lambda rows: _summarize_queries(instance_type, rows)) + evidence = run_sql(self._db.client, statement, lambda rows: _summarize_queries(instance_type, rows)) except SourceConnectionException as missing_privilege: # The privilege probe raises from the summary callback, outside run_sql's # own CheckError wrapping - re-raise with the statement so the failed step @@ -368,4 +369,4 @@ def _get_client(self) -> Engine: return engine def checks(self) -> ChecksProvider: - return RedshiftChecks(client=self.client) + return RedshiftChecks(db=self.borrow()) diff --git a/ingestion/src/metadata/ingestion/source/database/redshift/metadata.py b/ingestion/src/metadata/ingestion/source/database/redshift/metadata.py index 41cf64f0b87b..bf7f730e00a0 100644 --- a/ingestion/src/metadata/ingestion/source/database/redshift/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/redshift/metadata.py @@ -13,7 +13,7 @@ """ import traceback -from typing import Iterable, List, Optional # noqa: UP035 +from typing import Dict, Iterable, List, Optional # noqa: UP035 from sqlalchemy import sql, text from sqlalchemy.dialects.postgresql.base import PGDialect @@ -54,6 +54,7 @@ from metadata.ingestion.api.models import Either from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.database.common_db_source import ( CommonDbSourceService, TableNameAndType, @@ -76,6 +77,7 @@ REDSHIFT_EXTERNAL_TABLE_LOCATION, REDSHIFT_GET_ALL_CONSTRAINTS, REDSHIFT_GET_ALL_RELATION_INFO, + REDSHIFT_GET_ALL_SCHEMAS, REDSHIFT_GET_DATABASE_NAMES, REDSHIFT_GET_STORED_PROCEDURES, REDSHIFT_LIFE_CYCLE_QUERY, @@ -95,7 +97,6 @@ get_view_definition, ) from metadata.utils import fqn -from metadata.utils.filters import filter_by_database from metadata.utils.helpers import clean_up_starting_ending_double_quotes_in_string from metadata.utils.logger import ingestion_logger from metadata.utils.sqlalchemy_utils import ( @@ -277,6 +278,58 @@ def set_external_location_map(self, database_name: str) -> None: results = conn.execute(text(REDSHIFT_EXTERNAL_TABLE_LOCATION.format(database_name=database_name))).all() self.external_location_map = {(database_name, row.schemaname, row.tablename): row.location for row in results} + def _filtered_database_names_for_totals(self) -> List[str]: # noqa: UP006 + """Filtered database names for the progress denominator. Single configured + database when ``ingestAllDatabases`` is off, else the filtered result of the + lightweight ``pg_database`` enumeration. Emits no status side effects.""" + configured_db = self.get_configured_database() + if configured_db: + result = [configured_db] + else: + result = [db for db in self.get_database_names_raw() if not self._is_database_filtered(db)] + return result + + def _schema_names_by_database(self) -> "Optional[Dict[str, List[str]]]": # noqa: UP006,UP045 + """``{database: [schema_names]}`` for every visible database from a single + cross-database ``SVV_ALL_SCHEMAS`` — one round-trip, no per-database + reconnect. Returns ``None`` when the view is unavailable (older cluster or + restricted role) so the caller falls back to reconcile-only.""" + try: + rows = self.connection.execute(text(REDSHIFT_GET_ALL_SCHEMAS)).fetchall() + except Exception as exc: # pylint: disable=broad-except + logger.warning( + "SVV_ALL_SCHEMAS unavailable (%s); progress schema total will reconcile during the walk.", + exc, + ) + return None + by_database: Dict[str, List[str]] = {} # noqa: UP006 + for row in rows: + database_name = row[0] + schema_name = row[1] + if database_name is not None and schema_name is not None: + by_database.setdefault(str(database_name), []).append(str(schema_name)) + return by_database + + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Seed the run-level ``Database`` and ``DatabaseSchema`` counters upfront. + ``Database`` is the filtered DB count; ``DatabaseSchema`` is the post-filter + schema count per database from the cross-database ``SVV_ALL_SCHEMAS``. When + that view is unavailable the schema counter is marked reconcilable so the + walk fills its total instead.""" + database_names = self._filtered_database_names_for_totals() + totals.set_total(Database.__name__, len(database_names)) + schemas_by_database = self._schema_names_by_database() + if schemas_by_database is None: + totals.mark_reconcilable(DatabaseSchema.__name__) + else: + for database_name in database_names: + kept = [ + schema_name + for schema_name in schemas_by_database.get(database_name, []) + if not self._is_schema_filtered(database_name, schema_name) + ] + totals.seed_scope_total(DatabaseSchema.__name__, database_name, len(kept)) + def get_database_names(self) -> Iterable[str]: if not self.config.serviceConnection.root.config.ingestAllDatabases: # pyright: ignore[reportAttributeAccessIssue] configured_db = self.config.serviceConnection.root.config.database # pyright: ignore[reportAttributeAccessIssue] @@ -285,17 +338,13 @@ def get_database_names(self) -> Iterable[str]: yield configured_db else: for new_database in self.get_database_names_raw(): - database_fqn = fqn.build( - self.metadata, - entity_type=Database, - service_name=self.context.get().database_service, - database_name=new_database, - ) - - if filter_by_database( - self.source_config.databaseFilterPattern, - (database_fqn if self.source_config.useFqnForFiltering else new_database), - ): + if self._is_database_filtered(new_database): + database_fqn = fqn.build( + self.metadata, + entity_type=Database, + service_name=self.context.get().database_service, # pyright: ignore[reportAttributeAccessIssue] + database_name=new_database, + ) self.status.filter(database_fqn, "Database Filtered Out") continue diff --git a/ingestion/src/metadata/ingestion/source/database/redshift/queries.py b/ingestion/src/metadata/ingestion/source/database/redshift/queries.py index d49fedc7e01e..2f0e28bfdc47 100644 --- a/ingestion/src/metadata/ingestion/source/database/redshift/queries.py +++ b/ingestion/src/metadata/ingestion/source/database/redshift/queries.py @@ -293,6 +293,10 @@ SELECT datname FROM pg_database """ +REDSHIFT_GET_ALL_SCHEMAS = """ +SELECT database_name, schema_name FROM SVV_ALL_SCHEMAS +""" + REDSHIFT_TEST_GET_QUERIES = """ SELECT has_table_privilege('SVV_TABLE_INFO', 'SELECT') as can_access_svv_table_info, diff --git a/ingestion/src/metadata/ingestion/source/database/redshift/utils.py b/ingestion/src/metadata/ingestion/source/database/redshift/utils.py index 4db9843248a0..b215a18e4162 100644 --- a/ingestion/src/metadata/ingestion/source/database/redshift/utils.py +++ b/ingestion/src/metadata/ingestion/source/database/redshift/utils.py @@ -45,6 +45,19 @@ ischema_names["geography"] = GEOGRAPHY ischema_names.update({"binary varying": sqltypes.VARBINARY}) ischema_names.update(REDSHIFT_ISCHEMA_NAMES) +# Redshift Spectrum external tables (backed by the Glue/Hive catalog) report +# Hive-style column types via svv_external_columns. These have no PostgreSQL +# equivalent in ischema_names, so they resolved to UNKNOWN and broke +# column-level test type selection (issue #29589). Map the common scalar Hive +# types to concrete types (dataTypeDisplay still shows the raw Hive type). +ischema_names.update( + { + "string": sqltypes.VARCHAR, + "char": sqltypes.CHAR, + "tinyint": create_sqlalchemy_type("TINYINT"), + "double": sqltypes.DOUBLE_PRECISION, + } +) logger = ingestion_logger() diff --git a/ingestion/src/metadata/ingestion/source/database/salesforce/metadata.py b/ingestion/src/metadata/ingestion/source/database/salesforce/metadata.py index 68dcc0d264d5..730b7a5e470f 100644 --- a/ingestion/src/metadata/ingestion/source/database/salesforce/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/salesforce/metadata.py @@ -13,7 +13,7 @@ """ import traceback -from typing import Any, Iterable, List, Optional, Tuple # noqa: UP035 +from typing import Any, Iterable, List, Optional, Tuple, cast # noqa: UP035 from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createDatabaseSchema import ( @@ -47,12 +47,10 @@ from metadata.generated.schema.type.basic import EntityName, FullyQualifiedEntityName from metadata.ingestion.api.models import Either from metadata.ingestion.api.steps import InvalidSourceException -from metadata.ingestion.connections.test_connections import ( - raise_test_connection_exception, -) +from metadata.ingestion.connections.connection import BaseConnection # noqa: TC001 from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection, get_test_connection_fn +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.ingestion.source.database.stored_procedures_mixin import QueryByProcedure from metadata.utils import fqn @@ -81,7 +79,13 @@ def __init__(self, config, metadata: OpenMetadata): self.ssl_manager: SSLManager = check_ssl_and_init(self.service_connection) if self.ssl_manager: self.service_connection = self.ssl_manager.setup_ssl(self.service_connection) - self.client = get_connection(self.service_connection) + self._connection = create_connection(self.service_connection) + self.client = cast("BaseConnection", self._connection).client + try: + self.test_connection() + except Exception: + self.close() + raise self.table_constraints = None self.database_source_state = set() @@ -369,11 +373,3 @@ def get_source_url( logger.debug(traceback.format_exc()) logger.warning(f"Unable to get source url for {table_name}: {exc}") return None - - def close(self): - """Nothing to close""" - - def test_connection(self) -> None: - test_connection_fn = get_test_connection_fn(self.service_connection) - result = test_connection_fn(self.client, self.service_connection) - raise_test_connection_exception(result) diff --git a/ingestion/src/metadata/ingestion/source/database/sas/metadata.py b/ingestion/src/metadata/ingestion/source/database/sas/metadata.py index da5521f35f86..2a3b6d78f285 100644 --- a/ingestion/src/metadata/ingestion/source/database/sas/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/sas/metadata.py @@ -20,7 +20,7 @@ import traceback from dataclasses import dataclass from datetime import datetime, timezone -from typing import Any, Iterable, Optional, Tuple # noqa: UP035 +from typing import TYPE_CHECKING, Any, Iterable, Optional, Tuple, cast # noqa: UP035 from requests.exceptions import HTTPError @@ -73,7 +73,7 @@ from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import get_connection, test_connection_common +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.column_type_parser import ColumnTypeParser from metadata.ingestion.source.database.database_service import DatabaseServiceSource from metadata.ingestion.source.database.sas.client import SASClient @@ -81,6 +81,10 @@ from metadata.utils import fqn from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from metadata.ingestion.connections.connection import BaseConnection + + logger = ingestion_logger() @@ -179,9 +183,13 @@ def __init__(self, config: WorkflowSource, metadata: OpenMetadata): self.source_config: DatabaseServiceMetadataPipeline = self.config.sourceConfig.config self.service_connection = self.config.serviceConnection.root.config - self.sas_client = get_connection(self.service_connection) - self.connection_obj = self.sas_client - self.test_connection() + self._connection = create_connection(self.service_connection) + self.sas_client = cast("BaseConnection", self._connection).client + try: + self.test_connection() + except Exception: + self.close() + raise self.db_service_name = self.config.serviceName self.db_name = None @@ -924,9 +932,3 @@ def get_stored_procedures(self) -> Iterable[Any]: def yield_stored_procedure(self, stored_procedure: Any) -> Iterable[Either[CreateStoredProcedureRequest]]: """Not implemented""" - - def close(self) -> None: - pass - - def test_connection(self) -> None: - test_connection_common(self.metadata, self.connection_obj, self.service_connection) diff --git a/ingestion/src/metadata/ingestion/source/database/snowflake/connection.py b/ingestion/src/metadata/ingestion/source/database/snowflake/connection.py index a8a29bd1c188..f56d199c42ac 100644 --- a/ingestion/src/metadata/ingestion/source/database/snowflake/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/snowflake/connection.py @@ -76,6 +76,7 @@ from sqlalchemy.engine import Row + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.classifier import Matcher @@ -316,15 +317,22 @@ class SnowflakeChecks: before the gate. """ - def __init__(self, client: Engine, service_connection: SnowflakeConnectionConfig) -> None: - self.client = client + def __init__(self, db: Borrowed[Engine], service_connection: SnowflakeConnectionConfig) -> None: + self._db = db self.service_connection = service_connection self.errors = _snowflake_errors(service_connection.accountUsageSchema) - self._engine_wrapper = SnowflakeEngineWrapper( - service_connection=service_connection, - engine=client, - database_name=None, - ) + self._wrapper: SnowflakeEngineWrapper | None = None + + @property + def _engine_wrapper(self) -> SnowflakeEngineWrapper: + """Built on first use: it holds the engine, and reading the borrow builds it.""" + if self._wrapper is None: + self._wrapper = SnowflakeEngineWrapper( + service_connection=self.service_connection, + engine=self._db.client, + database_name=None, + ) + return self._wrapper def _database(self) -> str | None: """Resolve (and cache) the database to probe. Runs ``SHOW DATABASES`` only @@ -357,16 +365,16 @@ def check_access(self) -> Evidence: tcp_probe(host, port) except NetworkUnreachableError as error: raise CheckError(error, Evidence(command=f"TCP connect {host}:{port}")) from error - return ping(self.client) + return ping(self._db.client) @check(DatabaseStep.GetDatabases) def get_databases(self) -> Evidence: - return run_sql(self.client, SNOWFLAKE_GET_DATABASES, lambda rows: _count_summary(rows, "database")) + return run_sql(self._db.client, SNOWFLAKE_GET_DATABASES, lambda rows: _count_summary(rows, "database")) @check(DatabaseStep.GetSchemas) def get_schemas(self) -> Evidence: statement = SNOWFLAKE_TEST_GET_SCHEMAS.format(database_name=self._database()) - return run_sql(self.client, statement, lambda rows: _count_summary(rows, "schema")) + return run_sql(self._db.client, statement, lambda rows: _count_summary(rows, "schema")) @check(DatabaseStep.GetTables) def get_tables(self) -> Evidence: @@ -378,7 +386,7 @@ def summarize(rows: Sequence[Row]) -> str: counts.append(len(rows)) return _count_summary(rows, "table") - evidence = run_sql(self.client, statement, summarize) + evidence = run_sql(self._db.client, statement, summarize) if not counts[0]: evidence = replace(evidence, caveat=_no_tables_caveat(database)) return evidence @@ -386,27 +394,27 @@ def summarize(rows: Sequence[Row]) -> str: @check(DatabaseStep.GetViews) def get_views(self) -> Evidence: statement = SNOWFLAKE_TEST_GET_VIEWS.format(database_name=self._database()) - return run_sql(self.client, statement, lambda rows: _count_summary(rows, "view")) + return run_sql(self._db.client, statement, lambda rows: _count_summary(rows, "view")) @check(DatabaseStep.GetStreams) def get_streams(self) -> Evidence: statement = SNOWFLAKE_TEST_GET_STREAMS.format(database_name=self._database()) - return run_sql(self.client, statement, lambda rows: _count_summary(rows, "stream")) + return run_sql(self._db.client, statement, lambda rows: _count_summary(rows, "stream")) @check(DatabaseStep.GetTags) def get_tags(self) -> Evidence: statement = SNOWFLAKE_TEST_FETCH_TAG.format(account_usage=self.service_connection.accountUsageSchema) - return run_sql(self.client, statement, lambda _: "tags accessible") + return run_sql(self._db.client, statement, lambda _: "tags accessible") @check(DatabaseStep.GetQueries) def get_queries(self) -> Evidence: statement = SNOWFLAKE_TEST_GET_QUERIES.format(account_usage=self.service_connection.accountUsageSchema) - return run_sql(self.client, statement, lambda _: "query history accessible") + return run_sql(self._db.client, statement, lambda _: "query history accessible") @check(DatabaseStep.GetAccessHistory) def get_access_history(self) -> Evidence: statement = SNOWFLAKE_ACCESS_HISTORY_PROBE.format(account_usage=self.service_connection.accountUsageSchema) - return run_sql(self.client, statement, lambda _: "access history accessible") + return run_sql(self._db.client, statement, lambda _: "access history accessible") class SnowflakeConnection(BaseConnection[SnowflakeConnectionConfig, Engine]): @@ -520,6 +528,6 @@ def get_connection(self) -> Engine: def checks(self) -> ChecksProvider: return SnowflakeChecks( - client=self.client, + db=self.borrow(), service_connection=self.service_connection, ) diff --git a/ingestion/src/metadata/ingestion/source/database/snowflake/lineage.py b/ingestion/src/metadata/ingestion/source/database/snowflake/lineage.py index 468d6aef3ab1..a987b138355f 100644 --- a/ingestion/src/metadata/ingestion/source/database/snowflake/lineage.py +++ b/ingestion/src/metadata/ingestion/source/database/snowflake/lineage.py @@ -245,17 +245,17 @@ def _yield_access_history_lineage(self) -> Iterable[Either[AddLineageRequest]]: The two phases are isolated: a catastrophic failure in the combined ACCESS_HISTORY phase must not stop the COPY_HISTORY phase, and vice versa. """ - self.progress.set_total("LineageRecords", None) + self.progress_tracking.manual.set_total("LineageRecords", None) try: for either in self._yield_combined_access_history(): - self.progress.track("LineageRecords") + self.progress_tracking.manual.track("LineageRecords") yield either except Exception as exc: logger.warning("ACCESS_HISTORY combined lineage phase failed: %s", exc) logger.debug(traceback.format_exc()) try: for either in self._yield_copy_history_lineage(): - self.progress.track("LineageRecords") + self.progress_tracking.manual.track("LineageRecords") yield either except Exception as exc: logger.warning("COPY_HISTORY lineage phase failed: %s", exc) diff --git a/ingestion/src/metadata/ingestion/source/database/snowflake/metadata.py b/ingestion/src/metadata/ingestion/source/database/snowflake/metadata.py index 8bbdc086e0cf..0a54ac111b23 100644 --- a/ingestion/src/metadata/ingestion/source/database/snowflake/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/snowflake/metadata.py @@ -76,6 +76,7 @@ IncrementalConfig, ) from metadata.ingestion.source.database.multi_db_source import MultiDBSource +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.database.snowflake.constants import ( DEFAULT_STREAM_COLUMNS, PROCEDURE_TYPE_URL_MAP, @@ -129,7 +130,7 @@ normalize_names, ) from metadata.utils import fqn -from metadata.utils.filters import filter_by_database, filter_by_schema +from metadata.utils.filters import filter_by_database from metadata.utils.logger import ingestion_logger from metadata.utils.sqlalchemy_utils import ( get_all_table_comments, @@ -217,8 +218,6 @@ class SnowflakeSource( service_connection: SnowflakeConnection - progress_tracking_enabled = True - def __init__( self, config, @@ -468,31 +467,17 @@ def _schema_names_by_database(self) -> "Optional[Dict[str, List[str]]]": # noqa by_database[database_name].append(str(schema_name)) return by_database - def _is_schema_filtered(self, database_name: str, schema_name: str) -> bool: - """Whether a schema fails the schema filter pattern, matched the same way - as the lazy producer (FQN or bare name per ``useFqnForFiltering``). - Context-free: the FQN is built with the explicit database name.""" - schema_fqn = fqn.build( - self.metadata, - entity_type=DatabaseSchema, - service_name=self.context.get().database_service, # pyright: ignore[reportAttributeAccessIssue] - database_name=database_name, - schema_name=schema_name, - ) - filter_name = schema_fqn if self.source_config.useFqnForFiltering and schema_fqn else schema_name - return filter_by_schema(self.source_config.schemaFilterPattern, filter_name) - - def _declare_progress_totals(self) -> None: + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: """Seed the run-level ``Database`` and ``DatabaseSchema`` global counters upfront. ``Database`` is the filtered DB count; ``DatabaseSchema`` is the post-filter schema count per database from the account-wide SHOW. When that SHOW is unavailable, the schema counter is marked reconcilable so the walk fills its total instead.""" database_names = self._filtered_database_names() - self.progress.set_total(Database.__name__, len(database_names)) + totals.set_total(Database.__name__, len(database_names)) schemas_by_database = self._schema_names_by_database() if schemas_by_database is None: - self.progress.set_reconcilable(DatabaseSchema.__name__) + totals.mark_reconcilable(DatabaseSchema.__name__) else: for database_name in database_names: kept = [ @@ -500,11 +485,9 @@ def _declare_progress_totals(self) -> None: for schema_name in schemas_by_database.get(database_name, []) if not self._is_schema_filtered(database_name, schema_name) ] - self.progress.seed_scope_total(DatabaseSchema.__name__, database_name, len(kept)) + totals.seed_scope_total(DatabaseSchema.__name__, database_name, len(kept)) def get_database_names(self) -> Iterable[str]: - if self.progress_tracking_enabled: - self._declare_progress_totals() for database_name in self._filtered_database_names(): try: self.set_inspector(database_name=database_name) diff --git a/ingestion/src/metadata/ingestion/source/database/unitycatalog/connection.py b/ingestion/src/metadata/ingestion/source/database/unitycatalog/connection.py index 608eeb327888..3db5d7513f3a 100644 --- a/ingestion/src/metadata/ingestion/source/database/unitycatalog/connection.py +++ b/ingestion/src/metadata/ingestion/source/database/unitycatalog/connection.py @@ -8,23 +8,41 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - """ Source connection handler """ +from __future__ import annotations + from copy import deepcopy -from functools import partial -from typing import Optional +from typing import TYPE_CHECKING, Optional from urllib.parse import quote_plus from databricks.sdk import WorkspaceClient +from databricks.sdk.errors import ( + NotFound, + PermissionDenied, + ResourceDoesNotExist, + Unauthenticated, +) from databricks.sdk.service.catalog import TableType from sqlalchemy import text from sqlalchemy.engine import Engine -from metadata.generated.schema.entity.automations.workflow import ( - Workflow as AutomationWorkflow, +from metadata.core.connections.test_connection import ( + ErrorPack, + Evidence, + Matchers, + check, + when, +) +from metadata.core.connections.test_connection.check import CheckError +from metadata.core.connections.test_connection.checks.database import DatabaseStep +from metadata.core.connections.test_connection.constants import STEP_TIMEOUT_SECONDS +from metadata.core.connections.test_connection.network import ( + NETWORK_ERRORS, + NetworkUnreachableError, + tcp_probe, ) from metadata.generated.schema.entity.services.connections.database.databricks.azureAdSetup import ( AzureAdSetup, @@ -38,21 +56,20 @@ from metadata.generated.schema.entity.services.connections.database.unityCatalogConnection import ( UnityCatalogConnection as UnityCatalogConnectionConfig, ) -from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - TestConnectionResult, -) from metadata.ingestion.connections.builders import ( create_generic_db_connection, get_connection_args_common, init_empty_connection_arguments, ) from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.connections.test_connections import ( - SourceConnectionException, - test_connection_steps, +from metadata.ingestion.connections.test_connections import SourceConnectionException +from metadata.ingestion.source.database.databricks.auth import ( + get_auth_config, + normalize_host_port, +) +from metadata.ingestion.source.database.databricks.connection import ( + DatabricksApiConnection, ) -from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.database.databricks.auth import get_auth_config from metadata.ingestion.source.database.databricks.log_filters import ( suppress_user_agent_entry_deprecation_log, ) @@ -65,14 +82,96 @@ UNITY_CATALOG_TEST_COLUMN_LINEAGE, UNITY_CATALOG_TEST_TABLE_LINEAGE, ) -from metadata.utils.constants import THREE_MIN -from metadata.utils.db_utils import get_host_from_host_port + +if TYPE_CHECKING: + from collections.abc import Callable + + from metadata.core.connections.lifetime import Borrowed + from metadata.core.connections.test_connection import ChecksProvider suppress_user_agent_entry_deprecation_log() INTERNAL_CATALOG = "__databricks_internal" VIEW_TABLE_TYPES = {TableType.VIEW, TableType.MATERIALIZED_VIEW} VIEW_LISTING_SCAN_LIMIT = 100 +DEFAULT_UNITY_CATALOG_PORT = 443 +LINEAGE_PROBE_COMMAND = ( + "SELECT COUNT(*) FROM system.access.table_lineage; SELECT COUNT(*) FROM system.access.column_lineage" +) +TAG_PROBE_COMMAND = "SELECT * FROM information_schema.{catalog_tags,schema_tags,table_tags,column_tags} LIMIT 1" + +UNITY_CATALOG_ERRORS = ErrorPack( + when(Matchers.exception(Unauthenticated)).diagnose( + "Authentication failed", + fix="The workspace rejected the credentials. Verify the personal access token, OAuth " + "client secret, or Azure AD credentials are valid and not expired.", + ), + when(Matchers.contains("invalid access token")).diagnose( + "Authentication failed", + fix="The workspace rejected the access token. Verify it is valid, not expired, and " + "belongs to a user with access to this workspace.", + ), + when(Matchers.contains("token is expired")).diagnose( + "Access token expired", + fix="The access token has expired. Generate a new token and update the connection.", + ), + when(Matchers.exception(PermissionDenied)).diagnose( + "Insufficient privileges", + fix="Grant the connection's principal the privileges the failing step needs: USE CATALOG " + "on the catalog, USE SCHEMA on the schema, and SELECT on its tables.", + ), + when(Matchers.contains("permission_denied")).diagnose( + "Insufficient privileges", + fix="Grant the connection's principal the privileges the failing step needs: USE CATALOG " + "on the catalog, USE SCHEMA on the schema, and SELECT on its tables.", + ), + when(Matchers.contains("insufficient_permissions")).diagnose( + "Insufficient privileges", + fix="Grant the connection's principal the privileges the failing step needs: USE CATALOG " + "on the catalog, USE SCHEMA on the schema, and SELECT on its tables.", + ), + when(Matchers.exception(ResourceDoesNotExist, NotFound)).diagnose( + "Object not found", + fix="The configured catalog or schema does not exist, or is not visible to the " + "connection's principal. Verify the names and the USE CATALOG / USE SCHEMA grants.", + ), + when(Matchers.contains("no_such_catalog")).diagnose( + "Catalog not found", + fix="The configured catalog does not exist or is not visible. Verify the catalog name and " + "that the principal has USE CATALOG on it.", + ), + when(Matchers.contains("no_such_schema")).diagnose( + "Schema not found", + fix="The configured schema does not exist or is not visible. Verify the schema name and " + "that the principal has USE SCHEMA on it.", + ), + when(Matchers.contains("table_or_view_not_found")).diagnose( + "Table or view not found", + fix="The referenced table or view does not exist or is not visible. Verify the object " + "exists and the principal has SELECT on it.", + ), + when(Matchers.contains("malformed_request")).diagnose( + "Invalid HTTP path", + fix="The HTTP Path is malformed. Copy it from the SQL warehouse (or cluster) Connection " + "Details in Databricks - it must look like /sql/1.0/warehouses/.", + ), + when(Matchers.contains("no valid connection settings")).diagnose( + "SQL warehouse not configured", + fix="The GetQueries and GetTags steps open a SQL connection, which needs an HTTP Path. Set " + "it to a running SQL warehouse (/sql/1.0/warehouses/). Metadata ingestion " + "works without it, but query-log lineage and tag extraction do not.", + ), + when(Matchers.contains("failed to connect to the database")).diagnose( + "SQL warehouse not reachable", + fix="Could not open a SQL connection over the configured HTTP Path. Verify the SQL " + "warehouse is running and the principal can use it, and that the HTTP Path is correct.", + ), + when(Matchers.contains("does not exist")).diagnose( + "Object not found", + fix="Verify the configured catalog, schema, and HTTP path exist and the connection's " + "principal is authorized to use them.", + ), +).including(NETWORK_ERRORS) def _require_resolved_catalog_and_schema(table_obj: DatabricksTable) -> tuple[str, str]: @@ -127,8 +226,6 @@ def get_tables(connection: WorkspaceClient, table_obj: DatabricksTable) -> None: Validate that tables can be listed from the resolved catalog and schema. """ catalog_name, schema_name = _require_resolved_catalog_and_schema(table_obj) - # Only one table is needed to validate access; max_results=1 avoids - # downloading the schema's full table list in a single response. for table in connection.tables.list(catalog_name=catalog_name, schema_name=schema_name, max_results=1): table_obj.name = table.name break @@ -156,8 +253,45 @@ def get_views(connection: WorkspaceClient, table_obj: DatabricksTable) -> None: break +def read_tag_tables(engine: Engine, table_obj: DatabricksTable) -> None: + """ + Validate that the information_schema tag tables are readable for the resolved + catalog and schema. + """ + with engine.connect() as connection: + connection.execute( + text(UNITY_CATALOG_GET_CATALOGS_TAGS.format(database=table_obj.catalog_name).replace(";", " limit 1;")) + ) + connection.execute( + text(UNITY_CATALOG_GET_ALL_SCHEMA_TAGS.format(database=table_obj.catalog_name).replace(";", " limit 1;")) + ) + connection.execute( + text( + UNITY_CATALOG_GET_ALL_TABLE_TAGS.format( + database=table_obj.catalog_name, schema=table_obj.schema_name + ).replace(";", " limit 1;") + ) + ) + connection.execute( + text( + UNITY_CATALOG_GET_ALL_TABLE_COLUMNS_TAGS.format( + database=table_obj.catalog_name, schema=table_obj.schema_name + ).replace(";", " limit 1;") + ) + ) + + +def read_lineage_tables(engine: Engine) -> None: + """ + Validate that the system.access lineage tables are readable. + """ + with engine.connect() as conn: + conn.execute(text(UNITY_CATALOG_TEST_TABLE_LINEAGE)).fetchone() + conn.execute(text(UNITY_CATALOG_TEST_COLUMN_LINEAGE)).fetchone() + + def get_connection_url(connection: UnityCatalogConnectionConfig) -> str: - url = f"{connection.scheme.value}://{connection.hostPort}" + url = f"{connection.scheme.value}://{normalize_host_port(connection.hostPort)}" if connection.catalog: url = f"{url}?catalog={quote_plus(connection.catalog)}" return url @@ -178,7 +312,7 @@ def get_connection(connection: UnityCatalogConnectionConfig) -> WorkspaceClient: client_params["azure_client_secret"] = connection.authType.azureClientSecret.get_secret_value() client_params["azure_tenant_id"] = connection.authType.azureTenantId - return WorkspaceClient(host=get_host_from_host_port(connection.hostPort), **client_params) + return WorkspaceClient(host=normalize_host_port(connection.hostPort), **client_params) def get_sqlalchemy_connection(connection: UnityCatalogConnectionConfig) -> Engine: @@ -207,77 +341,151 @@ def get_sqlalchemy_connection(connection: UnityCatalogConnectionConfig) -> Engin return engine +class UnityCatalogChecks: + """Test-connection checks for Unity Catalog. + + Catalog, schema and table steps borrow the workspace client; lineage and tag + steps borrow the SQL-warehouse Engine. Each is built on first read, in a check. + """ + + errors = UNITY_CATALOG_ERRORS + + def __init__( + self, + workspace: Borrowed[WorkspaceClient], + sql: Borrowed[Engine], + service_connection: UnityCatalogConnectionConfig, + ) -> None: + self._workspace = workspace + self._sql = sql + self.service_connection = service_connection + self.table_obj = DatabricksTable() + + def _probe_target(self) -> tuple[str, int]: + # Same normalization the client uses, so the probe targets the host it connects to. + host_port = normalize_host_port(self.service_connection.hostPort) + host, _, port = host_port.rpartition(":") + if host and port.isdigit(): + return host, int(port) + return host_port, DEFAULT_UNITY_CATALOG_PORT + + @staticmethod + def _probe(operation: Callable[[], None], command: str, summarize: Callable[[], str]) -> Evidence: + """Run a listing helper, reporting the command it attempted; on failure + re-raise as ``CheckError`` so the failed step still carries that command.""" + try: + operation() + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + return Evidence(summary=summarize(), command=command) + + @check(DatabaseStep.CheckAccess) + def check_access(self) -> Evidence: + host, port = self._probe_target() + try: + tcp_probe(host, port) + except NetworkUnreachableError as error: + raise CheckError(error, Evidence(command=f"TCP connect {host}:{port}")) from error + return self._probe(self._list_first_catalog, "catalogs.list()", lambda: "connection established") + + def _list_first_catalog(self) -> None: + """Prove the workspace answers an authenticated call, without paging every catalog.""" + next(iter(self._workspace.client.catalogs.list()), None) + + @check(DatabaseStep.GetDatabases) + def check_databases(self) -> Evidence: + configured = self.service_connection.catalog + return self._probe( + lambda: get_catalogs(self._workspace.client, self.table_obj, configured), + f"catalogs.get({configured!r})" if configured else "catalogs.list()", + lambda: f"catalog '{self.table_obj.catalog_name}' resolved", + ) + + @check(DatabaseStep.GetSchemas) + def check_schemas(self) -> Evidence: + configured = self.service_connection.databaseSchema + return self._probe( + lambda: get_schemas(self._workspace.client, self.table_obj, configured), + f"schemas.get({configured!r})" if configured else "schemas.list()", + lambda: f"schema '{self.table_obj.schema_name}' resolved", + ) + + @check(DatabaseStep.GetTables) + def check_tables(self) -> Evidence: + return self._probe( + lambda: get_tables(self._workspace.client, self.table_obj), + "tables.list()", + lambda: f"tables enumerated in '{self.table_obj.catalog_name}.{self.table_obj.schema_name}'", + ) + + @check(DatabaseStep.GetViews) + def check_views(self) -> Evidence: + return self._probe( + lambda: get_views(self._workspace.client, self.table_obj), + "tables.list(omit_columns=True)", + lambda: f"views enumerated in '{self.table_obj.catalog_name}.{self.table_obj.schema_name}'", + ) + + def _require_warehouse(self, command: str) -> None: + """Fail before building an engine that cannot connect: without an httpPath the + driver has no warehouse to dial. The message is what the pack diagnoses.""" + if not self.service_connection.httpPath: + cause = SourceConnectionException( + "no valid connection settings: the SQL warehouse HTTP Path is not configured" + ) + raise CheckError(cause, Evidence(command=command)) + + @check(DatabaseStep.GetQueries) + def check_queries(self) -> Evidence: + self._require_warehouse(LINEAGE_PROBE_COMMAND) + return self._probe( + lambda: read_lineage_tables(self._sql.client), + LINEAGE_PROBE_COMMAND, + lambda: "lineage tables accessible", + ) + + @check(DatabaseStep.GetTags) + def check_tags(self) -> Evidence: + self._require_warehouse(TAG_PROBE_COMMAND) + return self._probe( + lambda: read_tag_tables(self._sql.client, self.table_obj), + TAG_PROBE_COMMAND, + lambda: "tag tables accessible", + ) + + +class UnityCatalogSqlConnection(BaseConnection[UnityCatalogConnectionConfig, Engine]): + """Owns the SQL-warehouse Engine: a separate lifetime from the workspace client.""" + + def _get_client(self) -> Engine: + engine = get_sqlalchemy_connection(self.service_connection) + self._on_close(engine.dispose) + return engine + + class UnityCatalogConnection(BaseConnection[UnityCatalogConnectionConfig, WorkspaceClient]): + def __init__(self, service_connection: UnityCatalogConnectionConfig) -> None: + super().__init__(service_connection) + # Honor the user-facing connectionTimeout as the per-step budget; a cold + # serverless warehouse can exceed the framework default. + self.step_timeout_seconds = service_connection.connectionTimeout or STEP_TIMEOUT_SECONDS + # Sub-owners, not clients: constructing them opens nothing. + self.sql = UnityCatalogSqlConnection(service_connection) + self.api = DatabricksApiConnection(service_connection) + def _get_client(self) -> WorkspaceClient: return get_connection(self.service_connection) - def test_connection( - self, - metadata: OpenMetadata, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 - ) -> TestConnectionResult: - """ - Test connection. This can be executed either as part - of a metadata workflow or during an Automation Workflow - """ - connection = self.client - service_connection = self.service_connection - - table_obj = DatabricksTable() - engine = get_sqlalchemy_connection(service_connection) - - def get_tags(service_connection: UnityCatalogConnectionConfig, table_obj: DatabricksTable): - engine = get_sqlalchemy_connection(service_connection) - with engine.connect() as connection: - connection.execute( - text( - UNITY_CATALOG_GET_CATALOGS_TAGS.format(database=table_obj.catalog_name).replace( - ";", " limit 1;" - ) - ) - ) - connection.execute( - text( - UNITY_CATALOG_GET_ALL_SCHEMA_TAGS.format(database=table_obj.catalog_name).replace( - ";", " limit 1;" - ) - ) - ) - connection.execute( - text( - UNITY_CATALOG_GET_ALL_TABLE_TAGS.format( - database=table_obj.catalog_name, schema=table_obj.schema_name - ).replace(";", " limit 1;") - ) - ) - connection.execute( - text( - UNITY_CATALOG_GET_ALL_TABLE_COLUMNS_TAGS.format( - database=table_obj.catalog_name, schema=table_obj.schema_name - ).replace(";", " limit 1;") - ) - ) - - def test_lineage_tables(engine: Engine): - with engine.connect() as conn: - conn.execute(text(UNITY_CATALOG_TEST_TABLE_LINEAGE)).fetchone() - conn.execute(text(UNITY_CATALOG_TEST_COLUMN_LINEAGE)).fetchone() - - test_fn = { - "CheckAccess": connection.catalogs.list, - "GetDatabases": partial(get_catalogs, connection, table_obj, service_connection.catalog), - "GetSchemas": partial(get_schemas, connection, table_obj, service_connection.databaseSchema), - "GetTables": partial(get_tables, connection, table_obj), - "GetViews": partial(get_views, connection, table_obj), - "GetQueries": partial(test_lineage_tables, engine), - "GetTags": partial(get_tags, service_connection, table_obj), - } - - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=service_connection.type.value, # pyright: ignore[reportOptionalMemberAccess] - automation_workflow=automation_workflow, - timeout_seconds=service_connection.connectionTimeout or timeout_seconds, + def close(self) -> None: + # Not _on_close: that registry is reset by close(), so a sub-owner + # registered once would not be released on a later reuse cycle. + self.api.close() + self.sql.close() + super().close() + + def checks(self) -> ChecksProvider: + return UnityCatalogChecks( + workspace=self.borrow(), + sql=self.sql.borrow(), + service_connection=self.service_connection, ) diff --git a/ingestion/src/metadata/ingestion/source/database/unitycatalog/lineage.py b/ingestion/src/metadata/ingestion/source/database/unitycatalog/lineage.py index a01b49f50b21..16dca7ce3405 100644 --- a/ingestion/src/metadata/ingestion/source/database/unitycatalog/lineage.py +++ b/ingestion/src/metadata/ingestion/source/database/unitycatalog/lineage.py @@ -14,7 +14,7 @@ import traceback from collections import defaultdict -from typing import Iterable, Optional # noqa: UP035 +from typing import TYPE_CHECKING, Iterable, Optional, cast # noqa: UP035 from sqlalchemy import text @@ -40,10 +40,10 @@ from metadata.ingestion.api.steps import InvalidSourceException, Source from metadata.ingestion.lineage.sql_lineage import get_column_fqn from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.connections import test_connection_common -from metadata.ingestion.source.database.unitycatalog.connection import ( - get_connection, - get_sqlalchemy_connection, +from metadata.ingestion.source.connections import ( + create_connection, + run_test_connection, + test_connection_common, ) from metadata.ingestion.source.database.unitycatalog.queries import ( UNITY_CATALOG_COLUMN_LINEAGE, @@ -55,6 +55,12 @@ from metadata.utils.helpers import retry_with_docker_host from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from metadata.ingestion.source.database.unitycatalog.connection import ( + UnityCatalogConnection as UnityCatalogConnectionHandler, + ) + + logger = ingestion_logger() @@ -74,17 +80,22 @@ def __init__( self.metadata = metadata self.service_connection = self.config.serviceConnection.root.config self.source_config = self.config.sourceConfig.config - self.connection_obj = get_connection(self.service_connection) - self.engine = get_sqlalchemy_connection(self.service_connection) + self._connection = create_connection(self.service_connection) + connection = cast("UnityCatalogConnectionHandler", self._connection) + self.connection_obj = connection.client + self.engine = connection.sql.client self.table_lineage_map: dict[str, set[str]] = defaultdict(set) self.column_lineage_map: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list) self.external_location_map: dict[str, str] = {} - self.test_connection() + try: + self.test_connection() + except Exception: + self.close() + raise def close(self): - """ - By default, there is nothing to close - """ + if self._connection is not None: + self._connection.close() def prepare(self): """ @@ -341,4 +352,7 @@ def _iter(self, *_, **__) -> Iterable[Either[AddLineageRequest]]: yield from self._process_external_location_lineage(table, databricks_table_fqn) def test_connection(self) -> None: - test_connection_common(self.metadata, self.connection_obj, self.service_connection) + if self._connection is not None: + run_test_connection(self.metadata, self._connection) + else: + test_connection_common(self.metadata, self.connection_obj, self.service_connection) diff --git a/ingestion/src/metadata/ingestion/source/database/unitycatalog/metadata.py b/ingestion/src/metadata/ingestion/source/database/unitycatalog/metadata.py index a78be8dccdfb..0e1084067647 100644 --- a/ingestion/src/metadata/ingestion/source/database/unitycatalog/metadata.py +++ b/ingestion/src/metadata/ingestion/source/database/unitycatalog/metadata.py @@ -16,7 +16,7 @@ import traceback from functools import partial from threading import RLock -from typing import Any, Callable, Iterable, List, Optional, Tuple # noqa: UP035 +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, cast # noqa: UP035 from databricks.sdk.service.catalog import ColumnInfo from databricks.sdk.service.catalog import TableConstraint as DBTableConstraint @@ -63,9 +63,10 @@ from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import TotalsDeclarer +from metadata.ingestion.source.connections import create_connection from metadata.ingestion.source.database.column_type_parser import ColumnTypeParser from metadata.ingestion.source.database.database_service import DatabaseServiceSource -from metadata.ingestion.source.database.databricks.client import DatabricksClient from metadata.ingestion.source.database.databricks.ownership import ( DatabricksOwnerResolver, ) @@ -77,10 +78,6 @@ ) from metadata.ingestion.source.database.multi_db_source import MultiDBSource from metadata.ingestion.source.database.stored_procedures_mixin import QueryByProcedure -from metadata.ingestion.source.database.unitycatalog.connection import ( - get_connection, - get_sqlalchemy_connection, -) from metadata.ingestion.source.database.unitycatalog.incremental_table_processor import ( UnityCatalogIncrementalTableProcessor, ) @@ -92,6 +89,7 @@ ) from metadata.ingestion.source.database.unitycatalog.queries import ( UNITY_CATALOG_GET_ALL_SCHEMA_TAGS, + UNITY_CATALOG_GET_ALL_SCHEMAS, UNITY_CATALOG_GET_ALL_TABLE_COLUMNS_TAGS, UNITY_CATALOG_GET_ALL_TABLE_TAGS, UNITY_CATALOG_GET_CATALOGS_TAGS, @@ -103,6 +101,12 @@ from metadata.utils.logger import ingestion_logger from metadata.utils.tag_utils import get_ometa_tag_and_classification +if TYPE_CHECKING: + from metadata.ingestion.source.database.unitycatalog.connection import ( + UnityCatalogConnection as UnityCatalogConnectionHandler, + ) + + logger = ingestion_logger() UNITY_CATALOG_TAG = "UNITY CATALOG TAG" @@ -134,7 +138,9 @@ def __init__( self.service_connection: UnityCatalogConnection = self.config.serviceConnection.root.config self._state_lock = RLock() self.external_location_map = {} - self.client = get_connection(self.service_connection) + self._connection = create_connection(self.service_connection) + connection = cast("UnityCatalogConnectionHandler", self._connection) + self.client = connection.client self.connection_obj = self.client self.table_constraints = [] self.context.storage_location = None @@ -142,7 +148,7 @@ def __init__( self._catalog_cache: dict[str, Any] = {} self._schema_cache: dict[tuple[str, str], Any] = {} self.owner_resolver = DatabricksOwnerResolver( - api_client=DatabricksClient(self.service_connection), + api_client=connection.api.client, metadata=self.metadata, include_owners=self.source_config.includeOwners, ) @@ -156,10 +162,14 @@ def __init__( self.incremental.start_datetime_utc, ) - self.test_connection() - self._sql_connection_map = {} - self.engine = get_sqlalchemy_connection(self.service_connection) + self.engine = connection.sql.client + + try: + self.test_connection() + except Exception: + self.close() + raise @property def sql_connection(self) -> Connection: @@ -213,6 +223,63 @@ def create(cls, config_dict, metadata: OpenMetadata, pipeline_name: Optional[str incremental_config = IncrementalConfig.create(config.sourceConfig.config.incremental, pipeline_name, metadata) # pyright: ignore[reportArgumentType, reportAttributeAccessIssue, reportOptionalMemberAccess] return cls(config, metadata, incremental_config) + def _filtered_database_names_for_totals(self) -> List[str]: # noqa: UP006 + """Filtered database names for the progress denominator. Single configured + catalog when one is set on the connection, else the filtered result of the + catalog enumeration. Emits no status side effects.""" + configured_db = self.get_configured_database() + if configured_db: + result = [configured_db] + else: + result = [db for db in self.get_database_names_raw() if not self._is_database_filtered(db)] + return result + + def _schema_names_by_database(self) -> "Optional[Dict[str, List[str]]]": # noqa: UP006,UP045 + """``{database: [schema_names]}`` for every visible catalog from a single + cross-catalog ``system.information_schema.schemata`` query — one round-trip, + no per-catalog reconnect. Returns ``None`` when the view is unavailable + (missing permissions or the system schema not enabled) so the caller falls + back to reconcile-only.""" + try: + rows = self.sql_connection.execute(text(UNITY_CATALOG_GET_ALL_SCHEMAS)).fetchall() + except Exception as exc: # pylint: disable=broad-except + logger.warning( + "system.information_schema.schemata unavailable (%s); progress schema total will reconcile during the walk.", + exc, + ) + return None + by_database: Dict[str, List[str]] = {} # noqa: UP006 + for row in rows: + database_name = row[0] + schema_name = row[1] + if database_name is not None and schema_name is not None: + by_database.setdefault(str(database_name), []).append(str(schema_name)) + return by_database + + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Seed the run-level ``Database`` and ``DatabaseSchema`` counters upfront. + ``Database`` is the filtered DB count; ``DatabaseSchema`` is the post-filter + schema count per database from the cross-catalog + ``system.information_schema.schemata``. When that view is unavailable the + schema counter is marked reconcilable so the walk fills its total instead.""" + database_names = self._filtered_database_names_for_totals() + totals.set_total(Database.__name__, len(database_names)) + schemas_by_database = self._schema_names_by_database() + if schemas_by_database is None: + totals.mark_reconcilable(DatabaseSchema.__name__) + else: + # Catalog identifiers are case-insensitive: the walk's scope key keeps the + # configured/SDK-listed casing while the view returns catalog_name in its + # own casing, so match case-insensitively to avoid seeding a spurious 0. + schemas_by_lower = {db.lower(): schemas for db, schemas in schemas_by_database.items()} + for database_name in database_names: + kept = [ + schema_name + for schema_name in schemas_by_lower.get(database_name.lower(), []) + if not self._is_schema_filtered(database_name, schema_name) + ] + totals.seed_scope_total(DatabaseSchema.__name__, database_name, len(kept)) + def get_database_names(self) -> Iterable[str]: """ Default case with a single database. @@ -818,8 +885,8 @@ def close(self): sql_connections = list(self._sql_connection_map.values()) for sql_connection in sql_connections: sql_connection.close() - if self.engine: - self.engine.dispose() + if self._connection is not None: + self._connection.close() # pylint: disable=arguments-renamed def get_owner_ref(self, owner: Optional[str]) -> Optional[EntityReferenceList]: # noqa: UP045 diff --git a/ingestion/src/metadata/ingestion/source/database/unitycatalog/queries.py b/ingestion/src/metadata/ingestion/source/database/unitycatalog/queries.py index 27f48e0dbcf6..630a534e4e91 100644 --- a/ingestion/src/metadata/ingestion/source/database/unitycatalog/queries.py +++ b/ingestion/src/metadata/ingestion/source/database/unitycatalog/queries.py @@ -136,3 +136,7 @@ WHERE 1=0 """ ) + +UNITY_CATALOG_GET_ALL_SCHEMAS = """ +SELECT catalog_name, schema_name FROM system.information_schema.schemata +""" diff --git a/ingestion/src/metadata/ingestion/source/database/usage_source.py b/ingestion/src/metadata/ingestion/source/database/usage_source.py index 2865c635d0b5..3ed4e8629744 100644 --- a/ingestion/src/metadata/ingestion/source/database/usage_source.py +++ b/ingestion/src/metadata/ingestion/source/database/usage_source.py @@ -150,6 +150,13 @@ def yield_table_queries(self) -> Iterable[TableQuery]: logger.debug(traceback.format_exc()) logger.warning(f"Unexpected exception processing row [{row}]: {exc}") logger.info(f"Processed {row_count} query log entries for usage") + result_limit = getattr(self.source_config, "resultLimit", None) + if isinstance(result_limit, int) and row_count >= result_limit: + logger.debug( + f"Reached the configured resultLimit of {result_limit} query log entries; " + f"if more queries exist they were truncated and usage may be incomplete. " + f"Consider increasing resultLimit." + ) yield TableQueries(queries=queries) except Exception as exc: if query: @@ -166,12 +173,12 @@ def _iter(self, *_, **__) -> Iterable[Either[TableQuery]]: days = max(1, (self.end - self.start).days) result_limit = self.source_config.resultLimit # pyright: ignore[reportOptionalMemberAccess, reportAttributeAccessIssue] if result_limit is not None: - self.progress.seed_scope_total("Queries", "run", result_limit * days) + self.progress_tracking.manual.seed_scope_total("Queries", "run", result_limit * days) processed = 0 for table_queries in self.get_table_query(): if table_queries: count = len(table_queries.queries) # pyright: ignore[reportAttributeAccessIssue] - self.progress.track("Queries", count) + self.progress_tracking.manual.track("Queries", count) processed += count yield Either(right=table_queries) - self.progress.reconcile_scope_total("Queries", "run", processed) + self.progress_tracking.manual.reconcile_scope_total("Queries", "run", processed) diff --git a/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/client.py b/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/client.py index 1fbbe413aaff..73e8faeb8e79 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/client.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/client.py @@ -171,6 +171,16 @@ def list_dags(self, limit: int = 100, offset: int = 0) -> dict: response = self.client.get(f"{self._prefix}/dags?limit={limit}&offset={offset}") return self._parse_response(response) + def get_dags_count(self) -> Optional[int]: # noqa: UP045 + try: + response = self.list_dags(limit=1) + total_entries = response.get("total_entries") + if isinstance(total_entries, int): + return total_entries + except Exception as exc: + logger.debug(f"Could not fetch DAG count: {exc}") + return None + def get_dag_tasks(self, dag_id: str) -> dict: if self.mwaa_client: return self.mwaa_client.get_dag_tasks(dag_id) diff --git a/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/source.py b/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/source.py index a49d8ca7829c..d443b11ccc63 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/source.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/airflow/api/source.py @@ -48,6 +48,7 @@ from metadata.ingestion.models.ometa_classification import OMetaTagAndClassification from metadata.ingestion.models.pipeline_status import OMetaPipelineStatus from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.pipeline.airflow.api.models import AirflowApiDagDetails from metadata.ingestion.source.pipeline.pipeline_service import PipelineServiceSource from metadata.utils import fqn @@ -92,6 +93,21 @@ def get_pipelines_list(self) -> Iterable[AirflowApiDagDetails]: logger.debug(traceback.format_exc()) logger.warning(f"Error building DAG details for {dag_data.get('dag_id')}: {exc}") + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Seed the ``Pipeline`` denominator from the Airflow REST DAG count. + + Skipped when a ``pipelineFilterPattern`` is configured: the cheap + server-side DAG count cannot honor the include/exclude regex, so the + declared total would overstate the pipelines actually processed. Since + ``Pipeline`` is a leaf counter that is never reconciled down, a filtered + run would otherwise sit permanently below 100%; fall back to + denominator-less progress instead.""" + if self.has_pipeline_filter(): + return + count = self.connection.get_dags_count() + if isinstance(count, int) and count > 0: + totals.set_total("Pipeline", count) + def get_pipeline_name(self, pipeline_details: AirflowApiDagDetails) -> str: return pipeline_details.dag_id diff --git a/ingestion/src/metadata/ingestion/source/pipeline/airflow/connection.py b/ingestion/src/metadata/ingestion/source/pipeline/airflow/connection.py index 06c368c5d18e..96d74d1f207f 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/airflow/connection.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/airflow/connection.py @@ -13,21 +13,42 @@ Source connection handler """ -import os # noqa: I001 -from functools import partial, singledispatch -from typing import Any, Optional -from urllib.parse import quote +from __future__ import annotations + +import os +from functools import singledispatch +from typing import TYPE_CHECKING, Any, Optional +from urllib.parse import quote, urlparse -from airflow import __version__ as airflow_version -from airflow import settings -from airflow.models.serialized_dag import SerializedDagModel from packaging import version +from requests.exceptions import ConnectionError as RequestsConnectionError +from requests.exceptions import JSONDecodeError, SSLError, Timeout from sqlalchemy import create_engine from sqlalchemy.engine import Engine +from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import sessionmaker -from metadata.generated.schema.entity.automations.workflow import ( - Workflow as AutomationWorkflow, +from airflow import __version__ as airflow_version +from airflow import settings +from airflow.models.serialized_dag import SerializedDagModel +from metadata.core.connections.test_connection import ( + ErrorPack, + Evidence, + Matchers, + check, + when, +) +from metadata.core.connections.test_connection.check import CheckError +from metadata.core.connections.test_connection.checks.database import run_sql +from metadata.core.connections.test_connection.checks.pipeline import ( + PipelineStep, + verify_access, +) +from metadata.core.connections.test_connection.classifier import exception_chain +from metadata.core.connections.test_connection.network import ( + NETWORK_ERRORS, + NetworkUnreachableError, + tcp_probe, ) from metadata.generated.schema.entity.services.connections.database.mysqlConnection import ( MysqlConnection as MysqlConnectionConfig, @@ -44,20 +65,21 @@ from metadata.generated.schema.entity.services.connections.pipeline.backendConnection import ( BackendConnection, ) -from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - TestConnectionResult, -) from metadata.ingestion.connections.connection import BaseConnection from metadata.ingestion.connections.query_logger import attach_query_tracker -from metadata.ingestion.connections.test_connections import ( - SourceConnectionException, - test_connection_engine_step, - test_connection_steps, -) -from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.utils.constants import THREE_MIN +from metadata.ingestion.connections.test_connections import SourceConnectionException +from metadata.ingestion.source.pipeline.airflow.api.client import AirflowApiClient from metadata.utils.logger import ingestion_logger +if TYPE_CHECKING: + from collections.abc import Callable + + from sqlalchemy.orm import Session + + from metadata.core.connections.lifetime import Borrowed + from metadata.core.connections.test_connection import ChecksProvider + from metadata.core.connections.test_connection.classifier import Matcher + logger = ingestion_logger() ORM_ACCESS_BLOCKED_ERROR = "Direct database access via the ORM" @@ -198,10 +220,6 @@ def get_connection(connection: AirflowConnectionConfig): ) if isinstance(connection.connection, AirflowRestApiConnection): - from metadata.ingestion.source.pipeline.airflow.api.client import ( # pylint: disable=import-outside-toplevel # noqa: PLC0415 - AirflowApiClient, - ) - return AirflowApiClient(connection) try: @@ -211,12 +229,6 @@ def get_connection(connection: AirflowConnectionConfig): raise SourceConnectionException(msg) from exc -class AirflowPipelineDetailsAccessError(Exception): - """ - Raise when Pipeline information is not retrieved - """ - - class AirflowTaskDetailsAccessError(Exception): """ Raise when Task detail information is not retrieved @@ -277,96 +289,193 @@ def _decorated_check_access(client, host, auth_config, verify: bool) -> Any: # return result -def _test_api_connection( - metadata: OpenMetadata, - client, - service_connection: AirflowConnectionConfig, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 -) -> TestConnectionResult: - rest_config = service_connection.connection - host = str(service_connection.hostPort) if getattr(service_connection, "hostPort", None) else None - auth_config = getattr(rest_config, "authConfig", None) - verify = getattr(rest_config, "verifySSL", True) - - test_fn = { - "CheckAccess": lambda: _decorated_check_access(client, host, auth_config, verify), - "PipelineDetailsAccess": lambda: client.list_dags(limit=1), - "TaskDetailAccess": lambda: True, - } - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=service_connection.type.value, - automation_workflow=automation_workflow, - timeout_seconds=timeout_seconds, - ) +def _http_status(*codes: int) -> Matcher: + """Match an Airflow REST error by HTTP status, across the cause chain.""" + wanted = frozenset(codes) + + def match(error: BaseException) -> bool: + return any( + getattr(getattr(current, "response", None), "status_code", None) in wanted + for current in exception_chain(error) + ) + + return match -def test_connection( - metadata: OpenMetadata, - connection_obj, - service_connection: AirflowConnectionConfig, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 -) -> TestConnectionResult: +def _db_message(*tokens: str) -> Matcher: + """Match a metadata-DB driver error by message token. + + Requires a SQLAlchemy error in the cause chain, so a REST/transport failure + that happens to carry the same words is never diagnosed as a database problem. """ - Test connection. This can be executed either as part - of a metadata workflow or during an Automation Workflow + needles = [token.lower() for token in tokens] + + def match(error: BaseException) -> bool: + chain = list(exception_chain(error)) + result = False + if any(isinstance(current, SQLAlchemyError) for current in chain): + text = " ".join(str(current).lower() for current in chain) + result = any(needle in text for needle in needles) + return result + + return match + + +# Only signals we exercised live or that follow directly from HTTP / driver +# documentation are diagnosed here; everything else keeps its raw error log. +AIRFLOW_ERRORS = ErrorPack( + when(_http_status(401)).diagnose( + "Authentication failed", + fix="Airflow rejected the credentials. Check the username and password (or token) are correct and not expired.", + ), + when(_http_status(403)).diagnose( + "Access denied", + fix="The credentials are valid but lack access. Grant this user permission to read the Airflow REST API.", + ), + when(_http_status(404)).diagnose( + "Endpoint not found", + fix="Airflow returned 404 for this URL. Check the Host and Port point to the Airflow web " + "server, not a UI or console page.", + ), + # A URL that is not the Airflow REST API (an SSO login page, the marketing + # site) answers with HTML that fails to decode as JSON. + when(Matchers.exception(JSONDecodeError)).diagnose( + "Host is not the Airflow REST API", + fix="The host replied with a web page, not the Airflow REST API. Point the Host and Port " + "at the Airflow web server and make sure its REST API is enabled.", + ), + when(Matchers.exception(SSLError)).diagnose( + "TLS verification failed", + fix="The server's certificate could not be verified. Check the Host, or uncheck " + "'Verify SSL' if you use a self-signed certificate.", + ), + when(Matchers.exception(Timeout)).diagnose( + "Connection timed out", + fix="Airflow did not respond in time. Check the Host and Port and that a firewall allows access to it.", + ), + when(Matchers.exception(RequestsConnectionError)).diagnose( + "Cannot reach the host", + fix="Could not reach the host. Check the Host and Port for typos and that it is reachable.", + ), + # Metadata-DB backend path. MySQL answers a bad login with "Access denied" + # (1045) and PostgreSQL with "password authentication failed" (28P01). Gated + # to a SQLAlchemy error so a REST failure carrying the same words is never + # mislabeled as a database problem. + when(_db_message("access denied", "password authentication failed")).diagnose( + "Database authentication failed", + fix="The Airflow metadata database rejected the credentials. Check the database username and password.", + ), +).including(NETWORK_ERRORS) + + +class AirflowChecks: + """Test-connection checks for Airflow. + + The client is dual-mode: an ``AirflowApiClient`` (REST) or a SQLAlchemy + ``Engine`` (metadata-DB backend). ``CheckAccess`` is the gate - it proves the + host and credentials before the later steps run. The client is borrowed from + the connection that owns it; a check never builds or authenticates its own. """ - from metadata.generated.schema.entity.utils.airflowRestApiConnection import ( # pylint: disable=import-outside-toplevel # noqa: PLC0415 - AirflowRestApiConnection, - ) - if isinstance(service_connection.connection, AirflowRestApiConnection): - return _test_api_connection( - metadata, - connection_obj, - service_connection, - automation_workflow, - timeout_seconds, + errors = AIRFLOW_ERRORS + + def __init__(self, client: Borrowed[Any]) -> None: + self._client = client + + @property + def client(self) -> Any: + return self._client.client + + @check(PipelineStep.CheckAccess) + def check_access(self) -> Evidence: + client = self.client + if isinstance(client, AirflowApiClient): + host, auth_config, verify = self._rest_context(client) + self._preflight(client, host) + return verify_access( + lambda: _decorated_check_access(client, host, auth_config, verify), + command="read the Airflow REST API version", + ) + return run_sql(client, "SELECT 1", lambda _: "connection established") + + @staticmethod + def _preflight(client: AirflowApiClient, host: str | None) -> None: + """TCP-probe the host so an unreachable Airflow fails fast as a network + error, instead of waiting out the REST client's connect-retry budget. + + Skipped for MWAA, whose transport is the AWS SDK rather than a socket to + ``host``, and when the host carries no resolvable host:port. + """ + if client.mwaa_client is not None or not host: + return + parsed = urlparse(host) + port = parsed.port or (443 if parsed.scheme == "https" else 80) + if parsed.hostname: + try: + tcp_probe(parsed.hostname, port) + except NetworkUnreachableError as error: + raise CheckError(error, Evidence(command=f"TCP connect {parsed.hostname}:{port}")) from error + + @staticmethod + def _rest_context(client: AirflowApiClient) -> tuple[str | None, Any, bool]: + """Derive host, auth config and verifySSL from the borrowed REST client. + + Read off the client the connection already built, so the provider never + sees the raw config (which is the ability to build a second client). + """ + config = client.config + host = str(config.hostPort) if getattr(config, "hostPort", None) else None + rest_config = config.connection + auth_config = getattr(rest_config, "authConfig", None) + verify = getattr(rest_config, "verifySSL", True) + return host, auth_config, verify + + @check(PipelineStep.PipelineDetailsAccess) + def pipeline_details_access(self) -> Evidence: + client = self.client + if isinstance(client, AirflowApiClient): + return verify_access( + lambda: client.list_dags(limit=1), + command="list one DAG via the Airflow REST API", + ) + return self._backend_step( + lambda session: session.query(SerializedDagModel.dag_id).first(), + command="SELECT dag_id FROM serialized_dag LIMIT 1", + summary="serialized_dag reachable", ) - session_maker = sessionmaker(bind=connection_obj) - session = session_maker() + @check(PipelineStep.TaskDetailAccess) + def task_detail_access(self) -> Evidence: + client = self.client + if isinstance(client, AirflowApiClient): + return Evidence(summary="task details are read per-DAG during ingestion") + return self._backend_step( + _test_task_detail_access, + command="SELECT data FROM serialized_dag LIMIT 1", + summary="serialized_dag task payload reachable", + ) - def test_pipeline_details_access(session): + def _backend_step(self, run: Callable[[Session], object], command: str, summary: str) -> Evidence: + """Run a query against a session bound to the borrowed engine. + + The session is a per-call working handle over the owned engine, not a + second client. On failure re-raise as ``CheckError`` carrying the command, + so the failed step still reports what it ran. + """ try: - # Query only the dag_id column to avoid version compatibility issues - # The data_compressed column doesn't exist in Airflow 2.2.5 - result = session.query(SerializedDagModel.dag_id).first() - return result # noqa: RET504, TRY300 - except Exception as e: - raise AirflowPipelineDetailsAccessError(f"Pipeline details access error: {e}") # noqa: B904 - - test_fn = { - "CheckAccess": partial(test_connection_engine_step, connection_obj), - "PipelineDetailsAccess": partial(test_pipeline_details_access, session), - "TaskDetailAccess": partial(_test_task_detail_access, session), - } - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=service_connection.type.value, - automation_workflow=automation_workflow, - timeout_seconds=timeout_seconds, - ) + with sessionmaker(bind=self.client)() as session: + run(session) + except Exception as cause: + raise CheckError(cause, Evidence(command=command)) from cause + return Evidence(summary=summary, command=command) class AirflowConnection(BaseConnection[AirflowConnectionConfig, Any]): def _get_client(self) -> Any: - return get_connection(self.service_connection) - - def test_connection( - self, - metadata: OpenMetadata, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 - ) -> TestConnectionResult: - return test_connection( - metadata, - self.client, - self.service_connection, - automation_workflow, - timeout_seconds, - ) + client = get_connection(self.service_connection) + if isinstance(client, Engine): + self._on_close(client.dispose) + return client + + def checks(self) -> ChecksProvider: + return AirflowChecks(self.borrow()) diff --git a/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/client.py b/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/client.py index f295241b9811..cbfbc696eca0 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/client.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/client.py @@ -13,7 +13,7 @@ """ import traceback -from typing import Iterable, List, Optional, Tuple # noqa: UP035 +from typing import Any, Iterable, List, Optional, Tuple # noqa: UP035 from metadata.generated.schema.entity.services.connections.pipeline.dbtCloudConnection import ( DBTCloudConnection, @@ -38,6 +38,21 @@ logger = ometa_logger() API_VERSION = "api/v2" +# Bounds the error body kept in the step's error log. +ERROR_DETAIL_LIMIT = 200 + +# Between-retry sleep for the test calls; the client default (30s) would blow a step budget. +TEST_RETRY_WAIT_SECONDS = 2 + + +class DBTCloudApiError(Exception): + """A dbt Cloud API call answered with a non-success HTTP status.""" + + def __init__(self, status_code: int, path: str, detail: str) -> None: + super().__init__(f"dbt Cloud API returned HTTP {status_code} for {path}: {detail}") + self.status_code = status_code + self.path = path + class DBTCloudClient: """ @@ -125,20 +140,37 @@ def _get_jobs( f"environment_id: `{environment_id}` or job_id: `{job_id}` : {exc}" ) - def test_get_jobs(self) -> List[DBTJob]: # noqa: UP006 + def _test_get(self, path: str, params: dict | None = None) -> Any: + """ + Authenticated GET that raises DBTCloudApiError on a non-success status. + + Uses get_raw: dbt Cloud nests the error `code` under `status`, which get does + not recognise, so it would drop the status and return None. + """ + response = self.client.get_raw(path, data=params, retry_wait=TEST_RETRY_WAIT_SECONDS) + if not response.ok: + raise DBTCloudApiError(response.status_code, path, response.text[:ERROR_DETAIL_LIMIT]) + return response.json() + + def test_check_access(self) -> None: + """ + Read one job: the smallest authenticated call proving host, token and account id. + """ + self._test_get(f"/accounts/{self.config.accountId}/jobs/", params={"limit": 1, "offset": 0}) + + def test_get_jobs(self) -> list[DBTJob]: """ test fetch jobs for an account in dbt cloud """ - job_list = self.client.get(f"/accounts/{self.config.accountId}/jobs/") + job_list = self._test_get(f"/accounts/{self.config.accountId}/jobs/") return DBTJobList.model_validate(job_list).Jobs - def test_get_runs(self) -> List[DBTRun]: # noqa: UP006 + def test_get_runs(self) -> list[DBTRun]: """ test fetch runs for a job in dbt cloud """ - result = self.client.get(f"/accounts/{self.config.accountId}/runs/") - run_list = DBTRunList.model_validate(result).Runs - return run_list # noqa: RET504 + result = self._test_get(f"/accounts/{self.config.accountId}/runs/") + return DBTRunList.model_validate(result).Runs or [] def get_jobs(self) -> Iterable[DBTJob]: """ @@ -175,6 +207,58 @@ def get_jobs(self) -> Iterable[DBTJob]: logger.debug(traceback.format_exc()) logger.error(f"Unable to get job info :{exc}") + def _get_jobs_total_count( + self, + project_id: Optional[str] = None, # noqa: UP045 + environment_id: Optional[str] = None, # noqa: UP045 + ) -> int: + """Read the paginated ``total_count`` for a single job filter. Returns + 0 on any failure so a single bad filter never aborts the whole count.""" + try: + filters = [] + if project_id: + filters.append(f"project_id={project_id}") + if environment_id: + filters.append(f"environment_id={environment_id}") + query_string = "?" + "&".join(filters) if filters else "" + + result = self.client.get( + f"/accounts/{self.config.accountId}/jobs/{query_string}", + data={"offset": 0, "limit": 1}, + ) + job_list_response = DBTJobList.model_validate(result) + if job_list_response.extra and job_list_response.extra.pagination: + return job_list_response.extra.pagination.total_count + except Exception as exc: + logger.debug( + f"Could not fetch job count for project_id: `{project_id}`, environment_id: `{environment_id}` : {exc}" + ) + return 0 + + def get_jobs_count(self) -> Optional[int]: # noqa: UP045 + """ + Total number of jobs that will be ingested for the configured filters, + mirroring the ``get_jobs`` filter priority, or ``None`` when it cannot + be determined. + """ + try: + if self.job_ids: + return len(self.job_ids) + + if self.project_ids or self.environment_ids: + project_list = self.project_ids or [None] + env_list = self.environment_ids or [None] + total = 0 + for project_id in project_list: + for environment_id in env_list: + total += self._get_jobs_total_count(project_id=project_id, environment_id=environment_id) + return total + + return self._get_jobs_total_count() + except Exception as exc: + logger.debug(f"Could not fetch job count: {exc}") + return None + def get_latest_successful_run_id(self, job_id: int) -> Optional[int]: # noqa: UP045 """ Get the latest successful run ID for a given job. diff --git a/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/connection.py b/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/connection.py index 93a92d2b5186..b5d291ce74df 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/connection.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/connection.py @@ -13,52 +13,165 @@ Source connection handler """ -from functools import partial -from typing import Optional +from __future__ import annotations -from metadata.generated.schema.entity.automations.workflow import ( - Workflow as AutomationWorkflow, +from typing import TYPE_CHECKING + +from requests.exceptions import ConnectionError as RequestsConnectionError +from requests.exceptions import JSONDecodeError, SSLError, Timeout + +from metadata.core.connections.test_connection import ( + Diagnosis, + ErrorPack, + Evidence, + Matchers, + check, + when, ) +from metadata.core.connections.test_connection.checks.pipeline import ( + PipelineStep, + fetch_list, + verify_access, +) +from metadata.core.connections.test_connection.classifier import exception_chain +from metadata.core.connections.test_connection.network import NETWORK_ERRORS from metadata.generated.schema.entity.services.connections.pipeline.dbtCloudConnection import ( DBTCloudConnection as DBTCloudConnectionConfig, ) -from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - TestConnectionResult, -) from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.connections.test_connections import test_connection_steps -from metadata.ingestion.ometa.ometa_api import OpenMetadata -from metadata.ingestion.source.pipeline.dbtcloud.client import DBTCloudClient -from metadata.utils.constants import THREE_MIN +from metadata.ingestion.source.pipeline.dbtcloud.client import ( + DBTCloudApiError, + DBTCloudClient, +) + +if TYPE_CHECKING: + from metadata.core.connections.lifetime import Borrowed + from metadata.core.connections.test_connection import ChecksProvider + from metadata.core.connections.test_connection.classifier import Matcher + +TOKENS_DOC = "https://docs.getdbt.com/docs/dbt-apis/authentication" +RATE_LIMITS_DOC = "https://docs.getdbt.com/docs/dbt-apis/rate-limits" + +ACCOUNT_ID_FIX = ( + "Check the Account Id - it is the number in https:///settings/accounts// - " + "and that the Token belongs to that account." +) + + +def _http_status(*codes: int) -> Matcher: + """Match a dbt Cloud API error by HTTP status, across the cause chain.""" + wanted = frozenset(codes) + + def match(error: BaseException) -> bool: + return any( + isinstance(current, DBTCloudApiError) and current.status_code in wanted + for current in exception_chain(error) + ) + + return match + + +NO_JOBS_CAVEAT = Diagnosis( + title="No jobs visible", + remediation="The account is readable but has no job. Ingestion reads pipelines from dbt Cloud " + "jobs, so it would find nothing.", +) + +DBTCLOUD_ERRORS = ErrorPack( + # A wrong account id answers 403 "Token is not scoped to account.", never 404. + when(Matchers.contains("not scoped to account")).diagnose( + "Token is not scoped to this account", + fix=ACCOUNT_ID_FIX, + doc=TOKENS_DOC, + ), + when(_http_status(401)).diagnose( + "Authentication failed", + fix="dbt Cloud rejected the token. Check the Token is a valid, unexpired service token or " + "personal access token.", + doc=TOKENS_DOC, + ), + when(_http_status(403)).diagnose( + "Access denied", + fix=f"dbt Cloud refused the request. {ACCOUNT_ID_FIX} If both are right, check the token's " + "permission set covers the projects to ingest.", + doc=TOKENS_DOC, + ), + when(_http_status(404)).diagnose( + "Endpoint not found", + fix=f"Host and Account Id build the path the API answered 404 for. {ACCOUNT_ID_FIX}", + ), + when(_http_status(429)).diagnose( + "Rate limited", + fix="dbt Cloud rate limits the API at 5,000 requests per minute per account and then " + "enforces a five-minute cooldown. Retry in five minutes.", + doc=RATE_LIMITS_DOC, + ), + # A Host that is a valid URL but not the dbt Cloud API (e.g. the marketing site) + # redirects to an HTML page, which answers 200 and fails to decode. + when(Matchers.exception(JSONDecodeError)).diagnose( + "Host is not the dbt Cloud API", + fix="Host answered with a response that is not dbt Cloud API JSON. Set it to your dbt " + "Cloud access URL, e.g. https://cloud.getdbt.com.", + ), + when(Matchers.exception(SSLError)).diagnose( + "TLS verification failed", + fix="The host's certificate could not be verified. Check Host points at dbt Cloud and that " + "any TLS-intercepting proxy is trusted where ingestion runs.", + ), + when(Matchers.exception(Timeout)).diagnose( + "Connection timed out", + fix="dbt Cloud did not answer in time. Check that a firewall or network ACL allows egress " + "to Host from where ingestion runs.", + ), + when(Matchers.exception(RequestsConnectionError)).diagnose( + "Cannot reach the host", + fix="Check Host for typos and that it resolves from where ingestion runs. dbt Cloud is " + "regional - the access URL differs per region.", + ), +).including(NETWORK_ERRORS) + + +class DBTCloudChecks: + """Test-connection checks for dbt Cloud. + + ``CheckAccess`` is the gate: it reads one job, which proves the host, the token + and the account id at once, so the later steps are skipped rather than each + re-dialling the API. The client is borrowed from the connection that owns it. + """ + + errors = DBTCLOUD_ERRORS + + def __init__(self, dbt: Borrowed[DBTCloudClient]) -> None: + self._dbt = dbt + + @check(PipelineStep.CheckAccess) + def check_access(self) -> Evidence: + return verify_access( + lambda: self._dbt.client.test_check_access(), # noqa: PLW0108 + command="read one job of the configured account", + ) + + @check(PipelineStep.GetJobs) + def get_jobs(self) -> Evidence: + return fetch_list( + lambda: self._dbt.client.test_get_jobs(), # noqa: PLW0108 + noun="job", + command="fetch the jobs of the account", + empty_caveat=NO_JOBS_CAVEAT, + ) + + @check(PipelineStep.GetRuns) + def get_runs(self) -> Evidence: + return fetch_list( + lambda: self._dbt.client.test_get_runs(), # noqa: PLW0108 + noun="run", + command="fetch the runs of the account", + ) class DBTCloudConnection(BaseConnection[DBTCloudConnectionConfig, DBTCloudClient]): def _get_client(self) -> DBTCloudClient: - connection = self.service_connection - return DBTCloudClient(connection) - - def test_connection( - self, - metadata: OpenMetadata, - automation_workflow: Optional[AutomationWorkflow] = None, # noqa: UP045 - timeout_seconds: Optional[int] = THREE_MIN, # noqa: UP045 - ) -> TestConnectionResult: - """ - Test connection. This can be executed either as part - of a metadata workflow or during an Automation Workflow - """ - client = self.client - service_connection = self.service_connection - - test_fn = { - "GetJobs": client.test_get_jobs, - "GetRuns": partial(client.test_get_runs), - } - - return test_connection_steps( - metadata=metadata, - test_fn=test_fn, - service_type=service_connection.type.value, # pyright: ignore[reportOptionalMemberAccess] - automation_workflow=automation_workflow, - timeout_seconds=timeout_seconds, - ) + return DBTCloudClient(self.service_connection) + + def checks(self) -> ChecksProvider: + return DBTCloudChecks(dbt=self.borrow()) diff --git a/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/metadata.py b/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/metadata.py index b0d2a52e9efe..60506b451be6 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/metadata.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/dbtcloud/metadata.py @@ -58,6 +58,7 @@ from metadata.ingestion.models.ometa_lineage import LineageRequest from metadata.ingestion.models.pipeline_status import OMetaPipelineStatus from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.pipeline.dbtcloud.models import DBTJob, DBTModel from metadata.ingestion.source.pipeline.pipeline_service import PipelineServiceSource from metadata.utils import fqn @@ -378,6 +379,21 @@ def _yield_column_lineage(self, model: DBTModel, to_entity_fqn: str) -> Iterable logger.debug(traceback.format_exc()) logger.warning(f"Failed to parse compiled SQL for column lineage of model {model.name}: {exc}") + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + """Seed the ``Pipeline`` denominator from the dbt Cloud job count. + + Skipped when a ``pipelineFilterPattern`` is configured: the count sums + the API's job ``total_count`` and cannot honor the include/exclude + regex, so the declared total would overstate the pipelines actually + processed. Since ``Pipeline`` is a leaf counter that is never reconciled + down, a filtered run would otherwise sit permanently below 100%; fall + back to denominator-less progress instead.""" + if self.has_pipeline_filter(): + return + count = self.client.get_jobs_count() + if isinstance(count, int) and count > 0: + totals.set_total("Pipeline", count) + def get_pipelines_list(self) -> Iterable[DBTJob]: """ Get List of all pipelines diff --git a/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/client.py b/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/client.py index f2002e0e20b8..1eae7c3731a7 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/client.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/client.py @@ -12,6 +12,7 @@ Client to interact with Kafka Connect REST APIs """ +import re import traceback from typing import Iterable, List, Optional # noqa: UP035 from urllib.parse import urlparse @@ -105,6 +106,71 @@ def parse_cdc_topic_name(topic_name: str, database_server_name: str = None) -> d return {} +# Kafka Connect's RegexRouter uses Java replacement backreferences: numbered +# ($1 / ${1}) and named (${name}). Both convert to Python's re \g<...> form, +# which also disambiguates "$12" from "$1" followed by "2". +JAVA_NAMED_BACKREF_PATTERN = re.compile(r"\$\{(\w+)\}") +JAVA_NUMBERED_BACKREF_PATTERN = re.compile(r"\$(\d+)") + + +# Java named capture group (?...) -> Python (?P...); the negative +# lookahead keeps lookbehind (?<= / (?") + + +def _to_python_replacement(replacement: str) -> str: + """Convert Java RegexRouter backreferences ($1, ${1}, ${name}) to Python \\g<...>.""" + replacement = JAVA_NAMED_BACKREF_PATTERN.sub(r"\\g<\1>", replacement) + return JAVA_NUMBERED_BACKREF_PATTERN.sub(r"\\g<\1>", replacement) + + +def _apply_regex_router(topic_name: str, connector_config: dict, transform: str) -> str: + """Apply a single RegexRouter transform to a topic name.""" + regex = connector_config.get(f"transforms.{transform}.regex") + replacement = connector_config.get(f"transforms.{transform}.replacement", "") + result = topic_name + if regex: + try: + python_regex = JAVA_NAMED_GROUP_PATTERN.sub(r"(?P<\1>", regex) + result = re.sub(python_regex, _to_python_replacement(replacement), topic_name) + except re.error as exc: + logger.warning(f"Invalid RegexRouter config for transform '{transform}': {exc}") + return result + + +def apply_topic_routing_transforms(topic_name: str, connector_config: dict) -> str: + """ + Apply Kafka Connect topic-routing SMTs that deterministically rewrite the + destination topic name (RegexRouter / TopicRegexRouter). + + Kafka Connect applies transforms in the order listed in the ``transforms`` + config, so a statically-constructed topic name must be rewritten the same way + before it can be matched against the real topic in OpenMetadata. Dynamic + routers such as Debezium's EventRouter resolve to a value only known per-row + and are handled separately by matching against already-ingested topics. + + Args: + topic_name: The statically-constructed topic name. + connector_config: The Kafka Connect connector configuration. + + Returns: + The topic name after applying deterministic routing transforms. + """ + if not topic_name or not isinstance(connector_config, dict): + return topic_name + + transforms = connector_config.get("transforms", "") + if not transforms: + return topic_name + + result = topic_name + for transform in [name.strip() for name in transforms.split(",") if name.strip()]: + transform_type = connector_config.get(f"transforms.{transform}.type", "") + if "RegexRouter" in transform_type: + result = _apply_regex_router(result, connector_config, transform) + return result + + class KafkaConnectClient: """ Wrapper on top of KafkaConnect REST API diff --git a/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/metadata.py b/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/metadata.py index 6497267c2f51..8be5c3845528 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/metadata.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/kafkaconnect/metadata.py @@ -12,9 +12,10 @@ KafkaConnect source to extract metadata from OM UI """ +import re import traceback from datetime import datetime -from typing import Iterable, List, Optional # noqa: UP035 +from typing import Iterable, List, Optional, Pattern # noqa: UP035 from metadata.generated.schema.api.data.createPipeline import CreatePipelineRequest from metadata.generated.schema.api.lineage.addLineage import AddLineageRequest @@ -58,7 +59,10 @@ from metadata.ingestion.models.pipeline_status import OMetaPipelineStatus from metadata.ingestion.ometa.ometa_api import OpenMetadata, T from metadata.ingestion.ometa.utils import model_str -from metadata.ingestion.source.pipeline.kafkaconnect.client import parse_cdc_topic_name +from metadata.ingestion.source.pipeline.kafkaconnect.client import ( + apply_topic_routing_transforms, + parse_cdc_topic_name, +) from metadata.ingestion.source.pipeline.kafkaconnect.constants import ( CDC_ENVELOPE_FIELDS, CONNECTOR_CLASS_TO_SERVICE_TYPE, @@ -371,20 +375,12 @@ def _parse_and_resolve_topics( if raw: topics_to_process = [KafkaConnectTopics(name=t.strip()) for t in raw.split(",") if t.strip()] if not topics_to_process and database_server_name and pipeline_details.conn_type == ConnectorType.SOURCE.value: - topics_to_process = self._parse_cdc_topics_from_config( + topics_to_process = self._resolve_source_topics( pipeline_details=pipeline_details, database_server_name=database_server_name, + effective_messaging_service=effective_messaging_service, ) - if not topics_to_process and effective_messaging_service: - logger.info( - f"Falling back to searching topics by prefix in messaging service '{effective_messaging_service}'" - ) - topics_to_process = self._search_topics_by_prefix( - database_server_name=database_server_name, - messaging_service_name=effective_messaging_service, - ) - if not topics_to_process and is_storage_sink and pipeline_details.config: topics_regex = pipeline_details.config.get("topics.regex") if topics_regex: @@ -1112,6 +1108,7 @@ def _match_topic_to_dataset( For CDC sources: Match by parsing topic names (format: {server}.{schema}.{table}) For sinks: Match by name equality (topic.name == dataset.table) """ + matched_topic = None # For JDBC/Generic Sink connectors: match by name equality if pipeline_details.conn_type == ConnectorType.SINK.value: @@ -1155,26 +1152,52 @@ def _match_topic_to_dataset( # For CDC Source connectors: match by parsing topic names elif pipeline_details.conn_type == ConnectorType.SOURCE.value and database_server_name: + expected_topic = self._expected_source_topic_name(dataset_details, database_server_name, pipeline_details) for topic_name, topic_entity in topic_entities_map.items(): - topic_info = parse_cdc_topic_name(str(topic_name), database_server_name) - - # Match by table name (and optionally schema) - if topic_info.get("table") == dataset_details.table: - # If schema is specified in dataset, verify it matches - if dataset_details.schema: - if topic_info.get("database") == dataset_details.schema: - logger.info( - f"Matched CDC dataset (schema={dataset_details.schema}, table={dataset_details.table}) to topic '{topic_name}'" - ) - return topic_entity - else: - # No schema specified, just match by table name - logger.info(f"Matched CDC dataset table '{dataset_details.table}' to topic '{topic_name}'") - return topic_entity + if self._source_topic_matches(str(topic_name), expected_topic, dataset_details, database_server_name): + logger.info(f"Matched CDC dataset table '{dataset_details.table}' to topic '{topic_name}'") + matched_topic = topic_entity + break + else: + logger.warning(f"No matching CDC topic found for dataset table '{dataset_details.table}'") - logger.warning(f"No matching CDC topic found for dataset table '{dataset_details.table}'") + return matched_topic - return None + def _expected_source_topic_name( + self, + dataset_details: KafkaConnectDatasetDetails, + database_server_name: str, + pipeline_details: KafkaConnectPipelineDetails, + ) -> Optional[str]: # noqa: UP045 + """ + Build the post-transform topic name a CDC source table is expected to + produce, so a RegexRouter-renamed topic can be matched by going forward + (table -> topic) instead of reverse-parsing the topic name. + """ + expected = None + if dataset_details.table: + table_part = dataset_details.table + if dataset_details.schema: + table_part = f"{dataset_details.schema}.{dataset_details.table}" + constructed = f"{database_server_name}.{table_part}" + expected = apply_topic_routing_transforms(constructed, getattr(pipeline_details, "config", None) or {}) + return expected + + def _source_topic_matches( + self, + topic_name: str, + expected_topic: Optional[str], # noqa: UP045 + dataset_details: KafkaConnectDatasetDetails, + database_server_name: str, + ) -> bool: + """Match a CDC topic to a dataset by forward transform, falling back to reverse name parsing.""" + matches = expected_topic is not None and topic_name == expected_topic + if not matches: + topic_info = parse_cdc_topic_name(topic_name, database_server_name) + table_matches = topic_info.get("table") == dataset_details.table + schema_matches = not dataset_details.schema or topic_info.get("database") == dataset_details.schema + matches = table_matches and schema_matches + return matches def _parse_cdc_topics_from_config( self, pipeline_details: KafkaConnectPipelineDetails, database_server_name: str @@ -1224,6 +1247,10 @@ def _parse_cdc_topics_from_config( # table_entry is already "schema.table" format topic_name = f"{database_server_name}.{table_entry}" + # Apply topic-routing SMTs (e.g. RegexRouter) so the name matches + # the real post-transform topic in OpenMetadata. + topic_name = apply_topic_routing_transforms(topic_name, pipeline_details.config) + topics_found.append(KafkaConnectTopics(name=topic_name)) logger.debug(f"Parsed CDC topic from config: {topic_name}") @@ -1235,6 +1262,252 @@ def _parse_cdc_topics_from_config( return topics_found + def _resolve_source_topics( + self, + pipeline_details: KafkaConnectPipelineDetails, + database_server_name: str, + effective_messaging_service: Optional[str], # noqa: UP045 + ) -> List[KafkaConnectTopics]: # noqa: UP006 + """ + Resolve topics for a source connector, trying in order: Debezium outbox + EventRouter pattern matching, CDC topic names from config, then a prefix + search in the messaging service. + """ + topics_to_process = [] + if self._has_outbox_event_router(pipeline_details.config): + logger.info("Detected Debezium outbox EventRouter - resolving topics by routing pattern") + topics_to_process = self._resolve_outbox_topics( + connector_config=pipeline_details.config or {}, + messaging_service_name=effective_messaging_service, + ) + + if not topics_to_process: + topics_to_process = self._parse_cdc_topics_from_config( + pipeline_details=pipeline_details, + database_server_name=database_server_name, + ) + + if not topics_to_process and effective_messaging_service: + logger.info( + f"Falling back to searching topics by prefix in messaging service '{effective_messaging_service}'" + ) + topics_to_process = self._search_topics_by_prefix( + database_server_name=database_server_name, + messaging_service_name=effective_messaging_service, + ) + + return topics_to_process + + def _has_outbox_event_router(self, connector_config: Optional[dict]) -> bool: # noqa: UP045 + """Return True if the connector uses a Debezium outbox EventRouter SMT.""" + has_event_router = False + if connector_config: + transforms = connector_config.get("transforms", "") + for transform in [name.strip() for name in transforms.split(",") if name.strip()]: + transform_type = connector_config.get(f"transforms.{transform}.type", "") + if "EventRouter" in transform_type: + has_event_router = True + break + return has_event_router + + def _build_outbox_topic_pattern(self, connector_config: dict) -> Optional[Pattern]: # noqa: UP045 + """ + Build a regex matching topics produced by a Debezium outbox EventRouter. + + The routed topic comes from ``route.topic.replacement``, whose ``${...}`` + tokens (e.g. ``${routedByValue}``) are row-level values unknown at + ingestion time, so they become wildcards. Any RegexRouter in the chain is + applied to the template so the two transforms compose. + """ + pattern = None + transform = self._event_router_transform(connector_config) + template = ( + connector_config.get(f"transforms.{transform}.route.topic.replacement", "outbox.event.${routedByValue}") + if transform + else None + ) + if template: + routed_value_token = "routedByValuePlaceholderToken" + templated = re.sub(r"\$\{[^}]*\}", routed_value_token, template) + templated = apply_topic_routing_transforms(templated, connector_config) + static_text = re.sub(r"[^A-Za-z0-9]", "", templated.replace(routed_value_token, "")) + if not static_text: + logger.warning( + f"Outbox route.topic.replacement '{template}' has no static text; refusing to build a " + "near-catch-all pattern that would link the outbox table to unrelated topics." + ) + else: + escaped = re.escape(templated).replace(routed_value_token, ".*") + try: + pattern = re.compile(f"^{escaped}$") + except re.error as exc: + logger.warning(f"Unable to build outbox topic pattern from '{template}': {exc}") + + return pattern + + def _event_router_transform(self, connector_config: dict) -> Optional[str]: # noqa: UP045 + """Return the name of the connector's Debezium outbox EventRouter transform, if any.""" + transform_name = None + transforms = [name.strip() for name in connector_config.get("transforms", "").split(",") if name.strip()] + for transform in transforms: + if "EventRouter" in connector_config.get(f"transforms.{transform}.type", ""): + transform_name = transform + break + return transform_name + + def _resolve_outbox_topics( + self, + connector_config: dict, + messaging_service_name: Optional[str], # noqa: UP045 + ) -> List[KafkaConnectTopics]: # noqa: UP006 + """ + Resolve Debezium outbox topics by matching the EventRouter routing pattern + against topics already ingested in the messaging service. + """ + topics_found = [] + pattern = self._build_outbox_topic_pattern(connector_config) + + if not pattern: + logger.debug("No outbox EventRouter pattern could be derived from connector config") + elif not messaging_service_name: + logger.warning( + "Cannot resolve outbox topics without a messaging service. " + "Ensure the messaging service is configured and topics are ingested." + ) + else: + for topic in self._get_service_topics(messaging_service_name): + topic_name = model_str(topic.name) + if pattern.match(topic_name): + topics_found.append(KafkaConnectTopics(name=topic_name, fqn=model_str(topic.fullyQualifiedName))) + logger.debug(f"Matched outbox topic: {topic_name}") + logger.info(f"Resolved {len(topics_found)} outbox topic(s) via EventRouter pattern '{pattern.pattern}'") + + return topics_found + + def _get_service_topics(self, messaging_service_name: str) -> List[Topic]: # noqa: UP006 + """Return all topics for a messaging service, caching per service name.""" + if messaging_service_name not in self._topics_cache: + self._topics_cache[messaging_service_name] = list( + self.metadata.list_all_entities( + entity=Topic, + params={"service": messaging_service_name}, + ) + ) + logger.debug( + f"Cached {len(self._topics_cache[messaging_service_name])} topics " + f"for messaging service: {messaging_service_name}" + ) + return self._topics_cache[messaging_service_name] + + def _is_outbox_fanout(self, pipeline_details, dataset_entity, topic_entities_map, single_dataset: bool) -> bool: + """ + Return True when an outbox EventRouter connector should fan the source + table out to every resolved topic. + + Routed topics carry no table attribution. A single-table connector is + unambiguously the outbox; with several captured tables we only fan out the + one identifiable as the outbox table by its EventRouter columns, so + unrelated tables don't get speculative lineage. + """ + return ( + self._has_outbox_event_router(pipeline_details.config) + and dataset_entity is not None + and bool(topic_entities_map) + and (single_dataset or self._dataset_is_outbox_table(dataset_entity, pipeline_details.config)) + ) + + def _outbox_event_columns(self, connector_config: dict, transform: str) -> set: + """Return the source columns the EventRouter reads: routing field, id, key and payload.""" + prefix = f"transforms.{transform}" + return { + connector_config.get(f"{prefix}.route.by.field", "aggregatetype"), + connector_config.get(f"{prefix}.table.field.event.id", "id"), + connector_config.get(f"{prefix}.table.field.event.key", "aggregateid"), + connector_config.get(f"{prefix}.table.field.event.payload", "payload"), + } + + def _dataset_is_outbox_table(self, dataset_entity, connector_config: dict) -> bool: + """ + Return True if the dataset is the outbox table. + + Identified by carrying the full set of columns the EventRouter reads + (routing field, id, key, payload). A normal captured table would not have + aggregatetype, aggregateid and payload together, so this avoids fanning a + non-outbox table out to the routed topics on a single column-name match. + """ + transform = self._event_router_transform(connector_config) + is_outbox = False + if transform: + required = {name.lower() for name in self._outbox_event_columns(connector_config, transform)} + columns = {model_str(column.name).lower() for column in (getattr(dataset_entity, "columns", None) or [])} + is_outbox = required.issubset(columns) + return is_outbox + + def _iter_outbox_lineage( + self, + dataset_entity, + topic_entities_map: dict, + pipeline_entity, + pipeline_details: KafkaConnectPipelineDetails, + dataset_details: KafkaConnectDatasetDetails, + ) -> Iterable[Either[AddLineageRequest]]: + """Yield table -> topic lineage for every topic an outbox connector routes to.""" + for topic_name, topic_entity in topic_entities_map.items(): + if topic_entity is not None: + column_lineage = self._safe_build_column_lineage( + dataset_entity, topic_entity, pipeline_details, dataset_details + ) + self.lineage_results.append( + { + "connector": pipeline_details.name, + "table_fqn": model_str(dataset_entity.fullyQualifiedName), + "topic_fqn": model_str(topic_entity.fullyQualifiedName), + "status": "SUCCESS", + "reason": "Table → Topic (outbox EventRouter)", + } + ) + logger.info(f"Created outbox lineage: {model_str(dataset_entity.fullyQualifiedName)} → {topic_name}") + yield Either( # pyright: ignore[reportCallIssue] + right=self._build_lineage_request(dataset_entity, topic_entity, pipeline_entity, column_lineage) + ) + + def _safe_build_column_lineage(self, from_entity, topic_entity, pipeline_details, dataset_details): + """Build column-level lineage without failing entity-level lineage.""" + column_lineage = None + try: + column_lineage = self.build_column_lineage( + from_entity=from_entity, + to_entity=topic_entity, + topic_entity=topic_entity, + pipeline_details=pipeline_details, + dataset_details=dataset_details, + ) + except Exception as exc: + logger.warning(f"Failed to build column-level lineage for {pipeline_details.name}: {exc}") + logger.debug(traceback.format_exc()) + return column_lineage + + def _build_lineage_request(self, from_entity, to_entity, pipeline_entity, column_lineage) -> AddLineageRequest: + """Construct an AddLineageRequest edge between two data assets.""" + lineage_details = LineageDetails( # pyright: ignore[reportCallIssue] + pipeline=EntityReference(id=pipeline_entity.id.root, type="pipeline"), # pyright: ignore[reportCallIssue] + source=LineageSource.PipelineLineage, + columnsLineage=column_lineage, + ) + return AddLineageRequest( + edge=EntitiesEdge( + fromEntity=EntityReference( # pyright: ignore[reportCallIssue] + id=from_entity.id, + type=ENTITY_REFERENCE_TYPE_MAP[type(from_entity).__name__], + ), + toEntity=EntityReference( # pyright: ignore[reportCallIssue] + id=to_entity.id, + type=ENTITY_REFERENCE_TYPE_MAP[type(to_entity).__name__], + ), + lineageDetails=lineage_details, + ) + ) + def yield_pipeline_lineage_details( # noqa: C901 self, pipeline_details: KafkaConnectPipelineDetails ) -> Iterable[Either[AddLineageRequest]]: @@ -1425,6 +1698,20 @@ def yield_pipeline_lineage_details( # noqa: C901 ) continue + # Outbox EventRouter: one source table fans out to many routed + # topics, so link the table to every pattern-resolved topic. + if self._is_outbox_fanout( + pipeline_details, current_dataset_entity, topic_entities_map, len(datasets_to_process) == 1 + ): + yield from self._iter_outbox_lineage( + dataset_entity=current_dataset_entity, + topic_entities_map=topic_entities_map, + pipeline_entity=pipeline_entity, + pipeline_details=pipeline_details, + dataset_details=dataset_details, + ) + continue + # Table dataset: Match topic 1:1 matched_topic_entity = self._match_topic_to_dataset( dataset_details=dataset_details, diff --git a/ingestion/src/metadata/ingestion/source/pipeline/pipeline_service.py b/ingestion/src/metadata/ingestion/source/pipeline/pipeline_service.py index e094b737ead0..8f1846115603 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/pipeline_service.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/pipeline_service.py @@ -351,6 +351,13 @@ def get_services(self) -> Iterable[WorkflowSource]: def yield_create_request_pipeline_service(self, config: WorkflowSource): yield Either(right=self.metadata.get_create_service_from_source(entity=PipelineService, config=config)) + def has_pipeline_filter(self) -> bool: + """Whether a ``pipelineFilterPattern`` that actually drops pipelines is + configured. An empty pattern object filters nothing, so a progress + pre-count stays accurate only while this is ``False``.""" + pattern = self.source_config.pipelineFilterPattern + return bool(pattern and (pattern.includes or pattern.excludes)) + def get_pipeline(self) -> Any: for pipeline_detail in self.get_pipelines_list(): pipeline_name = self.get_pipeline_name(pipeline_detail) diff --git a/ingestion/src/metadata/ingestion/source/storage/s3/connection.py b/ingestion/src/metadata/ingestion/source/storage/s3/connection.py index a2de7cf805db..7a315a4a21e3 100644 --- a/ingestion/src/metadata/ingestion/source/storage/s3/connection.py +++ b/ingestion/src/metadata/ingestion/source/storage/s3/connection.py @@ -26,98 +26,47 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from botocore.exceptions import EndpointConnectionError, NoCredentialsError +from botocore.exceptions import EndpointConnectionError from metadata.clients.aws_client import AWSClient from metadata.core.connections.test_connection import ErrorPack, Matchers, check, when +from metadata.core.connections.test_connection.aws import AWS_ERRORS, aws_code from metadata.core.connections.test_connection.checks.storage import ( StorageStep, list_buckets, list_metrics, probe_buckets, ) -from metadata.core.connections.test_connection.classifier import exception_chain -from metadata.core.connections.test_connection.network import NETWORK_ERRORS from metadata.generated.schema.entity.services.connections.storage.s3Connection import ( S3Connection as S3ConnectionConfig, ) from metadata.ingestion.connections.connection import BaseConnection if TYPE_CHECKING: - from collections.abc import Callable - from botocore.client import BaseClient + from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import ChecksProvider from metadata.core.connections.test_connection.records import Evidence -def aws_error_code(*codes: str) -> Callable[[BaseException], bool]: - """Match a botocore ``ClientError`` by its structured AWS error code. - - botocore carries the code at ``error.response['Error']['Code']``; matching - that is sturdier than a substring search of the message (a bucket name or - message text echoing a code cannot false-match) and mirrors how the framework - matches errno / status_code elsewhere. Walks the cause chain like the other - matchers. - """ - wanted = frozenset(codes) - - def match(error: BaseException) -> bool: - for current in exception_chain(error): - response = getattr(current, "response", None) - if isinstance(response, dict) and response.get("Error", {}).get("Code") in wanted: - return True - return False - - return match - - -# botocore raises every AWS-side rejection as a ClientError carrying the service -# error code at ``response['Error']['Code']``, so the pack matches on those stable -# codes. Client-side failures (missing credentials, unreachable endpoint) surface -# as dedicated botocore exception types and are matched by type. +# Only what is specific to S3; the rest comes from AWS_ERRORS. S3_ERRORS = ErrorPack( - when(aws_error_code("InvalidAccessKeyId")).diagnose( - "Invalid AWS access key", - fix="The awsAccessKeyId does not exist in AWS; check the configured credentials.", - ), - when(aws_error_code("SignatureDoesNotMatch")).diagnose( - "AWS secret key does not match", - fix="The awsSecretAccessKey is wrong for this awsAccessKeyId; re-enter the credential pair.", - ), - when(aws_error_code("UnrecognizedClientException")).diagnose( - "AWS credentials not recognized", - fix="The security token or access key is invalid; check the configured credentials.", - ), - when(aws_error_code("InvalidClientTokenId")).diagnose( - "AWS security token is invalid", - fix="The awsSessionToken (or access key) is invalid for this region; refresh the credentials.", - ), - when(aws_error_code("ExpiredToken")).diagnose( - "AWS session token expired", - fix="Temporary credentials have expired; refresh the awsSessionToken.", - ), - when(aws_error_code("NoSuchBucket")).diagnose( + when(aws_code("NoSuchBucket")).diagnose( "Bucket not found", fix="Verify the configured bucketNames exist in this AWS account and region.", ), - when(aws_error_code("AccessDenied", "AccessDeniedException")).diagnose( + when(aws_code("AccessDenied", "AccessDeniedException")).diagnose( "Not authorized", fix="Grant s3:ListAllMyBuckets (or s3:ListBucket on the configured buckets) " "and cloudwatch:ListMetrics to the identity used.", ), - when(Matchers.exception(NoCredentialsError)).diagnose( - "No AWS credentials found", - fix="No credentials were configured or resolvable; set awsAccessKeyId/awsSecretAccessKey " - "or make an IAM role available where ingestion runs.", - ), when(Matchers.exception(EndpointConnectionError)).diagnose( "Cannot reach the AWS endpoint", fix="Check awsRegion (and endPointURL for S3-compatible services), and that the " "network allows access to it from where ingestion runs.", ), -).including(NETWORK_ERRORS) +).including(AWS_ERRORS) @dataclass @@ -145,29 +94,25 @@ def get_connection(connection: S3ConnectionConfig) -> S3ObjectStoreClient: class S3Checks: """Test-connection checks for S3. - The client is built lazily inside the checks: an assume-role configuration - calls STS while the boto3 session is created, so building it while the - provider is constructed would touch the network before the runner's gate - (and outside its per-step timeout). ``connect`` is ``BaseConnection.client`` - underneath, so both steps share the one cached client. + Reading the borrowed store is what builds it, so an assume-role config's STS + handshake stays behind the runner's gate. """ errors = S3_ERRORS - def __init__(self, connect: Callable[[], S3ObjectStoreClient], bucket_names: list[str] | None) -> None: - self._connect = connect + def __init__(self, store: Borrowed[S3ObjectStoreClient], bucket_names: list[str] | None) -> None: + self._store = store self.bucket_names = bucket_names @check(StorageStep.ListBuckets) def check_buckets(self) -> Evidence: - client = self._connect() if self.bucket_names: - return probe_buckets(client.s3_client, self.bucket_names) - return list_buckets(client.s3_client) + return probe_buckets(self._store.client.s3_client, self.bucket_names) + return list_buckets(self._store.client.s3_client) @check(StorageStep.GetMetrics) def get_metrics(self) -> Evidence: - return list_metrics(self._connect().cloudwatch_client, "AWS/S3") + return list_metrics(self._store.client.cloudwatch_client, "AWS/S3") class S3Connection(BaseConnection[S3ConnectionConfig, S3ObjectStoreClient]): @@ -176,6 +121,6 @@ def _get_client(self) -> S3ObjectStoreClient: def checks(self) -> ChecksProvider: return S3Checks( - connect=lambda: self.client, + store=self.borrow(), bucket_names=self.service_connection.bucketNames, ) diff --git a/ingestion/src/metadata/profiler/source/fetcher/entity_fetcher.py b/ingestion/src/metadata/profiler/source/fetcher/entity_fetcher.py index 4747139befec..f93720822fc1 100644 --- a/ingestion/src/metadata/profiler/source/fetcher/entity_fetcher.py +++ b/ingestion/src/metadata/profiler/source/fetcher/entity_fetcher.py @@ -23,6 +23,7 @@ from metadata.ingestion.api.models import Either from metadata.ingestion.api.status import Status from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import ManualProgress from metadata.profiler.source.fetcher.fetcher_strategy import ( DatabaseFetcherStrategy, FetcherStrategy, @@ -41,11 +42,13 @@ def __init__( metadata: OpenMetadata, global_profiler_config: Optional[Settings], # noqa: UP045 status: Status, + progress: ManualProgress, ): self.config = config self.metadata = metadata self.global_profiler_config = global_profiler_config self.status = status + self.progress = progress self.strategy = self._get_strategy() def _get_strategy(self) -> FetcherStrategy: @@ -53,10 +56,14 @@ def _get_strategy(self) -> FetcherStrategy: service_type = service_class(self.config.source.type) if service_type is DatabaseService: - return DatabaseFetcherStrategy(self.config, self.metadata, self.global_profiler_config, self.status) + return DatabaseFetcherStrategy( + self.config, self.metadata, self.global_profiler_config, self.status, self.progress + ) if service_type is StorageService: - return StorageFetcherStrategy(self.config, self.metadata, self.global_profiler_config, self.status) + return StorageFetcherStrategy( + self.config, self.metadata, self.global_profiler_config, self.status, self.progress + ) raise NotImplementedError(f"Fetcher strategy not implemented for service type {service_type}") diff --git a/ingestion/src/metadata/profiler/source/fetcher/fetcher_strategy.py b/ingestion/src/metadata/profiler/source/fetcher/fetcher_strategy.py index 4b35a89e4623..dcbe1549eb35 100644 --- a/ingestion/src/metadata/profiler/source/fetcher/fetcher_strategy.py +++ b/ingestion/src/metadata/profiler/source/fetcher/fetcher_strategy.py @@ -33,6 +33,7 @@ from metadata.ingestion.api.status import Status from metadata.ingestion.models.entity_interface import EntityInterfaceWithTags from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import ManualProgress from metadata.profiler.source.fetcher.config import EntityFilterConfigInterface from metadata.profiler.source.fetcher.profiler_source_factory import ( profiler_source_factory, @@ -47,6 +48,9 @@ validate_regex, ) from metadata.utils.fqn import split +from metadata.utils.logger import profiler_logger + +logger = profiler_logger() FIELDS = ["tableProfilerConfig", "columns", "customMetrics", "tags"] CONTAINER_FIELDS = ["dataModel", "tags"] @@ -91,12 +95,14 @@ def __init__( metadata: OpenMetadata, global_profiler_config: Optional[Settings], # noqa: UP045 status: Status, + progress: ManualProgress, ) -> None: self.config = config self.source_config = config.source.sourceConfig.config self.metadata = metadata self.global_profiler_config = global_profiler_config self.status = status + self.progress = progress def filter_classifications(self, entity: EntityInterfaceWithTags) -> bool: """Given a list of entities, filter out entities that do not match the classification filter pattern @@ -139,8 +145,9 @@ def __init__( metadata: OpenMetadata, global_profiler_config: Optional[Settings], # noqa: UP045 status: Status, + progress: ManualProgress, ) -> None: - super().__init__(config, metadata, global_profiler_config, status) + super().__init__(config, metadata, global_profiler_config, status, progress) self.database_filter_pattern = _build_regex_from_filter(self.source_config.databaseFilterPattern) self.schema_filter_pattern = _build_regex_from_filter(self.source_config.schemaFilterPattern) self.table_filter_pattern = _build_regex_from_filter(self.source_config.tableFilterPattern) @@ -280,9 +287,26 @@ def _get_table_entities(self, database: Database) -> Iterable[Table]: continue yield table + def _seed_table_total(self, database: Database, db_fqn: str) -> None: + """Seed this database's server-side-filtered table count so % and ETA + have an immediate denominator. A failure only skips the seed — the + scope still reconciles to the observed count.""" + try: + total = self.metadata.list_entities(entity=Table, params=self._build_table_params(database), limit=1).total + except Exception as exc: + logger.debug(f"Could not seed table total for `{db_fqn}`: {exc}") + total = None + if total is not None: + self.progress.seed_scope_total(Table.__name__, db_fqn, total) + else: + self.progress.mark_reconcilable(Table.__name__) + def fetch(self) -> Iterator[Either[ProfilerSourceAndEntity]]: """Fetch database entity""" for database in self._get_database_entities(): + db_fqn = getattr(database.fullyQualifiedName, "root", None) or str(database.name.root) + self._seed_table_total(database, db_fqn) + observed = 0 try: profiler_source = profiler_source_factory.create( self.config.source.type.lower(), @@ -293,6 +317,8 @@ def fetch(self) -> Iterator[Either[ProfilerSourceAndEntity]]: ) for table in self._get_table_entities(database): + observed += 1 + self.progress.track_asset(Table.__name__) yield Either( left=None, right=ProfilerSourceAndEntity( @@ -303,12 +329,14 @@ def fetch(self) -> Iterator[Either[ProfilerSourceAndEntity]]: except Exception as exc: yield Either( left=StackTraceError( - name=database.fullyQualifiedName.root, # type: ignore + name=db_fqn, error=f"Error listing source and entities for database due to [{exc}]", stackTrace=traceback.format_exc(), ), right=None, ) + finally: + self.progress.reconcile_scope_total(Table.__name__, db_fqn, observed) class StorageFetcherStrategy(FetcherStrategy): @@ -320,8 +348,9 @@ def __init__( metadata: OpenMetadata, global_profiler_config: Optional[Settings], # noqa: UP045 status: Status, + progress: ManualProgress, ) -> None: - super().__init__(config, metadata, global_profiler_config, status) + super().__init__(config, metadata, global_profiler_config, status, progress) def _filter_buckets(self, container: Container) -> bool: """Filter buckets (top-level containers) based on the bucket filter pattern @@ -421,7 +450,10 @@ def fetch(self) -> Iterator[Either[ProfilerSourceAndEntity]]: self.global_profiler_config, ) - for container in self._get_container_entities(): + containers = list(self._get_container_entities()) + self.progress.set_total(Container.__name__, len(containers)) + for container in containers: + self.progress.track_asset(Container.__name__) yield Either( left=None, right=ProfilerSourceAndEntity( diff --git a/ingestion/src/metadata/profiler/source/metadata.py b/ingestion/src/metadata/profiler/source/metadata.py index d9ce165cf08b..e6f5c8880d8b 100644 --- a/ingestion/src/metadata/profiler/source/metadata.py +++ b/ingestion/src/metadata/profiler/source/metadata.py @@ -12,7 +12,7 @@ OpenMetadata source for the profiler """ -from typing import Iterable, List, Optional # noqa: UP035 +from typing import ClassVar, Iterable, List, Optional # noqa: UP035 from metadata.generated.schema.metadataIngestion.databaseServiceAutoClassificationPipeline import ( DatabaseServiceAutoClassificationPipeline, # noqa: TC001 @@ -31,6 +31,11 @@ from metadata.ingestion.api.step import Step # noqa: TC001 from metadata.ingestion.api.steps import Source from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.modes import ProgressMode +from metadata.ingestion.progress.tracking import ( + ProgressTracking, + attach_progress_tracking, +) from metadata.profiler.source.fetcher.entity_fetcher import EntityFetcher from metadata.profiler.source.model import ProfilerSourceAndEntity from metadata.utils.class_helper import ( @@ -55,6 +60,15 @@ class OpenMetadataSource(Source): We do this here as well. """ + progress_mode: ClassVar[ProgressMode] = ProgressMode.MANUAL + + @property + def progress_tracking(self) -> ProgressTracking: + """Composed per-source progress state. The profiler source is MANUAL: + the topology runner does not count it, so it drives + ``progress_tracking.manual`` from the fetcher.""" + return attach_progress_tracking(self) + @property def name(self) -> str: return "OpenMetadata Service" @@ -112,7 +126,13 @@ def test_connection(self) -> None: def _iter(self, *_, **__) -> Iterable[Either[ProfilerSourceAndEntity]]: global_profiler_config = self.metadata.get_profiler_config_settings() - entity_fetcher = EntityFetcher(self.config, self.metadata, global_profiler_config, self.status) + entity_fetcher = EntityFetcher( + self.config, + self.metadata, + global_profiler_config, + self.status, + self.progress_tracking.manual, + ) yield from entity_fetcher.fetch() @classmethod diff --git a/ingestion/src/metadata/sdk/__init__.py b/ingestion/src/metadata/sdk/__init__.py index c61ac5584ca6..16382b6475b2 100644 --- a/ingestion/src/metadata/sdk/__init__.py +++ b/ingestion/src/metadata/sdk/__init__.py @@ -33,6 +33,7 @@ Pipelines, Queries, SearchIndexes, + Settings, StorageServices, StoredProcedures, Tables, @@ -184,6 +185,7 @@ def reset() -> None: pipelines = Pipelines # pylint: disable=invalid-name queries = Queries # pylint: disable=invalid-name search_indexes = SearchIndexes # pylint: disable=invalid-name +settings = Settings # pylint: disable=invalid-name storage_services = StorageServices # pylint: disable=invalid-name stored_procedures = StoredProcedures # pylint: disable=invalid-name tables = Tables # pylint: disable=invalid-name @@ -251,6 +253,8 @@ def reset() -> None: "queries", "SearchIndexes", "search_indexes", + "Settings", + "settings", "StorageServices", "storage_services", "StoredProcedures", diff --git a/ingestion/src/metadata/sdk/entities/__init__.py b/ingestion/src/metadata/sdk/entities/__init__.py index 1b0060f9918d..36d7d6ed26cc 100644 --- a/ingestion/src/metadata/sdk/entities/__init__.py +++ b/ingestion/src/metadata/sdk/entities/__init__.py @@ -26,6 +26,7 @@ from metadata.sdk.entities.pipelines import Pipelines from metadata.sdk.entities.queries import Queries from metadata.sdk.entities.searchindexes import SearchIndexes +from metadata.sdk.entities.settings import Settings from metadata.sdk.entities.storage_services import StorageServices from metadata.sdk.entities.storedprocedures import StoredProcedures from metadata.sdk.entities.tables import Tables @@ -61,6 +62,7 @@ "Pipelines", "Queries", "SearchIndexes", + "Settings", "StorageServices", "StoredProcedures", "Tables", diff --git a/ingestion/src/metadata/sdk/entities/glossaryterms.py b/ingestion/src/metadata/sdk/entities/glossaryterms.py index eef8580b1ae3..edf706c6ca9f 100644 --- a/ingestion/src/metadata/sdk/entities/glossaryterms.py +++ b/ingestion/src/metadata/sdk/entities/glossaryterms.py @@ -2,13 +2,23 @@ GlossaryTerms entity SDK with fluent API """ -from typing import Type # noqa: UP035 +from __future__ import annotations + +import uuid +from typing import Any, Optional, Sequence, Type, Union # noqa: UP035 +from urllib.parse import urlencode from metadata.generated.schema.api.data.createGlossaryTerm import ( CreateGlossaryTermRequest, ) from metadata.generated.schema.entity.data.glossaryTerm import GlossaryTerm from metadata.sdk.entities.base import BaseEntity +from metadata.sdk.types import UuidLike + +DEFAULT_RELATION_TYPE = "relatedTo" +_GLOSSARY_TERM_TYPE = "glossaryTerm" + +TermRef = Union[str, GlossaryTerm, UuidLike] # noqa: UP007 class GlossaryTerms(BaseEntity[GlossaryTerm, CreateGlossaryTermRequest]): @@ -18,3 +28,96 @@ class GlossaryTerms(BaseEntity[GlossaryTerm, CreateGlossaryTermRequest]): def entity_type(cls) -> Type[GlossaryTerm]: # noqa: UP006 """Return the GlossaryTerm entity type""" return GlossaryTerm + + # ------------------------------------------------------------------ + # Typed relations + # ------------------------------------------------------------------ + @classmethod + def add_relation( + cls, + from_term: TermRef, + to_term: TermRef, + relation_type: str = DEFAULT_RELATION_TYPE, + ) -> GlossaryTerm: + """Add a typed relation from one glossary term to another. + + ``from_term`` / ``to_term`` accept a glossary term entity, a UUID/id, or a + fully-qualified name. ``relation_type`` is any built-in (``broader``, + ``narrower``, ``synonym``, ...) or a custom type registered via + :meth:`metadata.sdk.Settings.define_glossary_relation_type`. + """ + rest_client, endpoint = cls._relations_context() + payload = { + "term": {"id": cls._resolve_term_id(to_term), "type": _GLOSSARY_TERM_TYPE}, + "relationType": relation_type, + } + response = rest_client.post( + f"{endpoint}/{cls._resolve_term_id(from_term)}/relations", + json=payload, + ) + return cls._coerce_entity(response) + + @classmethod + def remove_relation( + cls, + from_term: TermRef, + to_term: TermRef, + relation_type: Optional[str] = None, # noqa: UP045 + ) -> GlossaryTerm: + """Remove a relation from one glossary term to another. + + When ``relation_type`` is ``None`` all relation types between the two terms + are removed. + """ + rest_client, endpoint = cls._relations_context() + from_id = cls._resolve_term_id(from_term) + to_id = cls._resolve_term_id(to_term) + path = f"{endpoint}/{from_id}/relations/{to_id}" + if relation_type: + path = f"{path}?{urlencode({'relationType': relation_type})}" + response = rest_client.delete(path) + return cls._coerce_entity(response) + + @classmethod + def relations_graph( + cls, + term: TermRef, + *, + depth: int = 1, + relation_types: Optional[Sequence[str]] = None, # noqa: UP045 + ) -> dict[str, Any]: + """Fetch the relation graph rooted at ``term`` (a ``nodes`` + ``edges`` map).""" + rest_client, endpoint = cls._relations_context() + params: dict[str, Any] = {"depth": depth} + if relation_types: + params["relationTypes"] = ",".join(relation_types) + term_id = cls._resolve_term_id(term) + path = f"{endpoint}/{term_id}/relationsGraph?{urlencode(params, safe=',')}" + return rest_client.get(path) + + @classmethod + def relation_type_usage(cls) -> dict[str, int]: + """Return per-relation-type usage counts across all glossary terms.""" + rest_client, endpoint = cls._relations_context() + return rest_client.get(f"{endpoint}/relationTypes/usage") + + # ------------------------------------------------------------------ + # Helpers + # ------------------------------------------------------------------ + @classmethod + def _relations_context(cls) -> tuple[Any, str]: + client = cls._get_client() + return cls._get_rest_client(client), cls._get_endpoint_path(client) + + @classmethod + def _resolve_term_id(cls, term: TermRef) -> str: + identifier = getattr(term, "id", None) + if identifier is not None: + return cls._stringify_identifier(identifier) + value = cls._stringify_identifier(term) + try: + uuid.UUID(value) + resolved = value + except ValueError: + resolved = cls._stringify_identifier(cls.retrieve_by_name(value).id) + return resolved diff --git a/ingestion/src/metadata/sdk/entities/settings.py b/ingestion/src/metadata/sdk/entities/settings.py new file mode 100644 index 000000000000..f3520326c671 --- /dev/null +++ b/ingestion/src/metadata/sdk/entities/settings.py @@ -0,0 +1,178 @@ +"""SDK facade for glossary term relation settings.""" + +from __future__ import annotations + +import json +from typing import Any, Optional, Union, cast + +from metadata.ingestion.ometa.client import APIError +from metadata.sdk.client import OpenMetadata +from metadata.sdk.types import OMetaClient # noqa: TC001 + +GLOSSARY_TERM_RELATION_SETTINGS = "glossaryTermRelationSettings" +_SETTINGS_ENDPOINT = "/system/settings" +_MAX_REGISTRATION_ATTEMPTS = 3 +_MISSING_RELATION_TYPES = object() +_RECONCILABLE_REGISTRATION_STATUS_CODES = (400, 409, 412, 422) +_RETRYABLE_REGISTRATION_STATUS_CODES = (409, 412) + + +class Settings: + """Facade limited to glossary term relation settings. + + Type registration preserves the server's missing, null, or array + representation and reconciles a fresh snapshot after potential concurrent + updates. It never reads or writes other system setting types. + """ + + _default_client: Optional[OMetaClient] = None # noqa: UP045 + + @classmethod + def use_client(cls, client: Union[OpenMetadata, OMetaClient]) -> None: # noqa: UP007 + """Register a default client for settings calls.""" + cls._default_client = client.ometa if isinstance(client, OpenMetadata) else client + + @classmethod + def _get_rest_client(cls) -> Any: + client = cls._default_client + if client is None: + client = OpenMetadata.get_default_client() + rest_client = getattr(client, "client", None) + if rest_client is None: + raise RuntimeError("OpenMetadata client does not expose a REST interface") + return rest_client + + @classmethod + def glossary_relation_settings(cls) -> dict[str, Any]: + """Return only the glossary term relation configuration.""" + setting = cls._get_rest_client().get(f"{_SETTINGS_ENDPOINT}/{GLOSSARY_TERM_RELATION_SETTINGS}") or {} + return cls._relation_config(setting) + + @staticmethod + def _relation_config(setting: dict[str, Any]) -> dict[str, Any]: + config = setting.get("configValue") or setting.get("config_value") or {} + if not isinstance(config, dict): + raise TypeError("glossary relation settings must be a JSON object") + return config + + @classmethod + def glossary_relation_types(cls) -> list[dict[str, Any]]: + """Return the configured glossary term relation types.""" + relation_types, _, _ = cls._glossary_relation_types_snapshot() + return relation_types + + @classmethod + def _glossary_relation_types_snapshot( + cls, + ) -> tuple[list[dict[str, Any]], object, dict[str, Any]]: + config = cls.glossary_relation_settings() + raw_relation_types = config.get("relationTypes", _MISSING_RELATION_TYPES) + if raw_relation_types is _MISSING_RELATION_TYPES or raw_relation_types is None: + return [], raw_relation_types, config + if not isinstance(raw_relation_types, list): + raise TypeError("glossary relationTypes must be an array, null, or absent") + return ( + cast("list[dict[str, Any]]", raw_relation_types), + raw_relation_types, + config, + ) + + @classmethod + def define_glossary_relation_type( + cls, + relation_type: dict[str, Any], + ) -> Optional[dict[str, Any]]: # noqa: UP045 + """Register a glossary term relation type. + + Preserves the current ``relationTypes`` representation when building the + patch. A 400 or 422 response is reconciled once, but retries only when + the error identifies a failed JSON-Patch ``test`` operation. Explicit + 409 or 412 precondition failures may retry from a fresh snapshot. A + concurrently registered matching name becomes an idempotent no-op. + + Returns only the updated glossary relation configuration, or ``None`` + if the name already existed. + """ + name = relation_type.get("name") + if not name: + raise ValueError("relation_type must include a 'name'") + + rest_client = cls._get_rest_client() + attempts = 0 + snapshot = cls._glossary_relation_types_snapshot() + while True: + relation_types, snapshot_value, config_snapshot = snapshot + if any(entry.get("name") == name for entry in relation_types): + return None + + patch = cls._build_relation_type_patch( + snapshot_value, + config_snapshot, + relation_type, + ) + try: + updated_setting = rest_client.patch( + f"{_SETTINGS_ENDPOINT}/{GLOSSARY_TERM_RELATION_SETTINGS}", + data=json.dumps(patch), + ) + return cls._relation_config(updated_setting) if updated_setting is not None else None + except APIError as exc: + status_code = cls._registration_error_status(exc) + if status_code not in _RECONCILABLE_REGISTRATION_STATUS_CODES: + raise + latest_snapshot = cls._glossary_relation_types_snapshot() + if any(entry.get("name") == name for entry in latest_snapshot[0]): + return None + if not cls._is_retryable_registration_failure(exc, status_code) or latest_snapshot == snapshot: + raise + attempts += 1 + if attempts >= _MAX_REGISTRATION_ATTEMPTS: + raise + snapshot = latest_snapshot + + @staticmethod + def _build_relation_type_patch( + snapshot_value: object, + config_snapshot: dict[str, Any], + relation_type: dict[str, Any], + ) -> list[dict[str, Any]]: + if snapshot_value is _MISSING_RELATION_TYPES: + return [ + {"op": "test", "path": "", "value": config_snapshot}, + { + "op": "add", + "path": "/relationTypes", + "value": [relation_type], + }, + ] + if snapshot_value is None: + return [ + {"op": "test", "path": "/relationTypes", "value": None}, + {"op": "replace", "path": "/relationTypes", "value": [relation_type]}, + ] + return [ + {"op": "test", "path": "/relationTypes", "value": snapshot_value}, + {"op": "add", "path": "/relationTypes/-", "value": relation_type}, + ] + + @staticmethod + def _registration_error_status(error: APIError) -> int: + return error.status_code or error.code + + @staticmethod + def _is_retryable_registration_failure(error: APIError, status_code: int) -> bool: + if status_code in _RETRYABLE_REGISTRATION_STATUS_CODES: + return True + if status_code not in (400, 422): + return False + message = str(error).casefold() + identifies_test_operation = any( + marker in message + for marker in ( + "operation 'test'", + 'operation "test"', + "test operation", + "json patch test", + ) + ) + return identifies_test_operation and any(marker in message for marker in ("fail", "mismatch", "did not match")) diff --git a/ingestion/src/metadata/utils/filters.py b/ingestion/src/metadata/utils/filters.py index b9e7bb01a4d9..5de7442f49bb 100644 --- a/ingestion/src/metadata/utils/filters.py +++ b/ingestion/src/metadata/utils/filters.py @@ -412,3 +412,15 @@ def filter_by_server(server_filter_pattern: Optional[FilterPattern], server_name :return: True for filtering, False otherwise """ return _filter(server_filter_pattern, server_name) + + +def filter_pattern_enabled(filter_pattern: Optional[FilterPattern]) -> bool: # noqa: UP045 + """ + Return True when the pattern would actually include or exclude something, + i.e. the user configured includes or excludes. An unset (None) or empty + pattern returns False. + + :param filter_pattern: Model defining filtering logic + :return: True when includes/excludes are configured, False otherwise + """ + return bool(filter_pattern and (filter_pattern.includes or filter_pattern.excludes)) diff --git a/ingestion/src/metadata/utils/progress_tracking.py b/ingestion/src/metadata/utils/progress_tracking.py deleted file mode 100644 index 4bd69a6a394c..000000000000 --- a/ingestion/src/metadata/utils/progress_tracking.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2025 Collate -# Licensed under the Collate Community License, Version 1.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Shared mixin that lazily owns a per-source ProgressRegistry. - -Any Source that mixes this in gets a ``progress`` registry discoverable by the -workflow reporter (which scans steps for the ``_progress_registry`` attribute), -without participating in the topology runner. -""" - -from metadata.utils.progress_registry import ProgressRegistry - - -class ProgressTrackingMixin: - @property - def progress(self) -> ProgressRegistry: - """Per-Source progress registry. First access is single-threaded - (in _iter, before worker threads spawn), so lazy init is safe.""" - registry = self.__dict__.get("_progress_registry") - if registry is None: - registry = ProgressRegistry() - self.__dict__["_progress_registry"] = registry - return registry diff --git a/ingestion/src/metadata/workflow/base.py b/ingestion/src/metadata/workflow/base.py index 08a1004d111e..a2ccd03de673 100644 --- a/ingestion/src/metadata/workflow/base.py +++ b/ingestion/src/metadata/workflow/base.py @@ -461,9 +461,9 @@ def _report_ingestion_status(self): f"Processes: {metrics.active_processes}" ) - reporter = self._progress_reporter() - if reporter is not None: - text = reporter.cli() + registry = self._find_progress_registry() + if registry is not None: + text = registry.render_cli() if text: logger.info("Ingestion progress:\n%s", text) diff --git a/ingestion/src/metadata/workflow/context/app_metadata_context.py b/ingestion/src/metadata/workflow/context/app_metadata_context.py new file mode 100644 index 000000000000..009f8a6f2ce4 --- /dev/null +++ b/ingestion/src/metadata/workflow/context/app_metadata_context.py @@ -0,0 +1,33 @@ +""" +Application metadata context definition. + +Generic, domain-agnostic context that an AppRunner can populate to surface +app-specific structured data on the run's PipelineStatus.metadata (dumped under +the ``appMetadata`` key). Kept intentionally free-form so any application can +attach run metadata without the framework needing to know its shape. +""" + +from typing import Any, Union + +from pydantic import Field + +from metadata.workflow.context.base import BaseContext, BaseContextFieldsEnum + + +class AppMetadataContextFieldsEnum(BaseContextFieldsEnum): + """ + Enum defining all available app-metadata context fields. + """ + + DATA = "data" + + +class AppMetadataContext(BaseContext): + """ + Context for arbitrary application-provided run metadata. + """ + + data: Union[dict[str, Any], None] = Field( # noqa: UP007 + default=None, + description="Arbitrary structured metadata attached by the application runner", + ) diff --git a/ingestion/src/metadata/workflow/context/context_manager.py b/ingestion/src/metadata/workflow/context/context_manager.py index 155683e64414..4826a52dab58 100644 --- a/ingestion/src/metadata/workflow/context/context_manager.py +++ b/ingestion/src/metadata/workflow/context/context_manager.py @@ -10,6 +10,7 @@ from enum import Enum from typing import Any, Optional +from metadata.workflow.context.app_metadata_context import AppMetadataContext from metadata.workflow.context.base import BaseContext, BaseContextFieldsEnum from metadata.workflow.context.workflow_context import WorkflowContext @@ -25,6 +26,7 @@ class ContextsEnum(Enum): """ WORKFLOW = "workflow" + APP_METADATA = "appMetadata" class ContextManager: @@ -37,6 +39,7 @@ class ContextManager: # List of Contexts workflow: WorkflowContext = WorkflowContext() + appMetadata: AppMetadataContext = AppMetadataContext() # noqa: N815 def __new__(cls): if cls._instance is None: diff --git a/ingestion/src/metadata/workflow/profiler.py b/ingestion/src/metadata/workflow/profiler.py index 833637df103c..dd2e4befdcb1 100644 --- a/ingestion/src/metadata/workflow/profiler.py +++ b/ingestion/src/metadata/workflow/profiler.py @@ -12,6 +12,8 @@ Workflow definition for the profiler """ +import traceback + from metadata.ingestion.api.steps import Processor, Sink from metadata.ingestion.source.connections import test_connection_common from metadata.profiler.processor.processor import ProfilerProcessor @@ -20,7 +22,7 @@ from metadata.utils.helpers import retry_with_docker_host from metadata.utils.importer import import_sink_class from metadata.utils.logger import profiler_logger -from metadata.utils.ssl_manager import get_ssl_connection +from metadata.utils.ssl_manager import SSLManager, check_ssl_and_init from metadata.workflow.ingestion import IngestionWorkflow logger = profiler_logger() @@ -72,9 +74,16 @@ def test_connection(self) -> None: @retry_with_docker_host(config=self.config.source) def main(self): service_config = self.config.source.serviceConnection.root.config - conn = get_ssl_connection(service_config) - - test_connection_common(self.metadata, conn, service_config) + try: + # To be cleaned up as part of https://github.com/open-metadata/OpenMetadata/issues/15913 + ssl_manager = check_ssl_and_init(service_config) + if isinstance(ssl_manager, SSLManager): + service_config = ssl_manager.setup_ssl(service_config) + except Exception: + logger.debug("Failed to setup SSL for the connection") + logger.debug(traceback.format_exc()) + + test_connection_common(self.metadata, None, service_config) return main(self) diff --git a/ingestion/src/metadata/workflow/progress_render.py b/ingestion/src/metadata/workflow/progress_render.py deleted file mode 100644 index dcbb4f4ce56d..000000000000 --- a/ingestion/src/metadata/workflow/progress_render.py +++ /dev/null @@ -1,179 +0,0 @@ -# Copyright 2025 Collate -# Licensed under the Collate Community License, Version 1.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" -Render a ProgressRegistry snapshot tree for humans (CLI) and for the server -(nested progressNode payload). - -Dependency-free on purpose (stdlib only) so both the workflow base and the -status mixin can import it without a circular dependency. -""" - -from typing import List, Optional, Tuple # noqa: UP035 - -from metadata.utils.progress_registry import ProgressNodeSnapshot, ProgressRegistry - - -def render_progress_tree(root: Optional[ProgressNodeSnapshot]) -> str: # noqa: UP045 - """Active-scope tree: the run rollup, then one indented line per in-flight - branch. Known counts render ``processed/expected``; lazy counts render a - bare ``processed``.""" - lines: List[str] = [] # noqa: UP006 - if root is not None: - _render_node(root, 0, lines) - return "\n".join(lines) - - -def _render_node(node: ProgressNodeSnapshot, depth: int, lines: List[str]) -> None: # noqa: UP006 - prefix = " " * depth + ("└ " if depth else "") - label = f"{node.label} " if node.label else "" - type_ = f"{node.child_type} " if node.child_type else "" - if node.child_type is None: - count = "" - else: - count = f"{node.processed}/{node.expected}" if node.expected is not None else str(node.processed) - overflow = f" (+{node.overflow} more)" if node.overflow else "" - lines.append(f"{prefix}{label}{type_}{count}{overflow}".rstrip()) - for child in node.children: - _render_node(child, depth + 1, lines) - - -def snapshot_to_progress_payload(root: Optional[ProgressNodeSnapshot]) -> Optional[dict]: # noqa: UP045 - """Map a snapshot tree to the ProgressUpdate.progress (progressNode) shape.""" - return _node_to_payload(root) if root is not None else None - - -def format_eta(seconds: int) -> str: - """Human ``~45s`` / ``~6m`` / ``~1h 20m`` from a rounded seconds count.""" - if seconds < 60: - result = f"~{seconds}s" - elif seconds < 3600: - result = f"~{seconds // 60}m" - else: - result = f"~{seconds // 3600}h {(seconds % 3600) // 60}m" - return result - - -class ProgressReporter: - """Presentation of a registry's state. The registry stays a pure state - object; this reporter knows how to render it for CLI and for the SSE - payload. Connector-agnostic — the rollup header is generic.""" - - def __init__(self, registry: ProgressRegistry) -> None: - self._registry = registry - - def cli(self) -> str: - snapshot = self._registry.snapshot() - counters = self._registry.global_counters() - header = self._header(counters) - if snapshot is None: - return header if counters else "" - lines: List[str] = [] # noqa: UP006 - _render_joined(snapshot, [], lines) - tree = "\n".join(lines) - return f"{header}\n{tree}" if tree else header - - def _header(self, counters: "List[Tuple[str, int, Optional[int]]]") -> str: # noqa: UP006,UP045 - lines: List[str] = [] # noqa: UP006 - driver = self._driver_counter(counters) - eta = self.eta_seconds() - for type_, done, total in counters: - line = f"{type_} {done}/{total}" if total is not None else f"{type_} {done}" - if eta is not None and driver is not None and type_ == driver[0]: - line = f"{line} {format_eta(eta)}" - lines.append(line) - assets = self._registry.assets_ingested() - if assets > 0: - lines.append(f"Ingested: {assets:,} assets") - return "\n".join(lines) - - def global_counters(self) -> "List[Tuple[str, int, Optional[int]]]": # noqa: UP006,UP045 - """Run-level counters ``(type, done, total)`` for the SSE - ``ProgressUpdate.globalCounters``. Independent of the progress tree, so - reported even when the active tree is momentarily empty.""" - return self._registry.global_counters() - - def assets_ingested(self) -> int: - """Monotonic run-total of leaf assets ingested (tables + stored - procedures + other leaf entities). Independent of the tree, so it stays - correct after scope pruning and is authoritative on the terminal event.""" - return self._registry.assets_ingested() - - def _driver_counter( - self, - counters: "Optional[List[Tuple[str, int, Optional[int]]]]" = None, # noqa: UP006,UP045 - ) -> "Optional[Tuple[str, int, Optional[int]]]": # noqa: UP006,UP045 - """The ETA driver: the last-declared global counter that has a known - total (finest-grained real unit of work), or ``None`` when no counter - declares a total.""" - pool = self._registry.global_counters() if counters is None else counters - driver = None - for counter in pool: - if counter[2] is not None: - driver = counter - return driver - - def eta_seconds(self) -> Optional[int]: # noqa: UP045 - """Overall run ETA in seconds from the driver counter's cumulative rate: - ``elapsed * (total - done) / done``. ``None`` during warm-up (``done == - 0``), when there is no driver, when the driver is complete (``done >= - total``), or before elapsed time is available.""" - driver = self._driver_counter() - result = None - if driver is not None: - _, done, total = driver - elapsed = self._registry.elapsed_seconds() - if done > 0 and total is not None and done < total and elapsed is not None and elapsed > 0: - result = round(elapsed * (total - done) / done) - return result - - def payload(self) -> Optional[dict]: # noqa: UP045 - """Bare ``progressNode`` tree (validates against ``ProgressUpdate``, - which is ``extra='forbid'``). The run-root ``processed`` carries the - monotonic asset total; ``expected`` is unknown (no global count).""" - snapshot = self._registry.snapshot() - result = None - if snapshot is not None: - tree = snapshot_to_progress_payload(snapshot) - if tree is not None: - tree["processed"] = self._registry.assets_ingested() - tree["expected"] = None - result = tree - return result - - -def _render_joined(node: ProgressNodeSnapshot, ancestors: "List[str]", lines: "List[str]") -> None: # noqa: UP006 - """Render active nodes with ancestor labels joined by '.' so sibling-level - hierarchy collapses into a single readable label, e.g. ``sales.public Table 45/310``.""" - path = [*ancestors, node.label] if node.label else list(ancestors) - if node.children: - for child in node.children: - _render_joined(child, path, lines) - else: - joined_label = ".".join(path) if path else "" - type_ = f"{node.child_type} " if node.child_type else "" - if node.child_type is None: - count = "" - else: - count = f"{node.processed}/{node.expected}" if node.expected is not None else str(node.processed) - overflow = f" (+{node.overflow} more)" if node.overflow else "" - lines.append(f"{joined_label} {type_}{count}{overflow}".strip()) - - -def _node_to_payload(node: ProgressNodeSnapshot) -> dict: - return { - "label": node.label, - "entityType": node.child_type, - "processed": node.processed, - "expected": node.expected, - "active": node.active, - "overflow": node.overflow, - "children": [_node_to_payload(child) for child in node.children], - } diff --git a/ingestion/src/metadata/workflow/workflow_status_mixin.py b/ingestion/src/metadata/workflow/workflow_status_mixin.py index 96a43e81ffbb..b9444d2ba309 100644 --- a/ingestion/src/metadata/workflow/workflow_status_mixin.py +++ b/ingestion/src/metadata/workflow/workflow_status_mixin.py @@ -16,10 +16,7 @@ import uuid from datetime import datetime from enum import Enum -from typing import TYPE_CHECKING, Optional, Tuple # noqa: UP035 - -if TYPE_CHECKING: - from metadata.workflow.progress_render import ProgressReporter +from typing import Optional, Tuple # noqa: UP035 from metadata.generated.schema.entity.services.ingestionPipelines.ingestionPipeline import ( IngestionPipeline, @@ -40,9 +37,9 @@ from metadata.generated.schema.type.basic import Map, Timestamp from metadata.ingestion.api.step import Step, Summary from metadata.ingestion.ometa.ometa_api import OpenMetadata +from metadata.ingestion.progress.registry import ProgressRegistry from metadata.utils.logger import ometa_logger from metadata.workflow.context.context_manager import ContextManager -from metadata.workflow.progress_render import ProgressReporter logger = ometa_logger() @@ -176,17 +173,17 @@ def build_ingestion_status(self) -> Optional[IngestionStatus]: # noqa: UP045 ] ) - def _progress_reporter(self) -> Optional["ProgressReporter"]: - """Reporter for the first workflow step that ran a topology walk. Reads - the backing attribute so we never create an empty registry on a step - that never tracked progress.""" - reporter = None + def _find_progress_registry(self) -> Optional[ProgressRegistry]: # noqa: UP045 + """Registry of the first workflow step that tracked progress. Reads the + backing attribute so we never create an empty registry on a step that + never tracked progress.""" + result = None for step in self.workflow_steps(): # pyright: ignore[reportAttributeAccessIssue] - registry = getattr(step, "_progress_registry", None) - if registry is not None: - reporter = ProgressReporter(registry) + tracking = getattr(step, "_progress_tracking", None) + if tracking is not None: + result = tracking.registry break - return reporter + return result def send_progress_update(self, update_type: ProgressUpdateType = ProgressUpdateType.PROCESSING) -> None: """ @@ -199,11 +196,11 @@ def send_progress_update(self, update_type: ProgressUpdateType = ProgressUpdateT and self.ingestion_pipeline and self.ingestion_pipeline.fullyQualifiedName ): - reporter = self._progress_reporter() - progress_data = reporter.payload() if reporter is not None else None - counters = reporter.global_counters() if reporter is not None else [] - eta_seconds = reporter.eta_seconds() if reporter is not None else None - total_assets = reporter.assets_ingested() if reporter is not None else None + registry = self._find_progress_registry() + progress_data = registry.sse_payload() if registry is not None else None + counters = registry.global_counters() if registry is not None else [] + eta_seconds = registry.eta_seconds() if registry is not None else None + total_assets = registry.assets_ingested() if registry is not None else None progress_update = ProgressUpdate( runId=self.run_id, diff --git a/ingestion/tests/cli_e2e/test_cli_exasol.py b/ingestion/tests/cli_e2e/test_cli_exasol.py index 29286bbb8821..23a088642360 100644 --- a/ingestion/tests/cli_e2e/test_cli_exasol.py +++ b/ingestion/tests/cli_e2e/test_cli_exasol.py @@ -18,11 +18,16 @@ from typing import List # noqa: UP035 import pytest +import yaml from sqlalchemy import text +from ingestion.tests.integration.sources.database.exasol.base import wait_for_system_table from metadata.generated.schema.entity.data.table import Table from metadata.ingestion.api.status import Status +from metadata.ingestion.source.database.exasol.queries import EXASOL_SQL_STATEMENT +from metadata.ingestion.source.database.exasol.usage import ExasolUsageSource +from .base.config_builders.builders import BaseBuilder # noqa: TID252 from .base.e2e_types import E2EType # noqa: TID252 from .common.test_cli_db import CliCommonDB # noqa: TID252 from .common_e2e_sqa_mixins import SQACommonMethods # noqa: TID252 @@ -31,6 +36,7 @@ SCHEMA_NAME = "openmetadata_schema" TABLE_NAME = "datatypes" VIEW_NAME = f"view_{TABLE_NAME}" +JOIN_TABLE_NAME = "IGNORE_TABLE" TABLE_COMMENT = "OpenMetadata Exasol CLI table comment" COLUMN_COMMENT = "OpenMetadata Exasol CLI column comment" DB_PORT = 8563 @@ -41,6 +47,31 @@ CONTAINER_NAME = f"db_container_{CONTAINER_SUFFIX}" +class UsageConfigBuilder(BaseBuilder): + """Builder class for database usage config.""" + + def __init__(self, config: dict, config_args: dict | None = None) -> None: + super().__init__(config, config_args) + self.source = self.config_args.get("source", f"{self.config['source']['type']}-usage") + self.query_log_duration = self.config_args.get("queryLogDuration", 1) + self.result_limit = self.config_args.get("resultLimit", 10000) + self.filename = self.config_args.get("filename", "/tmp/exasol_usage") + + def build(self) -> dict: + self.config["source"]["type"] = self.source + self.config["source"]["sourceConfig"] = { + "config": { + "type": "DatabaseUsage", + "queryLogDuration": self.query_log_duration, + "resultLimit": self.result_limit, + } + } + self.config["processor"] = {"type": "query-parser", "config": {}} + self.config["stage"] = {"type": "table-usage", "config": {"filename": self.filename}} + self.config["bulkSink"] = {"type": "metadata-usage", "config": {"filename": self.filename}} + return self.config + + class ExasolCliTest(CliCommonDB.TestSuite, SQACommonMethods): """ Exasol CLI Tests @@ -77,6 +108,15 @@ class ExasolCliTest(CliCommonDB.TestSuite, SQACommonMethods): FROM {SCHEMA_NAME}.{TABLE_NAME} """ + join_usage_query: str = f""" + SELECT + table_source.col_boolean, + join_source.col_varchar + FROM {SCHEMA_NAME}.{TABLE_NAME} AS table_source + JOIN {SCHEMA_NAME}.{JOIN_TABLE_NAME} AS join_source + ON table_source.col_boolean = join_source.col_boolean + """ + insert_data_queries: List[str] = [ # noqa: RUF012, UP006 f""" INSERT INTO {SCHEMA_NAME}.{TABLE_NAME} (col_boolean, col_decimal, col_date, col_timestamp, col_char, col_varchar) VALUES @@ -166,6 +206,101 @@ def test_table_filter_excludes(self) -> None: sink_status, source_status = self.retrieve_statuses(result) self.assert_filtered_tables_excludes(source_status, sink_status) + @pytest.mark.order(10) + def test_usage(self) -> None: + """Run the usage workflow and verify query rows are attached to the table.""" + self.delete_table_and_view() + self.create_table_and_view() + self.build_config_file() + self.run_command() + + table = self.openmetadata.get_by_name( + entity=Table, + fqn=self.fqn_created_table(), + fields=["usageSummary", "lifeCycle"], + ) + self.assertIsNotNone(table) + + with self.engine.begin() as connection: + connection.execute(text(self.join_usage_query)) + + wait_for_system_table( + self.engine, + EXASOL_SQL_STATEMENT.format( + start_time="2000-01-01 00:00:00", + end_time="2999-01-01 00:00:00", + filters=ExasolUsageSource.filters, + result_limit=20, + ), + expected_count=1, + timeout_seconds=120, + ) + + self.build_config_file(E2EType.INGEST) + with open(self.test_file_path, "r", encoding="utf-8") as file: # noqa: PTH123 + config = yaml.safe_load(file) + + config = UsageConfigBuilder(config).build() + + with open(self.test_file_path, "w", encoding="utf-8") as file: # noqa: PTH123 + yaml.dump(config, file, default_flow_style=False) + + result = self.run_command("usage") + sink_status, source_status = self.retrieve_statuses(result) + + self.assertEqual(len(source_status.failures), 0) + self.assertEqual(len(source_status.warnings), 0) + self.assertEqual(len(sink_status.failures), 0) + self.assertEqual(len(sink_status.warnings), 0) + self.assertGreaterEqual(len(sink_status.records), 1) + self.assertEqual(len(sink_status.updated_records), 0) + + table = self.openmetadata.get_by_name( + entity=Table, + fqn=self.fqn_created_table(), + fields=["usageSummary", "lifeCycle", "joins"], + ) + self.assertIsNotNone(table) + self.assertGreaterEqual(table.usageSummary.dailyStats.count, 1) + self.assertGreaterEqual(table.usageSummary.weeklyStats.count, 1) + self.assertGreaterEqual(table.usageSummary.monthlyStats.count, 1) + self.assertTrue( + table.lifeCycle is not None and table.lifeCycle.accessed is not None, + ) + + queries = self.openmetadata.get_entity_queries(table.id.root, fields=["queryUsedIn"]) + self.assertGreater(len(queries), 0) + select_queries = [ + query for query in queries if query.query.root and query.query.root.lstrip().upper().startswith("SELECT") + ] + self.assertGreater(len(select_queries), 0) + + self.assertTrue( + any( + any( + query_used_in.id.root == table.id.root + for query_used_in in (query.queryUsedIn.root if query.queryUsedIn else []) + ) + for query in select_queries + ) + ) + + boolean_join = next( + ( + column_join + for column_join in table.joins.columnJoins + if column_join.columnName.root.lower() == "col_boolean" + ), + None, + ) + self.assertIsNotNone(boolean_join, "Expected a col_boolean column join") + self.assertTrue( + any( + joined_with.fullyQualifiedName.root.lower().endswith(f".{JOIN_TABLE_NAME.lower()}.col_boolean") + for joined_with in boolean_join.joinedWith + ), + ) + def assert_for_table_with_profiler(self, source_status: Status, sink_status: Status) -> None: super().assert_for_table_with_profiler(source_status, sink_status) diff --git a/ingestion/tests/integration/airflow/test_airflow_api_connection.py b/ingestion/tests/integration/airflow/test_airflow_api_connection.py index ed33233fbac6..126d54c4d0bf 100644 --- a/ingestion/tests/integration/airflow/test_airflow_api_connection.py +++ b/ingestion/tests/integration/airflow/test_airflow_api_connection.py @@ -743,6 +743,7 @@ def test_full_workflow_integration(self, mock_airflow_responses, mock_openmetada mock_tracked_rest_cls, [ mock_airflow_responses["version"], # _detect_api_version + mock_airflow_responses["dags"], # declare_progress_totals -> get_dags_count mock_airflow_responses["dags"], # get_all_dags page 1 mock_airflow_responses["tasks"]["sample_etl_dag"], # dag tasks mock_airflow_responses["dag_runs"]["sample_etl_dag"], # dag runs diff --git a/ingestion/tests/integration/connections/test_ssrs_connection.py b/ingestion/tests/integration/connections/test_ssrs_connection.py index c3cf43c7a7ad..6191908994a2 100644 --- a/ingestion/tests/integration/connections/test_ssrs_connection.py +++ b/ingestion/tests/integration/connections/test_ssrs_connection.py @@ -23,7 +23,7 @@ ) from metadata.ingestion.connections.test_connections import SourceConnectionException from metadata.ingestion.source.dashboard.ssrs.client import MAX_RETRIES, SsrsClient -from metadata.ingestion.source.dashboard.ssrs.connection import get_connection +from metadata.ingestion.source.dashboard.ssrs.connection import SsrsConnection as SsrsConnectionHandler class _MockHandler(BaseHTTPRequestHandler): @@ -112,34 +112,34 @@ def ssrs_always_failing_url(): class TestSsrsConnection: def test_get_connection(self, ssrs_mock_url): connection = SsrsConnection(hostPort=ssrs_mock_url, username="test_user", password="test_pass") - client = get_connection(connection) + client = SsrsConnectionHandler(connection).client assert isinstance(client, SsrsClient) def test_get_connection_test_access(self, ssrs_mock_url): connection = SsrsConnection(hostPort=ssrs_mock_url, username="test_user", password="test_pass") - client = get_connection(connection) + client = SsrsConnectionHandler(connection).client client.test_access() def test_get_connection_test_get_reports(self, ssrs_mock_url): connection = SsrsConnection(hostPort=ssrs_mock_url, username="test_user", password="test_pass") - client = get_connection(connection) + client = SsrsConnectionHandler(connection).client client.test_get_reports() def test_connection_bad_host(self): connection = SsrsConnection(hostPort="http://localhost:1", username="test_user", password="test_pass") - client = get_connection(connection) + client = SsrsConnectionHandler(connection).client with pytest.raises(SourceConnectionException): client.test_access() def test_connection_bad_host_get_reports(self): connection = SsrsConnection(hostPort="http://localhost:1", username="test_user", password="test_pass") - client = get_connection(connection) + client = SsrsConnectionHandler(connection).client with pytest.raises(SourceConnectionException): client.test_get_reports() def test_get_reports_retries_transient_failures(self, ssrs_flaky_url): connection = SsrsConnection(hostPort=ssrs_flaky_url, username="test_user", password="test_pass") - client = get_connection(connection) + client = SsrsConnectionHandler(connection).client reports = list(client.get_reports()) assert reports == [] assert _FlakyHandler.request_count == 3 @@ -153,7 +153,7 @@ def test_get_reports_raises_on_persistent_failure(self, ssrs_always_failing_url) username="test_user", password="test_pass", ) - client = get_connection(connection) + client = SsrsConnectionHandler(connection).client with pytest.raises(SourceConnectionException): list(client.get_reports()) assert _AlwaysFailingHandler.request_count == MAX_RETRIES + 1 diff --git a/ingestion/tests/integration/sources/database/exasol/test_exasol_queries.py b/ingestion/tests/integration/sources/database/exasol/base.py similarity index 56% rename from ingestion/tests/integration/sources/database/exasol/test_exasol_queries.py rename to ingestion/tests/integration/sources/database/exasol/base.py index 6408250c660a..58843ff56b28 100644 --- a/ingestion/tests/integration/sources/database/exasol/test_exasol_queries.py +++ b/ingestion/tests/integration/sources/database/exasol/base.py @@ -16,12 +16,6 @@ from sqlalchemy import create_engine, text from sqlalchemy.engine import Engine -from metadata.ingestion.source.database.exasol.queries import ( - EXASOL_SQL_STATEMENT, - EXASOL_SYSTEM_METRICS_QUERY, - EXASOL_TEST_GET_QUERIES, -) - DB_VERSION = "2025.1.8" DB_PORT = 8563 CONTAINER_SUFFIX = "exasolquery" @@ -37,7 +31,7 @@ def wait_for_system_table( query: str, expected_count: int, params: dict[str, object] | None = None, - timeout_seconds: int = 60, + timeout_seconds: int = 120, interval_seconds: int = 5, ) -> list[dict[str, object]]: """Poll the query until the expected rows are visible and return them.""" @@ -107,7 +101,7 @@ def _prepare_exasol_objects(engine: Engine) -> None: connection.execute(text(statement)) -class TestExasolQueries: +class ExasolTestBase: engine: ClassVar[Engine] @classmethod @@ -138,111 +132,3 @@ def setup_class(cls): def teardown_class(cls): cls.engine.dispose() subprocess.run(["docker", "kill", CONTAINER_NAME], check=True, encoding="utf-8") - - def test_connection_test_get_queries(self): - query = EXASOL_TEST_GET_QUERIES - rows = wait_for_system_table(self.engine, query, expected_count=1, timeout_seconds=120) - columns = {column.lower() for column in rows[0]} - - assert columns == { - "sql_text", - "command_name", - "user_name", - "start_time", - "stop_time", - "duration", - } - assert len(rows) == 1 - - def test_sql_statement_query(self): - query = EXASOL_SQL_STATEMENT.format( - start_time="2000-01-01 00:00:00", - end_time="2999-01-01 00:00:00", - filters="", - result_limit=5, - ) - - rows = wait_for_system_table(self.engine, query, expected_count=5, timeout_seconds=120) - columns = {column.lower() for column in rows[0]} - - assert columns == { - "query_text", - "query_type", - "user_name", - "start_time", - "end_time", - "duration", - } - assert len(rows) == 5 - - def test_system_metrics_query_ignores_similarly_named_tables(self): - seed_rows = [ - f""" - INSERT INTO {SCHEMA_NAME}.{TABLE_NAME} ( - col_boolean, - col_decimal, - col_date, - col_timestamp, - col_timestamp_local, - col_char, - col_varchar - ) VALUES - (TRUE, 1.5, '2023-07-13', '2023-07-13 06:04:45', '2023-07-13 04:04:45', 'x', 'y') - """, - f""" - INSERT INTO {SCHEMA_NAME}.{SIMILAR_TABLE_NAME} ( - col_boolean, - col_decimal, - col_date, - col_timestamp, - col_timestamp_local, - col_char, - col_varchar - ) VALUES - (TRUE, 1.5, '2023-07-13', '2023-07-13 06:04:45', '2023-07-13 04:04:45', 'x', 'y') - """, - ] - - with self.engine.begin() as connection: - for statement in seed_rows: - connection.execute(text(statement)) - - dml_statements = [ - f""" - DELETE FROM {SCHEMA_NAME}.{TABLE_NAME} - WHERE col_char = 'x' - """, - f""" - DELETE FROM {SCHEMA_NAME}.{SIMILAR_TABLE_NAME} - WHERE col_char = 'x' - """, - ] - with self.engine.begin() as connection: - for statement in dml_statements: - connection.execute(text(statement)) - - target_params = { - "database_name": "default", - "schema": SCHEMA_NAME, - "table": TABLE_NAME, - "operation": "DELETE", - "table_match_pattern": rf"(?s).*\b{SCHEMA_NAME}\.{TABLE_NAME}\b.*", - } - - rows = wait_for_system_table( - self.engine, - EXASOL_SYSTEM_METRICS_QUERY, - expected_count=1, - params=target_params, - timeout_seconds=120, - ) - columns = {column.lower() for column in rows[0]} - - assert columns == { - "database", - "schema", - "table", - "starttime", - "rows", - } - assert len(rows) == 1 diff --git a/ingestion/tests/integration/sources/database/exasol/test_queries.py b/ingestion/tests/integration/sources/database/exasol/test_queries.py new file mode 100644 index 000000000000..c5fa4e7df412 --- /dev/null +++ b/ingestion/tests/integration/sources/database/exasol/test_queries.py @@ -0,0 +1,135 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from sqlalchemy import text + +from ingestion.tests.integration.sources.database.exasol.base import ( + SCHEMA_NAME, + SIMILAR_TABLE_NAME, + TABLE_NAME, + ExasolTestBase, + wait_for_system_table, +) +from metadata.ingestion.source.database.exasol.queries import ( + EXASOL_SQL_STATEMENT, + EXASOL_SYSTEM_METRICS_QUERY, + EXASOL_TEST_GET_QUERIES, +) + + +class TestExasolQueries(ExasolTestBase): + def test_connection_test_get_queries(self): + query = EXASOL_TEST_GET_QUERIES + rows = wait_for_system_table(self.engine, query, expected_count=1, timeout_seconds=120) + columns = {column.lower() for column in rows[0]} + + assert columns == { + "sql_text", + "command_name", + "user_name", + "start_time", + "stop_time", + "duration", + } + assert len(rows) == 1 + + def test_sql_statement_query(self): + query = EXASOL_SQL_STATEMENT.format( + start_time="2000-01-01 00:00:00", + end_time="2999-01-01 00:00:00", + filters="", + result_limit=5, + ) + + rows = wait_for_system_table(self.engine, query, expected_count=5, timeout_seconds=120) + columns = {column.lower() for column in rows[0]} + + assert columns == { + "query_text", + "query_type", + "user_name", + "start_time", + "end_time", + "duration", + } + assert len(rows) == 5 + + def test_system_metrics_query_ignores_similarly_named_tables(self): + seed_rows = [ + f""" + INSERT INTO {SCHEMA_NAME}.{TABLE_NAME} ( + col_boolean, + col_decimal, + col_date, + col_timestamp, + col_timestamp_local, + col_char, + col_varchar + ) VALUES + (TRUE, 1.5, '2023-07-13', '2023-07-13 06:04:45', '2023-07-13 04:04:45', 'x', 'y') + """, + f""" + INSERT INTO {SCHEMA_NAME}.{SIMILAR_TABLE_NAME} ( + col_boolean, + col_decimal, + col_date, + col_timestamp, + col_timestamp_local, + col_char, + col_varchar + ) VALUES + (TRUE, 1.5, '2023-07-13', '2023-07-13 06:04:45', '2023-07-13 04:04:45', 'x', 'y') + """, + ] + + with self.engine.begin() as connection: + for statement in seed_rows: + connection.execute(text(statement)) + + dml_statements = [ + f""" + DELETE FROM {SCHEMA_NAME}.{TABLE_NAME} + WHERE col_char = 'x' + """, + f""" + DELETE FROM {SCHEMA_NAME}.{SIMILAR_TABLE_NAME} + WHERE col_char = 'x' + """, + ] + with self.engine.begin() as connection: + for statement in dml_statements: + connection.execute(text(statement)) + + target_params = { + "database_name": "default", + "schema": SCHEMA_NAME, + "table": TABLE_NAME, + "operation": "DELETE", + "table_match_pattern": rf"(?s).*\b{SCHEMA_NAME}\.{TABLE_NAME}\b.*", + } + + rows = wait_for_system_table( + self.engine, + EXASOL_SYSTEM_METRICS_QUERY, + expected_count=1, + params=target_params, + timeout_seconds=120, + ) + columns = {column.lower() for column in rows[0]} + + assert columns == { + "database", + "schema", + "table", + "starttime", + "rows", + } + assert len(rows) == 1 diff --git a/ingestion/tests/integration/sources/database/exasol/test_usage.py b/ingestion/tests/integration/sources/database/exasol/test_usage.py new file mode 100644 index 000000000000..b184abb506bb --- /dev/null +++ b/ingestion/tests/integration/sources/database/exasol/test_usage.py @@ -0,0 +1,230 @@ +from sqlalchemy import text + +from ingestion.tests.integration.sources.database.exasol.base import ( + DB_PORT, + SCHEMA_NAME, + TABLE_NAME, + VIEW_NAME, + ExasolTestBase, + wait_for_system_table, +) +from metadata.generated.schema.api.services.createDatabaseService import ( + CreateDatabaseServiceRequest, +) +from metadata.generated.schema.entity.services.connections.database.exasolConnection import ( + ExasolConnection, + Tls, +) +from metadata.generated.schema.entity.services.databaseService import ( + DatabaseConnection, + DatabaseService, + DatabaseServiceType, +) +from metadata.generated.schema.metadataIngestion.databaseServiceMetadataPipeline import ( + DatabaseMetadataConfigType, +) +from metadata.generated.schema.metadataIngestion.databaseServiceQueryUsagePipeline import ( + DatabaseUsageConfigType, +) +from metadata.ingestion.source.database.exasol.queries import EXASOL_SQL_STATEMENT +from metadata.workflow.metadata import MetadataWorkflow +from metadata.workflow.usage import UsageWorkflow + + +class TestExasolUsage(ExasolTestBase): + def test_usage_workflow_publishes_stage_data(self, metadata, tmp_path): + exasol_connection = ExasolConnection( + username="sys", + password="exasol", + hostPort=f"localhost:{DB_PORT}", + tls=Tls.ignore_certificate, + ) + workflow_connection = DatabaseConnection(config=exasol_connection).model_dump() + service_request = CreateDatabaseServiceRequest( + name=f"docker_test_exasol_{id(self)}", + serviceType=DatabaseServiceType.Exasol, + connection=DatabaseConnection(config=exasol_connection), + ) + + service = metadata.create_or_update(data=service_request) + try: + metadata_config = { + "source": { + "type": "exasol", + "serviceName": service.fullyQualifiedName.root, + "serviceConnection": workflow_connection, + "sourceConfig": { + "config": { + "type": DatabaseMetadataConfigType.DatabaseMetadata.value, + "includeTables": True, + "includeViews": True, + "includeDDL": True, + "markDeletedTables": True, + } + }, + }, + "sink": {"type": "metadata-rest", "config": {}}, + "workflowConfig": { + "loggerLevel": "DEBUG", + "openMetadataServerConfig": metadata.config.model_dump(), + }, + } + + metadata_workflow = MetadataWorkflow.create(metadata_config) + metadata_workflow.execute() + metadata_workflow.raise_from_status() + + with self.engine.begin() as connection: + connection.execute( + text( + f""" + INSERT INTO {SCHEMA_NAME}.{TABLE_NAME} ( + col_boolean, + col_decimal, + col_date, + col_timestamp, + col_timestamp_local, + col_char, + col_varchar + ) VALUES + (TRUE, 1.5, '2023-07-13', '2023-07-13 06:04:45', '2023-07-13 04:04:45', 'x', 'y') + """ + ) + ) + connection.execute( + text( + f""" + SELECT + col_boolean, + col_decimal, + col_date, + col_timestamp, + col_timestamp_local, + col_char, + col_varchar + FROM {SCHEMA_NAME}.{TABLE_NAME} + LIMIT 1 + """ + ) + ) + connection.execute( + text( + f""" + INSERT INTO {SCHEMA_NAME}.{TABLE_NAME} ( + col_boolean, + col_decimal, + col_date, + col_timestamp, + col_timestamp_local, + col_char, + col_varchar + ) VALUES + (TRUE, 2.5, '2023-07-14', '2023-07-14 06:04:45', '2023-07-14 04:04:45', 'z', 'w') + """ + ) + ) + connection.execute( + text( + f""" + CREATE OR REPLACE VIEW {SCHEMA_NAME}.{VIEW_NAME} AS + SELECT + col_boolean, + col_decimal, + col_date, + col_timestamp, + col_timestamp_local, + col_char, + col_varchar + FROM {SCHEMA_NAME}.{TABLE_NAME} + """ + ) + ) + connection.execute( + text( + f""" + SELECT + col_boolean, + col_decimal, + col_date, + col_timestamp, + col_timestamp_local, + col_char, + col_varchar + FROM {SCHEMA_NAME}.{VIEW_NAME} + LIMIT 1 + """ + ) + ) + + wait_for_system_table( + self.engine, + EXASOL_SQL_STATEMENT.format( + start_time="2000-01-01 00:00:00", + end_time="2999-01-01 00:00:00", + filters="", + result_limit=10, + ), + expected_count=3, + timeout_seconds=120, + ) + + usage_config = { + "source": { + "type": "exasol-usage", + "serviceName": service.fullyQualifiedName.root, + "serviceConnection": workflow_connection, + "sourceConfig": { + "config": { + "type": DatabaseUsageConfigType.DatabaseUsage.value, + "queryLogDuration": 1, + "resultLimit": 10000, + } + }, + }, + "processor": {"type": "query-parser", "config": {}}, + "stage": { + "type": "table-usage", + "config": {"filename": str(tmp_path / "exasol_usage")}, + }, + "bulkSink": { + "type": "metadata-usage", + "config": {"filename": str(tmp_path / "exasol_usage")}, + }, + "workflowConfig": { + "loggerLevel": "DEBUG", + "openMetadataServerConfig": metadata.config.model_dump(), + }, + } + + usage_workflow = UsageWorkflow.create(usage_config) + usage_workflow.execute() + usage_workflow.raise_from_status() + + table_usage = usage_workflow.steps[1].table_usage + table_queries = usage_workflow.steps[1].table_queries + + assert table_usage + assert table_queries + + usage_counts = {table: value.count for (table, _), value in table_usage.items()} + assert any(TABLE_NAME.lower() in table.lower() for table in usage_counts) + assert sum(usage_counts.values()) >= 3 + + recorded_queries = [ + query for queries in table_queries.values() for query in queries if query.query and query.query.root + ] + assert any( + query.query.root.upper().startswith("SELECT") and TABLE_NAME.lower() in query.query.root.lower() + for query in recorded_queries + ) + assert any( + query.query.root.upper().startswith("SELECT") and VIEW_NAME.lower() in query.query.root.lower() + for query in recorded_queries + ) + finally: + metadata.delete( + entity=DatabaseService, + entity_id=service.id, + recursive=True, + hard_delete=True, + ) diff --git a/ingestion/tests/unit/connections/test_connection_lifecycle.py b/ingestion/tests/unit/connections/test_connection_lifecycle.py new file mode 100644 index 000000000000..d56c64d4c3c8 --- /dev/null +++ b/ingestion/tests/unit/connections/test_connection_lifecycle.py @@ -0,0 +1,137 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Lifecycle tests for BaseConnection and the connection seam. A source reuses its +BaseConnection for the test-connection step without a second sign-in; standalone +callers own teardown. +""" + +import logging +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +from metadata.ingestion.connections.connection import BaseConnection +from metadata.ingestion.source import connections as connections_module + + +class FakeClient: + def __init__(self): + self.closed = False + + +class FakeConnection(BaseConnection): + def __init__(self, service_connection): + super().__init__(service_connection) + self.build_count = 0 + self.last_client = None + + def _get_client(self) -> FakeClient: + self.build_count += 1 + client = FakeClient() + self.last_client = client + self._on_close(lambda: setattr(client, "closed", True)) + return client + + def checks(self): + _ = self.client + return MagicMock() + + +def _service_connection(): + return SimpleNamespace(type=SimpleNamespace(value="Fake")) + + +def _patch_runner(): + return patch( + "metadata.ingestion.connections.connection.TestConnectionRunner", + return_value=MagicMock(run=MagicMock(return_value="ok")), + ) + + +def test_test_connection_does_not_close_or_rebuild(): + conn = FakeConnection(_service_connection()) + client = conn.client + with _patch_runner(): + conn.test_connection(MagicMock()) + + assert conn.build_count == 1 + assert conn.client is client + assert client.closed is False + + +def test_context_manager_closes_client(): + conn = FakeConnection(_service_connection()) + with conn: + client = conn.client + assert client.closed is True + assert conn._client is None + + +def test_reopen_after_close_rebuilds_and_logs(caplog): + conn = FakeConnection(_service_connection()) + first = conn.client + conn.close() + + with caplog.at_level(logging.INFO): + second = conn.client + + assert conn.build_count == 2 + assert second is not first + assert first.closed is True + assert any("was closed; opening a new client" in r.message for r in caplog.records) + + +def test_first_build_does_not_log_reopen(caplog): + conn = FakeConnection(_service_connection()) + with caplog.at_level(logging.INFO): + _ = conn.client + assert not any("opening a new client" in r.message for r in caplog.records) + + +def test_create_connection_returns_owner(): + with patch.object(connections_module, "_get_connection_class_from_spec", return_value=FakeConnection): + conn = connections_module.create_connection(_service_connection()) + assert isinstance(conn, FakeConnection) + + +def test_create_connection_none_for_non_migrated(): + with patch.object(connections_module, "_get_connection_class_from_spec", return_value=None): + assert connections_module.create_connection(_service_connection()) is None + + +class OverrideConnection(FakeConnection): + """Mirrors connectors that override test_connection without a `close` param.""" + + def test_connection(self, metadata, automation_workflow=None, timeout_seconds=None): + _ = self.client + return "ok" + + +def test_run_test_connection_handles_overridden_signature_without_close(): + owner = OverrideConnection(_service_connection()) + client = owner.client + with patch.object(connections_module, "raise_test_connection_exception"): + connections_module.run_test_connection(MagicMock(), owner) + + assert owner.build_count == 1 + assert owner.client is client + assert client.closed is False + + +def test_run_test_connection_reuses_without_rebuild_or_close(): + owner = FakeConnection(_service_connection()) + client = owner.client + with patch.object(connections_module, "raise_test_connection_exception"), _patch_runner(): + connections_module.run_test_connection(MagicMock(), owner) + + assert owner.build_count == 1 + assert owner.client is client + assert client.closed is False diff --git a/ingestion/tests/unit/core/connections/test_connection/test_aws.py b/ingestion/tests/unit/core/connections/test_connection/test_aws.py new file mode 100644 index 000000000000..de9b4ca83c53 --- /dev/null +++ b/ingestion/tests/unit/core/connections/test_connection/test_aws.py @@ -0,0 +1,146 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The shared AWS error pack and its structured-code matcher.""" + +import pytest +from botocore.exceptions import ( + ClientError, + EndpointConnectionError, + NoCredentialsError, + NoRegionError, +) + +from metadata.core.connections.test_connection.aws import ( + AWS_ERRORS, + aws_code, + aws_error_code, +) + + +def _client_error(code: str, message: str = "denied", operation: str = "GetDatabases") -> ClientError: + return ClientError({"Error": {"Code": code, "Message": message}}, operation) + + +def test_aws_error_code_reads_the_structured_code(): + assert aws_error_code(_client_error("AccessDeniedException")) == "AccessDeniedException" + + +def test_aws_error_code_walks_the_cause_chain(): + cause = _client_error("ExpiredToken") + wrapper = RuntimeError("driver wrapped it") + wrapper.__cause__ = cause + + assert aws_error_code(wrapper) == "ExpiredToken" + + +def test_aws_error_code_is_none_for_a_non_client_error(): + assert aws_error_code(RuntimeError("boom")) is None + + +def test_aws_code_matches_only_the_listed_codes(): + matcher = aws_code("ExpiredToken", "ExpiredTokenException") + + assert matcher(_client_error("ExpiredTokenException")) is True + assert matcher(_client_error("AccessDenied")) is False + + +def test_aws_code_ignores_the_message_text(): + # The structured code is EntityNotFoundException; the message echoes "AccessDenied". + error = _client_error("EntityNotFoundException", message="database 'AccessDenied-logs' not found") + + assert aws_code("AccessDenied")(error) is False + + +@pytest.mark.parametrize( + ("code", "expected"), + [ + # An unknown access key ID, per protocol. + ("InvalidAccessKeyId", "AWS access key not recognized"), + ("UnrecognizedClientException", "AWS access key not recognized"), + ("InvalidClientTokenId", "AWS access key not recognized"), + # A wrong secret, per protocol. + ("SignatureDoesNotMatch", "AWS secret key does not match"), + ("InvalidSignatureException", "AWS secret key does not match"), + ("ExpiredToken", "AWS session token expired"), + ("ExpiredTokenException", "AWS session token expired"), + ], +) +def test_aws_errors_classifies_every_authentication_code(code, expected): + diagnosis = AWS_ERRORS.classify(_client_error(code)) + + assert diagnosis is not None + assert diagnosis.title == expected + + +@pytest.mark.parametrize("code", ["InvalidSignatureException", "SignatureDoesNotMatch"]) +@pytest.mark.parametrize( + "message", + [ + "Signature expired: 20260709T101500Z is now earlier than 20260709T102000Z", + "Signature not yet current: 20260709T104500Z is still later than 20260709T102000Z", + ], +) +def test_aws_errors_tells_clock_skew_apart_from_a_wrong_secret(code, message): + diagnosis = AWS_ERRORS.classify(_client_error(code, message=message)) + + assert diagnosis is not None + assert diagnosis.title == "Request signature expired" + + +def test_aws_errors_still_reads_a_signature_mismatch_as_a_wrong_secret(): + error = _client_error( + "InvalidSignatureException", + message="The request signature we calculated does not match the signature you provided.", + ) + + assert AWS_ERRORS.classify(error).title == "AWS secret key does not match" + + +def test_aws_errors_ignores_ec2_only_auth_failure(): + # AuthFailure is EC2-only. + assert AWS_ERRORS.classify(_client_error("AuthFailure")) is None + + +def test_aws_errors_classifies_missing_credentials(): + diagnosis = AWS_ERRORS.classify(NoCredentialsError()) + + assert diagnosis is not None + assert "credentials" in diagnosis.title.lower() + + +def test_aws_errors_classifies_missing_region(): + diagnosis = AWS_ERRORS.classify(NoRegionError()) + + assert diagnosis is not None + assert "region" in diagnosis.title.lower() + + +def test_aws_errors_classifies_an_unreachable_endpoint(): + diagnosis = AWS_ERRORS.classify(EndpointConnectionError(endpoint_url="https://glue.bad-region.amazonaws.com")) + + assert diagnosis is not None + assert "endpoint" in diagnosis.title.lower() + + +def test_aws_errors_folds_in_the_network_pack(): + diagnosis = AWS_ERRORS.classify(ConnectionRefusedError("refused")) + + assert diagnosis is not None + assert "refused" in diagnosis.title.lower() + + +def test_aws_errors_leaves_authorization_to_the_connector(): + """AccessDenied's remedy names service-specific IAM actions.""" + assert AWS_ERRORS.classify(_client_error("AccessDeniedException")) is None + + +def test_aws_errors_unmatched_returns_none(): + assert AWS_ERRORS.classify(Exception("novel error")) is None diff --git a/ingestion/tests/unit/core/connections/test_connection/test_base_connection.py b/ingestion/tests/unit/core/connections/test_connection/test_base_connection.py index e0762414f276..cf38ca2e9cf0 100644 --- a/ingestion/tests/unit/core/connections/test_connection/test_base_connection.py +++ b/ingestion/tests/unit/core/connections/test_connection/test_base_connection.py @@ -100,10 +100,10 @@ def close(self): super().close() -def test_test_connection_closes_on_success(): +def test_test_connection_does_not_close_on_success(): connection = _RecordingConnection(_service_connection()) connection.test_connection(_Metadata()) - assert connection.closes == 1 + assert connection.closes == 0 class _FailingConnection(_RecordingConnection): @@ -111,10 +111,17 @@ def checks(self): raise RuntimeError("boom") -def test_test_connection_closes_even_on_error(): +def test_test_connection_does_not_close_on_error(): connection = _FailingConnection(_service_connection()) with pytest.raises(RuntimeError): connection.test_connection(_Metadata()) + assert connection.closes == 0 + + +def test_context_manager_closes(): + connection = _RecordingConnection(_service_connection()) + with connection: + connection.test_connection(_Metadata()) assert connection.closes == 1 diff --git a/ingestion/tests/unit/core/connections/test_connection/test_network.py b/ingestion/tests/unit/core/connections/test_connection/test_network.py index 2fe8bb0411b8..87de3cab0d83 100644 --- a/ingestion/tests/unit/core/connections/test_connection/test_network.py +++ b/ingestion/tests/unit/core/connections/test_connection/test_network.py @@ -11,6 +11,7 @@ """Unit tests for the TCP reachability preflight and its diagnosis pack.""" import socket +from unittest.mock import patch import pytest @@ -50,6 +51,48 @@ def test_tcp_probe_raises_network_error_when_port_is_closed(closed_port): assert isinstance(exc.value.__cause__, ConnectionRefusedError) +def _ipv6_loopback_available() -> bool: + available = True + try: + with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as probe: + probe.bind(("::1", 0)) + except OSError: + available = False + return available + + +@pytest.mark.skipif(not _ipv6_loopback_available(), reason="IPv6 loopback not available") +def test_tcp_probe_reaches_an_ipv6_host(): + # Handing the hostname to create_connection lets it dial the IPv6 address; + # the old IPv4-only lookup would have read this host as unreachable. + sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) + sock.bind(("::1", 0)) + sock.listen(1) + port = sock.getsockname()[1] + try: + assert tcp_probe("::1", port) is None + finally: + sock.close() + + +def test_tcp_probe_hands_the_hostname_to_create_connection(): + # Passing the hostname (not a pre-resolved IPv4 address) is what lets + # create_connection try every resolved address, IPv4 and IPv6, in turn. + with patch("socket.create_connection") as connect: + tcp_probe("airflow.example.com", 8080, timeout=20) + + connect.assert_called_once_with(("airflow.example.com", 8080), timeout=20) + + +def test_tcp_probe_raises_when_the_name_cannot_be_resolved(): + with ( + patch("socket.create_connection", side_effect=socket.gaierror(-2, "Name or service not known")), + pytest.raises(NetworkUnreachableError) as exc, + ): + tcp_probe("nope.example.com", 443) + assert isinstance(exc.value.__cause__, socket.gaierror) + + def test_network_errors_classifies_connection_refused(): error = NetworkUnreachableError("h:1 is not reachable") error.__cause__ = ConnectionRefusedError(61, "Connection refused") diff --git a/ingestion/tests/unit/lineage/test_lineage_progress.py b/ingestion/tests/unit/lineage/test_lineage_progress.py index 3048bc7a95e2..392a9112e76c 100644 --- a/ingestion/tests/unit/lineage/test_lineage_progress.py +++ b/ingestion/tests/unit/lineage/test_lineage_progress.py @@ -60,4 +60,4 @@ def fake_generate(producer_fn, processor_fn, args, **kwargs): with patch.object(LineageSource, "generate_lineage_with_processes", staticmethod(fake_generate)): list(LineageSource.yield_query_lineage(source)) - assert source.progress.global_counters() == [("Queries", 4, 4)] + assert source.progress_tracking.registry.global_counters() == [("Queries", 4, 4)] diff --git a/ingestion/tests/unit/lineage/test_lineage_source.py b/ingestion/tests/unit/lineage/test_lineage_source.py index 47aa32e9a506..8b88e5b1b589 100644 --- a/ingestion/tests/unit/lineage/test_lineage_source.py +++ b/ingestion/tests/unit/lineage/test_lineage_source.py @@ -171,6 +171,49 @@ def test_yield_table_query_from_database(self): self.assertEqual(queries[0].databaseName, "db1") self.assertEqual(queries[0].serviceName, "test_service") + def _mock_engine_with_rows(self, rows): + mock_engine = Mock() + mock_connection = Mock() + mock_connection.execute.return_value = rows + mock_engine.connect.return_value.__enter__ = Mock(return_value=mock_connection) + mock_engine.connect.return_value.__exit__ = Mock(return_value=None) + return mock_engine + + def test_result_limit_truncation_logged_when_reached(self): + """A debug truncation notice is logged when the query log fills resultLimit""" + self.lineage_source.source_config.resultLimit = 2 + rows = [ + {"query_text": "SELECT * FROM t1", "database_name": "db1", "schema_name": "s1"}, + {"query_text": "SELECT * FROM t2", "database_name": "db1", "schema_name": "s1"}, + ] + mock_engine = self._mock_engine_with_rows(rows) + + with ( + patch.object(self.lineage_source, "get_engine", return_value=[mock_engine]), + patch("metadata.ingestion.source.database.lineage_source.logger") as mock_logger, + ): + list(self.lineage_source.yield_table_query()) + + assert any("resultLimit" in str(call.args[0]) for call in mock_logger.debug.call_args_list) + + def test_result_limit_non_int_does_not_raise(self): + """A non-int resultLimit (e.g. absent/mocked) skips the check without TypeError""" + self.lineage_source.source_config.resultLimit = Mock() + rows = [ + {"query_text": "SELECT * FROM t1", "database_name": "db1", "schema_name": "s1"}, + ] + mock_engine = self._mock_engine_with_rows(rows) + + with ( + patch.object(self.lineage_source, "get_engine", return_value=[mock_engine]), + patch("metadata.ingestion.source.database.lineage_source.logger") as mock_logger, + ): + queries = list(self.lineage_source.yield_table_query()) + + # Processing completes and no truncation notice is emitted + self.assertEqual(len(queries), 1) + assert not any("resultLimit" in str(call.args[0]) for call in mock_logger.debug.call_args_list) + def test_yield_table_queries_from_logs(self): """Test yielding table queries from CSV log files""" with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f: diff --git a/ingestion/tests/unit/lineage/test_snowflake_access_history_progress.py b/ingestion/tests/unit/lineage/test_snowflake_access_history_progress.py index aae250b67a4d..d31c3eb07783 100644 --- a/ingestion/tests/unit/lineage/test_snowflake_access_history_progress.py +++ b/ingestion/tests/unit/lineage/test_snowflake_access_history_progress.py @@ -14,7 +14,6 @@ from metadata.ingestion.api.models import Either from metadata.ingestion.source.database.snowflake.lineage import SnowflakeLineageSource -from metadata.workflow.progress_render import ProgressReporter class TestAccessHistoryProgress: @@ -28,5 +27,5 @@ def test_tracks_lineage_records_without_total_or_eta(self): results = list(SnowflakeLineageSource._yield_access_history_lineage(source)) assert len(results) == 4 - assert source.progress.global_counters() == [("LineageRecords", 4, None)] - assert ProgressReporter(source.progress).eta_seconds() is None + assert source.progress_tracking.registry.global_counters() == [("LineageRecords", 4, None)] + assert source.progress_tracking.registry.eta_seconds() is None diff --git a/ingestion/tests/unit/observability/profiler/test_container_fetcher.py b/ingestion/tests/unit/observability/profiler/test_container_fetcher.py index 3da99135e8ed..9998bbcb9af3 100644 --- a/ingestion/tests/unit/observability/profiler/test_container_fetcher.py +++ b/ingestion/tests/unit/observability/profiler/test_container_fetcher.py @@ -14,6 +14,7 @@ """ import uuid +from unittest.mock import MagicMock, patch from metadata.generated.schema.entity.data.container import ( Container, @@ -35,7 +36,10 @@ from metadata.generated.schema.type.entityReference import EntityReference from metadata.generated.schema.type.tagLabel import TagLabel from metadata.ingestion.api.status import Status +from metadata.ingestion.progress.modes import ManualProgress +from metadata.ingestion.progress.registry import ProgressRegistry from metadata.profiler.source.fetcher.fetcher_strategy import StorageFetcherStrategy +from metadata.profiler.source.profiler_source_interface import ProfilerSourceInterface # Test containers with different characteristics STRUCTURED_CONTAINER = Container( @@ -108,6 +112,7 @@ def get_storage_fetcher(source_config): metadata=..., global_profiler_config=..., status=Status(), + progress=ManualProgress(ProgressRegistry()), ) @@ -197,3 +202,30 @@ def test_combined_filters(): assert UNSTRUCTURED_CONTAINER not in filtered assert TAGGED_CONTAINER not in filtered assert len(filtered) == 1 + + +class TestStorageFetcherProgress: + def test_sets_exact_total_and_tracks_each_container(self): + registry = ProgressRegistry() + progress = ManualProgress(registry) + + strategy = StorageFetcherStrategy.__new__(StorageFetcherStrategy) + strategy.progress = progress + strategy.config = MagicMock() + strategy.metadata = MagicMock() + strategy.global_profiler_config = None + strategy._get_container_entities = lambda: [ + STRUCTURED_CONTAINER, + UNSTRUCTURED_CONTAINER, + TAGGED_CONTAINER, + ] + + with patch( + "metadata.profiler.source.fetcher.fetcher_strategy.profiler_source_factory.create", + return_value=MagicMock(spec=ProfilerSourceInterface), + ): + records = list(strategy.fetch()) + + assert len(records) == 3 + assert registry.global_counters() == [("Container", 3, 3)] + assert registry.assets_ingested() == 3 diff --git a/ingestion/tests/unit/observability/profiler/test_entity_fetcher.py b/ingestion/tests/unit/observability/profiler/test_entity_fetcher.py index 8fb8a327d701..817c7c7d3eb6 100644 --- a/ingestion/tests/unit/observability/profiler/test_entity_fetcher.py +++ b/ingestion/tests/unit/observability/profiler/test_entity_fetcher.py @@ -14,6 +14,7 @@ """ import uuid +from types import SimpleNamespace from unittest.mock import MagicMock, patch import pytest @@ -40,6 +41,8 @@ from metadata.generated.schema.type.entityReference import EntityReference from metadata.generated.schema.type.tagLabel import TagLabel from metadata.ingestion.api.status import Status +from metadata.ingestion.progress.modes import ManualProgress +from metadata.ingestion.progress.registry import ProgressRegistry from metadata.profiler.source.fetcher.fetcher_strategy import DatabaseFetcherStrategy from metadata.profiler.source.profiler_source_interface import ProfilerSourceInterface @@ -79,6 +82,7 @@ def get_db_fetcher(source_config): metadata=..., global_profiler_config=..., status=Status(), + progress=ManualProgress(ProgressRegistry()), ) @@ -142,6 +146,12 @@ def test_include_views(): service=SERVICE_REF, ) +NO_FQN_DB = Database( + id=uuid.uuid4(), + name="no_fqn", + service=SERVICE_REF, +) + FINANCE_SCHEMA_REF = EntityReference( id=uuid.uuid4(), name="finance", @@ -289,11 +299,13 @@ def _make_fetcher(source_config_overrides=None): cfg["source"]["sourceConfig"]["config"].update(source_config_overrides) workflow_config = OpenMetadataWorkflowConfig(**cfg) mock_metadata = MagicMock() + mock_metadata.list_entities.return_value = SimpleNamespace(total=0) return DatabaseFetcherStrategy( config=workflow_config, metadata=mock_metadata, global_profiler_config=None, status=Status(), + progress=ManualProgress(ProgressRegistry()), ) @@ -733,3 +745,164 @@ def create_side_effect(*args, **kwargs): assert "connection failed for prod" in results[0].left.error assert results[1].right is not None assert results[1].right.entity == ORDERS_TABLE + + @patch("metadata.profiler.source.fetcher.fetcher_strategy.profiler_source_factory") + def test_fetch_does_not_abort_loop_when_database_lacks_fqn(self, mock_factory): + """A database missing fullyQualifiedName must not raise out of fetch() + and abort the remaining databases. It degrades to a single error record + while the sibling database is still fully processed.""" + mock_factory.create.return_value = MagicMock(spec=ProfilerSourceInterface) + fetcher = _make_fetcher({"includeViews": True}) + fetcher.metadata.list_all_entities.side_effect = [ + iter([NO_FQN_DB, PROD_DB]), + iter([ORDERS_TABLE]), + ] + + results = list(fetcher.fetch()) + + errors = [r.left for r in results if r.left] + entities = [r.right.entity for r in results if r.right] + assert len(errors) == 1 + assert errors[0].name == "no_fqn" + assert entities == [ORDERS_TABLE] + + +def _db_strategy_with_progress(tables, server_total, capture=None): + """DatabaseFetcherStrategy wired with a real ProgressRegistry, with its + database/table enumeration and profiler_source stubbed so fetch() runs in + isolation. `server_total` is what the seed count call reports.""" + registry = ProgressRegistry() + progress = ManualProgress(registry) + + strategy = DatabaseFetcherStrategy.__new__(DatabaseFetcherStrategy) + strategy.progress = progress + strategy.config = SimpleNamespace(source=SimpleNamespace(type="mysql")) + strategy.global_profiler_config = None + strategy.metadata = MagicMock() + strategy.metadata.list_entities.return_value = SimpleNamespace(total=server_total) + + database = SimpleNamespace(fullyQualifiedName=SimpleNamespace(root="svc.db")) + strategy._get_database_entities = lambda: iter([database]) + strategy._build_table_params = lambda db: {} + + def _tables(_db): + first = True + for table in tables: + if capture is not None and first: + capture["mid"] = registry.global_counters() + first = False + yield table + + strategy._get_table_entities = _tables + return strategy, registry, progress + + +def _multi_db_strategy_with_progress(db_specs): + """DatabaseFetcherStrategy wired with a real ProgressRegistry across + MULTIPLE databases, each with its own seeded server total and its own + table list, to guard the per-database-scope reconciliation that sums + into a single global `Table` counter. `db_specs` is an ordered mapping + of database FQN -> (seed_total, tables).""" + registry = ProgressRegistry() + progress = ManualProgress(registry) + + strategy = DatabaseFetcherStrategy.__new__(DatabaseFetcherStrategy) + strategy.progress = progress + strategy.config = SimpleNamespace(source=SimpleNamespace(type="mysql")) + strategy.global_profiler_config = None + strategy.metadata = MagicMock() + strategy.metadata.list_entities.side_effect = [SimpleNamespace(total=seed) for seed, _ in db_specs.values()] + + databases = [SimpleNamespace(fullyQualifiedName=SimpleNamespace(root=fqn)) for fqn in db_specs] + strategy._get_database_entities = lambda: iter(databases) + strategy._build_table_params = lambda db: {} + strategy._get_table_entities = lambda db: iter(db_specs[db.fullyQualifiedName.root][1]) + return strategy, registry, progress + + +class TestDatabaseFetcherProgress: + def test_seeds_server_total_then_reconciles_to_observed(self): + with patch( + "metadata.profiler.source.fetcher.fetcher_strategy.profiler_source_factory.create", + return_value=MagicMock(spec=ProfilerSourceInterface), + ): + strategy, registry, _ = _db_strategy_with_progress(tables=[TABLE, TABLE], server_total=5) + records = list(strategy.fetch()) + + assert len(records) == 2 + assert registry.global_counters() == [("Table", 2, 2)] + assert registry.assets_ingested() == 2 + + def test_seed_visible_before_reconcile(self): + capture = {} + with patch( + "metadata.profiler.source.fetcher.fetcher_strategy.profiler_source_factory.create", + return_value=MagicMock(spec=ProfilerSourceInterface), + ): + strategy, _, _ = _db_strategy_with_progress(tables=[TABLE, TABLE], server_total=5, capture=capture) + list(strategy.fetch()) + + assert capture["mid"] == [("Table", 0, 5)] + + def test_seed_failure_falls_back_to_reconcile(self): + with patch( + "metadata.profiler.source.fetcher.fetcher_strategy.profiler_source_factory.create", + return_value=MagicMock(spec=ProfilerSourceInterface), + ): + strategy, registry, _ = _db_strategy_with_progress(tables=[TABLE], server_total=0) + strategy.metadata.list_entities.side_effect = RuntimeError("boom") + records = list(strategy.fetch()) + + assert len(records) == 1 + assert registry.global_counters() == [("Table", 1, 1)] + assert registry.assets_ingested() == 1 + + def test_multi_database_aggregates_into_single_table_counter(self): + """Each database seeds and reconciles its own scope, but they all + roll up into one global `Table` counter: seeded totals (3 + 2) walk + down to observed totals (2 + 2) as each database's tables complete.""" + with patch( + "metadata.profiler.source.fetcher.fetcher_strategy.profiler_source_factory.create", + return_value=MagicMock(spec=ProfilerSourceInterface), + ): + strategy, registry, _ = _multi_db_strategy_with_progress( + { + "svc.db1": (3, [TABLE, TABLE]), + "svc.db2": (2, [TABLE, TABLE]), + } + ) + records = list(strategy.fetch()) + + assert len(records) == 4 + assert registry.global_counters() == [("Table", 4, 4)] + assert registry.assets_ingested() == 4 + + def test_partial_db_failure_walks_back_phantom_seed(self): + """A failure creating the profiler source for db1 must not leave its + seeded total (5) inflating the shared `Table` counter: the `finally` + reconcile walks the phantom seed back to `observed=0` for that scope, + while db2 still contributes its real, completed total.""" + + def create_side_effect(*args, **kwargs): + database = args[2] + if database.fullyQualifiedName.root == "svc.db1": + raise RuntimeError("connection failed for db1") + return MagicMock(spec=ProfilerSourceInterface) + + with patch( + "metadata.profiler.source.fetcher.fetcher_strategy.profiler_source_factory.create", + side_effect=create_side_effect, + ): + strategy, registry, _ = _multi_db_strategy_with_progress( + { + "svc.db1": (5, [TABLE, TABLE]), + "svc.db2": (2, [TABLE, TABLE]), + } + ) + records = list(strategy.fetch()) + + errors = [record for record in records if record.left is not None] + assert len(errors) == 1 + assert "connection failed for db1" in errors[0].left.error + assert registry.global_counters() == [("Table", 2, 2)] + assert registry.assets_ingested() == 2 diff --git a/ingestion/tests/unit/observability/profiler/test_workflow.py b/ingestion/tests/unit/observability/profiler/test_workflow.py index 3708893d60aa..004ad72626c1 100644 --- a/ingestion/tests/unit/observability/profiler/test_workflow.py +++ b/ingestion/tests/unit/observability/profiler/test_workflow.py @@ -39,6 +39,8 @@ from metadata.generated.schema.type.filterPattern import FilterPattern from metadata.generated.schema.type.tagLabel import TagLabel from metadata.ingestion.api.status import Status +from metadata.ingestion.progress.modes import ManualProgress +from metadata.ingestion.progress.registry import ProgressRegistry from metadata.profiler.api.models import ProfilerProcessorConfig from metadata.profiler.interface.sqlalchemy.profiler_interface import ( SQAProfilerInterface, @@ -183,14 +185,18 @@ def test_build_regex_from_filter(): def test_build_database_params(): """Verify that database filter patterns are correctly translated to API params""" # No filter pattern -> only service param - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_database_params() assert params == {"service": "my_service"} # Include filter -> databaseRegex with include mode include_config = deepcopy(config) include_config["source"]["sourceConfig"]["config"]["databaseFilterPattern"] = {"includes": ["db.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**include_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**include_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_database_params() assert params["databaseRegex"] == "db.*" assert params["regexMode"] == "include" @@ -199,7 +205,9 @@ def test_build_database_params(): # Exclude filter -> databaseRegex with exclude mode exclude_config = deepcopy(config) exclude_config["source"]["sourceConfig"]["config"]["databaseFilterPattern"] = {"excludes": ["temp.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**exclude_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**exclude_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_database_params() assert params["databaseRegex"] == "temp.*" assert params["regexMode"] == "exclude" @@ -207,7 +215,9 @@ def test_build_database_params(): # Multiple includes -> combined with OR multi_config = deepcopy(config) multi_config["source"]["sourceConfig"]["config"]["databaseFilterPattern"] = {"includes": ["finance.*", "sales.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**multi_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**multi_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_database_params() assert params["databaseRegex"] == "(finance.*)|(sales.*)" assert params["regexMode"] == "include" @@ -216,7 +226,9 @@ def test_build_database_params(): fqn_config = deepcopy(config) fqn_config["source"]["sourceConfig"]["config"]["useFqnForFiltering"] = True fqn_config["source"]["sourceConfig"]["config"]["databaseFilterPattern"] = {"includes": ["my_service.db.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**fqn_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**fqn_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_database_params() assert params["regexFilterByFqn"] == "true" @@ -231,14 +243,18 @@ def test_build_table_params(): ) # No filter pattern -> only service and database params - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_table_params(database) assert params == {"service": "my_service", "database": "my_service.db"} # Schema include filter schema_config = deepcopy(config) schema_config["source"]["sourceConfig"]["config"]["schemaFilterPattern"] = {"includes": ["one_schema"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**schema_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**schema_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_table_params(database) assert params["databaseSchemaRegex"] == "one_schema" assert params["regexMode"] == "include" @@ -247,7 +263,9 @@ def test_build_table_params(): # Table exclude filter table_config = deepcopy(config) table_config["source"]["sourceConfig"]["config"]["tableFilterPattern"] = {"excludes": ["temp.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**table_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**table_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_table_params(database) assert params["tableRegex"] == "temp.*" assert params["regexMode"] == "exclude" @@ -257,7 +275,9 @@ def test_build_table_params(): both_config = deepcopy(config) both_config["source"]["sourceConfig"]["config"]["schemaFilterPattern"] = {"includes": ["finance"]} both_config["source"]["sourceConfig"]["config"]["tableFilterPattern"] = {"includes": ["orders.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**both_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**both_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_table_params(database) assert params["databaseSchemaRegex"] == "finance" assert params["tableRegex"] == "orders.*" @@ -269,7 +289,9 @@ def test_build_table_params(): fqn_config["source"]["sourceConfig"]["config"]["schemaFilterPattern"] = { "excludes": ["my_service.db.another_schema"] } - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**fqn_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**fqn_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_table_params(database) assert params["databaseSchemaRegex"] == "my_service.db.another_schema" assert params["regexMode"] == "exclude" @@ -278,7 +300,9 @@ def test_build_table_params(): conflict_config = deepcopy(config) conflict_config["source"]["sourceConfig"]["config"]["schemaFilterPattern"] = {"includes": ["finance"]} conflict_config["source"]["sourceConfig"]["config"]["tableFilterPattern"] = {"excludes": ["temp.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**conflict_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**conflict_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_table_params(database) assert params["databaseSchemaRegex"] == "finance" assert params["regexMode"] == "include" @@ -288,7 +312,9 @@ def test_build_table_params(): conflict_config2 = deepcopy(config) conflict_config2["source"]["sourceConfig"]["config"]["schemaFilterPattern"] = {"excludes": ["hr"]} conflict_config2["source"]["sourceConfig"]["config"]["tableFilterPattern"] = {"includes": ["orders.*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**conflict_config2), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**conflict_config2), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore params = fetcher._build_table_params(database) assert params["tableRegex"] == "orders.*" assert params["regexMode"] == "include" @@ -361,14 +387,18 @@ def test_filter_classifications(): # Include classification -> only tables with matching tags include_config = deepcopy(config) include_config["source"]["sourceConfig"]["config"]["classificationFilterPattern"] = {"includes": ["tag*"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**include_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**include_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore filtered = [t for t in all_tables if not fetcher.filter_classifications(t)] assert len(filtered) == 2 # Exclude classification exclude_config = deepcopy(config) exclude_config["source"]["sourceConfig"]["config"]["classificationFilterPattern"] = {"excludes": ["tag2"]} - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**exclude_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**exclude_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore filtered = [t for t in all_tables if not fetcher.filter_classifications(t)] assert len(filtered) == 1 @@ -378,7 +408,9 @@ def test_filter_classifications(): "excludes": ["tag1"], "includes": ["tag2"], } - fetcher = DatabaseFetcherStrategy(OpenMetadataWorkflowConfig(**both_config), None, None, Status()) # type: ignore + fetcher = DatabaseFetcherStrategy( + OpenMetadataWorkflowConfig(**both_config), None, None, Status(), ManualProgress(ProgressRegistry()) + ) # type: ignore filtered = [t for t in all_tables if not fetcher.filter_classifications(t)] assert len(filtered) == 1 diff --git a/ingestion/tests/unit/ometa/test_lineage_sql_query_patch.py b/ingestion/tests/unit/ometa/test_lineage_sql_query_patch.py index c2a3fb49149e..64bebb1dc294 100644 --- a/ingestion/tests/unit/ometa/test_lineage_sql_query_patch.py +++ b/ingestion/tests/unit/ometa/test_lineage_sql_query_patch.py @@ -42,6 +42,10 @@ class StubbedLineage(OMetaLineageMixin): def __init__(self, existing_edge): self.client = MagicMock() self._existing_edge = existing_edge + # MagicMocks so tests can assert whether the post-write graph GET / cache seeding ran. + self.get_lineage_by_id = MagicMock(return_value={}) + self.get_lineage_by_name = MagicMock(return_value={}) + self._update_cache = MagicMock(return_value=None) def _get_lineage_edge_for_references(self, from_entity, to_entity): return self._existing_edge @@ -52,15 +56,6 @@ def get_lineage_edge_by_name(self, *args, **kwargs): def get_suffix(self, entity): return "/lineage" - def get_lineage_by_id(self, *args, **kwargs): - return {} - - def get_lineage_by_name(self, *args, **kwargs): - return {} - - def _update_cache(self, *args, **kwargs): - return None - def edge_lookup(stored_query=None): """Server edge-lookup payload, optionally carrying an already-stored sqlQuery.""" @@ -139,3 +134,101 @@ def test_patches_sql_query(self, stored, incoming, expected): ) assert_patched(service.client, expected) + + +FROM_FQN = "svc.db.sch.source" +TO_FQN = "svc.db.sch.target" + + +def id_request(with_fqn=True): + """add_lineage request whose fromEntity optionally carries an FQN.""" + from_entity = ( + EntityReference(id=FROM_ID, type="table", fullyQualifiedName=FROM_FQN) + if with_fqn + else EntityReference(id=FROM_ID, type="table") + ) + return AddLineageRequest( + edge=EntitiesEdge( + fromEntity=from_entity, + toEntity=EntityReference(id=TO_ID, type="table"), + lineageDetails=incoming_details(INCOMING_QUERY), + ) + ) + + +class TestReturnLineageSkipsGraphGet: + """return_lineage=False must skip the expensive post-write lineage-graph GET while + still writing the edge and returning the source FQN the sink needs.""" + + def test_add_lineage_skips_graph_get_and_cache(self): + # No pre-existing edge: the write must land as a PUT, not a PATCH. + service = StubbedLineage(None) + + result = service.add_lineage(id_request(), check_patch=True, return_lineage=False) + + service.get_lineage_by_id.assert_not_called() + service._update_cache.assert_not_called() + assert service.client.put.called + assert result == {"entity": {"fullyQualifiedName": FROM_FQN, "id": FROM_ID, "type": "table"}} + + def test_add_lineage_default_fetches_graph(self): + service = StubbedLineage(edge_lookup(None)) + + service.add_lineage(id_request(), check_patch=True) + + service.get_lineage_by_id.assert_called_once() + + def test_add_lineage_by_name_skips_graph_get(self): + # No pre-existing edge: the write must land as a PUT, not a PATCH. + service = StubbedLineage(None) + + result = service.add_lineage_by_name( + from_entity_fqn=FROM_FQN, + from_entity_type="table", + to_entity_fqn=TO_FQN, + to_entity_type="table", + lineage_details=incoming_details(INCOMING_QUERY), + check_patch=True, + return_lineage=False, + ) + + service.get_lineage_by_name.assert_not_called() + assert service.client.put.called + assert result == {"entity": {"fullyQualifiedName": FROM_FQN}} + + def test_add_lineage_by_name_default_fetches_graph(self): + service = StubbedLineage(edge_lookup(None)) + + service.add_lineage_by_name( + from_entity_fqn=FROM_FQN, + from_entity_type="table", + to_entity_fqn=TO_FQN, + to_entity_type="table", + lineage_details=incoming_details(INCOMING_QUERY), + check_patch=True, + ) + + service.get_lineage_by_name.assert_called_once() + + +class TestEntityRefSummary: + """_entity_ref_summary rebuilds the minimal sink payload, degrading FQN to None + when the reference does not carry one.""" + + def test_with_fqn(self): + reference = EntityReference(id=FROM_ID, type="table", fullyQualifiedName=FROM_FQN) + + assert OMetaLineageMixin._entity_ref_summary(reference) == { + "fullyQualifiedName": FROM_FQN, + "id": FROM_ID, + "type": "table", + } + + def test_without_fqn(self): + reference = EntityReference(id=FROM_ID, type="table") + + assert OMetaLineageMixin._entity_ref_summary(reference) == { + "fullyQualifiedName": None, + "id": FROM_ID, + "type": "table", + } diff --git a/ingestion/tests/unit/progress/__init__.py b/ingestion/tests/unit/progress/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/ingestion/tests/unit/progress/test_progress_modes.py b/ingestion/tests/unit/progress/test_progress_modes.py new file mode 100644 index 000000000000..074d8c1a9343 --- /dev/null +++ b/ingestion/tests/unit/progress/test_progress_modes.py @@ -0,0 +1,116 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""ProgressMode knob, TotalsDeclarer and ManualProgress facades.""" + +import pytest + +from metadata.ingestion.progress.modes import ( + ManualProgress, + ProgressMode, + ProgressModeError, + TotalsDeclarer, +) +from metadata.ingestion.progress.registry import ProgressRegistry +from metadata.ingestion.progress.tracking import ProgressTracking + + +def test_manual_raises_in_auto_mode(): + with pytest.raises(ProgressModeError): + _ = ProgressTracking(ProgressMode.AUTO, "AutoSource").manual + + +def test_manual_raises_in_off_mode(): + with pytest.raises(ProgressModeError): + _ = ProgressTracking(ProgressMode.OFF, "OffSource").manual + + +def test_manual_is_cached_per_tracking(): + tracking = ProgressTracking(ProgressMode.MANUAL, "ManualSource") + assert tracking.manual is tracking.manual + + +def test_manual_wraps_the_tracking_registry(): + tracking = ProgressTracking(ProgressMode.MANUAL, "ManualSource") + tracking.manual.set_total("Workspaces", 3) + assert ("Workspaces", 0, 3) in tracking.registry.global_counters() + + +def test_track_asset_counts_toward_both_progress_and_assets_ingested(): + tracking = ProgressTracking(ProgressMode.MANUAL, "ManualSource") + tracking.manual.set_total("Table", 3) + tracking.manual.track_asset("Table") + tracking.manual.track_asset("Table") + assert ("Table", 2, 3) in tracking.registry.global_counters() + assert tracking.registry.assets_ingested() == 2 + + +def test_plain_track_does_not_count_as_an_asset(): + tracking = ProgressTracking(ProgressMode.MANUAL, "ManualSource") + tracking.manual.set_total("Queries", 5) + tracking.manual.track("Queries") + tracking.manual.track("Queries") + assert ("Queries", 2, 5) in tracking.registry.global_counters() + assert tracking.registry.assets_ingested() == 0 + + +def test_totals_declarer_exposes_no_counting_methods(): + declarer = TotalsDeclarer(ProgressRegistry()) + for name in ("track", "advance", "open", "close", "reconcile_scope_total"): + assert not hasattr(declarer, name) + + +def test_totals_declarer_sets_denominators(): + registry = ProgressRegistry() + totals = TotalsDeclarer(registry) + totals.set_total("Database", 4) + totals.seed_scope_total("DatabaseSchema", "db1", 3) + totals.mark_reconcilable("Table") + counters = {t: (done, total) for t, done, total in registry.global_counters()} + assert counters["Database"] == (0, 4) + assert counters["DatabaseSchema"] == (0, 3) + assert registry.is_reconcilable("DatabaseSchema") + assert registry.is_reconcilable("Table") + + +def test_declare_progress_totals_default_is_noop(): + from metadata.ingestion.api.topology_runner import TopologyRunnerMixin + + class _Plain(TopologyRunnerMixin): + pass + + registry = ProgressRegistry() + _Plain().declare_progress_totals(TotalsDeclarer(registry)) + assert registry.global_counters() == [] + + +def test_manual_group_flow_drives_registry_like_the_old_helpers(): + registry = ProgressRegistry() + manual = ManualProgress(registry) + manual.declare_groups("Workspaces", 2) + manual.open_group("Finance", {"Dashboard": 2, "Chart": None}) + manual.advance("Finance", "Dashboard") + manual.advance("Finance", "Dashboard") + manual.advance("Finance", "Chart") + manual.close_group("Finance") + counters = {t: (done, total) for t, done, total in registry.global_counters()} + assert counters["Workspaces"] == (1, 2) + assert registry.assets_ingested() == 3 + assert registry.snapshot() is None + + +def test_manual_counter_api_passthrough(): + registry = ProgressRegistry() + manual = ManualProgress(registry) + manual.seed_scope_total("Queries", "run", 100) + manual.track("Queries", 40) + manual.reconcile_scope_total("Queries", "run", 40) + counters = {t: (done, total) for t, done, total in registry.global_counters()} + assert counters["Queries"] == (40, 40) diff --git a/ingestion/tests/unit/progress/test_runner_tracker.py b/ingestion/tests/unit/progress/test_runner_tracker.py new file mode 100644 index 000000000000..bb7fda6a56ca --- /dev/null +++ b/ingestion/tests/unit/progress/test_runner_tracker.py @@ -0,0 +1,187 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""TopologyProgressTracker: gating, path resolution, handles, totals hook.""" + +from unittest.mock import MagicMock + +import pytest + +from metadata.ingestion.api.topology_runner import TopologyRunnerMixin +from metadata.ingestion.models.topology import TopologyContextManager, get_topology_node, get_topology_root +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.ingestion.progress.runner_tracker import ( + NO_OP_NODE_PROGRESS, + NodeProgress, + TopologyProgressTracker, +) +from metadata.ingestion.source.database.database_service import DatabaseServiceTopology + + +class _FakeSource(TopologyRunnerMixin): + topology = DatabaseServiceTopology() + + def __init__(self, mode=ProgressMode.AUTO): + self.progress_mode = mode + self.context = TopologyContextManager(self.topology) + self.status = MagicMock() + self.declared = 0 + + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + self.declared += 1 + totals.set_total("Database", 7) + + +def _table_node(source): + return get_topology_node("table", source.topology) + + +def _database_node(source): + return get_topology_node("database", source.topology) + + +def test_for_node_returns_noop_when_mode_is_not_auto(): + for mode in (ProgressMode.MANUAL, ProgressMode.OFF): + source = _FakeSource(mode) + tracker = TopologyProgressTracker(source) + assert tracker.for_node(_table_node(source), is_leaf=True) is NO_OP_NODE_PROGRESS + assert "_progress_tracking" not in source.__dict__ + + +def test_for_node_returns_noop_for_root_node(): + source = _FakeSource() + tracker = TopologyProgressTracker(source) + root = get_topology_root(source.topology)[0] + tracker.on_walk_start([root]) + assert tracker.is_root_node(root) + assert tracker.for_node(root, is_leaf=False) is NO_OP_NODE_PROGRESS + + +def test_for_node_returns_lazy_handle_for_auto_leaf(): + source = _FakeSource() + tracker = TopologyProgressTracker(source) + handle = tracker.for_node(_table_node(source), is_leaf=True) + assert isinstance(handle, NodeProgress) + assert handle.wants_eager_count is False + + +def test_totals_hook_called_exactly_once_and_only_for_real_nodes(): + source = _FakeSource() + tracker = TopologyProgressTracker(source) + root = get_topology_root(source.topology)[0] + tracker.on_walk_start([root]) + tracker.for_node(root, is_leaf=False) + assert source.declared == 0 + tracker.for_node(_database_node(source), is_leaf=False) + tracker.for_node(_table_node(source), is_leaf=True) + assert source.declared == 1 + assert ("Database", 0, 7) in source.progress_tracking.registry.global_counters() + + +class _RaisingTotalsSource(_FakeSource): + def declare_progress_totals(self, totals: TotalsDeclarer) -> None: + self.declared += 1 + raise RuntimeError("totals query blew up") + + +def test_totals_hook_failure_does_not_abort_the_walk(): + source = _RaisingTotalsSource() + tracker = TopologyProgressTracker(source) + handle = tracker.for_node(_database_node(source), is_leaf=False) + assert isinstance(handle, NodeProgress) # walk continues, no exception propagates + tracker.for_node(_table_node(source), is_leaf=True) + assert source.declared == 1 # marked declared up front, so it is not retried per node + + +def test_leaf_handle_counts_open_and_advance(): + source = _FakeSource() + tracker = TopologyProgressTracker(source) + handle = tracker.for_node(_table_node(source), is_leaf=True) + handle.open(2) + handle.advance_leaf() + handle.advance_leaf() + snapshot = source.progress_tracking.registry.snapshot() + assert snapshot.child_type == "Table" + assert snapshot.processed == 2 + + +def test_container_handle_is_lazy_without_reconcilable_counter(): + source = _FakeSource() + tracker = TopologyProgressTracker(source) + handle = tracker.for_node(_database_node(source), is_leaf=False) + assert handle.wants_eager_count is False + handle.open(None) + assert source.progress_tracking.registry.snapshot().expected_by_type.get("Database") is None + + +def test_container_handle_reconciles_when_counter_is_reconcilable(): + source = _FakeSource() + source.progress_tracking.registry.seed_scope_total("DatabaseSchema", "salesdb", 1) + tracker = TopologyProgressTracker(source) + key = source._node_primary_stage(_database_node(source)).context + setattr(source.context.get(), key, "salesdb") + schema_node = get_topology_node("databaseSchema", source.topology) + handle = tracker.for_node(schema_node, is_leaf=False) + assert handle.wants_eager_count is True + handle.open(3) + counters = {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + assert counters["DatabaseSchema"] == (0, 3) + + +def test_enter_scope_closes_and_tracks_on_exit(): + source = _FakeSource() + source.progress_tracking.registry.set_total("Database", 7) + tracker = TopologyProgressTracker(source) + node = _database_node(source) + handle = tracker.for_node(node, is_leaf=False) + key = source._node_primary_stage(node).context + setattr(source.context.get(), key, "salesdb") + closed = [] + source.progress_tracking.registry.close = lambda path: closed.append(list(path)) + with handle.enter_scope(): + pass + assert closed == [["salesdb"]] + counters = {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + assert counters["Database"][0] == 1 + + +def test_enter_scope_prunes_without_counting_on_failure(): + source = _FakeSource() + source.progress_tracking.registry.set_total("Database", 7) + tracker = TopologyProgressTracker(source) + node = _database_node(source) + handle = tracker.for_node(node, is_leaf=False) + key = source._node_primary_stage(node).context + setattr(source.context.get(), key, "salesdb") + closed = [] + source.progress_tracking.registry.close = lambda path: closed.append(list(path)) + with pytest.raises(RuntimeError), handle.enter_scope(): + raise RuntimeError("boom") + assert closed == [["salesdb"]] + counters = {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + assert counters["Database"][0] == 0 + + +def test_enter_scope_is_noop_without_context_value(): + source = _FakeSource() + tracker = TopologyProgressTracker(source) + handle = tracker.for_node(_database_node(source), is_leaf=False) + with handle.enter_scope(): + pass + assert source.progress_tracking.registry.snapshot() is None # nothing opened, nothing closed + + +def test_current_path_resolves_ancestor_context(): + source = _FakeSource() + tracker = TopologyProgressTracker(source) + assert tracker.current_path() == [] + db_key = source._node_primary_stage(_database_node(source)).context + setattr(source.context.get(), db_key, "salesdb") + assert tracker.current_path("DatabaseSchema") == ["salesdb"] diff --git a/ingestion/tests/unit/sdk/test_glossary_relations.py b/ingestion/tests/unit/sdk/test_glossary_relations.py new file mode 100644 index 000000000000..70271ed56bf0 --- /dev/null +++ b/ingestion/tests/unit/sdk/test_glossary_relations.py @@ -0,0 +1,290 @@ +"""Unit tests for the glossary term relations + settings SDK facades.""" + +import json +from dataclasses import dataclass, field + +import pytest + +from metadata.ingestion.ometa.client import APIError +from metadata.sdk import GlossaryTerms, Settings + +FROM_ID = "11111111-1111-1111-1111-111111111111" +TO_ID = "22222222-2222-2222-2222-222222222222" +RELATION_SETTINGS_PATH = "/system/settings/glossaryTermRelationSettings" + + +@dataclass +class FakeRestClient: + get_response: dict[str, object] = field(default_factory=dict) + get_responses: list[dict[str, object]] = field(default_factory=list) + patch_response: dict[str, object] | None = None + patch_errors: list[Exception] = field(default_factory=list) + post_calls: list[tuple[str, dict[str, object]]] = field(default_factory=list) + delete_calls: list[str] = field(default_factory=list) + get_calls: list[str] = field(default_factory=list) + patch_calls: list[tuple[str, dict[str, object]]] = field(default_factory=list) + + def post(self, path: str, **kwargs: object) -> None: + self.post_calls.append((path, kwargs)) + + def delete(self, path: str) -> None: + self.delete_calls.append(path) + + def get(self, path: str) -> dict[str, object]: + self.get_calls.append(path) + if self.get_responses: + return self.get_responses.pop(0) + return self.get_response + + def patch(self, path: str, **kwargs: object) -> dict[str, object] | None: + self.patch_calls.append((path, kwargs)) + if self.patch_errors: + raise self.patch_errors.pop(0) + return self.patch_response + + +@dataclass +class FakeMetadataClient: + client: FakeRestClient + + @staticmethod + def get_suffix(_entity_type: object) -> str: + return "/glossaryTerms" + + +@pytest.fixture +def rest_client() -> FakeRestClient: + return FakeRestClient() + + +@pytest.fixture(autouse=True) +def wire_client(rest_client: FakeRestClient, monkeypatch: pytest.MonkeyPatch) -> None: + ometa = FakeMetadataClient(rest_client) + monkeypatch.setattr(GlossaryTerms, "_default_client", ometa) + monkeypatch.setattr(Settings, "_default_client", ometa) + + +def patch_payload(rest_client: FakeRestClient, call_index: int = 0) -> list[dict[str, object]]: + _, kwargs = rest_client.patch_calls[call_index] + patch_data = kwargs["data"] + assert isinstance(patch_data, str) + return json.loads(patch_data) + + +def test_add_relation_posts_typed_payload(rest_client: FakeRestClient): + GlossaryTerms.add_relation(FROM_ID, TO_ID, "prescribes") + + assert rest_client.post_calls == [ + ( + f"/glossaryTerms/{FROM_ID}/relations", + { + "json": { + "term": {"id": TO_ID, "type": "glossaryTerm"}, + "relationType": "prescribes", + } + }, + ) + ] + + +def test_remove_relation_targets_relation_type(rest_client: FakeRestClient): + GlossaryTerms.remove_relation(FROM_ID, TO_ID, "prescribes") + + assert rest_client.delete_calls == [f"/glossaryTerms/{FROM_ID}/relations/{TO_ID}?relationType=prescribes"] + + +def test_remove_relation_encodes_special_chars(rest_client: FakeRestClient): + GlossaryTerms.remove_relation(FROM_ID, TO_ID, "a&b") + + assert rest_client.delete_calls == [f"/glossaryTerms/{FROM_ID}/relations/{TO_ID}?relationType=a%26b"] + + +def test_relations_graph_builds_query(rest_client: FakeRestClient): + rest_client.get_response = {"nodes": [], "edges": []} + + result = GlossaryTerms.relations_graph(FROM_ID, depth=2, relation_types=["prescribes", "treats"]) + + assert rest_client.get_calls == [f"/glossaryTerms/{FROM_ID}/relationsGraph?depth=2&relationTypes=prescribes,treats"] + assert result == {"nodes": [], "edges": []} + + +def test_relation_type_usage(rest_client: FakeRestClient): + rest_client.get_response = {"prescribes": 3} + + usage = GlossaryTerms.relation_type_usage() + + assert rest_client.get_calls == ["/glossaryTerms/relationTypes/usage"] + assert usage == {"prescribes": 3} + + +def test_glossary_relation_settings_returns_only_relation_config( + rest_client: FakeRestClient, +): + relation_config = {"relationTypes": [{"name": "prescribes"}]} + rest_client.get_response = { + "configType": "glossaryTermRelationSettings", + "configValue": relation_config, + } + + result = Settings.glossary_relation_settings() + + assert rest_client.get_calls == [RELATION_SETTINGS_PATH] + assert result == relation_config + + +def test_define_relation_type_appends_when_absent(rest_client: FakeRestClient): + rest_client.get_response = {"configValue": {"relationTypes": []}} + + Settings.define_glossary_relation_type({"name": "prescribes", "displayName": "prescribes"}) + + assert len(rest_client.patch_calls) == 1 + path, _ = rest_client.patch_calls[0] + assert path == RELATION_SETTINGS_PATH + patch = patch_payload(rest_client) + assert patch[0] == {"op": "test", "path": "/relationTypes", "value": []} + assert patch[1]["op"] == "add" + assert patch[1]["path"] == "/relationTypes/-" + patch_value = patch[1]["value"] + assert isinstance(patch_value, dict) + assert patch_value["name"] == "prescribes" + + +def test_define_relation_type_is_idempotent(rest_client: FakeRestClient): + rest_client.get_response = {"configValue": {"relationTypes": [{"name": "prescribes"}]}} + + result = Settings.define_glossary_relation_type({"name": "prescribes"}) + + assert result is None + assert not rest_client.patch_calls + + +def test_define_relation_type_initializes_null_relation_types(rest_client: FakeRestClient): + rest_client.get_response = {"configValue": {"relationTypes": None}} + + Settings.define_glossary_relation_type({"name": "prescribes"}) + + assert patch_payload(rest_client) == [ + {"op": "test", "path": "/relationTypes", "value": None}, + { + "op": "replace", + "path": "/relationTypes", + "value": [{"name": "prescribes"}], + }, + ] + + +def test_define_relation_type_initializes_absent_relation_types(rest_client: FakeRestClient): + rest_client.get_response = {"configValue": {}} + + Settings.define_glossary_relation_type({"name": "prescribes"}) + + assert patch_payload(rest_client) == [ + {"op": "test", "path": "", "value": {}}, + { + "op": "add", + "path": "/relationTypes", + "value": [{"name": "prescribes"}], + }, + ] + + +def test_define_relation_type_rechecks_after_concurrent_registration(rest_client: FakeRestClient): + rest_client.get_responses = [ + {"configValue": {"relationTypes": []}}, + {"configValue": {"relationTypes": [{"name": "prescribes"}]}}, + ] + rest_client.patch_errors = [APIError({"code": 422, "message": "unprocessable settings patch"})] + + result = Settings.define_glossary_relation_type({"name": "prescribes"}) + + assert result is None + assert len(rest_client.get_calls) == 2 + assert len(rest_client.patch_calls) == 1 + + +@pytest.mark.parametrize("status_code", [400, 422]) +def test_define_relation_type_retries_absent_initialization_after_test_failure( + rest_client: FakeRestClient, + status_code: int, +): + rest_client.get_responses = [ + {"configValue": {}}, + {"configValue": {"relationTypes": [{"name": "treats"}]}}, + ] + rest_client.patch_errors = [ + APIError( + { + "code": status_code, + "message": "The JSON Patch operation 'test' failed for path ''", + } + ) + ] + rest_client.patch_response = {"configValue": {"relationTypes": []}} + + result = Settings.define_glossary_relation_type({"name": "prescribes"}) + + assert result == {"relationTypes": []} + assert len(rest_client.get_calls) == 2 + assert len(rest_client.patch_calls) == 2 + assert patch_payload(rest_client, 0)[0] == {"op": "test", "path": "", "value": {}} + assert patch_payload(rest_client, 1)[0] == { + "op": "test", + "path": "/relationTypes", + "value": [{"name": "treats"}], + } + + +def test_define_relation_type_retries_only_after_snapshot_changes(rest_client: FakeRestClient): + rest_client.get_responses = [ + {"configValue": {"relationTypes": []}}, + { + "configValue": { + "relationTypes": [ + {"name": "treats", "optionalField": None}, + ] + } + }, + ] + rest_client.patch_errors = [APIError({"code": 412, "message": "precondition failed"})] + rest_client.patch_response = {"configValue": {"relationTypes": []}} + + result = Settings.define_glossary_relation_type({"name": "prescribes"}) + + assert result == {"relationTypes": []} + assert len(rest_client.get_calls) == 2 + assert len(rest_client.patch_calls) == 2 + assert patch_payload(rest_client, 1)[0] == { + "op": "test", + "path": "/relationTypes", + "value": [{"name": "treats", "optionalField": None}], + } + + +@pytest.mark.parametrize("status_code", [400, 422]) +def test_define_relation_type_does_not_retry_unrelated_invalid_patch( + rest_client: FakeRestClient, + status_code: int, +): + rest_client.get_responses = [ + {"configValue": {"relationTypes": []}}, + {"configValue": {"relationTypes": [{"name": "treats"}]}}, + ] + rest_client.patch_errors = [ + APIError( + { + "code": status_code, + "message": "relation type test failed validation", + } + ) + ] + + with pytest.raises(APIError, match="failed validation"): + Settings.define_glossary_relation_type({"name": "prescribes"}) + + assert len(rest_client.get_calls) == 2 + assert len(rest_client.patch_calls) == 1 + + +def test_define_relation_type_requires_name(): + with pytest.raises(ValueError): + Settings.define_glossary_relation_type({"displayName": "no name"}) diff --git a/ingestion/tests/unit/sink/test_metadata_rest_lineage.py b/ingestion/tests/unit/sink/test_metadata_rest_lineage.py new file mode 100644 index 000000000000..fef561bfd514 --- /dev/null +++ b/ingestion/tests/unit/sink/test_metadata_rest_lineage.py @@ -0,0 +1,92 @@ +# Copyright 2026 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +write_lineage status-identifier tests. + +The sink writes lineage with return_lineage=False, so add_lineage answers with the +minimal ``{"entity": ...}`` payload rebuilt from the request instead of the server +graph. Either.right must stay non-None even for producers that build id-only edge +references (dbt, pipeline sources, external tables): ReturnStep.run only counts a +record in scanned status when right is not None, and write_override_lineage only +patches the lineage-processed flag under the same condition. +""" + +from unittest.mock import MagicMock + +from metadata.generated.schema.api.lineage.addLineage import AddLineageRequest +from metadata.generated.schema.type.entityLineage import EntitiesEdge, LineageDetails +from metadata.generated.schema.type.entityLineage import Source as LineageSource +from metadata.generated.schema.type.entityReference import EntityReference +from metadata.ingestion.sink.metadata_rest import MetadataRestSink, MetadataRestSinkConfig + +FROM_ID = "d311bdf2-c4a9-4be3-9937-3b26309759af" +TO_ID = "abea43f7-ccc2-4daf-9dfb-115549461244" +FROM_FQN = "svc.db.sch.source" + + +def make_sink(add_lineage_response): + metadata = MagicMock() + metadata.add_lineage.return_value = add_lineage_response + return MetadataRestSink(config=MetadataRestSinkConfig(), metadata=metadata) + + +def lineage_request(with_fqn): + from_entity = ( + EntityReference(id=FROM_ID, type="table", fullyQualifiedName=FROM_FQN) + if with_fqn + else EntityReference(id=FROM_ID, type="table") + ) + return AddLineageRequest( + edge=EntitiesEdge( + fromEntity=from_entity, + toEntity=EntityReference(id=TO_ID, type="table"), + lineageDetails=LineageDetails(source=LineageSource.QueryLineage), + ) + ) + + +def entity_summary(fqn): + """Mirror of the {"entity": ...} payload add_lineage builds via _entity_ref_summary + when return_lineage=False.""" + return {"entity": {"fullyQualifiedName": fqn, "id": FROM_ID, "type": "table"}} + + +class TestWriteLineageStatusIdentifier: + def test_returns_fqn_when_reference_carries_one(self): + sink = make_sink(entity_summary(FROM_FQN)) + + result = sink.write_lineage(lineage_request(with_fqn=True)) + + assert result.right == FROM_FQN + + def test_falls_back_to_type_id_label_for_id_only_references(self): + sink = make_sink(entity_summary(None)) + + result = sink.write_lineage(lineage_request(with_fqn=False)) + + assert result.right == f"table:{FROM_ID}" + + def test_skips_graph_fetch_via_return_lineage_flag(self): + sink = make_sink(entity_summary(FROM_FQN)) + request = lineage_request(with_fqn=True) + + sink.write_lineage(request) + + sink.metadata.add_lineage.assert_called_once_with(request, check_patch=True, return_lineage=False) + + def test_propagates_error_as_left(self): + sink = make_sink({"error": "boom"}) + + result = sink.write_lineage(lineage_request(with_fqn=True)) + + assert result.left is not None + assert result.left.error == "boom" + assert result.right is None diff --git a/ingestion/tests/unit/source/dashboard/grafana/test_connection.py b/ingestion/tests/unit/source/dashboard/grafana/test_connection.py index 828c0bdab924..e7b86944977d 100644 --- a/ingestion/tests/unit/source/dashboard/grafana/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/grafana/test_connection.py @@ -22,15 +22,6 @@ def test_grafana_connection_is_base_connection(): assert issubclass(GrafanaConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = GrafanaConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_test_connection_runs_steps(): conn = GrafanaConnection(MagicMock()) conn._client = MagicMock() @@ -38,3 +29,20 @@ def test_test_connection_runs_steps(): result = conn.test_connection(metadata=MagicMock()) assert result is mock_step.return_value + + +def _client_kwargs(verify_ssl_value): + service_connection = MagicMock() + service_connection.verifySSL = verify_ssl_value + conn = GrafanaConnection(service_connection) + with patch(f"{CONNECTION_MODULE}.GrafanaApiClient") as mock_client: + conn._get_client() + return mock_client.call_args.kwargs + + +def test_verify_ssl_honors_explicit_false(): + assert _client_kwargs(False)["verify_ssl"] is False + + +def test_verify_ssl_defaults_to_true_when_unset(): + assert _client_kwargs(None)["verify_ssl"] is True diff --git a/ingestion/tests/unit/source/dashboard/hex/test_connection.py b/ingestion/tests/unit/source/dashboard/hex/test_connection.py index 523b56409ba0..e276f3e361ac 100644 --- a/ingestion/tests/unit/source/dashboard/hex/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/hex/test_connection.py @@ -22,15 +22,6 @@ def test_hex_connection_is_base_connection(): assert issubclass(HexConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = HexConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_test_connection_runs_steps(): conn = HexConnection(MagicMock()) conn._client = MagicMock() diff --git a/ingestion/tests/unit/source/dashboard/looker/test_connection.py b/ingestion/tests/unit/source/dashboard/looker/test_connection.py index 7355e54d7a7e..a3dffd4f8514 100644 --- a/ingestion/tests/unit/source/dashboard/looker/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/looker/test_connection.py @@ -8,37 +8,421 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Unit tests for Looker connection handling.""" +"""Unit tests for Looker test-connection checks.""" +import socket from unittest.mock import MagicMock, patch +import pytest +from looker_sdk.error import SDKError + +from metadata.core.connections.lifetime import Borrowed +from metadata.core.connections.test_connection.check import CheckError, collect_checks +from metadata.core.connections.test_connection.checks.dashboard import DashboardStep from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.source.dashboard.looker.connection import LookerConnection +from metadata.ingestion.source.dashboard.looker.connection import ( + LOOKER_ERRORS, + LookerChecks, + LookerConnection, + LookerSettings, + UnsupportedApiVersionError, +) +from metadata.utils.constants import THREE_MIN CONNECTION_MODULE = "metadata.ingestion.source.dashboard.looker.connection" +LOGIN_404 = "https://cloud.google.com/looker/docs/r/err/4.0/404/post/api/4.0/login" +DASHBOARDS_404 = "https://cloud.google.com/looker/docs/r/err/4.0/404/get/api/4.0/dashboards" +DASHBOARDS_429 = "https://cloud.google.com/looker/docs/r/err/4.0/429/get/api/4.0/dashboards" +DASHBOARDS_400 = "https://cloud.google.com/looker/docs/r/err/4.0/400/get/api/4.0/dashboards" +DASHBOARDS_401 = "https://cloud.google.com/looker/docs/r/err/4.0/401/get/api/4.0/dashboards" +DASHBOARDS_403 = "https://cloud.google.com/looker/docs/r/err/4.0/403/get/api/4.0/dashboards" + + +def _sdk_error(message: str, documentation_url: str = "") -> SDKError: + """A Looker SDK error: it carries no status code, only a message and the + documentation URL that encodes the status of the call that failed.""" + return SDKError(message, documentation_url=documentation_url) + + +def _versions(*supported: str) -> MagicMock: + versions = MagicMock() + versions.supported_versions = [MagicMock(version=version) for version in supported] + + return versions + + +def _checks() -> tuple[LookerChecks, MagicMock]: + """A provider over a borrowed client - the one its connection owns.""" + client = MagicMock() + + return LookerChecks(looker=Borrowed.of(client)), client + def test_looker_connection_is_base_connection(): assert issubclass(LookerConnection, BaseConnection) -def test_get_client_initialises_the_sdk(): +def _config(host: str = "https://looker.example.com", client_id: str = "id", secret: str = "secret") -> MagicMock: config = MagicMock() - config.clientId = "client-id" - config.clientSecret.get_secret_value.return_value = "secret" - config.hostPort = "https://looker.example.com" + config.hostPort = host + config.clientId = client_id + config.clientSecret.get_secret_value.return_value = secret + + return config + + +def test_get_client_initialises_the_sdk(): with patch(f"{CONNECTION_MODULE}.looker_sdk") as mock_sdk: - conn = LookerConnection(config) + conn = LookerConnection(_config()) client = conn.client assert client is mock_sdk.init40.return_value mock_sdk.init40.assert_called_once() -def test_test_connection_runs_steps(): - conn = LookerConnection(MagicMock()) - conn._client = MagicMock() - with patch(f"{CONNECTION_MODULE}.test_connection_steps") as mock_step: - result = conn.test_connection(metadata=MagicMock()) +def test_the_sdk_is_configured_from_this_service_not_the_environment(monkeypatch): + # A long-lived worker populates the SDK's env vars once, so a second connection + # in the same process must not inherit the first one's host or credentials. + monkeypatch.setenv("LOOKERSDK_BASE_URL", "https://first.example.com") + monkeypatch.setenv("LOOKERSDK_CLIENT_ID", "first-id") + monkeypatch.setenv("LOOKERSDK_CLIENT_SECRET", "first-secret") + + settings = LookerSettings(_config(host="https://second.example.com", client_id="second-id", secret="second-secret")) + + assert settings.base_url == "https://second.example.com" + assert settings.read_config() == { + "base_url": "https://second.example.com", + "client_id": "second-id", + "client_secret": "second-secret", + } + + +def test_checks_run_against_the_client_the_connection_owns(): + # The provider borrows the client its connection owns, so every step shares the + # one the connection builds, caches, and closes. + with patch(f"{CONNECTION_MODULE}.looker_sdk") as mock_sdk: + conn = LookerConnection(MagicMock()) + provider = conn.checks() + provider.check_access() + + assert isinstance(provider, LookerChecks) + mock_sdk.init40.return_value.me.assert_called_once_with() + assert conn._client is mock_sdk.init40.return_value + + +def test_building_the_provider_does_not_build_the_client(): + # Building it while the provider is assembled would run before the gate. + with patch(f"{CONNECTION_MODULE}.looker_sdk") as mock_sdk: + conn = LookerConnection(MagicMock()) + conn.checks() + + mock_sdk.init40.assert_not_called() + + +def test_the_client_is_built_once_and_shared_across_checks(): + with patch(f"{CONNECTION_MODULE}.looker_sdk") as mock_sdk: + mock_sdk.init40.return_value.versions.return_value = _versions("4.0") + conn = LookerConnection(MagicMock()) + provider = conn.checks() + provider.check_access() + provider.validate_version() + + mock_sdk.init40.assert_called_once() + + +def test_collect_checks_maps_every_step(): + provider, _ = _checks() + collected = collect_checks(provider) + + assert set(collected) == { + DashboardStep.CheckAccess, + DashboardStep.ValidateVersion, + DashboardStep.ListDashboards, + DashboardStep.ListLookMLModels, + } + + +def test_check_access_reads_the_authenticated_user(): + provider, client = _checks() + + evidence = provider.check_access() + + client.me.assert_called_once_with() + assert evidence.summary == "authenticated" + assert evidence.command == "log in and read the authenticated user" + + +def test_check_access_wraps_a_rejected_login_as_check_error(): + # The SDK logs in on its first call, so bad credentials fail the gate rather + # than escaping while the provider is built. + provider, client = _checks() + client.me.side_effect = _sdk_error("Not found", documentation_url=LOGIN_404) + + with pytest.raises(CheckError) as exc_info: + provider.check_access() + + assert isinstance(exc_info.value.cause, SDKError) + assert exc_info.value.evidence.command == "log in and read the authenticated user" + + +def test_validate_version_passes_when_the_sdk_version_is_supported(): + provider, client = _checks() + client.versions.return_value = _versions("3.1", "4.0") + + evidence = provider.validate_version() + + assert evidence.summary == "API 4.0 is supported" + assert evidence.command == "list the API versions the instance supports" + + +def test_validate_version_fails_when_the_sdk_version_is_missing(): + provider, client = _checks() + client.versions.return_value = _versions("3.1") + + with pytest.raises(CheckError) as exc_info: + provider.validate_version() + + assert isinstance(exc_info.value.cause, UnsupportedApiVersionError) + assert "3.1" in str(exc_info.value.cause) + assert exc_info.value.evidence.command == "list the API versions the instance supports" + + +def test_list_dashboards_counts_what_it_enumerated(): + provider, client = _checks() + client.all_dashboards.return_value = [MagicMock(), MagicMock()] + + evidence = provider.list_dashboards() + + client.all_dashboards.assert_called_once_with(fields="id,title") + assert evidence.summary == "2 dashboards enumerated" + assert evidence.caveat is None + + +def test_list_dashboards_warns_when_none_are_visible(): + provider, client = _checks() + client.all_dashboards.return_value = [] + + evidence = provider.list_dashboards() + + assert evidence.summary == "0 dashboards enumerated" + assert evidence.caveat is not None + assert evidence.caveat.title == "No dashboards visible" + + +def test_list_lookml_models_warns_when_none_are_visible(): + # Not mandatory: unreadable models cost lineage, not the connection. + provider, client = _checks() + client.all_lookml_models.return_value = [] + + evidence = provider.list_lookml_models() + + client.all_lookml_models.assert_called_once_with(limit=1) + assert evidence.caveat is not None + assert evidence.caveat.title == "No LookML models visible" + + +def test_list_lookml_models_wraps_a_failure_as_check_error(): + provider, client = _checks() + client.all_lookml_models.side_effect = _sdk_error("Not found", documentation_url=DASHBOARDS_404) + + with pytest.raises(CheckError) as exc_info: + provider.list_lookml_models() + + assert exc_info.value.evidence.command == "list LookML models" + + +def test_rejected_credentials_are_diagnosed_as_an_auth_failure(): + # A rejected login is a 404 on /login: the endpoint, not the status, tells it + # apart from a wrong host. + diagnosis = LOOKER_ERRORS.classify(_sdk_error("Not found", documentation_url=LOGIN_404)) + + assert diagnosis is not None + assert diagnosis.title == "Authentication failed" + + +def test_rejected_credentials_are_diagnosed_from_the_raw_login_body(): + # A failed login raises the raw body as the message and leaves + # documentation_url empty; the URL is still in the text the rules read. + diagnosis = LOOKER_ERRORS.classify(_sdk_error('{"message": "Not found", "documentation_url": "' + LOGIN_404 + '"}')) + + assert diagnosis is not None + assert diagnosis.title == "Authentication failed" + + +def test_rejected_credentials_are_diagnosed_when_str_omits_the_doc_url(): + # looker-sdk only renders documentation_url in __str__ from 24.x on; on the + # oldest supported version (22.20.0) it lives on the attribute alone. + class OldSdkError(Exception): + documentation_url = LOGIN_404 + + diagnosis = LOOKER_ERRORS.classify(OldSdkError("Not found")) + + assert diagnosis is not None + assert diagnosis.title == "Authentication failed" + + +def test_a_network_error_carrying_an_incidental_404_stays_a_network_error(): + # "404" inside a port must not read as an HTTP 404 from a non-Looker host. + error = _sdk_error( + "HTTPConnectionPool(host='looker.example.com', port=8404): Max retries exceeded with url: " + "/api/4.0/login (Caused by NewConnectionError('Connection refused'))" + ) + + diagnosis = LOOKER_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == "Connection refused" + + +def test_a_404_away_from_login_is_diagnosed_as_a_missing_resource(): + diagnosis = LOOKER_ERRORS.classify(_sdk_error("Not found", documentation_url=DASHBOARDS_404)) + + assert diagnosis is not None + assert diagnosis.title == "Resource not found" + + +def test_a_429_is_diagnosed_as_rate_limiting(): + diagnosis = LOOKER_ERRORS.classify(_sdk_error("Too many requests", documentation_url=DASHBOARDS_429)) + + assert diagnosis is not None + assert diagnosis.title == "Rate limited by Looker" + + +def test_an_undocumented_status_keeps_its_raw_error(): + # The API spec has no 401 anywhere and no 403 on the endpoints these checks + # call, so neither gets an invented diagnosis. + assert LOOKER_ERRORS.classify(_sdk_error("nope", documentation_url=DASHBOARDS_401)) is None + assert LOOKER_ERRORS.classify(_sdk_error("nope", documentation_url=DASHBOARDS_403)) is None + + +def test_lookers_generic_404_page_is_diagnosed_as_an_auth_failure(): + # What a live Looker returns for a rejected sign-in - and for a host that is not + # a live instance, so the two cannot be told apart. + diagnosis = LOOKER_ERRORS.classify( + _sdk_error( + "Looker Not Found (404)

Looker is unavailable.

" + ) + ) + + assert diagnosis is not None + assert diagnosis.title == "Authentication failed" + + +def test_a_host_that_is_not_looker_is_diagnosed(): + # A non-Looker server answers with its own 404 body, carrying no Looker error + # document. + diagnosis = LOOKER_ERRORS.classify(_sdk_error('{"code":404,"message":"HTTP 404 Not Found"}')) + + assert diagnosis is not None + assert diagnosis.title == "The host is not serving the Looker API" + + +def test_a_looker_error_with_an_undiagnosed_status_keeps_its_raw_error(): + # A Looker 400 whose message reads "parameter not found" must not be blamed on + # Host Port: it carries an error document, so it is a Looker answer. + diagnosis = LOOKER_ERRORS.classify(_sdk_error("parameter not found", documentation_url=DASHBOARDS_400)) + + assert diagnosis is None + + +def test_a_looker_error_whose_message_mentions_a_transport_word_keeps_its_raw_error(): + # A structured Looker error (carries a doc) whose text happens to contain a + # transport token must not be read as a network failure. + diagnosis = LOOKER_ERRORS.classify(_sdk_error("Query exceeded the timeout", documentation_url=DASHBOARDS_400)) + + assert diagnosis is None + + +def test_the_step_timeout_keeps_the_legacy_three_minute_budget(): + # Listing dashboards and LookML models can be slow on large instances. + assert LookerConnection.step_timeout_seconds == THREE_MIN + + +def test_a_looker_404_outranks_the_not_a_looker_host_fallback(): + # Ordering guard: a genuine Looker 404 carries a documentation URL and must keep + # the sharper diagnosis. + diagnosis = LOOKER_ERRORS.classify(_sdk_error("Not found", documentation_url=DASHBOARDS_404)) + + assert diagnosis is not None + assert diagnosis.title == "Resource not found" + + +def test_missing_credentials_are_diagnosed(): + diagnosis = LOOKER_ERRORS.classify(_sdk_error("Required auth credentials not found.")) + + assert diagnosis is not None + assert diagnosis.title == "Missing credentials" + + +def test_an_unsupported_api_version_is_diagnosed(): + diagnosis = LOOKER_ERRORS.classify(UnsupportedApiVersionError("API 4.0 is not listed")) + + assert diagnosis is not None + assert diagnosis.title == "API 4.0 is not supported by this instance" + + +def test_a_dns_failure_is_diagnosed_from_the_flattened_message(): + # The SDK's transport catches every IOError and re-raises it as an SDKError + # whose message is the stringified original, so the exception type is gone and + # only the text can be matched. + error = _sdk_error( + "HTTPSConnectionPool(host='nope.cloud.looker.com', port=443): Max retries exceeded with " + 'url: /api/4.0/login (Caused by NameResolutionError("Failed to resolve ' + "'nope.cloud.looker.com' ([Errno 8] nodename nor servname provided, or not known)\"))" + ) + + diagnosis = LOOKER_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == "Host could not be resolved" + + +def test_a_refused_connection_is_diagnosed_from_the_flattened_message(): + error = _sdk_error( + "HTTPSConnectionPool(host='looker.example.com', port=19999): Max retries exceeded with " + "url: /api/4.0/login (Caused by NewConnectionError('Connection refused'))" + ) + + diagnosis = LOOKER_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == "Connection refused" + + +def test_a_tls_failure_is_diagnosed_from_the_flattened_message(): + error = _sdk_error( + "HTTPSConnectionPool(host='looker.example.com', port=443): Max retries exceeded with url: " + "/api/4.0/login (Caused by SSLError(SSLCertVerificationError(1, 'certificate verify " + "failed: self signed certificate')))" + ) + + diagnosis = LOOKER_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == "TLS verification failed" + + +def test_an_unreachable_host_is_diagnosed_from_the_flattened_message(): + error = _sdk_error( + "HTTPSConnectionPool(host='looker.example.com', port=443): Max retries exceeded with url: " + "/api/4.0/login (Caused by NewConnectionError('Network is unreachable'))" + ) + + diagnosis = LOOKER_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == "Cannot reach the host" + + +def test_the_shared_network_pack_still_classifies_a_raw_socket_error(): + # Anything raised outside the SDK's transport keeps its type, so the folded + # NETWORK_ERRORS rules remain the fallback. + diagnosis = LOOKER_ERRORS.classify(socket.gaierror("nodename nor servname provided")) + + assert diagnosis is not None + assert diagnosis.title == "Host could not be resolved" + - assert result is mock_step.return_value +def test_an_unknown_error_is_not_classified(): + assert LOOKER_ERRORS.classify(_sdk_error("something entirely new")) is None diff --git a/ingestion/tests/unit/source/dashboard/metabase/test_connection.py b/ingestion/tests/unit/source/dashboard/metabase/test_connection.py index b784de0e7b4a..65aa23153c0a 100644 --- a/ingestion/tests/unit/source/dashboard/metabase/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/metabase/test_connection.py @@ -22,15 +22,6 @@ def test_metabase_connection_is_base_connection(): assert issubclass(MetabaseConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = MetabaseConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_test_connection_runs_steps(): conn = MetabaseConnection(MagicMock()) conn._client = MagicMock() diff --git a/ingestion/tests/unit/source/dashboard/microstrategy/test_connection.py b/ingestion/tests/unit/source/dashboard/microstrategy/test_connection.py index 1eedccef4333..898b0d29858a 100644 --- a/ingestion/tests/unit/source/dashboard/microstrategy/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/microstrategy/test_connection.py @@ -22,15 +22,6 @@ def test_microstrategy_connection_is_base_connection(): assert issubclass(MicroStrategyConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = MicroStrategyConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_test_connection_runs_steps(): conn = MicroStrategyConnection(MagicMock()) conn._client = MagicMock() diff --git a/ingestion/tests/unit/source/dashboard/powerbi/test_connection.py b/ingestion/tests/unit/source/dashboard/powerbi/test_connection.py index 5192fa14631d..65891df5f85e 100644 --- a/ingestion/tests/unit/source/dashboard/powerbi/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/powerbi/test_connection.py @@ -16,11 +16,13 @@ import pytest from requests.exceptions import HTTPError +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection.check import CheckError, collect_checks from metadata.core.connections.test_connection.checks.dashboard import DashboardStep from metadata.ingestion.api.steps import InvalidSourceException from metadata.ingestion.connections.connection import BaseConnection from metadata.ingestion.ometa.client import APIError +from metadata.ingestion.source.dashboard.powerbi.client import PowerBiApiClient from metadata.ingestion.source.dashboard.powerbi.connection import ( POWERBI_ERRORS, PowerBIChecks, @@ -44,26 +46,17 @@ def _raw_http_error(status_code: int) -> HTTPError: return HTTPError("server said no", response=response) -def _checks(api_client_cls) -> tuple[PowerBIChecks, MagicMock]: - """A provider whose lazily-built REST client is the returned mock.""" +def _checks() -> tuple[PowerBIChecks, MagicMock]: + """A provider over a borrowed client - the one its connection owns.""" api_client = MagicMock() - api_client_cls.return_value = api_client - return PowerBIChecks(connection=MagicMock()), api_client + powerbi_client = MagicMock(api_client=api_client) + return PowerBIChecks(powerbi=Borrowed.of(powerbi_client)), api_client def test_powerbi_connection_is_base_connection(): assert issubclass(PowerBIConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = PowerBIConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_checks_does_not_touch_the_network(): with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: conn = PowerBIConnection(MagicMock()) @@ -73,20 +66,33 @@ def test_checks_does_not_touch_the_network(): mock_client.assert_not_called() -def test_collect_checks_maps_every_step(): +def test_checks_reuse_the_connections_client_and_never_authenticate_twice(): + # The provider borrows the client its connection owns, so the checks and the + # ingestion share one authenticated session instead of acquiring a second token. with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, _ = _checks(mock_client) + # PowerBiClient validates its api_client field, so the fake must carry the spec. + mock_client.return_value = MagicMock(spec=PowerBiApiClient) + conn = PowerBIConnection(MagicMock(pbitFilesSource=None)) + provider = conn.checks() + + provider.check_access() + provider.get_dashboards() + + assert mock_client.call_count == 1 + + +def test_collect_checks_maps_every_step(): + provider, _ = _checks() collected = collect_checks(provider) assert set(collected) == {DashboardStep.CheckAccess, DashboardStep.GetDashboards} def test_check_access_authenticates(): - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, client = _checks(mock_client) - client.get_auth_token.return_value = ("token", "3600") + provider, client = _checks() + client.get_auth_token.return_value = ("token", "3600") - evidence = provider.check_access() + evidence = provider.check_access() client.get_auth_token.assert_called_once_with() assert evidence.summary == "authenticated" @@ -94,55 +100,50 @@ def test_check_access_authenticates(): def test_check_access_wraps_failure_as_check_error(): - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, client = _checks(mock_client) - client.get_auth_token.side_effect = InvalidSourceException("no token") + provider, client = _checks() + client.get_auth_token.side_effect = InvalidSourceException("no token") - with pytest.raises(CheckError) as exc_info: - provider.check_access() + with pytest.raises(CheckError) as exc_info: + provider.check_access() assert isinstance(exc_info.value.cause, InvalidSourceException) assert exc_info.value.evidence.command == "acquire OAuth token" def test_get_dashboards_counts_results(): - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, client = _checks(mock_client) - client.fetch_dashboards.return_value = [object(), object(), object()] + provider, client = _checks() + client.fetch_dashboards.return_value = [object(), object(), object()] - evidence = provider.get_dashboards() + evidence = provider.get_dashboards() assert evidence.summary == "3 dashboards enumerated" assert evidence.command == "fetch dashboards" def test_get_dashboards_caps_the_count(): - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, client = _checks(mock_client) - client.fetch_dashboards.return_value = [object()] * 250 + provider, client = _checks() + client.fetch_dashboards.return_value = [object()] * 250 - evidence = provider.get_dashboards() + evidence = provider.get_dashboards() assert evidence.summary == "100+ dashboards enumerated" assert evidence.caveat is None def test_get_dashboards_at_cap_shows_plus(): - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, client = _checks(mock_client) - client.fetch_dashboards.return_value = [object()] * 100 + provider, client = _checks() + client.fetch_dashboards.return_value = [object()] * 100 - evidence = provider.get_dashboards() + evidence = provider.get_dashboards() assert evidence.summary == "100+ dashboards enumerated" def test_get_dashboards_empty_passes_with_caveat(): - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, client = _checks(mock_client) - client.fetch_dashboards.return_value = None + provider, client = _checks() + client.fetch_dashboards.return_value = None - evidence = provider.get_dashboards() + evidence = provider.get_dashboards() assert evidence.summary == "0 dashboards enumerated" assert evidence.caveat is not None @@ -150,25 +151,23 @@ def test_get_dashboards_empty_passes_with_caveat(): def test_get_dashboards_wraps_failure_as_check_error(): - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider, client = _checks(mock_client) - client.fetch_dashboards.side_effect = _api_error(403) + provider, client = _checks() + client.fetch_dashboards.side_effect = _api_error(403) - with pytest.raises(CheckError) as exc_info: - provider.get_dashboards() + with pytest.raises(CheckError) as exc_info: + provider.get_dashboards() assert exc_info.value.evidence.command == "fetch dashboards" def test_get_dashboards_wraps_client_build_failure(): - # Client construction (MSAL discovery) happens inside fetch_list's try, so a - # build failure still reports the step's command rather than escaping raw. - with patch(f"{CONNECTION_MODULE}.PowerBiApiClient") as mock_client: - provider = PowerBIChecks(connection=MagicMock()) - mock_client.side_effect = ValueError("authority discovery failed") + # Reading the borrow is what builds the client (MSAL discovery), and that read + # happens inside fetch_list's try, so a build failure still reports the step's + # command rather than escaping raw. + provider = PowerBIChecks(powerbi=Borrowed(MagicMock(side_effect=ValueError("authority discovery failed")))) - with pytest.raises(CheckError) as exc_info: - provider.get_dashboards() + with pytest.raises(CheckError) as exc_info: + provider.get_dashboards() assert exc_info.value.evidence.command == "fetch dashboards" assert isinstance(exc_info.value.cause, ValueError) diff --git a/ingestion/tests/unit/source/dashboard/sigma/test_connection.py b/ingestion/tests/unit/source/dashboard/sigma/test_connection.py index 74e658df30df..27e97b799c0b 100644 --- a/ingestion/tests/unit/source/dashboard/sigma/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/sigma/test_connection.py @@ -22,15 +22,6 @@ def test_sigma_connection_is_base_connection(): assert issubclass(SigmaConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = SigmaConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_test_connection_runs_steps(): conn = SigmaConnection(MagicMock()) conn._client = MagicMock() diff --git a/ingestion/tests/unit/source/dashboard/ssrs/test_connection.py b/ingestion/tests/unit/source/dashboard/ssrs/test_connection.py index 7a7650a94866..41c1a52b1b0c 100644 --- a/ingestion/tests/unit/source/dashboard/ssrs/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/ssrs/test_connection.py @@ -22,15 +22,6 @@ def test_ssrs_connection_is_base_connection(): assert issubclass(SsrsConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = SsrsConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_test_connection_runs_steps(): conn = SsrsConnection(MagicMock()) conn._client = MagicMock() diff --git a/ingestion/tests/unit/source/dashboard/superset/test_connection.py b/ingestion/tests/unit/source/dashboard/superset/test_connection.py index b56f0ee7435b..e047c0ccbd19 100644 --- a/ingestion/tests/unit/source/dashboard/superset/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/superset/test_connection.py @@ -22,15 +22,6 @@ def test_superset_connection_is_base_connection(): assert issubclass(SupersetConnection, BaseConnection) -def test_get_client_delegates_to_get_connection(): - with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: - conn = SupersetConnection(MagicMock()) - client = conn.client - - assert client is mock_get.return_value - mock_get.assert_called_once_with(conn.service_connection) - - def test_test_connection_runs_steps(): conn = SupersetConnection(MagicMock()) conn._client = MagicMock() diff --git a/ingestion/tests/unit/source/dashboard/tableau/test_connection.py b/ingestion/tests/unit/source/dashboard/tableau/test_connection.py index 2196254f2fe0..a85c0ecdc5a7 100644 --- a/ingestion/tests/unit/source/dashboard/tableau/test_connection.py +++ b/ingestion/tests/unit/source/dashboard/tableau/test_connection.py @@ -1,23 +1,48 @@ -# Copyright 2025 Collate -# Licensed under the Collate Community License, Version 1.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Unit tests for Tableau connection handling.""" +"""Unit tests for Tableau test-connection checks.""" +import socket from unittest.mock import MagicMock, patch +import pytest +from requests.exceptions import HTTPError, SSLError +from tableauserverclient.server.endpoint.exceptions import ServerResponseError + +from metadata.core.connections.lifetime import Borrowed +from metadata.core.connections.test_connection.check import CheckError, collect_checks +from metadata.core.connections.test_connection.checks.dashboard import DashboardStep from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.source.dashboard.tableau.connection import TableauConnection +from metadata.ingestion.source.dashboard.tableau.client import ( + TableauChartsException, + TableauDataModelsException, + TableauOwnersNotFound, + TableauWorkBookException, +) +from metadata.ingestion.source.dashboard.tableau.connection import ( + TABLEAU_ERRORS, + TableauChecks, + TableauConnection, +) CONNECTION_MODULE = "metadata.ingestion.source.dashboard.tableau.connection" +def _server_error(code: str) -> ServerResponseError: + """A Tableau REST error: its code prefixes the HTTP status, e.g. 401002.""" + return ServerResponseError(code, "summary", "detail") + + +def _raw_http_error(status_code: int) -> HTTPError: + response = MagicMock() + response.status_code = status_code + return HTTPError("server said no", response=response) + + +def _checks() -> tuple[TableauChecks, MagicMock]: + """A provider over a borrowed client - the one its connection owns.""" + client = MagicMock() + return TableauChecks(server=Borrowed.of(client)), client + + def test_tableau_connection_is_base_connection(): assert issubclass(TableauConnection, BaseConnection) @@ -31,10 +56,227 @@ def test_get_client_delegates_to_get_connection(): mock_get.assert_called_once_with(conn.service_connection) -def test_test_connection_runs_steps(): - conn = TableauConnection(MagicMock()) - conn._client = MagicMock() - with patch(f"{CONNECTION_MODULE}.test_connection") as mock_step: - result = conn.test_connection(metadata=MagicMock()) +def test_close_signs_out_of_the_server_session(): + with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: + conn = TableauConnection(MagicMock()) + client = conn.client + conn.close() + + # sign_out() releases the server session and clears the SSL temp files. + client.sign_out.assert_called_once_with() + assert mock_get.call_count == 1 + + +def test_checks_does_not_touch_the_network(): + with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: + conn = TableauConnection(MagicMock()) + provider = conn.checks() + + assert isinstance(provider, TableauChecks) + mock_get.assert_not_called() + + +def test_checks_reuse_the_connections_client_and_never_sign_in_twice(): + # A Personal Access Token allows one active session: if the checks signed in + # again, they would invalidate the session the ingestion is about to use + # (issue #29804). The provider must read the client its connection owns. + with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: + conn = TableauConnection(MagicMock()) + owned = conn.client + provider = conn.checks() + + provider.server_info() + provider.get_workbooks() + + assert mock_get.call_count == 1 + owned.server_info.assert_called_once_with() + + +def test_collect_checks_maps_every_step(): + provider, _ = _checks() + collected = collect_checks(provider) + + assert set(collected) == { + DashboardStep.ServerInfo, + DashboardStep.ValidateApiVersion, + DashboardStep.ValidateSiteUrl, + DashboardStep.GetWorkbooks, + DashboardStep.GetViews, + DashboardStep.GetOwners, + DashboardStep.GetDataModels, + } + + +def test_server_info_signs_in(): + provider, client = _checks() + + evidence = provider.server_info() + + client.server_info.assert_called_once_with() + assert evidence.summary == "authenticated" + assert evidence.command == "sign in and read server info" + + +def test_server_info_wraps_sign_in_failure_as_check_error(): + # The client is built on first read, which happens inside the gate check, so + # bad credentials surface as a classified ServerInfo failure instead of + # escaping while the provider is being assembled. + provider = TableauChecks(server=Borrowed(MagicMock(side_effect=_server_error("401001")))) + + with pytest.raises(CheckError) as exc_info: + provider.server_info() + + assert isinstance(exc_info.value.cause, ServerResponseError) + assert exc_info.value.evidence.command == "sign in and read server info" + + +def test_validate_api_version_reports_the_version(): + provider, client = _checks() + client.server_api_version.return_value = "3.19" + + evidence = provider.validate_api_version() + + assert evidence.summary == "REST API version 3.19" + assert evidence.command == "read the server REST API version" + + +def test_validate_site_url_passes(): + provider, client = _checks() + + evidence = provider.validate_site_url() + + client.test_site_url.assert_called_once_with() + assert evidence.summary == "site name is well formed" + + +def test_validate_site_url_wraps_failure_as_check_error(): + provider, client = _checks() + client.test_site_url.side_effect = ValueError('The site url "https://x" is in incorrect format.') + + with pytest.raises(CheckError) as exc_info: + provider.validate_site_url() + + assert exc_info.value.evidence.command == "validate the configured site name" + + +def test_get_workbooks_passes(): + provider, client = _checks() + + evidence = provider.get_workbooks() + + client.test_get_workbooks.assert_called_once_with() + assert evidence.summary == "workbooks are readable" + + +def test_get_workbooks_wraps_failure_as_check_error(): + provider, client = _checks() + client.test_get_workbooks.side_effect = TableauWorkBookException("no workbooks") + + with pytest.raises(CheckError) as exc_info: + provider.get_workbooks() + + assert exc_info.value.evidence.command == "fetch workbooks" + assert isinstance(exc_info.value.cause, TableauWorkBookException) + + +def test_get_views_passes(): + provider, client = _checks() + + evidence = provider.get_views() + + client.test_get_workbook_views.assert_called_once_with() + assert evidence.summary == "workbook views are readable" + + +def test_get_owners_passes(): + provider, client = _checks() + + evidence = provider.get_owners() + + client.test_get_owners.assert_called_once_with() + assert evidence.summary == "workbook owners are resolvable" + + +def test_get_data_models_passes(): + provider, client = _checks() + + evidence = provider.get_data_models() + + client.test_get_datamodels.assert_called_once_with() + assert evidence.summary == "data sources are readable" + assert evidence.command == "query the Metadata API for the data sources of a workbook" + + +def test_get_data_models_wraps_failure_as_check_error(): + provider, client = _checks() + client.test_get_datamodels.side_effect = TableauDataModelsException("metadata api off") + + with pytest.raises(CheckError) as exc_info: + provider.get_data_models() + + assert isinstance(exc_info.value.cause, TableauDataModelsException) + + +@pytest.mark.parametrize( + ("error", "title"), + [ + (_server_error("401001"), "Authentication failed"), + (_server_error("401002"), "Authentication failed"), + (_server_error("403004"), "Insufficient permissions"), + (_server_error("404000"), "Resource not found"), + (_raw_http_error(401), "Authentication failed"), + (_raw_http_error(403), "Insufficient permissions"), + (_raw_http_error(404), "Resource not found"), + (SSLError("certificate verify failed"), "TLS verification failed"), + (TableauWorkBookException("nope"), "No workbooks visible"), + (TableauChartsException("nope"), "No views visible"), + (TableauOwnersNotFound("nope"), "Owner information not available"), + (TableauDataModelsException("nope"), "Data sources could not be read"), + (ValueError('The site url "https://x" is in incorrect format.'), "Invalid Site Name"), + (socket.gaierror("name resolution failed"), "Host could not be resolved"), + ], +) +def test_error_pack_classifies(error, title): + diagnosis = TABLEAU_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == title + + +def test_error_pack_classifies_a_wrapped_cause(): + # get_connection re-raises a sign-in failure as SourceConnectionException; the + # Tableau error survives in the cause chain and still classifies. + wrapper = RuntimeError("Unknown error connecting") + wrapper.__cause__ = _server_error("401001") + + diagnosis = TABLEAU_ERRORS.classify(wrapper) + + assert diagnosis is not None + assert diagnosis.title == "Authentication failed" + + +def test_error_pack_ignores_unrelated_code_attribute(): + # A non-Tableau exception exposing an int .code must not be read as an HTTP + # status just because it happens to equal 401/403/404. + class _AppError(Exception): + code = 403 + + assert TABLEAU_ERRORS.classify(_AppError("application code, not HTTP")) is None + + +def test_error_pack_ignores_unknown_error(): + assert TABLEAU_ERRORS.classify(ValueError("something else")) is None + + +def test_a_failing_sign_out_does_not_break_close(): + # close() unwinds teardowns without catching, so a sign-out that fails must not + # replace the error being unwound (or fail an otherwise clean close). + with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: + conn = TableauConnection(MagicMock()) + client = conn.client + client.sign_out.side_effect = ServerResponseError("401002", "summary", "detail") + + conn.close() - assert result is mock_step.return_value + client.sign_out.assert_called_once_with() + assert mock_get.call_count == 1 diff --git a/ingestion/tests/unit/source/database/athena/test_connection.py b/ingestion/tests/unit/source/database/athena/test_connection.py index 319ff4f84dd2..4fcdff0b8992 100644 --- a/ingestion/tests/unit/source/database/athena/test_connection.py +++ b/ingestion/tests/unit/source/database/athena/test_connection.py @@ -16,8 +16,10 @@ import pytest from botocore.exceptions import ClientError +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection.check import collect_checks from metadata.core.connections.test_connection.checks.database import DatabaseStep +from metadata.core.connections.test_connection.records import Evidence from metadata.generated.schema.entity.services.connections.database.athenaConnection import ( AthenaConnection as AthenaConnectionConfig, ) @@ -89,7 +91,7 @@ def test_checks_returns_provider_over_the_client(): conn._client = MagicMock() provider = conn.checks() assert isinstance(provider, AthenaChecks) - assert provider.client is conn._client + assert provider._db.client is conn._client def test_checks_wires_filter_pattern_and_catalog_from_service_connection(): @@ -102,7 +104,7 @@ def test_checks_wires_filter_pattern_and_catalog_from_service_connection(): def test_every_athena_step_resolves_to_a_check(): - provider = AthenaChecks(client_factory=MagicMock) + provider = AthenaChecks(db=Borrowed(MagicMock)) resolved = collect_checks(provider) assert set(resolved) == { DatabaseStep.CheckAccess, @@ -112,24 +114,50 @@ def test_every_athena_step_resolves_to_a_check(): } +def test_every_check_reports_the_command_it_ran(): + # pyathena reflects via the AWS API, so the shared SQL capture yields nothing; + # each reflection step names its API operation instead. + provider = _checks() + inspector = MagicMock() + inspector.get_schema_names.return_value = ["ecommerce"] + inspector.get_table_names.return_value = ["orders"] + inspector.get_view_names.return_value = ["v_orders"] + + with ( + patch(f"{CONNECTION_MODULE}.list_schemas", return_value=Evidence(summary="1 schema enumerated")), + patch(f"{CONNECTION_MODULE}.inspect", return_value=inspector), + ): + assert provider.get_schemas().command == "athena:ListDatabases (CatalogName=AwsDataCatalog)" + assert provider.get_tables().command == "athena:ListTableMetadata (CatalogName=AwsDataCatalog)" + assert provider.get_views().command == "athena:ListTableMetadata (CatalogName=AwsDataCatalog)" + + +def test_command_names_a_configured_catalog(): + provider = _checks(catalogId="my_catalog") + + with patch(f"{CONNECTION_MODULE}.list_schemas", return_value=Evidence(summary="ok")): + assert provider.get_schemas().command == "athena:ListDatabases (CatalogName=my_catalog)" + + def test_error_pack_classifies_access_denied_as_not_authorized(): diagnosis = ATHENA_ERRORS.classify(_client_error("AccessDeniedException")) assert diagnosis is not None assert diagnosis.title == "Not authorized" -def test_error_pack_classifies_unrecognized_client_as_auth_failure(): +def test_error_pack_classifies_unrecognized_client_as_unknown_access_key(): + # Athena is json-protocol: an unknown access key ID arrives as this. diagnosis = ATHENA_ERRORS.classify(_client_error("UnrecognizedClientException")) assert diagnosis is not None - assert diagnosis.title == "Authentication failed" + assert diagnosis.title == "AWS access key not recognized" -def test_error_pack_classifies_auth_failure_through_a_wrapping_cause(): +def test_error_pack_classifies_a_signature_error_through_a_wrapping_cause(): wrapped = RuntimeError("query failed") wrapped.__cause__ = _client_error("InvalidSignatureException") diagnosis = ATHENA_ERRORS.classify(wrapped) assert diagnosis is not None - assert diagnosis.title == "Authentication failed" + assert diagnosis.title == "AWS secret key does not match" def test_error_pack_classifies_missing_workgroup(): @@ -153,6 +181,13 @@ def test_error_pack_classifies_unwritable_result_location(): assert diagnosis.title == "Cannot write query results" +def test_error_pack_classifies_an_unusable_result_bucket(): + error = RuntimeError("An error occurred (InvalidRequestException): Unable to verify/create output bucket my-bucket") + diagnosis = ATHENA_ERRORS.classify(error) + assert diagnosis is not None + assert diagnosis.title == "Query result bucket not usable" + + def test_error_pack_classifies_unreachable_endpoint(): error = RuntimeError('Could not connect to the endpoint URL: "https://athena.bad.amazonaws.com/"') diagnosis = ATHENA_ERRORS.classify(error) @@ -180,22 +215,31 @@ def test_error_pack_classifies_sts_assume_role_denied_as_not_authorized(): assert diagnosis.title == "Not authorized" -def test_error_pack_classifies_invalid_token_as_auth_failure(): +def test_error_pack_classifies_invalid_client_token_as_unknown_access_key(): + # STS's code, from the assume-role leg. diagnosis = ATHENA_ERRORS.classify(_client_error("InvalidClientTokenId")) assert diagnosis is not None - assert diagnosis.title == "Authentication failed" + assert diagnosis.title == "AWS access key not recognized" -def test_error_pack_classifies_signature_mismatch_as_auth_failure(): +def test_error_pack_classifies_signature_mismatch_as_wrong_secret(): diagnosis = ATHENA_ERRORS.classify(_client_error("SignatureDoesNotMatch")) assert diagnosis is not None - assert diagnosis.title == "Authentication failed" + assert diagnosis.title == "AWS secret key does not match" -def test_error_pack_classifies_expired_token_as_auth_failure(): +def test_error_pack_classifies_expired_token(): diagnosis = ATHENA_ERRORS.classify(_client_error("ExpiredToken")) assert diagnosis is not None - assert diagnosis.title == "Authentication failed" + assert diagnosis.title == "AWS session token expired" + + +def test_error_pack_prefers_an_authentication_code_over_not_authorized_text(): + # The authorization rule sits above AWS_ERRORS; its message fallback must not + # swallow a rejected identity. + diagnosis = ATHENA_ERRORS.classify(_client_error("ExpiredToken", "not authorized: token expired")) + assert diagnosis is not None + assert diagnosis.title == "AWS session token expired" def test_error_pack_returns_none_for_unknown_error(): @@ -203,23 +247,39 @@ def test_error_pack_returns_none_for_unknown_error(): def test_client_is_built_lazily_not_at_construction(): + # Building the engine runs the STS assume-role handshake, so it must not happen + # while the provider is assembled - only when a check reads the borrow. calls = [] - provider = AthenaChecks(client_factory=lambda: calls.append(1) or MagicMock()) + provider = AthenaChecks(db=Borrowed(lambda: calls.append(1) or MagicMock())) + assert calls == [] - _ = provider.client - _ = provider.client + + _ = provider._db.client + assert calls == [1] +def test_client_is_built_once_by_its_owner_and_shared_across_checks(): + # Caching is the connection's job, not the provider's: every read of the borrow + # goes back to the owner, which builds once. + conn = AthenaConnection(_config()) + with patch.object(AthenaConnection, "_get_client", return_value=MagicMock()) as mock_build: + provider = conn.checks() + _ = provider._db.client + _ = provider._db.client + + assert mock_build.call_count == 1 + + def test_check_access_surfaces_client_build_failure_for_classification(): # An assume-role / credential failure while building the engine now happens # inside CheckAccess (the gate), so its exception propagates from the check and # the runner can classify it - instead of raising at provider construction. error = _client_error("InvalidClientTokenId", "The security token included in the request is invalid") - provider = AthenaChecks(client_factory=_raising_factory(error)) + provider = AthenaChecks(db=Borrowed(_raising_factory(error))) with pytest.raises(ClientError) as exc_info: provider.check_access() - assert ATHENA_ERRORS.classify(exc_info.value).title == "Authentication failed" + assert ATHENA_ERRORS.classify(exc_info.value).title == "AWS access key not recognized" def test_athena_url(): diff --git a/ingestion/tests/unit/source/database/bigquery/test_connection.py b/ingestion/tests/unit/source/database/bigquery/test_connection.py index 92be71c0eedc..2c7b934b729f 100644 --- a/ingestion/tests/unit/source/database/bigquery/test_connection.py +++ b/ingestion/tests/unit/source/database/bigquery/test_connection.py @@ -21,6 +21,7 @@ from google.api_core.exceptions import Forbidden, NotFound from google.auth.exceptions import DefaultCredentialsError, RefreshError +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import Evidence from metadata.core.connections.test_connection.check import collect_checks from metadata.core.connections.test_connection.checks.database import DatabaseStep @@ -132,7 +133,7 @@ def test_malformed_private_key_is_classified(): def _checks(service_connection, client=None) -> BigQueryChecks: engine = client if client is not None else MagicMock() - return BigQueryChecks(get_client=lambda: engine, service_connection=service_connection) + return BigQueryChecks(db=Borrowed.of(engine), service_connection=service_connection) def test_checks_cover_exactly_the_wired_steps(): @@ -152,13 +153,13 @@ def test_construction_does_not_build_the_client(): # The engine is built lazily inside CheckAccess, never at construction - so # credential parsing (and any connect) happens behind the gate, not before it. get_client = MagicMock() - BigQueryChecks(get_client=get_client, service_connection=_config()) + BigQueryChecks(db=Borrowed(get_client), service_connection=_config()) get_client.assert_not_called() def test_check_access_builds_client_lazily_and_pings(): get_client = MagicMock() - checks = BigQueryChecks(get_client=get_client, service_connection=_config()) + checks = BigQueryChecks(db=Borrowed(get_client), service_connection=_config()) with patch(f"{_CONNECTION_MODULE}.ping", return_value=Evidence(summary="connection established")) as mock_ping: evidence = checks.check_access() get_client.assert_called_once_with() @@ -171,7 +172,7 @@ def test_check_access_surfaces_malformed_key_error(): # inside CheckAccess, the error reaches the runner (here: the caller) to be # classified, instead of escaping before the test starts. error = InvalidPrivateKeyException("Cannot serialise key: Unable to load PEM file.") - checks = BigQueryChecks(get_client=MagicMock(side_effect=error), service_connection=_config()) + checks = BigQueryChecks(db=Borrowed(MagicMock(side_effect=error)), service_connection=_config()) with pytest.raises(InvalidPrivateKeyException): checks.check_access() diff --git a/ingestion/tests/unit/source/database/databricks/__init__.py b/ingestion/tests/unit/source/database/databricks/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/ingestion/tests/unit/source/database/databricks/test_connection.py b/ingestion/tests/unit/source/database/databricks/test_connection.py new file mode 100644 index 000000000000..4583038a746a --- /dev/null +++ b/ingestion/tests/unit/source/database/databricks/test_connection.py @@ -0,0 +1,349 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Unit tests for the Databricks BaseConnection wiring and test-connection checks.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from metadata.core.connections.lifetime import Borrowed +from metadata.core.connections.test_connection.check import CheckError, collect_checks +from metadata.core.connections.test_connection.checks.database import DatabaseStep +from metadata.core.connections.test_connection.network import NetworkUnreachableError +from metadata.generated.schema.entity.services.connections.database.databricks.personalAccessToken import ( + PersonalAccessToken, +) +from metadata.generated.schema.entity.services.connections.database.databricksConnection import ( + DatabricksConnection as DatabricksConnectionConfig, +) +from metadata.ingestion.connections.connection import BaseConnection +from metadata.ingestion.source.database.databricks.connection import ( + DATABRICKS_ERRORS, + DatabricksChecks, + DatabricksConnection, +) + +CONNECTION_MODULE = "metadata.ingestion.source.database.databricks.connection" + + +def _config() -> DatabricksConnectionConfig: + return DatabricksConnectionConfig( + hostPort="my-workspace.cloud.databricks.com:443", + authType=PersonalAccessToken(token="dapi-secret"), + httpPath="/sql/1.0/warehouses/abc123", + catalog="my_catalog", + ) + + +class _SqlAlchemyError(Exception): + """Mirror ``sqlalchemy.exc.DBAPIError``: wraps the driver error on ``.orig``.""" + + def __init__(self, orig: Exception) -> None: + super().__init__(str(orig)) + self.orig = orig + + +def test_databricks_connection_is_base_connection(): + assert issubclass(DatabricksConnection, BaseConnection) + + +def test_get_client_uses_the_databricks_url_builder(): + with patch(f"{CONNECTION_MODULE}.create_generic_db_connection") as mock_connection: + _ = DatabricksConnection(_config()).client + assert mock_connection.call_args.kwargs["get_connection_url_fn"].__name__ == "get_connection_url" + + +def test_close_disposes_the_engine_pool(): + engine = MagicMock() + with patch(f"{CONNECTION_MODULE}.create_generic_db_connection", return_value=engine): + connection = DatabricksConnection(_config()) + assert connection.client is engine + connection.close() + engine.dispose.assert_called_once_with() + + +def test_connection_timeout_drives_the_per_step_budget(): + from metadata.core.connections.test_connection.constants import STEP_TIMEOUT_SECONDS + + # connectionTimeout (default 120) must win over the 60s framework default, + # fed through BaseConnection.step_timeout_seconds. + default_config = _config() + assert DatabricksConnection(default_config).step_timeout_seconds == default_config.connectionTimeout + + slow_config = _config() + slow_config.connectionTimeout = 300 + assert DatabricksConnection(slow_config).step_timeout_seconds == 300 + + unset_config = _config() + unset_config.connectionTimeout = None + assert DatabricksConnection(unset_config).step_timeout_seconds == STEP_TIMEOUT_SECONDS + + +def test_invalid_token_message_is_classified(): + error = _SqlAlchemyError(Exception("Error during request to server: Invalid access token")) + assert DATABRICKS_ERRORS.classify(error).title == "Authentication failed" + + +def test_expired_token_message_is_classified(): + error = _SqlAlchemyError(Exception("the access token is expired, please refresh it")) + assert DATABRICKS_ERRORS.classify(error).title == "Access token expired" + + +def test_forbidden_message_is_classified(): + error = _SqlAlchemyError(Exception("HTTP Response code: 403, Forbidden")) + assert DATABRICKS_ERRORS.classify(error).title == "Access denied" + + +def test_malformed_http_path_is_classified(): + # A bad httpPath fails CheckAccess with MALFORMED_REQUEST; needs a diagnosis. + error = _SqlAlchemyError( + Exception( + "MALFORMED_REQUEST: Path /sql/1.0/warehouses/39c390db3a5e19e must match pattern " + "/sql/1.0/endpoints/ or /sql/1.0/warehouses/" + ) + ) + assert DATABRICKS_ERRORS.classify(error).title == "Invalid HTTP path" + + +def test_permission_denied_is_classified(): + error = _SqlAlchemyError(Exception("[PERMISSION_DENIED] User does not have SELECT on system.access.table_lineage")) + assert DATABRICKS_ERRORS.classify(error).title == "Insufficient privileges" + + +def test_insufficient_permissions_is_classified(): + error = _SqlAlchemyError(Exception("INSUFFICIENT_PERMISSIONS: requires USAGE on catalog")) + assert DATABRICKS_ERRORS.classify(error).title == "Insufficient privileges" + + +def test_table_or_view_not_found_is_classified(): + error = _SqlAlchemyError(Exception("[TABLE_OR_VIEW_NOT_FOUND] The table or view cannot be found")) + assert DATABRICKS_ERRORS.classify(error).title == "Table or view not found" + + +def test_schema_not_found_is_classified(): + error = _SqlAlchemyError(Exception("[SCHEMA_NOT_FOUND] The schema cannot be found")) + assert DATABRICKS_ERRORS.classify(error).title == "Schema not found" + + +def test_catalog_does_not_exist_is_classified(): + error = _SqlAlchemyError(Exception("Catalog 'nope' does not exist")) + assert DATABRICKS_ERRORS.classify(error).title == "Object not found" + + +def test_no_such_catalog_exception_is_classified(): + # NO_SUCH_CATALOG_EXCEPTION says "was not found", not "does not exist". + error = _SqlAlchemyError(Exception("[NO_SUCH_CATALOG_EXCEPTION] Catalog 'batata' was not found. SQLSTATE: 42704")) + assert DATABRICKS_ERRORS.classify(error).title == "Catalog not found" + + +def test_no_such_schema_exception_is_classified(): + error = _SqlAlchemyError(Exception("[NO_SUCH_SCHEMA_EXCEPTION] Schema 'nope' was not found")) + assert DATABRICKS_ERRORS.classify(error).title == "Schema not found" + + +def test_network_errors_classify_through_including(): + error = NetworkUnreachableError("workspace:443 is not reachable") + error.__cause__ = ConnectionRefusedError(61, "Connection refused") + assert DATABRICKS_ERRORS.classify(error).title == "Connection refused" + + +def test_unknown_error_returns_no_diagnosis(): + error = _SqlAlchemyError(Exception("something entirely unexpected")) + assert DATABRICKS_ERRORS.classify(error) is None + + +def test_checks_cover_exactly_the_seeded_steps(): + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) + collected = collect_checks(checks) + assert set(collected.keys()) == { + DatabaseStep.CheckAccess, + DatabaseStep.GetDatabases, + DatabaseStep.GetSchemas, + DatabaseStep.GetTables, + DatabaseStep.GetViews, + DatabaseStep.GetQueries, + DatabaseStep.GetViewDefinitions, + DatabaseStep.GetCatalogTags, + DatabaseStep.GetSchemaTags, + DatabaseStep.GetTableTags, + DatabaseStep.GetColumnTags, + DatabaseStep.GetTableLineage, + DatabaseStep.GetColumnLineage, + } + + +def test_construction_does_not_touch_the_network(): + # Building the provider must not connect - that belongs in a gated check. + engine = MagicMock() + DatabricksChecks(db=Borrowed.of(engine), service_connection=_config()) + engine.connect.assert_not_called() + + +def test_construction_does_not_build_the_inspector(): + # Regression: inspect(engine) connects eagerly, so building it in __init__ would + # connect before the gate (auth error escapes as a 500). Keep it lazy. + with patch(f"{CONNECTION_MODULE}.inspect") as mock_inspect: + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) + mock_inspect.assert_not_called() + _ = checks._engine_wrapper.inspector + mock_inspect.assert_called_once() + + +def test_check_access_probes_the_host_port_then_pings(): + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) + with ( + patch(f"{CONNECTION_MODULE}.tcp_probe") as mock_probe, + patch(f"{CONNECTION_MODULE}.run_sql", return_value=MagicMock()) as mock_run, + ): + checks.check_access() + mock_probe.assert_called_once_with("my-workspace.cloud.databricks.com", 443) + assert mock_run.call_count == 1 + + +def test_check_access_reports_unreachable_host_as_network_failure(): + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) + probe_error = NetworkUnreachableError("my-workspace.cloud.databricks.com:443 is not reachable") + probe_error.__cause__ = ConnectionRefusedError(61, "Connection refused") + with ( + patch(f"{CONNECTION_MODULE}.tcp_probe", side_effect=probe_error) as mock_probe, + pytest.raises(CheckError) as exc, + ): + checks.check_access() + mock_probe.assert_called_once_with("my-workspace.cloud.databricks.com", 443) + assert exc.value.cause is probe_error + assert DATABRICKS_ERRORS.classify(exc.value.cause).title == "Connection refused" + + +def test_probe_target_defaults_to_443_when_no_port(): + config = _config() + config.hostPort = "my-workspace.cloud.databricks.com" + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=config) + assert checks._probe_target() == ("my-workspace.cloud.databricks.com", 443) + + +def test_first_catalog_uses_configured_catalog_without_querying(): + engine = MagicMock() + checks = DatabricksChecks(db=Borrowed.of(engine), service_connection=_config()) + assert checks._first_catalog() == "my_catalog" + engine.connect.assert_not_called() + + +def test_listing_caps_rows_at_the_sample_size_at_the_source(): + # Bound the fetch (fetchmany), not fetchall-then-slice. Test-connection only; + # real ingestion goes through the common framework. + from metadata.core.connections.test_connection.checks.database import ( + DEFAULT_SAMPLE_ROWS, + ) + from metadata.ingestion.source.database.databricks.connection import ( + DatabricksEngineWrapper, + ) + + result = MagicMock() + result.fetchmany.return_value = [("t",)] + conn = MagicMock() + conn.execute.return_value = result + engine = MagicMock() + engine.connect.return_value.__enter__.return_value = conn + + wrapper = DatabricksEngineWrapper(Borrowed.of(engine)) + wrapper.first_catalog = "my_catalog" + wrapper.first_schema = "my_schema" + wrapper.get_tables() + result.fetchmany.assert_called_once_with(DEFAULT_SAMPLE_ROWS) + result.fetchall.assert_not_called() + + +def test_get_databases_reports_catalog_count(): + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) + with patch.object( + checks._engine_wrapper, "get_catalogs", return_value=[("my_catalog",), ("other",)] + ) as mock_catalogs: + evidence = checks.get_databases() + mock_catalogs.assert_called_once_with(catalog_name="my_catalog") + assert evidence.summary == "2 catalogs enumerated" + + +def test_get_databases_failure_reports_the_attempted_command_as_evidence(): + config = _config() + config.catalog = None + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=config) + with ( + patch.object(checks._engine_wrapper, "get_catalogs", side_effect=Exception("boom")), + pytest.raises(CheckError) as exc, + ): + checks.get_databases() + assert exc.value.evidence.command == "SHOW CATALOGS" + + +def test_get_databases_omits_the_command_when_catalog_is_configured(): + # A configured catalog is trusted without running SHOW CATALOGS. + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) + with patch.object(checks._engine_wrapper, "get_catalogs", return_value=[("my_catalog",)]): + evidence = checks.get_databases() + assert evidence.command is None + + +def test_probe_target_strips_a_pasted_url_scheme_and_path(): + # A pasted workspace URL must not reach the socket probe as the host, or the + # gate fails with a misleading DNS error before the driver. + config = _config() + config.hostPort = "https://my-workspace.cloud.databricks.com:443/sql/1.0/warehouses/x" + checks = DatabricksChecks(db=Borrowed.of(MagicMock()), service_connection=config) + assert checks._probe_target() == ("my-workspace.cloud.databricks.com", 443) + + +def test_connection_url_strips_a_pasted_url_scheme(): + from urllib.parse import urlparse + + from metadata.ingestion.source.database.databricks.connection import get_connection_url + + config = _config() + config.hostPort = "https://my-workspace.cloud.databricks.com:443" + parsed = urlparse(get_connection_url(config)) + assert parsed.hostname == "my-workspace.cloud.databricks.com" + assert parsed.port == 443 + + +def test_auth_host_derivation_strips_a_pasted_scheme(): + # OAuth/Azure-AD derive the workspace host from hostPort too; a pasted scheme + # must not leak in as the host or auth fails before the driver. + from metadata.ingestion.source.database.databricks.auth import _host, normalize_host_port + + assert normalize_host_port("https://ws.cloud.databricks.com:443/sql/x") == "ws.cloud.databricks.com:443" + connection = MagicMock() + connection.hostPort = "https://ws.cloud.databricks.com:443" + assert _host(connection) == "ws.cloud.databricks.com" + + +def test_schema_scoped_get_schemas_skips_use_catalog_when_catalog_unresolved(): + # first_catalog None (GetDatabases failed/skipped) must not emit USE CATALOG `None`. + from metadata.ingestion.source.database.databricks.connection import ( + DatabricksEngineWrapper, + ) + + engine = MagicMock() + wrapper = DatabricksEngineWrapper(Borrowed.of(engine)) + wrapper.first_catalog = None + assert wrapper.get_schemas(schema_name="my_schema") == ["my_schema"] + engine.connect.assert_not_called() + + +def test_get_tables_returns_empty_when_catalog_unresolved(): + from metadata.ingestion.source.database.databricks.connection import ( + DatabricksEngineWrapper, + ) + + engine = MagicMock() + wrapper = DatabricksEngineWrapper(Borrowed.of(engine)) + wrapper.first_catalog = None + wrapper.first_schema = "my_schema" + assert wrapper.get_tables() == [] + engine.connect.assert_not_called() diff --git a/ingestion/tests/unit/source/database/glue/test_connection.py b/ingestion/tests/unit/source/database/glue/test_connection.py index cdc5dc4cca0c..518015789222 100644 --- a/ingestion/tests/unit/source/database/glue/test_connection.py +++ b/ingestion/tests/unit/source/database/glue/test_connection.py @@ -8,24 +8,68 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Unit tests for the Glue BaseConnection wiring (non-Engine: boto3 client).""" +"""Glue test-connection: its checks match its shipped definition (non-Engine: boto3 client).""" -from unittest.mock import patch +import json +from pathlib import Path +from unittest.mock import MagicMock, patch +import pytest +from botocore.exceptions import ClientError + +from metadata.core.connections.lifetime import Borrowed +from metadata.core.connections.test_connection.check import CheckError, collect_checks from metadata.generated.schema.entity.services.connections.database.glueConnection import ( GlueConnection as GlueConnectionConfig, ) from metadata.generated.schema.security.credentials.awsCredentials import AWSCredentials from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.source.database.glue.connection import GlueConnection +from metadata.ingestion.source.database.glue.connection import ( + GLUE_ERRORS, + GlueChecks, + GlueConnection, + list_databases, +) CONNECTION_MODULE = "metadata.ingestion.source.database.glue.connection" +_SEED = ( + Path(__file__).parents[6] + / "openmetadata-service/src/main/resources/json/data" + / "testConnections/database/glue.json" +) + def _config() -> GlueConnectionConfig: return GlueConnectionConfig(awsConfig=AWSCredentials(awsRegion="us-east-1")) +def _client(pages: dict[str, list[dict]] | None = None) -> MagicMock: + """A Glue client whose paginators yield one page per operation.""" + responses = pages or {} + client = MagicMock() + client.get_paginator.side_effect = lambda operation: _paginator(responses.get(operation, [{}])) + return client + + +def _paginator(pages: list[dict]) -> MagicMock: + paginator = MagicMock() + paginator.paginate.return_value = pages + return paginator + + +def _checks(client=None) -> GlueChecks: + return GlueChecks(catalog=Borrowed.of(client)) + + +def _check_names() -> set[str]: + return {step.value for step in collect_checks(_checks())} + + +def _client_error(code: str, operation: str = "GetDatabases") -> ClientError: + return ClientError({"Error": {"Code": code, "Message": "denied"}}, operation) + + def test_glue_connection_is_base_connection(): assert issubclass(GlueConnection, BaseConnection) @@ -33,5 +77,206 @@ def test_glue_connection_is_base_connection(): def test_get_client_builds_the_glue_client(): with patch(f"{CONNECTION_MODULE}.AWSClient") as mock_aws: client = GlueConnection(_config()).client + mock_aws.return_value.get_glue_client.assert_called_once_with() assert client is mock_aws.return_value.get_glue_client.return_value + + +def test_glue_checks_cover_expected_steps(): + assert _check_names() == {"GetDatabases", "GetTables"} + + +def test_glue_checks_match_definition_seed(): + definition_steps = {step["name"] for step in json.loads(_SEED.read_text())["steps"]} + assert _check_names() == definition_steps + + +def test_get_databases_is_the_connection_gate(): + steps = json.loads(_SEED.read_text())["steps"] + assert steps[0]["name"] == "GetDatabases" + assert steps[0]["category"] == "ConnectionGate" + + +def test_building_checks_does_not_build_the_client(): + with patch.object(GlueConnection, "_get_client") as mock_build: + GlueConnection(_config()).checks() + + mock_build.assert_not_called() + + +def test_get_databases_enumerates_the_catalog(): + client = _client({"get_databases": [{"DatabaseList": [{"Name": "a"}, {"Name": "b"}]}]}) + + evidence = _checks(client).get_databases() + + assert evidence.summary == "2 databases enumerated" + assert evidence.command == "glue:GetDatabases" + assert evidence.caveat is None + + +def test_get_databases_caps_reported_count_and_flags_more(): + paginator = _paginator([{"DatabaseList": [{"Name": "a"}, {"Name": "b"}, {"Name": "c"}]}]) + client = MagicMock() + client.get_paginator.return_value = paginator + + evidence = list_databases(client, limit=2) + + assert evidence.summary == "2 databases enumerated (showing first 2; more exist)" + client.get_paginator.assert_called_once_with("get_databases") + paginator.paginate.assert_called_once_with(PaginationConfig={"MaxItems": 3}) + + +def test_get_databases_warns_when_catalog_is_empty(): + client = _client({"get_databases": [{"DatabaseList": []}]}) + + evidence = _checks(client).get_databases() + + assert evidence.summary == "0 databases enumerated" + assert evidence.caveat is not None + assert "No databases visible" in evidence.caveat.title + + +def test_get_databases_failure_reports_the_command_it_ran(): + client = _client() + cause = _client_error("AccessDeniedException") + client.get_paginator.side_effect = cause + + with pytest.raises(CheckError) as failure: + _checks(client).get_databases() + + assert failure.value.cause is cause + assert failure.value.evidence.command == "glue:GetDatabases" + + +def test_get_tables_probes_the_first_database(): + client = _client( + { + "get_databases": [{"DatabaseList": [{"Name": "sales"}]}], + "get_tables": [{"TableList": [{"Name": "orders"}]}], + } + ) + + evidence = _checks(client).get_tables() + + assert evidence.summary == "1 table in database 'sales'" + assert evidence.command == "glue:GetTables (DatabaseName=sales)" + + +def test_get_tables_reports_a_caveat_when_no_database_can_be_probed(): + client = _client({"get_databases": [{"DatabaseList": []}]}) + + evidence = _checks(client).get_tables() + + assert evidence.command == "glue:GetDatabases" + assert evidence.caveat is not None + assert evidence.caveat.title == "No tables visible" + + +def test_get_tables_skips_an_empty_leading_database(): + # A catalog commonly leads with an empty 'default'; the probe must not stop there. + client = MagicMock() + tables = {"default": [{"TableList": []}], "ecommerce": [{"TableList": [{"Name": "orders"}]}]} + calls = {"n": 0} + + def paginator(operation): + if operation == "get_databases": + return _paginator([{"DatabaseList": [{"Name": "default"}, {"Name": "ecommerce"}]}]) + calls["n"] += 1 + return _paginator(tables["default" if calls["n"] == 1 else "ecommerce"]) + + client.get_paginator.side_effect = paginator + + evidence = _checks(client).get_tables() + + assert evidence.summary == "1 table in database 'ecommerce'" + assert evidence.command == "glue:GetTables (DatabaseName=ecommerce)" + assert evidence.caveat is None + + +def test_get_tables_warns_when_no_database_exposes_a_table(): + client = _client( + { + "get_databases": [{"DatabaseList": [{"Name": "a"}, {"Name": "b"}]}], + "get_tables": [{"TableList": []}], + } + ) + + evidence = _checks(client).get_tables() + + assert evidence.summary == "no tables in the first 2 databases" + assert evidence.caveat is not None + assert evidence.caveat.title == "No tables visible" + + +def test_get_tables_failure_names_the_database_it_probed(): + cause = _client_error("EntityNotFoundException", "GetTables") + client = _client({"get_databases": [{"DatabaseList": [{"Name": "sales"}]}]}) + tables_paginator = MagicMock() + tables_paginator.paginate.side_effect = cause + client.get_paginator.side_effect = lambda operation: ( + tables_paginator if operation == "get_tables" else _paginator([{"DatabaseList": [{"Name": "sales"}]}]) + ) + + with pytest.raises(CheckError) as failure: + _checks(client).get_tables() + + assert failure.value.cause is cause + assert failure.value.evidence.command == "glue:GetTables (DatabaseName=sales)" + + +def test_error_pack_access_denied(): + diagnosis = GLUE_ERRORS.classify( + ClientError( + { + "Error": { + "Code": "AccessDeniedException", + "Message": "User is not authorized to perform: glue:GetDatabases", + } + }, + "GetDatabases", + ) + ) + assert diagnosis is not None + assert "authorized" in diagnosis.title.lower() + + +def test_error_pack_entity_not_found(): + diagnosis = GLUE_ERRORS.classify(_client_error("EntityNotFoundException", "GetTables")) + assert diagnosis is not None + assert diagnosis.title == "Glue database not found" + + +def test_error_pack_inherits_the_shared_aws_diagnoses(): + # Glue is json-protocol: expired creds arrive as ExpiredTokenException. + diagnosis = GLUE_ERRORS.classify(_client_error("ExpiredTokenException")) + assert diagnosis is not None + assert diagnosis.title == "AWS session token expired" + + +def test_error_pack_classifies_an_unknown_access_key(): + diagnosis = GLUE_ERRORS.classify(_client_error("UnrecognizedClientException")) + assert diagnosis is not None + assert diagnosis.title == "AWS access key not recognized" + + +def test_error_pack_classifies_a_wrong_secret(): + diagnosis = GLUE_ERRORS.classify(_client_error("InvalidSignatureException")) + assert diagnosis is not None + assert diagnosis.title == "AWS secret key does not match" + + +def test_error_pack_classifies_an_sts_assume_role_denial(): + # The assume-role leg denies with the suffix-less code. + diagnosis = GLUE_ERRORS.classify(_client_error("AccessDenied", "AssumeRole")) + assert diagnosis is not None + assert diagnosis.title == "Not authorized" + + +def test_error_pack_inherits_the_network_pack_through_aws_errors(): + diagnosis = GLUE_ERRORS.classify(ConnectionRefusedError("refused")) + assert diagnosis is not None + assert "refused" in diagnosis.title.lower() + + +def test_error_pack_unmatched_returns_none(): + assert GLUE_ERRORS.classify(Exception("novel error")) is None diff --git a/ingestion/tests/unit/source/database/mssql/test_connection.py b/ingestion/tests/unit/source/database/mssql/test_connection.py index 7dd21d2214f3..823e86731289 100644 --- a/ingestion/tests/unit/source/database/mssql/test_connection.py +++ b/ingestion/tests/unit/source/database/mssql/test_connection.py @@ -17,6 +17,7 @@ import socket from unittest.mock import MagicMock, patch +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import collect_checks from metadata.core.connections.test_connection.checks.database import DEFAULT_SAMPLE_ROWS, DatabaseStep from metadata.generated.schema.entity.services.connections.database.mssqlConnection import ( @@ -74,7 +75,7 @@ def test_non_pyodbc_scheme_uses_common_url_builder(): def _checks() -> MssqlChecks: - return MssqlChecks(client=MagicMock(), get_databases_statement="SELECT 1") + return MssqlChecks(db=Borrowed.of(MagicMock()), get_databases_statement="SELECT 1") def test_every_definition_step_resolves_to_a_check(): diff --git a/ingestion/tests/unit/source/database/mysql/test_mysql_connection.py b/ingestion/tests/unit/source/database/mysql/test_mysql_connection.py index bc15ee311b58..0aac15a2341d 100644 --- a/ingestion/tests/unit/source/database/mysql/test_mysql_connection.py +++ b/ingestion/tests/unit/source/database/mysql/test_mysql_connection.py @@ -13,6 +13,7 @@ import json from pathlib import Path +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection.check import collect_checks from metadata.ingestion.source.database.mysql.connection import MYSQL_ERRORS, MySQLChecks @@ -24,7 +25,7 @@ def _check_names(): - checks = MySQLChecks(client=None, schema=None, queries_statement="") + checks = MySQLChecks(db=Borrowed.of(None), schema=None, queries_statement="") return {step.value for step in collect_checks(checks)} diff --git a/ingestion/tests/unit/source/database/postgres/test_connection.py b/ingestion/tests/unit/source/database/postgres/test_connection.py index 70c4fe6b1dbd..1d91a663c982 100644 --- a/ingestion/tests/unit/source/database/postgres/test_connection.py +++ b/ingestion/tests/unit/source/database/postgres/test_connection.py @@ -18,6 +18,7 @@ from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection.check import CheckError, collect_checks from metadata.core.connections.test_connection.checks.database import ( DEFAULT_SAMPLE_ROWS, @@ -198,7 +199,7 @@ def test_unknown_error_returns_no_diagnosis(): def test_checks_cover_exactly_the_seeded_steps(): engine = create_engine("sqlite://", poolclass=StaticPool) - checks = PostgresChecks(client=engine, query_statement_source=None) + checks = PostgresChecks(db=Borrowed.of(engine), query_statement_source=None) collected = collect_checks(checks) assert set(collected.keys()) == { DatabaseStep.CheckAccess, @@ -224,7 +225,7 @@ def test_check_access_reports_unreachable_host_as_network_failure(): client = MagicMock() client.url.host = "db.invalid" client.url.port = 5432 - checks = PostgresChecks(client=client, query_statement_source=None) + checks = PostgresChecks(db=Borrowed.of(client), query_statement_source=None) probe_error = NetworkUnreachableError("db.invalid:5432 is not reachable") probe_error.__cause__ = ConnectionRefusedError(61, "Connection refused") with ( @@ -250,7 +251,7 @@ def test_query_statement_is_built_lazily_not_at_construction(): side_effect=lambda engine: calls.append(1) or "total_exec_time", ): engine = create_engine("sqlite://", poolclass=StaticPool) - PostgresChecks(client=engine, query_statement_source=None) + PostgresChecks(db=Borrowed.of(engine), query_statement_source=None) assert calls == [] diff --git a/ingestion/tests/unit/source/database/redshift/test_connection.py b/ingestion/tests/unit/source/database/redshift/test_connection.py index 9da57de9a19d..72efeffcf3ed 100644 --- a/ingestion/tests/unit/source/database/redshift/test_connection.py +++ b/ingestion/tests/unit/source/database/redshift/test_connection.py @@ -20,6 +20,7 @@ from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection.check import CheckError, collect_checks from metadata.core.connections.test_connection.checks.database import ( DEFAULT_SAMPLE_ROWS, @@ -172,7 +173,7 @@ def test_get_queries_failure_reports_the_attempted_command_as_evidence(): # CheckError wrapping; get_queries must re-raise with the statement so the # failed step still shows the command it ran, like every other step. engine = MagicMock() - checks = RedshiftChecks(client=engine) + checks = RedshiftChecks(db=Borrowed.of(engine)) with ( patch(f"{CONNECTION_MODULE}.get_redshift_instance_type", return_value=RedshiftInstanceType.PROVISIONED), patch(f"{CONNECTION_MODULE}.run_sql", side_effect=SourceConnectionException("missing privilege")) as mock_run, @@ -186,7 +187,7 @@ def test_get_queries_failure_reports_the_attempted_command_as_evidence(): def test_checks_cover_exactly_the_seeded_steps(): engine = create_engine("sqlite://", poolclass=StaticPool) - checks = RedshiftChecks(client=engine) + checks = RedshiftChecks(db=Borrowed.of(engine)) collected = collect_checks(checks) assert set(collected.keys()) == { DatabaseStep.CheckAccess, @@ -202,7 +203,7 @@ def test_check_access_reports_unreachable_host_as_network_failure(): client = MagicMock() client.url.host = "cluster.invalid" client.url.port = 5439 - checks = RedshiftChecks(client=client) + checks = RedshiftChecks(db=Borrowed.of(client)) probe_error = NetworkUnreachableError("cluster.invalid:5439 is not reachable") probe_error.__cause__ = ConnectionRefusedError(61, "Connection refused") with ( @@ -228,5 +229,5 @@ def test_instance_type_probe_is_run_lazily_not_at_construction(): side_effect=lambda engine: calls.append(1), ): engine = create_engine("sqlite://", poolclass=StaticPool) - RedshiftChecks(client=engine) + RedshiftChecks(db=Borrowed.of(engine)) assert calls == [] diff --git a/ingestion/tests/unit/source/database/snowflake/test_connection.py b/ingestion/tests/unit/source/database/snowflake/test_connection.py index 1e181a0e74fc..6fb8e88c6ddd 100644 --- a/ingestion/tests/unit/source/database/snowflake/test_connection.py +++ b/ingestion/tests/unit/source/database/snowflake/test_connection.py @@ -19,6 +19,7 @@ import pytest +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection import Evidence from metadata.core.connections.test_connection.check import CheckError, collect_checks from metadata.core.connections.test_connection.checks.database import ( @@ -129,7 +130,7 @@ def test_account_usage_denial_honors_custom_schema(): # The pack is built from the configured accountUsageSchema, so a denial on a # custom schema is still diagnosed as an account_usage gap - not "Object not found". schema = "MYDB.MY_USAGE" - checks = SnowflakeChecks(client=MagicMock(), service_connection=_config(accountUsageSchema=schema)) + checks = SnowflakeChecks(db=Borrowed.of(MagicMock()), service_connection=_config(accountUsageSchema=schema)) error = _SnowflakeError("Object 'MYDB.MY_USAGE.QUERY_HISTORY' does not exist or not authorized.", errno=2003) assert checks.errors.classify(error).title == "Account usage not accessible" # the default pack, keyed on snowflake.account_usage, does not recognize the custom schema @@ -194,7 +195,7 @@ def fake(client, statement, summarize, *args, **kwargs): def test_get_tables_warns_when_no_user_tables(): # Empty probe (INFORMATION_SCHEMA filtered out) -> passing step with a caveat, # which the runner records as a Warning. - checks = SnowflakeChecks(client=MagicMock(), service_connection=_config(database="MYDB")) + checks = SnowflakeChecks(db=Borrowed.of(MagicMock()), service_connection=_config(database="MYDB")) with patch( "metadata.ingestion.source.database.snowflake.connection.run_sql", side_effect=_fake_run_sql([]), @@ -207,7 +208,7 @@ def test_get_tables_warns_when_no_user_tables(): def test_get_tables_has_no_caveat_when_tables_exist(): - checks = SnowflakeChecks(client=MagicMock(), service_connection=_config(database="MYDB")) + checks = SnowflakeChecks(db=Borrowed.of(MagicMock()), service_connection=_config(database="MYDB")) with patch( "metadata.ingestion.source.database.snowflake.connection.run_sql", side_effect=_fake_run_sql([object(), object()]), @@ -229,7 +230,7 @@ def test_table_and_view_probes_exclude_information_schema(): def test_checks_cover_exactly_the_wired_steps(): - checks = SnowflakeChecks(client=MagicMock(), service_connection=_config()) + checks = SnowflakeChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) collected = collect_checks(checks) assert set(collected.keys()) == { DatabaseStep.CheckAccess, @@ -246,7 +247,7 @@ def test_checks_cover_exactly_the_wired_steps(): def test_get_access_history_is_wired(): # ACCESS_HISTORY is the default lineage source; its probe is the GetAccessHistory step. - checks = SnowflakeChecks(client=MagicMock(), service_connection=_config()) + checks = SnowflakeChecks(db=Borrowed.of(MagicMock()), service_connection=_config()) assert DatabaseStep.GetAccessHistory in collect_checks(checks) @@ -254,7 +255,7 @@ def test_construction_touches_no_network(): # Regression for gotcha #2: building the provider must not connect or resolve a # database - that would run before the gate and bypass the preflight. client = MagicMock() - SnowflakeChecks(client=client, service_connection=_config()) + SnowflakeChecks(db=Borrowed.of(client), service_connection=_config()) client.connect.assert_not_called() client.execute.assert_not_called() @@ -263,7 +264,7 @@ def test_check_access_probes_account_host_and_reports_network_failure(): # check_access -> tcp_probe(.snowflakecomputing.com, 443); a probe # failure is wrapped as a CheckError whose cause classifies via the network # pack. tcp_probe is stubbed so the test is deterministic and fast. - checks = SnowflakeChecks(client=MagicMock(), service_connection=_config(account="acc")) + checks = SnowflakeChecks(db=Borrowed.of(MagicMock()), service_connection=_config(account="acc")) probe_error = NetworkUnreachableError("acc.snowflakecomputing.com:443 is not reachable") probe_error.__cause__ = TimeoutError("timed out") with ( @@ -284,7 +285,7 @@ def test_check_access_prefers_explicit_connection_argument_host(): # host is what the driver dials, so the gate probe must target it - not the # synthesized public account host (which may be unreachable for that deployment). checks = SnowflakeChecks( - client=MagicMock(), + db=Borrowed.of(MagicMock()), service_connection=_config(account="acc", connectionArguments={"host": "proxy.internal"}), ) probe_error = NetworkUnreachableError("proxy.internal:443 is not reachable") @@ -303,7 +304,7 @@ def test_check_access_honors_explicit_connection_argument_port(): # A custom host may listen on a non-443 port; the preflight must probe that # port, not the default 443, or it false-gates the whole connection test. checks = SnowflakeChecks( - client=MagicMock(), + db=Borrowed.of(MagicMock()), service_connection=_config(account="acc", connectionArguments={"host": "proxy.internal", "port": 8443}), ) with ( @@ -321,7 +322,7 @@ def test_get_schemas_runs_show_schemas_with_command_and_count(): # GetSchemas goes through run_sql (like the other probes), so it reports the # database-scoped SHOW SCHEMAS command and a counted summary - and a failure # would surface as a CheckError carrying that command. - checks = SnowflakeChecks(client=MagicMock(), service_connection=_config(database="MYDB")) + checks = SnowflakeChecks(db=Borrowed.of(MagicMock()), service_connection=_config(database="MYDB")) captured = {} def fake(client, statement, summarize, *args, **kwargs): @@ -339,6 +340,6 @@ def test_account_usage_queries_built_lazily_not_at_construction(): # The account_usage statements must be formatted inside their checks (behind # the gate), never at construction; constructing must not read the engine. client = MagicMock() - checks = SnowflakeChecks(client=client, service_connection=_config(account="acc")) + checks = SnowflakeChecks(db=Borrowed.of(client), service_connection=_config(account="acc")) assert checks._engine_wrapper.database_name is None client.connect.assert_not_called() diff --git a/ingestion/tests/unit/source/database/test_base_filter_predicates.py b/ingestion/tests/unit/source/database/test_base_filter_predicates.py new file mode 100644 index 000000000000..a777fc211a41 --- /dev/null +++ b/ingestion/tests/unit/source/database/test_base_filter_predicates.py @@ -0,0 +1,74 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The shared ``DatabaseServiceSource`` filter predicates: pure, FQN-aware, +honoring ``useFqnForFiltering``.""" + +from types import SimpleNamespace +from unittest.mock import MagicMock + +from metadata.generated.schema.type.filterPattern import FilterPattern +from metadata.ingestion.source.database.database_service import DatabaseServiceSource + + +class _StubSource(DatabaseServiceSource): + """Concrete stand-in for the ABC so the base predicates can be unit-tested + directly. Clearing ``__abstractmethods__`` lets ``object.__new__`` build a + bare instance without implementing the 11 unrelated abstract methods.""" + + +_StubSource.__abstractmethods__ = frozenset() + + +def _source(use_fqn, database_pattern=None, schema_pattern=None): + source = object.__new__(_StubSource) + source.metadata = MagicMock() + source.context = MagicMock() + source.context.get.return_value = SimpleNamespace(database_service="svc") + source.source_config = SimpleNamespace( + useFqnForFiltering=use_fqn, + databaseFilterPattern=database_pattern, + schemaFilterPattern=schema_pattern, + ) + return source + + +def test_database_not_filtered_when_pattern_is_none(): + assert _source(use_fqn=False)._is_database_filtered("db") is False + + +def test_database_filtered_by_bare_name_exclude(): + source = _source(use_fqn=False, database_pattern=FilterPattern(excludes=["db"])) + assert source._is_database_filtered("db") is True + assert source._is_database_filtered("other") is False + + +def test_database_fqn_matching_depends_on_use_fqn_flag(): + # Exclude targets the FQN "svc.db", which only matches when useFqnForFiltering is on. + pattern = FilterPattern(excludes=["svc.db"]) + assert _source(use_fqn=True, database_pattern=pattern)._is_database_filtered("db") is True + assert _source(use_fqn=False, database_pattern=pattern)._is_database_filtered("db") is False + + +def test_schema_not_filtered_when_pattern_is_none(): + assert _source(use_fqn=False)._is_schema_filtered("db", "sch") is False + + +def test_schema_filtered_by_bare_name_exclude(): + source = _source(use_fqn=False, schema_pattern=FilterPattern(excludes=["sch"])) + assert source._is_schema_filtered("db", "sch") is True + assert source._is_schema_filtered("db", "other") is False + + +def test_schema_fqn_matching_depends_on_use_fqn_flag(): + # Exclude targets the schema FQN "svc.db.sch". + pattern = FilterPattern(excludes=["svc.db.sch"]) + assert _source(use_fqn=True, schema_pattern=pattern)._is_schema_filtered("db", "sch") is True + assert _source(use_fqn=False, schema_pattern=pattern)._is_schema_filtered("db", "sch") is False diff --git a/ingestion/tests/unit/source/database/test_bigquery_progress_count.py b/ingestion/tests/unit/source/database/test_bigquery_progress_count.py new file mode 100644 index 000000000000..77bb96288c04 --- /dev/null +++ b/ingestion/tests/unit/source/database/test_bigquery_progress_count.py @@ -0,0 +1,124 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""BigQuery seeds ``Database`` (filtered projects) + per-project +``DatabaseSchema`` (filtered datasets) progress totals, reconciling when dataset +listing fails.""" + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.ingestion.progress.tracking import ProgressTracking +from metadata.ingestion.source.database.bigquery import metadata as bigquery_metadata + +BigquerySource = bigquery_metadata.BigquerySource + + +@pytest.fixture +def bigquery_source(): + source = object.__new__(BigquerySource) + source.source_config = SimpleNamespace( + useFqnForFiltering=False, + databaseFilterPattern=None, + schemaFilterPattern=None, + ) + source.metadata = MagicMock() + source.status = MagicMock() + source.context = MagicMock() + source.context.get.return_value = SimpleNamespace(database_service="svc") + source.__dict__["_progress_tracking"] = ProgressTracking(ProgressMode.AUTO, "Test") + return source + + +def _counters(source): + return {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + + +def test_declare_progress_totals_seeds_projects_and_datasets(bigquery_source): + bigquery_source.project_ids = ["p1", "p2"] + bigquery_source._is_database_filtered = lambda p: False + bigquery_source._raw_dataset_names = lambda p: {"p1": ["d1", "d2"], "p2": ["d3"]}[p] + bigquery_source._is_schema_filtered = lambda p, s: False + bigquery_source.declare_progress_totals(TotalsDeclarer(bigquery_source.progress_tracking.registry)) + counters = _counters(bigquery_source) + assert counters["Database"] == (0, 2) + assert counters["DatabaseSchema"] == (0, 3) + + +def test_declare_progress_totals_applies_filters(bigquery_source): + bigquery_source.project_ids = ["keep", "drop"] + bigquery_source._is_database_filtered = lambda p: p == "drop" + bigquery_source._raw_dataset_names = lambda p: ["d1", "skip"] + bigquery_source._is_schema_filtered = lambda p, s: s == "skip" + bigquery_source.declare_progress_totals(TotalsDeclarer(bigquery_source.progress_tracking.registry)) + counters = _counters(bigquery_source) + assert counters["Database"] == (0, 1) + assert counters["DatabaseSchema"] == (0, 1) + + +def test_declare_progress_totals_reconciles_when_listing_fails(bigquery_source): + bigquery_source.project_ids = ["p1"] + bigquery_source._is_database_filtered = lambda p: False + + def _boom(_project_id): + raise RuntimeError("list_datasets denied") + + bigquery_source._raw_dataset_names = _boom + bigquery_source._is_schema_filtered = lambda p, s: False + bigquery_source.declare_progress_totals(TotalsDeclarer(bigquery_source.progress_tracking.registry)) + registry = bigquery_source.progress_tracking.registry + assert registry.is_reconcilable("DatabaseSchema") is True + counters = _counters(bigquery_source) + assert counters["Database"] == (0, 1) + assert counters["DatabaseSchema"] == (0, None) + + +def test_raw_dataset_names_prefers_configured_schema(bigquery_source): + bigquery_source.service_connection = SimpleNamespace(databaseSchema="only_ds") + bigquery_source.client = MagicMock() + assert list(bigquery_source._raw_dataset_names("p1")) == ["only_ds"] + bigquery_source.client.list_datasets.assert_not_called() + + +def test_raw_dataset_names_lists_from_client(bigquery_source): + bigquery_source.service_connection = SimpleNamespace() + bigquery_source.client = MagicMock() + bigquery_source.client.list_datasets.return_value = [ + SimpleNamespace(dataset_id="d1"), + SimpleNamespace(dataset_id="d2"), + ] + assert list(bigquery_source._raw_dataset_names("p1")) == ["d1", "d2"] + bigquery_source.client.list_datasets.assert_called_once_with("p1") + + +def test_declare_progress_totals_builds_client_when_walk_has_not(bigquery_source): + """At declare time the walk has not run set_inspector yet, so self.client is + None; the totals path must build its own client and still seed schema totals + instead of silently degrading to reconcile.""" + bigquery_source.client = None + bigquery_source.service_connection = SimpleNamespace() + bigquery_source.project_ids = ["p1"] + bigquery_source._is_database_filtered = lambda p: False + bigquery_source._is_schema_filtered = lambda p, s: False + fake_client = MagicMock() + fake_client.list_datasets.return_value = [ + SimpleNamespace(dataset_id="d1"), + SimpleNamespace(dataset_id="d2"), + ] + with patch.object(bigquery_metadata, "get_bigquery_client_for_project", return_value=fake_client) as build_client: + bigquery_source.declare_progress_totals(TotalsDeclarer(bigquery_source.progress_tracking.registry)) + build_client.assert_called_once_with("p1", bigquery_source.service_connection) + fake_client.list_datasets.assert_called_once_with("p1") + counters = _counters(bigquery_source) + assert counters["Database"] == (0, 1) + assert counters["DatabaseSchema"] == (0, 2) diff --git a/ingestion/tests/unit/source/database/test_common_db_source_connection.py b/ingestion/tests/unit/source/database/test_common_db_source_connection.py new file mode 100644 index 000000000000..03560eca08c2 --- /dev/null +++ b/ingestion/tests/unit/source/database/test_common_db_source_connection.py @@ -0,0 +1,87 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""CommonDbSourceService owns a single BaseConnection and reuses it for the +test-connection step.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from metadata.ingestion.source.database.mysql.metadata import MysqlSource +from metadata.ingestion.source.database.postgres.metadata import PostgresSource + +MYSQL_CONFIG = { + "type": "mysql", + "serviceName": "local_mysql", + "serviceConnection": { + "config": { + "type": "Mysql", + "username": "openmetadata_user", + "authType": {"password": "openmetadata_password"}, + "hostPort": "mysql-host:3306", + } + }, + "sourceConfig": {"config": {"type": "DatabaseMetadata"}}, +} + +POSTGRES_CONFIG = { + "type": "postgres", + "serviceName": "local_postgres", + "serviceConnection": { + "config": { + "type": "Postgres", + "username": "openmetadata_user", + "authType": {"password": "openmetadata_password"}, + "hostPort": "postgres-host:5432", + "database": "postgres", + } + }, + "sourceConfig": {"config": {"type": "DatabaseMetadata"}}, +} + + +@pytest.fixture +def owned_connection(): + with patch("metadata.ingestion.source.database.common_db_source.create_connection") as mock_create_connection: + yield mock_create_connection.return_value + + +def test_owned_connection_reused_for_test_connection(owned_connection): + with patch("metadata.ingestion.source.database.database_service.run_test_connection") as mock_run_test_connection: + source = MysqlSource.create(MYSQL_CONFIG, MagicMock()) + + assert source.engine is owned_connection.client + mock_run_test_connection.assert_called_once_with(source.metadata, owned_connection) + + +def test_owned_connection_closed_when_test_connection_fails(owned_connection): + with ( + patch( + "metadata.ingestion.source.database.database_service.run_test_connection", + side_effect=RuntimeError("cannot connect"), + ), + pytest.raises(RuntimeError), + ): + MysqlSource.create(MYSQL_CONFIG, MagicMock()) + + owned_connection.close.assert_called_once() + + +def test_set_inspector_disposes_previous_connection(owned_connection): + with patch("metadata.ingestion.source.database.database_service.run_test_connection"): + source = PostgresSource.create(POSTGRES_CONFIG, MagicMock()) + + previous_engine = source.engine + source.set_inspector("other_db") + + previous_engine.dispose.assert_called_once() + owned_connection.close.assert_called_once() + assert source._connection is owned_connection diff --git a/ingestion/tests/unit/source/database/test_databricks_progress_count.py b/ingestion/tests/unit/source/database/test_databricks_progress_count.py new file mode 100644 index 000000000000..33e03d204342 --- /dev/null +++ b/ingestion/tests/unit/source/database/test_databricks_progress_count.py @@ -0,0 +1,113 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Databricks seeds ``Database`` + per-database ``DatabaseSchema`` progress totals +from a single cross-catalog ``system.information_schema.schemata``, and reconciles +when that view is unavailable.""" + +from types import SimpleNamespace +from unittest.mock import MagicMock, PropertyMock, patch + +import pytest + +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.ingestion.progress.tracking import ProgressTracking +from metadata.ingestion.source.database.databricks import metadata as databricks_metadata + +DatabricksSource = databricks_metadata.DatabricksSource + + +@pytest.fixture +def databricks_source(): + source = object.__new__(DatabricksSource) + source.source_config = SimpleNamespace( + useFqnForFiltering=False, + databaseFilterPattern=None, + schemaFilterPattern=None, + ) + source.metadata = MagicMock() + source.status = MagicMock() + source.context = MagicMock() + source.context.get.return_value = SimpleNamespace(database_service="svc") + source.__dict__["_progress_tracking"] = ProgressTracking(ProgressMode.AUTO, "Test") + return source + + +def _counters(source): + return {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + + +def test_declare_progress_totals_seeds_database_and_schema(databricks_source): + databricks_source._filtered_database_names_for_totals = lambda: ["db1", "db2"] + databricks_source._schema_names_by_database = lambda: {"db1": ["s1", "s2"], "db2": ["s3"]} + databricks_source._is_schema_filtered = lambda db, sch: False + databricks_source.declare_progress_totals(TotalsDeclarer(databricks_source.progress_tracking.registry)) + counters = _counters(databricks_source) + assert counters["Database"] == (0, 2) + assert counters["DatabaseSchema"] == (0, 3) + + +def test_declare_progress_totals_matches_catalog_case_insensitively(databricks_source): + databricks_source._filtered_database_names_for_totals = lambda: ["MyCatalog"] + databricks_source._schema_names_by_database = lambda: {"mycatalog": ["s1", "s2"]} + databricks_source._is_schema_filtered = lambda db, sch: False + databricks_source.declare_progress_totals(TotalsDeclarer(databricks_source.progress_tracking.registry)) + assert _counters(databricks_source)["DatabaseSchema"] == (0, 2) + + +def test_declare_progress_totals_applies_schema_filter(databricks_source): + databricks_source._filtered_database_names_for_totals = lambda: ["db1"] + databricks_source._schema_names_by_database = lambda: {"db1": ["keep", "drop"]} + databricks_source._is_schema_filtered = lambda db, sch: sch == "drop" + databricks_source.declare_progress_totals(TotalsDeclarer(databricks_source.progress_tracking.registry)) + assert _counters(databricks_source)["DatabaseSchema"] == (0, 1) + + +def test_declare_progress_totals_reconciles_when_view_unavailable(databricks_source): + databricks_source._filtered_database_names_for_totals = lambda: ["db1"] + databricks_source._schema_names_by_database = lambda: None + databricks_source.declare_progress_totals(TotalsDeclarer(databricks_source.progress_tracking.registry)) + registry = databricks_source.progress_tracking.registry + assert registry.is_reconcilable("DatabaseSchema") is True + counters = _counters(databricks_source) + assert counters["Database"] == (0, 1) + assert counters["DatabaseSchema"] == (0, None) + + +def test_schema_names_by_database_groups_rows_and_returns_none_on_error(databricks_source): + # `connection` is a read-only property on CommonDbSourceService (no setter), + # so it must be patched at the class level rather than assigned on the instance. + mock_connection = MagicMock() + mock_connection.execute.return_value.fetchall.return_value = [ + ("db1", "s1"), + ("db1", "s2"), + ("db2", "s3"), + ] + with patch.object(DatabricksSource, "connection", new_callable=PropertyMock) as mock_connection_property: + mock_connection_property.return_value = mock_connection + grouped = databricks_source._schema_names_by_database() + assert grouped == {"db1": ["s1", "s2"], "db2": ["s3"]} + + mock_connection.execute.side_effect = Exception("permission denied on system.information_schema.schemata") + assert databricks_source._schema_names_by_database() is None + + +def test_filtered_database_names_for_totals_uses_configured_database(databricks_source): + databricks_source.get_configured_database = lambda: "only_db" + databricks_source.get_database_names_raw = MagicMock() + assert databricks_source._filtered_database_names_for_totals() == ["only_db"] + databricks_source.get_database_names_raw.assert_not_called() + + +def test_filtered_database_names_for_totals_filters_all_databases(databricks_source): + databricks_source.get_configured_database = lambda: None + databricks_source.get_database_names_raw = lambda: iter(["keep", "drop"]) + databricks_source._is_database_filtered = lambda db: db == "drop" + assert databricks_source._filtered_database_names_for_totals() == ["keep"] diff --git a/ingestion/tests/unit/source/database/test_leaf_sources_inherit_base_test_connection.py b/ingestion/tests/unit/source/database/test_leaf_sources_inherit_base_test_connection.py new file mode 100644 index 000000000000..fd1ae4d3f710 --- /dev/null +++ b/ingestion/tests/unit/source/database/test_leaf_sources_inherit_base_test_connection.py @@ -0,0 +1,44 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Leaf database sources that own a BaseConnection must reuse it for the test +step by inheriting ``DatabaseServiceSource.test_connection`` — never a private +override that would build a second client.""" + +import pytest + +from metadata.ingestion.source.database.database_service import DatabaseServiceSource +from metadata.ingestion.source.database.datalake.metadata import DatalakeSource +from metadata.ingestion.source.database.deltalake.metadata import DeltalakeSource +from metadata.ingestion.source.database.domodatabase.metadata import DomodatabaseSource +from metadata.ingestion.source.database.glue.metadata import GlueSource +from metadata.ingestion.source.database.salesforce.metadata import SalesforceSource +from metadata.ingestion.source.database.sas.metadata import SasSource + +OWNED_LEAF_SOURCES = [ + DatalakeSource, + DeltalakeSource, + DomodatabaseSource, + GlueSource, + SalesforceSource, + SasSource, +] + + +@pytest.mark.parametrize("source_cls", OWNED_LEAF_SOURCES) +def test_leaf_source_inherits_base_test_connection(source_cls): + assert source_cls.test_connection is DatabaseServiceSource.test_connection + assert "test_connection" not in source_cls.__dict__ + + +@pytest.mark.parametrize("source_cls", OWNED_LEAF_SOURCES) +def test_leaf_source_releases_owner_via_base_close(source_cls): + assert source_cls.close is DatabaseServiceSource.close + assert "close" not in source_cls.__dict__ diff --git a/ingestion/tests/unit/source/database/test_mysql_progress_count.py b/ingestion/tests/unit/source/database/test_mysql_progress_count.py new file mode 100644 index 000000000000..b57cd0dacf3b --- /dev/null +++ b/ingestion/tests/unit/source/database/test_mysql_progress_count.py @@ -0,0 +1,52 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""MySQL declares the single-database ``Database`` denominator and defers the +``DatabaseSchema`` total to runner reconciliation.""" + +from types import SimpleNamespace + +import pytest + +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.ingestion.progress.tracking import ProgressTracking +from metadata.ingestion.source.database.mysql.metadata import MysqlSource + + +def _source(service_connection): + source = object.__new__(MysqlSource) + source.service_connection = service_connection + source.__dict__["_progress_tracking"] = ProgressTracking(ProgressMode.AUTO, "Test") + return source + + +@pytest.fixture +def mysql_source(): + return _source(SimpleNamespace(databaseName=None, database="mydb")) + + +def test_declare_progress_totals_seeds_single_database(mysql_source): + mysql_source.declare_progress_totals(TotalsDeclarer(mysql_source.progress_tracking.registry)) + counters = {t: (done, total) for t, done, total in mysql_source.progress_tracking.registry.global_counters()} + assert counters["Database"] == (0, 1) + + +def test_declare_progress_totals_marks_schema_reconcilable(mysql_source): + mysql_source.declare_progress_totals(TotalsDeclarer(mysql_source.progress_tracking.registry)) + assert mysql_source.progress_tracking.registry.is_reconcilable("DatabaseSchema") is True + counters = {t: (done, total) for t, done, total in mysql_source.progress_tracking.registry.global_counters()} + assert counters["DatabaseSchema"] == (0, None) + + +def test_declare_progress_totals_defaults_database_name_when_unset(mysql_source): + source = _source(SimpleNamespace(databaseName=None, database=None)) + source.declare_progress_totals(TotalsDeclarer(source.progress_tracking.registry)) + counters = {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + assert counters["Database"] == (0, 1) diff --git a/ingestion/tests/unit/source/database/test_redshift_progress_count.py b/ingestion/tests/unit/source/database/test_redshift_progress_count.py new file mode 100644 index 000000000000..cd9e18b4fc9d --- /dev/null +++ b/ingestion/tests/unit/source/database/test_redshift_progress_count.py @@ -0,0 +1,105 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Redshift seeds ``Database`` + per-database ``DatabaseSchema`` progress totals +from a single cross-database ``SVV_ALL_SCHEMAS``, and reconciles when that view +is unavailable.""" + +from types import SimpleNamespace +from unittest.mock import MagicMock, PropertyMock, patch + +import pytest + +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.ingestion.progress.tracking import ProgressTracking +from metadata.ingestion.source.database.redshift import metadata as redshift_metadata + +RedshiftSource = redshift_metadata.RedshiftSource + + +@pytest.fixture +def redshift_source(): + source = object.__new__(RedshiftSource) + source.source_config = SimpleNamespace( + useFqnForFiltering=False, + databaseFilterPattern=None, + schemaFilterPattern=None, + ) + source.metadata = MagicMock() + source.status = MagicMock() + source.context = MagicMock() + source.context.get.return_value = SimpleNamespace(database_service="svc") + source.__dict__["_progress_tracking"] = ProgressTracking(ProgressMode.AUTO, "Test") + return source + + +def _counters(source): + return {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + + +def test_declare_progress_totals_seeds_database_and_schema(redshift_source): + redshift_source._filtered_database_names_for_totals = lambda: ["db1", "db2"] + redshift_source._schema_names_by_database = lambda: {"db1": ["s1", "s2"], "db2": ["s3"]} + redshift_source._is_schema_filtered = lambda db, sch: False + redshift_source.declare_progress_totals(TotalsDeclarer(redshift_source.progress_tracking.registry)) + counters = _counters(redshift_source) + assert counters["Database"] == (0, 2) + assert counters["DatabaseSchema"] == (0, 3) + + +def test_declare_progress_totals_applies_schema_filter(redshift_source): + redshift_source._filtered_database_names_for_totals = lambda: ["db1"] + redshift_source._schema_names_by_database = lambda: {"db1": ["keep", "drop"]} + redshift_source._is_schema_filtered = lambda db, sch: sch == "drop" + redshift_source.declare_progress_totals(TotalsDeclarer(redshift_source.progress_tracking.registry)) + assert _counters(redshift_source)["DatabaseSchema"] == (0, 1) + + +def test_declare_progress_totals_reconciles_when_view_unavailable(redshift_source): + redshift_source._filtered_database_names_for_totals = lambda: ["db1"] + redshift_source._schema_names_by_database = lambda: None + redshift_source.declare_progress_totals(TotalsDeclarer(redshift_source.progress_tracking.registry)) + registry = redshift_source.progress_tracking.registry + assert registry.is_reconcilable("DatabaseSchema") is True + counters = _counters(redshift_source) + assert counters["Database"] == (0, 1) + assert counters["DatabaseSchema"] == (0, None) + + +def test_schema_names_by_database_groups_rows_and_returns_none_on_error(redshift_source): + # `connection` is a read-only property on CommonDbSourceService (no setter), + # so it must be patched at the class level rather than assigned on the instance. + mock_connection = MagicMock() + mock_connection.execute.return_value.fetchall.return_value = [ + ("db1", "s1"), + ("db1", "s2"), + ("db2", "s3"), + ] + with patch.object(RedshiftSource, "connection", new_callable=PropertyMock) as mock_connection_property: + mock_connection_property.return_value = mock_connection + grouped = redshift_source._schema_names_by_database() + assert grouped == {"db1": ["s1", "s2"], "db2": ["s3"]} + + mock_connection.execute.side_effect = Exception("permission denied on SVV_ALL_SCHEMAS") + assert redshift_source._schema_names_by_database() is None + + +def test_filtered_database_names_for_totals_uses_configured_database(redshift_source): + redshift_source.get_configured_database = lambda: "only_db" + redshift_source.get_database_names_raw = MagicMock() + assert redshift_source._filtered_database_names_for_totals() == ["only_db"] + redshift_source.get_database_names_raw.assert_not_called() + + +def test_filtered_database_names_for_totals_filters_all_databases(redshift_source): + redshift_source.get_configured_database = lambda: None + redshift_source.get_database_names_raw = lambda: iter(["keep", "drop"]) + redshift_source._is_database_filtered = lambda db: db == "drop" + assert redshift_source._filtered_database_names_for_totals() == ["keep"] diff --git a/ingestion/tests/unit/source/database/test_snowflake_progress_count.py b/ingestion/tests/unit/source/database/test_snowflake_progress_count.py index 321dcaa1f573..068be8965822 100644 --- a/ingestion/tests/unit/source/database/test_snowflake_progress_count.py +++ b/ingestion/tests/unit/source/database/test_snowflake_progress_count.py @@ -16,6 +16,7 @@ import pytest +from metadata.ingestion.progress.modes import TotalsDeclarer from metadata.ingestion.source.database.snowflake import metadata as snowflake_metadata SnowflakeSource = snowflake_metadata.SnowflakeSource @@ -61,7 +62,8 @@ def test_filtered_names_are_cached_so_status_is_not_double_emitted(self): source.status.filter.assert_called_once() def test_producer_setup_runs_per_kept_database_without_re_filtering(self): - from metadata.utils.progress_registry import ProgressRegistry + from metadata.ingestion.progress.modes import ProgressMode + from metadata.ingestion.progress.tracking import ProgressTracking source = _source(["A", "B"]) for setup in ( @@ -75,7 +77,7 @@ def test_producer_setup_runs_per_kept_database_without_re_filtering(self): "set_database_tags_map", ): setattr(source, setup, MagicMock()) - source.__dict__["_progress_registry"] = ProgressRegistry() + source.__dict__["_progress_tracking"] = ProgressTracking(ProgressMode.AUTO, "Test") with patch.object(snowflake_metadata, "filter_by_database", return_value=False): source._filtered_database_names() # warms the database names cache yielded = list(source.get_database_names()) @@ -87,7 +89,8 @@ def test_producer_setup_runs_per_kept_database_without_re_filtering(self): @pytest.fixture def snowflake_source(): """Minimal SnowflakeSource stub for push-totals tests.""" - from metadata.utils.progress_registry import ProgressRegistry + from metadata.ingestion.progress.modes import ProgressMode + from metadata.ingestion.progress.tracking import ProgressTracking source = object.__new__(SnowflakeSource) source.config = SimpleNamespace( @@ -102,7 +105,7 @@ def snowflake_source(): source.status = MagicMock() source.context = MagicMock() source.context.get.return_value = SimpleNamespace(database=None, database_service="svc") - source.__dict__["_progress_registry"] = ProgressRegistry() + source.__dict__["_progress_tracking"] = ProgressTracking(ProgressMode.AUTO, "Test") return source @@ -110,8 +113,8 @@ def test_declare_progress_totals_seeds_database_and_schema(snowflake_source): snowflake_source._filtered_database_names = lambda: ["db1", "db2"] snowflake_source._schema_names_by_database = lambda: {"db1": ["s1", "s2"], "db2": ["s3"]} snowflake_source._is_schema_filtered = lambda db, sch: False - snowflake_source._declare_progress_totals() - counters = {t: (d, total) for t, d, total in snowflake_source.progress.global_counters()} + snowflake_source.declare_progress_totals(TotalsDeclarer(snowflake_source.progress_tracking.registry)) + counters = {t: (d, total) for t, d, total in snowflake_source.progress_tracking.registry.global_counters()} assert counters["Database"] == (0, 2) assert counters["DatabaseSchema"] == (0, 3) @@ -120,16 +123,16 @@ def test_declare_progress_totals_applies_schema_filter(snowflake_source): snowflake_source._filtered_database_names = lambda: ["db1"] snowflake_source._schema_names_by_database = lambda: {"db1": ["keep", "drop"]} snowflake_source._is_schema_filtered = lambda db, sch: sch == "drop" - snowflake_source._declare_progress_totals() - counters = {t: (d, total) for t, d, total in snowflake_source.progress.global_counters()} + snowflake_source.declare_progress_totals(TotalsDeclarer(snowflake_source.progress_tracking.registry)) + counters = {t: (d, total) for t, d, total in snowflake_source.progress_tracking.registry.global_counters()} assert counters["DatabaseSchema"] == (0, 1) def test_declare_progress_totals_falls_back_when_account_show_unavailable(snowflake_source): snowflake_source._filtered_database_names = lambda: ["db1"] snowflake_source._schema_names_by_database = lambda: None - snowflake_source._declare_progress_totals() - assert snowflake_source.progress.is_reconcilable("DatabaseSchema") is True - counters = {t: (d, total) for t, d, total in snowflake_source.progress.global_counters()} + snowflake_source.declare_progress_totals(TotalsDeclarer(snowflake_source.progress_tracking.registry)) + assert snowflake_source.progress_tracking.registry.is_reconcilable("DatabaseSchema") is True + counters = {t: (d, total) for t, d, total in snowflake_source.progress_tracking.registry.global_counters()} assert counters["Database"] == (0, 1) assert counters["DatabaseSchema"] == (0, None) diff --git a/ingestion/tests/unit/source/database/test_snowflake_progress_path.py b/ingestion/tests/unit/source/database/test_snowflake_progress_path.py index db0aba64b405..538cf3c88a08 100644 --- a/ingestion/tests/unit/source/database/test_snowflake_progress_path.py +++ b/ingestion/tests/unit/source/database/test_snowflake_progress_path.py @@ -14,9 +14,10 @@ from types import SimpleNamespace from unittest.mock import MagicMock +from metadata.ingestion.progress.modes import ProgressMode +from metadata.ingestion.progress.registry import ProgressRegistry from metadata.ingestion.source.database import database_service from metadata.ingestion.source.database.snowflake import metadata as snowflake_metadata -from metadata.utils.progress_registry import ProgressRegistry class _ConcreteSource(database_service.DatabaseServiceSource): @@ -32,7 +33,7 @@ def _path_for(database, schema, entity_type_name): ctx = SimpleNamespace(database=database, database_schema=schema) source.context = MagicMock() source.context.get.return_value = ctx - return source.current_progress_path(entity_type_name) + return source.progress_tracker.current_path(entity_type_name) class TestSnowflakeProgressPath: @@ -65,14 +66,14 @@ def test_connector_references_no_count_constants(self): class TestProgressOptIn: - def test_database_family_is_off_by_default(self): - assert database_service.DatabaseServiceSource.progress_tracking_enabled is False + def test_database_family_is_auto_by_default(self): + assert database_service.DatabaseServiceSource.progress_mode is ProgressMode.AUTO - def test_concrete_db_source_inherits_off(self): - assert _ConcreteSource.progress_tracking_enabled is False + def test_concrete_db_source_inherits_auto(self): + assert _ConcreteSource.progress_mode is ProgressMode.AUTO - def test_snowflake_is_opted_in(self): - assert snowflake_metadata.SnowflakeSource.progress_tracking_enabled is True + def test_snowflake_is_auto(self): + assert snowflake_metadata.SnowflakeSource.progress_mode is ProgressMode.AUTO class TestStaleContextDoesNotStrandDatabases: @@ -83,7 +84,7 @@ class TestStaleContextDoesNotStrandDatabases: def _path(self, source, ctx, entity_type_name): source.context.get.return_value = ctx - return source.current_progress_path(entity_type_name) + return source.progress_tracker.current_path(entity_type_name) def test_second_database_completes_and_prunes(self): source = object.__new__(_ConcreteSource) diff --git a/ingestion/tests/unit/source/database/test_unitycatalog_progress_count.py b/ingestion/tests/unit/source/database/test_unitycatalog_progress_count.py new file mode 100644 index 000000000000..e7f320101280 --- /dev/null +++ b/ingestion/tests/unit/source/database/test_unitycatalog_progress_count.py @@ -0,0 +1,113 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Unity Catalog seeds ``Database`` + per-database ``DatabaseSchema`` progress +totals from a single cross-catalog ``system.information_schema.schemata``, and +reconciles when that view is unavailable.""" + +from types import SimpleNamespace +from unittest.mock import MagicMock, PropertyMock, patch + +import pytest + +from metadata.ingestion.progress.modes import ProgressMode, TotalsDeclarer +from metadata.ingestion.progress.tracking import ProgressTracking +from metadata.ingestion.source.database.unitycatalog import metadata as unitycatalog_metadata + +UnitycatalogSource = unitycatalog_metadata.UnitycatalogSource + + +@pytest.fixture +def unitycatalog_source(): + source = object.__new__(UnitycatalogSource) + source.source_config = SimpleNamespace( + useFqnForFiltering=False, + databaseFilterPattern=None, + schemaFilterPattern=None, + ) + source.metadata = MagicMock() + source.status = MagicMock() + source.context = MagicMock() + source.context.get.return_value = SimpleNamespace(database_service="svc") + source.__dict__["_progress_tracking"] = ProgressTracking(ProgressMode.AUTO, "Test") + return source + + +def _counters(source): + return {t: (done, total) for t, done, total in source.progress_tracking.registry.global_counters()} + + +def test_declare_progress_totals_seeds_database_and_schema(unitycatalog_source): + unitycatalog_source._filtered_database_names_for_totals = lambda: ["db1", "db2"] + unitycatalog_source._schema_names_by_database = lambda: {"db1": ["s1", "s2"], "db2": ["s3"]} + unitycatalog_source._is_schema_filtered = lambda db, sch: False + unitycatalog_source.declare_progress_totals(TotalsDeclarer(unitycatalog_source.progress_tracking.registry)) + counters = _counters(unitycatalog_source) + assert counters["Database"] == (0, 2) + assert counters["DatabaseSchema"] == (0, 3) + + +def test_declare_progress_totals_matches_catalog_case_insensitively(unitycatalog_source): + unitycatalog_source._filtered_database_names_for_totals = lambda: ["MyCatalog"] + unitycatalog_source._schema_names_by_database = lambda: {"mycatalog": ["s1", "s2"]} + unitycatalog_source._is_schema_filtered = lambda db, sch: False + unitycatalog_source.declare_progress_totals(TotalsDeclarer(unitycatalog_source.progress_tracking.registry)) + assert _counters(unitycatalog_source)["DatabaseSchema"] == (0, 2) + + +def test_declare_progress_totals_applies_schema_filter(unitycatalog_source): + unitycatalog_source._filtered_database_names_for_totals = lambda: ["db1"] + unitycatalog_source._schema_names_by_database = lambda: {"db1": ["keep", "drop"]} + unitycatalog_source._is_schema_filtered = lambda db, sch: sch == "drop" + unitycatalog_source.declare_progress_totals(TotalsDeclarer(unitycatalog_source.progress_tracking.registry)) + assert _counters(unitycatalog_source)["DatabaseSchema"] == (0, 1) + + +def test_declare_progress_totals_reconciles_when_view_unavailable(unitycatalog_source): + unitycatalog_source._filtered_database_names_for_totals = lambda: ["db1"] + unitycatalog_source._schema_names_by_database = lambda: None + unitycatalog_source.declare_progress_totals(TotalsDeclarer(unitycatalog_source.progress_tracking.registry)) + registry = unitycatalog_source.progress_tracking.registry + assert registry.is_reconcilable("DatabaseSchema") is True + counters = _counters(unitycatalog_source) + assert counters["Database"] == (0, 1) + assert counters["DatabaseSchema"] == (0, None) + + +def test_schema_names_by_database_groups_rows_and_returns_none_on_error(unitycatalog_source): + # `sql_connection` is a read-only property on UnitycatalogSource (no setter), + # so it must be patched at the class level rather than assigned on the instance. + mock_connection = MagicMock() + mock_connection.execute.return_value.fetchall.return_value = [ + ("db1", "s1"), + ("db1", "s2"), + ("db2", "s3"), + ] + with patch.object(UnitycatalogSource, "sql_connection", new_callable=PropertyMock) as mock_connection_property: + mock_connection_property.return_value = mock_connection + grouped = unitycatalog_source._schema_names_by_database() + assert grouped == {"db1": ["s1", "s2"], "db2": ["s3"]} + + mock_connection.execute.side_effect = Exception("permission denied on system.information_schema.schemata") + assert unitycatalog_source._schema_names_by_database() is None + + +def test_filtered_database_names_for_totals_uses_configured_database(unitycatalog_source): + unitycatalog_source.get_configured_database = lambda: "only_db" + unitycatalog_source.get_database_names_raw = MagicMock() + assert unitycatalog_source._filtered_database_names_for_totals() == ["only_db"] + unitycatalog_source.get_database_names_raw.assert_not_called() + + +def test_filtered_database_names_for_totals_filters_all_databases(unitycatalog_source): + unitycatalog_source.get_configured_database = lambda: None + unitycatalog_source.get_database_names_raw = lambda: iter(["keep", "drop"]) + unitycatalog_source._is_database_filtered = lambda db: db == "drop" + assert unitycatalog_source._filtered_database_names_for_totals() == ["keep"] diff --git a/ingestion/tests/unit/source/database/unitycatalog/test_connection.py b/ingestion/tests/unit/source/database/unitycatalog/test_connection.py index f2e6ae2b2463..257b4dc25bc7 100644 --- a/ingestion/tests/unit/source/database/unitycatalog/test_connection.py +++ b/ingestion/tests/unit/source/database/unitycatalog/test_connection.py @@ -8,10 +8,18 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Unit tests for the Unity Catalog BaseConnection wiring (non-Engine: WorkspaceClient).""" +"""Unit tests for the Unity Catalog BaseConnection wiring and test-connection checks.""" -from unittest.mock import patch +import socket +from unittest.mock import MagicMock, patch +import pytest +from databricks.sdk.errors import PermissionDenied, ResourceDoesNotExist, Unauthenticated + +from metadata.core.connections.lifetime import Borrowed +from metadata.core.connections.test_connection.check import CheckError, collect_checks +from metadata.core.connections.test_connection.checks.database import DatabaseStep +from metadata.core.connections.test_connection.network import NetworkUnreachableError from metadata.generated.schema.entity.services.connections.database.databricks.personalAccessToken import ( PersonalAccessToken, ) @@ -19,15 +27,53 @@ UnityCatalogConnection as UnityCatalogConnectionConfig, ) from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.source.database.unitycatalog.connection import UnityCatalogConnection +from metadata.ingestion.source.database.unitycatalog.connection import ( + LINEAGE_PROBE_COMMAND, + UNITY_CATALOG_ERRORS, + UnityCatalogChecks, + UnityCatalogConnection, + get_connection, + get_connection_url, +) CONNECTION_MODULE = "metadata.ingestion.source.database.unitycatalog.connection" +EXPECTED_STEPS = [ + DatabaseStep.CheckAccess, + DatabaseStep.GetDatabases, + DatabaseStep.GetSchemas, + DatabaseStep.GetTables, + DatabaseStep.GetViews, + DatabaseStep.GetQueries, + DatabaseStep.GetTags, +] + + +def _config(**overrides) -> UnityCatalogConnectionConfig: + defaults = { + "hostPort": "my-workspace.cloud.databricks.com:443", + "authType": PersonalAccessToken(token="dapi-secret"), + } + defaults.update(overrides) + return UnityCatalogConnectionConfig(**defaults) + + +def _named(name: str, **attributes) -> MagicMock: + mock = MagicMock(**attributes) + mock.name = name + return mock -def _config() -> UnityCatalogConnectionConfig: - return UnityCatalogConnectionConfig( - hostPort="test-host:443", - authType=PersonalAccessToken(token="test-token"), + +WAREHOUSE = {"httpPath": "/sql/1.0/warehouses/abc123"} + + +def _checks(client: MagicMock, sql: MagicMock | None = None, **config_overrides) -> UnityCatalogChecks: + """A provider over two borrowed clients: the workspace client and the + SQL-warehouse engine, each owned by its own connection.""" + return UnityCatalogChecks( + workspace=Borrowed.of(client), + sql=Borrowed.of(sql if sql is not None else MagicMock()), + service_connection=_config(**config_overrides), ) @@ -38,5 +84,335 @@ def test_unitycatalog_connection_is_base_connection(): def test_get_client_delegates_to_the_workspace_client_builder(): with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get_connection: client = UnityCatalogConnection(_config()).client + mock_get_connection.assert_called_once() assert client is mock_get_connection.return_value + + +def test_checks_exposes_the_provider_without_touching_the_network(): + with ( + patch(f"{CONNECTION_MODULE}.get_connection") as mock_get_connection, + patch(f"{CONNECTION_MODULE}.get_sqlalchemy_connection") as mock_engine, + ): + provider = UnityCatalogConnection(_config()).checks() + + assert isinstance(provider, UnityCatalogChecks) + # Neither client is built while the provider is assembled: both are borrowed. + mock_get_connection.assert_not_called() + mock_engine.assert_not_called() + + +def test_checks_borrow_the_clients_their_connections_own(): + with ( + patch(f"{CONNECTION_MODULE}.get_connection") as mock_get_connection, + patch(f"{CONNECTION_MODULE}.get_sqlalchemy_connection") as mock_engine, + ): + connection = UnityCatalogConnection(_config()) + provider = connection.checks() + + assert provider._workspace.client is connection.client + assert provider._sql.client is connection.sql.client + + # One workspace client, one engine - each built once, by its owner. + assert mock_get_connection.call_count == 1 + assert mock_engine.call_count == 1 + + +def test_sql_engine_is_never_built_when_no_warehouse_step_runs(): + # The lineage and tag steps need a SQL warehouse; a workspace configured + # without an httpPath must never pay for an engine it does not use. + with ( + patch(f"{CONNECTION_MODULE}.get_connection"), + patch(f"{CONNECTION_MODULE}.tcp_probe"), + patch(f"{CONNECTION_MODULE}.get_sqlalchemy_connection") as mock_engine, + ): + provider = UnityCatalogConnection(_config()).checks() + provider.check_access() + + mock_engine.assert_not_called() + + +def test_closing_the_connection_disposes_the_sql_engine(): + engine = MagicMock() + with ( + patch(f"{CONNECTION_MODULE}.get_connection"), + patch(f"{CONNECTION_MODULE}.get_sqlalchemy_connection", return_value=engine), + ): + connection = UnityCatalogConnection(_config()) + _ = connection.sql.client + connection.close() + + engine.dispose.assert_called_once_with() + + +def test_connection_timeout_drives_the_per_step_budget(): + with patch(f"{CONNECTION_MODULE}.get_connection"): + connection = UnityCatalogConnection(_config(connectionTimeout=300)) + + assert connection.step_timeout_seconds == 300 + + +def test_every_definition_step_resolves_to_a_check(): + resolved = collect_checks(_checks(MagicMock())) + + assert sorted(resolved) == sorted(EXPECTED_STEPS) + + +class TestHostNormalization: + # The probe, the WorkspaceClient, and the SQLAlchemy URL must all derive the same + # host, so a pasted workspace URL resolves consistently instead of one path seeing + # a mangled value. + @pytest.mark.parametrize( + "host_port", + [ + "https://my-workspace.cloud.databricks.com", + "https://my-workspace.cloud.databricks.com/sql/1.0/warehouses/abc", + "my-workspace.cloud.databricks.com", + ], + ) + def test_workspace_client_host_is_normalized(self, host_port): + with patch(f"{CONNECTION_MODULE}.WorkspaceClient") as mock_client: + get_connection(_config(hostPort=host_port)) + + assert mock_client.call_args.kwargs["host"] == "my-workspace.cloud.databricks.com" + + def test_connection_url_normalizes_the_host(self): + url = get_connection_url(_config(hostPort="https://my-workspace.cloud.databricks.com/sql/x")) + + assert "://my-workspace.cloud.databricks.com" in url + assert "https://" not in url.split("://", 1)[1] + + +class TestCheckAccess: + def test_probes_the_host_before_listing_catalogs(self): + client = MagicMock() + with patch(f"{CONNECTION_MODULE}.tcp_probe") as mock_probe: + evidence = _checks(client).check_access() + + mock_probe.assert_called_once_with("my-workspace.cloud.databricks.com", 443) + assert evidence.summary == "connection established" + assert evidence.command == "catalogs.list()" + + def test_defaults_to_port_443_when_host_port_omits_the_port(self): + with patch(f"{CONNECTION_MODULE}.tcp_probe") as mock_probe: + _checks(MagicMock(), hostPort="my-workspace.cloud.databricks.com").check_access() + + mock_probe.assert_called_once_with("my-workspace.cloud.databricks.com", 443) + + @pytest.mark.parametrize( + "host_port", + [ + "https://my-workspace.cloud.databricks.com", + "https://my-workspace.cloud.databricks.com/sql/1.0/warehouses/abc", + "my-workspace.cloud.databricks.com", + ], + ) + def test_normalizes_a_pasted_workspace_url_before_probing(self, host_port): + with patch(f"{CONNECTION_MODULE}.tcp_probe") as mock_probe: + _checks(MagicMock(), hostPort=host_port).check_access() + + mock_probe.assert_called_once_with("my-workspace.cloud.databricks.com", 443) + + def test_unreachable_host_fails_before_the_client_is_used(self): + client = MagicMock() + with ( + patch(f"{CONNECTION_MODULE}.tcp_probe", side_effect=NetworkUnreachableError("down")), + pytest.raises(CheckError) as failure, + ): + _checks(client).check_access() + + assert failure.value.evidence.command == "TCP connect my-workspace.cloud.databricks.com:443" + client.catalogs.list.assert_not_called() + + def test_rejected_credentials_surface_as_a_check_error_with_the_command(self): + client = MagicMock() + client.catalogs.list.side_effect = Unauthenticated("invalid access token") + with patch(f"{CONNECTION_MODULE}.tcp_probe"), pytest.raises(CheckError) as failure: + _checks(client).check_access() + + assert failure.value.evidence.command == "catalogs.list()" + assert isinstance(failure.value.cause, Unauthenticated) + + +class TestMetadataSteps: + def test_get_databases_resolves_the_first_non_internal_catalog(self): + client = MagicMock() + client.catalogs.list.return_value = iter([_named("__databricks_internal"), _named("main")]) + checks = _checks(client) + + evidence = checks.check_databases() + + assert checks.table_obj.catalog_name == "main" + assert evidence.command == "catalogs.list()" + assert evidence.summary == "catalog 'main' resolved" + + def test_get_databases_validates_the_configured_catalog(self): + client = MagicMock() + client.catalogs.get.return_value = _named("my_catalog") + checks = _checks(client, catalog="my_catalog") + + evidence = checks.check_databases() + + client.catalogs.get.assert_called_once_with("my_catalog") + client.catalogs.list.assert_not_called() + assert evidence.command == "catalogs.get('my_catalog')" + + def test_get_schemas_validates_the_configured_schema(self): + client = MagicMock() + client.schemas.get.return_value = _named("my_schema") + checks = _checks(client, databaseSchema="my_schema") + checks.table_obj.catalog_name = "my_catalog" + + evidence = checks.check_schemas() + + client.schemas.get.assert_called_once_with("my_catalog.my_schema") + assert evidence.command == "schemas.get('my_schema')" + assert evidence.summary == "schema 'my_schema' resolved" + + def test_get_tables_reports_the_resolved_scope(self): + client = MagicMock() + client.tables.list.return_value = iter([_named("orders")]) + checks = _checks(client) + checks.table_obj.catalog_name = "my_catalog" + checks.table_obj.schema_name = "my_schema" + + evidence = checks.check_tables() + + assert evidence.summary == "tables enumerated in 'my_catalog.my_schema'" + assert evidence.command == "tables.list()" + + def test_get_views_carries_the_command_when_the_scope_is_unresolved(self): + client = MagicMock() + + with pytest.raises(CheckError) as failure: + _checks(client).check_views() + + assert failure.value.evidence.command == "tables.list(omit_columns=True)" + client.tables.list.assert_not_called() + + +class TestWarehouseSteps: + def test_get_queries_reads_the_borrowed_engine(self): + engine = MagicMock() + with patch(f"{CONNECTION_MODULE}.read_lineage_tables") as mock_lineage: + checks = _checks(MagicMock(), sql=engine, **WAREHOUSE) + evidence = checks.check_queries() + + mock_lineage.assert_called_once_with(engine) + # The engine belongs to UnityCatalogSqlConnection: the check never disposes it. + engine.dispose.assert_not_called() + assert evidence.summary == "lineage tables accessible" + + def test_get_queries_wraps_a_probe_failure_as_check_error(self): + engine = MagicMock() + with ( + patch(f"{CONNECTION_MODULE}.read_lineage_tables", side_effect=PermissionDenied("PERMISSION_DENIED")), + pytest.raises(CheckError), + ): + _checks(MagicMock(), sql=engine, **WAREHOUSE).check_queries() + + engine.dispose.assert_not_called() + + def test_get_tags_probes_the_information_schema_tag_tables(self): + engine = MagicMock() + with patch(f"{CONNECTION_MODULE}.read_tag_tables") as mock_tags: + checks = _checks(MagicMock(), sql=engine, **WAREHOUSE) + evidence = checks.check_tags() + + mock_tags.assert_called_once_with(engine, checks.table_obj) + assert evidence.summary == "tag tables accessible" + + +class TestErrorPack: + @pytest.mark.parametrize( + ("error", "expected_title"), + [ + (Unauthenticated("workspace rejected the request"), "Authentication failed"), + (RuntimeError("Invalid access token."), "Authentication failed"), + (RuntimeError("the token is expired"), "Access token expired"), + (PermissionDenied("no grants"), "Insufficient privileges"), + (RuntimeError("PERMISSION_DENIED: user lacks USE CATALOG"), "Insufficient privileges"), + (RuntimeError("INSUFFICIENT_PERMISSIONS"), "Insufficient privileges"), + (ResourceDoesNotExist("catalog my_catalog"), "Object not found"), + (RuntimeError("NO_SUCH_CATALOG: my_catalog"), "Catalog not found"), + (RuntimeError("NO_SUCH_SCHEMA: my_schema"), "Schema not found"), + (RuntimeError("TABLE_OR_VIEW_NOT_FOUND: my_table"), "Table or view not found"), + (RuntimeError("MALFORMED_REQUEST: bad http path"), "Invalid HTTP path"), + (RuntimeError("No valid connection settings."), "SQL warehouse not configured"), + ( + RuntimeError("[FAILED_JDBC.CONNECTION] ... Failed to connect to the database. SQLSTATE: HV000"), + "SQL warehouse not reachable", + ), + (RuntimeError("Table system.access.table_lineage does not exist"), "Object not found"), + ], + ) + def test_maps_unity_catalog_errors_to_a_diagnosis(self, error, expected_title): + diagnosis = UNITY_CATALOG_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == expected_title + assert diagnosis.remediation + + def test_folds_in_the_shared_network_pack(self): + diagnosis = UNITY_CATALOG_ERRORS.classify(NetworkUnreachableError("host:443 is not reachable")) + + assert diagnosis is not None + assert diagnosis.title == "Cannot reach the host" + + def test_unresolvable_host_is_a_dns_diagnosis(self): + diagnosis = UNITY_CATALOG_ERRORS.classify(socket.gaierror("nodename nor servname provided")) + + assert diagnosis is not None + assert diagnosis.title == "Host could not be resolved" + + def test_an_unmatched_error_is_left_unclassified(self): + assert UNITY_CATALOG_ERRORS.classify(RuntimeError("something else entirely")) is None + + +def test_closing_disposes_the_sql_engine_on_every_reuse_cycle(): + # close() resets the teardown registry, so a sub-owner registered once in + # __init__ would leak its engine on the second cycle. + engines = [MagicMock(), MagicMock()] + with ( + patch(f"{CONNECTION_MODULE}.get_connection"), + patch(f"{CONNECTION_MODULE}.get_sqlalchemy_connection", side_effect=engines), + ): + connection = UnityCatalogConnection(_config()) + _ = connection.sql.client + connection.close() + _ = connection.sql.client + connection.close() + + for engine in engines: + engine.dispose.assert_called_once_with() + + +class TestNoWarehouseConfigured: + def test_get_queries_fails_without_building_an_engine(self): + with patch(f"{CONNECTION_MODULE}.get_sqlalchemy_connection") as mock_engine: + checks = _checks(MagicMock(), httpPath=None) + + with pytest.raises(CheckError) as exc_info: + checks.check_queries() + + mock_engine.assert_not_called() + assert exc_info.value.evidence.command == LINEAGE_PROBE_COMMAND + + def test_get_tags_fails_without_building_an_engine(self): + with patch(f"{CONNECTION_MODULE}.get_sqlalchemy_connection") as mock_engine: + checks = _checks(MagicMock(), httpPath=None) + + with pytest.raises(CheckError): + checks.check_tags() + + mock_engine.assert_not_called() + + def test_the_missing_warehouse_is_still_diagnosed(self): + checks = _checks(MagicMock(), httpPath=None) + + with pytest.raises(CheckError) as exc_info: + checks.check_queries() + + diagnosis = UNITY_CATALOG_ERRORS.classify(exc_info.value.cause) + assert diagnosis is not None + assert diagnosis.title == "SQL warehouse not configured" diff --git a/ingestion/tests/unit/source/pipeline/airflow/test_connection.py b/ingestion/tests/unit/source/pipeline/airflow/test_connection.py index db7966bef777..4f74781af2f7 100644 --- a/ingestion/tests/unit/source/pipeline/airflow/test_connection.py +++ b/ingestion/tests/unit/source/pipeline/airflow/test_connection.py @@ -8,16 +8,46 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Unit tests for Airflow connection handling.""" +"""Unit tests for Airflow connection handling and its test-connection checks.""" from unittest.mock import MagicMock, patch +import pytest +from requests.exceptions import ConnectionError as RequestsConnectionError +from requests.exceptions import HTTPError, JSONDecodeError, SSLError, Timeout +from sqlalchemy import create_engine +from sqlalchemy.engine import Engine +from sqlalchemy.exc import OperationalError + +from metadata.core.connections.lifetime import Borrowed +from metadata.core.connections.test_connection import collect_checks +from metadata.core.connections.test_connection.check import CheckError +from metadata.core.connections.test_connection.checks.pipeline import PipelineStep +from metadata.core.connections.test_connection.network import NetworkUnreachableError from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.source.pipeline.airflow.connection import AirflowConnection +from metadata.ingestion.source.pipeline.airflow.api.client import AirflowApiClient +from metadata.ingestion.source.pipeline.airflow.connection import ( + AIRFLOW_ERRORS, + AirflowChecks, + AirflowConnection, +) CONNECTION_MODULE = "metadata.ingestion.source.pipeline.airflow.connection" +def _rest_client(host="https://airflow.example.com:8080"): + client = MagicMock(spec=AirflowApiClient) + client.mwaa_client = None + client.config = MagicMock() + client.config.hostPort = host + client.config.connection = MagicMock(authConfig=None, verifySSL=True) + return client + + +def _rest_checks(client): + return AirflowChecks(Borrowed.of(client)) + + def test_airflow_connection_is_base_connection(): assert issubclass(AirflowConnection, BaseConnection) @@ -31,10 +61,201 @@ def test_get_client_delegates_to_get_connection(): mock_get.assert_called_once_with(conn.service_connection) -def test_test_connection_runs_steps(): - conn = AirflowConnection(MagicMock()) - conn._client = MagicMock() - with patch(f"{CONNECTION_MODULE}.test_connection") as mock_step: - result = conn.test_connection(metadata=MagicMock()) +def test_client_is_built_once_and_cached(): + with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: + conn = AirflowConnection(MagicMock()) + first = conn.client + second = conn.client + + assert first is second + mock_get.assert_called_once() + + +def test_engine_client_registers_dispose(): + engine = MagicMock(spec=Engine) + with patch(f"{CONNECTION_MODULE}.get_connection", return_value=engine): + conn = AirflowConnection(MagicMock()) + _ = conn.client + conn.close() + + engine.dispose.assert_called_once() + + +def test_checks_expose_every_step(): + with patch(f"{CONNECTION_MODULE}.get_connection"): + resolved = collect_checks(AirflowConnection(MagicMock()).checks()) + + assert set(resolved) == { + PipelineStep.CheckAccess, + PipelineStep.PipelineDetailsAccess, + PipelineStep.TaskDetailAccess, + } + + +def test_checks_borrow_the_connection_client(): + """The provider borrows the client BaseConnection owns, rather than building a + second one behind its back.""" + with patch(f"{CONNECTION_MODULE}.get_connection") as mock_get: + conn = AirflowConnection(MagicMock()) + provider = conn.checks() + + assert provider.client is conn.client + mock_get.assert_called_once() + + +# ── REST path ──────────────────────────────────────────────────────────────── + + +@patch(f"{CONNECTION_MODULE}.tcp_probe") +def test_rest_check_access_reads_the_version(_mock_probe): + client = _rest_client() + client.get_version.return_value = {"version": "2.9.0"} + + evidence = _rest_checks(client).check_access() + + client.get_version.assert_called_once_with() + assert evidence.summary == "authenticated" + + +@patch(f"{CONNECTION_MODULE}.tcp_probe") +def test_rest_check_access_failure_reports_a_check_error(_mock_probe): + client = _rest_client() + client.get_version.side_effect = RuntimeError("transport closed") + + with ( + patch( + "metadata.ingestion.source.pipeline.airflow.api.diagnostics.diagnose", + return_value=None, + ), + pytest.raises(CheckError) as failure, + ): + _rest_checks(client).check_access() + + assert failure.value.evidence.command == "read the Airflow REST API version" + + +@patch(f"{CONNECTION_MODULE}.tcp_probe", side_effect=NetworkUnreachableError("10.0.0.1:8080 is not reachable")) +def test_rest_gate_preflights_an_unreachable_host(_mock_probe): + """An unreachable host fails fast at the TCP preflight instead of waiting out + the REST client's connect-retry budget; get_version is never called.""" + client = _rest_client(host="http://10.0.0.1:8080") + + with pytest.raises(CheckError) as failure: + _rest_checks(client).check_access() + + assert failure.value.evidence.command == "TCP connect 10.0.0.1:8080" + client.get_version.assert_not_called() + assert AIRFLOW_ERRORS.classify(failure.value.cause).title == "Cannot reach the host" + + +@patch(f"{CONNECTION_MODULE}.tcp_probe") +def test_rest_gate_skips_preflight_for_mwaa(mock_probe): + """MWAA reaches Airflow through the AWS SDK, not a socket to the host, so the + preflight must not run for it.""" + client = _rest_client() + client.mwaa_client = MagicMock() + client.get_version.return_value = {"version": "2.9.0"} + + _rest_checks(client).check_access() + + mock_probe.assert_not_called() + + +def test_rest_pipeline_details_lists_one_dag(): + client = _rest_client() + + evidence = _rest_checks(client).pipeline_details_access() + + client.list_dags.assert_called_once_with(limit=1) + assert evidence.summary == "authenticated" + + +def test_rest_task_detail_access_is_a_noop_pass(): + client = _rest_client() + + evidence = _rest_checks(client).task_detail_access() + + assert "per-DAG" in evidence.summary + + +# ── Backend (metadata-DB) path ─────────────────────────────────────────────── + + +def test_backend_check_access_pings_the_engine(): + engine = create_engine("sqlite://") + + evidence = AirflowChecks(Borrowed.of(engine)).check_access() + + assert evidence.summary == "connection established" + + +def test_backend_step_reports_success(): + engine = create_engine("sqlite://") + checks = AirflowChecks(Borrowed.of(engine)) + + evidence = checks._backend_step(lambda session: None, command="SELECT 1", summary="ok") + + assert evidence.summary == "ok" + assert evidence.command == "SELECT 1" + + +def test_backend_step_wraps_failures_in_a_check_error(): + engine = create_engine("sqlite://") + checks = AirflowChecks(Borrowed.of(engine)) + + def boom(_session): + raise RuntimeError("no such table: serialized_dag") + + with pytest.raises(CheckError) as failure: + checks._backend_step(boom, command="SELECT dag_id", summary="ok") + + assert failure.value.evidence.command == "SELECT dag_id" + + +# ── Error pack ─────────────────────────────────────────────────────────────── + + +def _http_error(status_code): + error = HTTPError(f"{status_code}") + error.response = MagicMock(status_code=status_code) + return error + + +@pytest.mark.parametrize( + ("error", "title"), + [ + (_http_error(401), "Authentication failed"), + (_http_error(403), "Access denied"), + (_http_error(404), "Endpoint not found"), + (JSONDecodeError("Expecting value", "", 0), "Host is not the Airflow REST API"), + (SSLError("certificate verify failed"), "TLS verification failed"), + (Timeout("timed out"), "Connection timed out"), + (RequestsConnectionError("name resolution failed"), "Cannot reach the host"), + ( + OperationalError("SELECT 1", {}, Exception("Access denied for user 'airflow'@'%'")), + "Database authentication failed", + ), + ( + OperationalError("SELECT 1", {}, Exception('password authentication failed for user "airflow"')), + "Database authentication failed", + ), + ], +) +def test_error_pack_diagnoses_known_failures(error, title): + diagnosis = AIRFLOW_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == title + assert diagnosis.remediation + + +def test_db_matcher_ignores_a_rest_error_carrying_the_same_words(): + """A REST/transport error with no SQLAlchemy in its chain must not be diagnosed + as a database problem just because its message says 'access denied'.""" + rest_error = RuntimeError("Access denied by the upstream proxy") + + assert AIRFLOW_ERRORS.classify(rest_error) is None + - assert result is mock_step.return_value +def test_error_pack_leaves_an_unknown_error_unclassified(): + assert AIRFLOW_ERRORS.classify(ValueError("something else")) is None diff --git a/ingestion/tests/unit/source/pipeline/dbtcloud/test_connection.py b/ingestion/tests/unit/source/pipeline/dbtcloud/test_connection.py index cf1f76517669..64b028591466 100644 --- a/ingestion/tests/unit/source/pipeline/dbtcloud/test_connection.py +++ b/ingestion/tests/unit/source/pipeline/dbtcloud/test_connection.py @@ -8,16 +8,42 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Unit tests for dbt Cloud connection handling.""" +"""Unit tests for dbt Cloud connection handling and its test-connection checks.""" from unittest.mock import MagicMock, patch +import pytest +from requests.exceptions import ConnectionError as RequestsConnectionError +from requests.exceptions import JSONDecodeError, ReadTimeout, SSLError + +from metadata.core.connections.lifetime import Borrowed +from metadata.core.connections.test_connection import collect_checks +from metadata.core.connections.test_connection.check import CheckError +from metadata.core.connections.test_connection.checks.pipeline import PipelineStep from metadata.ingestion.connections.connection import BaseConnection -from metadata.ingestion.source.pipeline.dbtcloud.connection import DBTCloudConnection +from metadata.ingestion.source.pipeline.dbtcloud.client import ( + TEST_RETRY_WAIT_SECONDS, + DBTCloudApiError, +) +from metadata.ingestion.source.pipeline.dbtcloud.connection import ( + DBTCLOUD_ERRORS, + DBTCloudChecks, + DBTCloudConnection, +) CONNECTION_MODULE = "metadata.ingestion.source.pipeline.dbtcloud.connection" +@pytest.fixture +def client(): + return MagicMock() + + +@pytest.fixture +def checks(client): + return DBTCloudChecks(dbt=Borrowed.of(client)) + + def test_dbtcloud_connection_is_base_connection(): assert issubclass(DBTCloudConnection, BaseConnection) @@ -25,16 +51,193 @@ def test_dbtcloud_connection_is_base_connection(): def test_get_client_builds_the_client(): with patch(f"{CONNECTION_MODULE}.DBTCloudClient") as mock_builder: conn = DBTCloudConnection(MagicMock()) - client = conn.client + built = conn.client - assert client is mock_builder.return_value + assert built is mock_builder.return_value mock_builder.assert_called_once() -def test_test_connection_runs_steps(): - conn = DBTCloudConnection(MagicMock()) - conn._client = MagicMock() - with patch(f"{CONNECTION_MODULE}.test_connection_steps") as mock_step: - result = conn.test_connection(metadata=MagicMock()) +def test_checks_expose_every_step(): + with patch(f"{CONNECTION_MODULE}.DBTCloudClient"): + resolved = collect_checks(DBTCloudConnection(MagicMock()).checks()) + + assert set(resolved) == { + PipelineStep.CheckAccess, + PipelineStep.GetJobs, + PipelineStep.GetRuns, + } + + +def test_checks_borrow_the_connection_client(): + """The provider borrows the client BaseConnection owns, rather than opening a + second one behind its back.""" + with patch(f"{CONNECTION_MODULE}.DBTCloudClient") as mock_builder: + conn = DBTCloudConnection(MagicMock()) + provider = conn.checks() + + assert provider._dbt.client is conn.client + mock_builder.assert_called_once() + + +def test_check_access_proves_the_account_is_readable(checks, client): + evidence = checks.check_access() + + client.test_check_access.assert_called_once_with() + assert evidence.summary == "authenticated" + assert evidence.command == "read one job of the configured account" + + +def test_get_jobs_counts_the_jobs(checks, client): + client.test_get_jobs.return_value = [MagicMock(), MagicMock()] + + evidence = checks.get_jobs() + + assert evidence.summary == "2 jobs enumerated" + assert evidence.caveat is None + + +def test_get_jobs_caveats_an_account_with_no_jobs(checks, client): + client.test_get_jobs.return_value = [] + + evidence = checks.get_jobs() + + assert evidence.summary == "0 jobs enumerated" + assert evidence.caveat is not None + assert evidence.caveat.title == "No jobs visible" + + +def test_get_runs_counts_the_runs(checks, client): + client.test_get_runs.return_value = [MagicMock()] + + evidence = checks.get_runs() + + assert evidence.summary == "1 run enumerated" + + +def test_a_failed_check_still_reports_what_it_ran(checks, client): + client.test_get_runs.side_effect = DBTCloudApiError(403, "/accounts/1/runs/", "forbidden") + + with pytest.raises(CheckError) as failure: + checks.get_runs() + + assert failure.value.evidence.command == "fetch the runs of the account" + assert failure.value.cause is client.test_get_runs.side_effect + + +# The bodies dbt Cloud really answers with, captured against the live API: a wrong +# account id is a 403, never a 404. +NOT_SCOPED_BODY = ( + '{"status": {"code": 403, "is_success": false, ' + '"user_message": "Access denied: Token is not scoped to account.", "developer_message": null}, "data": null}' +) +INVALID_TOKEN_BODY = ( + '{"status": {"code": 401, "is_success": false, ' + '"user_message": "Invalid token.", "developer_message": null}, "data": null}' +) + + +@pytest.mark.parametrize( + ("error", "title"), + [ + ( + DBTCloudApiError(403, "/accounts/99999/jobs/", NOT_SCOPED_BODY), + "Token is not scoped to this account", + ), + (DBTCloudApiError(401, "/accounts/1/jobs/", INVALID_TOKEN_BODY), "Authentication failed"), + (DBTCloudApiError(403, "/accounts/1/jobs/", "forbidden"), "Access denied"), + (DBTCloudApiError(404, "/accounts/1/jobs/", "not found"), "Endpoint not found"), + (DBTCloudApiError(429, "/accounts/1/jobs/", "too many requests"), "Rate limited"), + (JSONDecodeError("Expecting value", "", 0), "Host is not the dbt Cloud API"), + (SSLError("certificate verify failed"), "TLS verification failed"), + (ReadTimeout("timed out"), "Connection timed out"), + (RequestsConnectionError("name resolution failed"), "Cannot reach the host"), + ], +) +def test_error_pack_diagnoses_known_failures(error, title): + diagnosis = DBTCLOUD_ERRORS.classify(error) + + assert diagnosis is not None + assert diagnosis.title == title + assert diagnosis.remediation + + +def test_error_pack_diagnoses_a_status_wrapped_by_a_check_error(): + """The runner classifies the cause of a CheckError, but a connector error can + also surface wrapped; the matcher walks the chain either way.""" + cause = DBTCloudApiError(401, "/accounts/1/jobs/", "unauthorized") + wrapped = RuntimeError("step failed") + wrapped.__cause__ = cause + + assert DBTCLOUD_ERRORS.classify(wrapped).title == "Authentication failed" + + +def test_error_pack_leaves_an_unknown_error_unclassified(): + assert DBTCLOUD_ERRORS.classify(ValueError("something else")) is None + + +CLIENT_MODULE = "metadata.ingestion.source.pipeline.dbtcloud.client" + + +def _dbtcloud_client(host="https://cloud.getdbt.com", account_id=1): + with patch(f"{CLIENT_MODULE}.TrackedREST"): + from metadata.ingestion.source.pipeline.dbtcloud.client import DBTCloudClient + + config = MagicMock() + config.host = host + config.accountId = account_id + config.token.get_secret_value.return_value = "secret-token" + + return DBTCloudClient(config) + + +def test_test_check_access_reads_a_single_job(): + client = _dbtcloud_client() + client.client.get_raw.return_value.ok = True + client.client.get_raw.return_value.json.return_value = {"data": []} + + client.test_check_access() + + call = client.client.get_raw.call_args + assert call[0][0] == "/accounts/1/jobs/" + assert call[1]["data"] == {"limit": 1, "offset": 0} + assert call[1]["retry_wait"] == TEST_RETRY_WAIT_SECONDS + + +def test_the_test_calls_reuse_the_shared_client(): + """They go through the owned REST client's get_raw, not a second session, so + they inherit its session, auth and retry adapter.""" + client = _dbtcloud_client() + client.client.get_raw.return_value.ok = True + client.client.get_raw.return_value.json.return_value = {} + + client.test_check_access() + + client.client.get_raw.assert_called_once() + + +def test_a_rejected_token_surfaces_its_http_status(): + """A dbt Cloud error body nests its code under `status`; the status must still + reach the error pack, or a bad token reads as an opaque validation error.""" + client = _dbtcloud_client() + client.client.get_raw.return_value.ok = False + client.client.get_raw.return_value.status_code = 401 + client.client.get_raw.return_value.text = INVALID_TOKEN_BODY + + with pytest.raises(DBTCloudApiError) as failure: + client.test_get_jobs() + + assert failure.value.status_code == 401 + assert DBTCLOUD_ERRORS.classify(failure.value).title == "Authentication failed" + + +def test_a_host_that_is_not_the_api_is_diagnosed(): + """A valid URL that is not the dbt Cloud API redirects to an HTML page, which + answers 200 and fails to decode.""" + client = _dbtcloud_client(host="https://www.getdbt.com") + client.client.get_raw.return_value.ok = True + client.client.get_raw.return_value.json.side_effect = JSONDecodeError("Expecting value", "", 0) + + with pytest.raises(JSONDecodeError) as failure: + client.test_get_jobs() - assert result is mock_step.return_value + assert DBTCLOUD_ERRORS.classify(failure.value).title == "Host is not the dbt Cloud API" diff --git a/ingestion/tests/unit/source/storage/s3/test_connection.py b/ingestion/tests/unit/source/storage/s3/test_connection.py index 8785bb42f4b2..82ee3cd9e889 100644 --- a/ingestion/tests/unit/source/storage/s3/test_connection.py +++ b/ingestion/tests/unit/source/storage/s3/test_connection.py @@ -17,6 +17,7 @@ import pytest from botocore.exceptions import ClientError, EndpointConnectionError, NoCredentialsError +from metadata.core.connections.lifetime import Borrowed from metadata.core.connections.test_connection.check import CheckError, collect_checks from metadata.core.connections.test_connection.checks.storage import list_buckets from metadata.ingestion.connections.connection import BaseConnection @@ -34,7 +35,7 @@ def _checks(client=None, bucket_names=None): - return S3Checks(connect=lambda: client, bucket_names=bucket_names) + return S3Checks(store=Borrowed.of(client), bucket_names=bucket_names) def _check_names(): @@ -164,13 +165,14 @@ def test_error_pack_signature_mismatch(): def test_error_pack_unrecognized_client(): diagnosis = S3_ERRORS.classify(_client_error("UnrecognizedClientException", "ListMetrics")) assert diagnosis is not None - assert "not recognized" in diagnosis.title.lower() + assert diagnosis.title == "AWS access key not recognized" def test_error_pack_invalid_client_token(): + # STS's code for an unknown access key ID. diagnosis = S3_ERRORS.classify(_client_error("InvalidClientTokenId", "ListBuckets")) assert diagnosis is not None - assert "security token" in diagnosis.title.lower() + assert diagnosis.title == "AWS access key not recognized" def test_error_pack_expired_token(): diff --git a/ingestion/tests/unit/test_connection_builders.py b/ingestion/tests/unit/test_connection_builders.py index b5ac9dde1dc7..c57f2bcb01e3 100644 --- a/ingestion/tests/unit/test_connection_builders.py +++ b/ingestion/tests/unit/test_connection_builders.py @@ -21,6 +21,8 @@ MysqlConnection, ) from metadata.ingestion.connections.builders import ( + _dialect_supports_autocommit, + create_generic_db_connection, get_connection_args_common, get_connection_options_dict, init_empty_connection_arguments, @@ -78,3 +80,50 @@ def test_init_empty_connection_arguments(self): self.assertEqual(new_args.root.get("hello"), "world") self.assertIsNone(new_args.root.get("not there")) + + +class FakeDialectWithAutocommit: + def get_isolation_level_values(self, dbapi_conn): + return ("READ COMMITTED", "AUTOCOMMIT") + + +class FakeDialectNoAutocommit: + def get_isolation_level_values(self, dbapi_conn): + return ("READ COMMITTED",) + + +class FakeDialectRaises: + def get_isolation_level_values(self, dbapi_conn): + raise NotImplementedError("dialect has no isolation levels") + + +def test_dialect_supports_autocommit_true(): + assert _dialect_supports_autocommit(FakeDialectWithAutocommit()) is True + + +def test_dialect_supports_autocommit_false_when_absent(): + assert _dialect_supports_autocommit(FakeDialectNoAutocommit()) is False + + +def test_dialect_supports_autocommit_false_when_raises(): + assert _dialect_supports_autocommit(FakeDialectRaises()) is False + + +def test_create_generic_db_connection_applies_autocommit(): + engine = create_generic_db_connection( + connection=object(), + get_connection_url_fn=lambda _conn: "sqlite://", + get_connection_args_fn=lambda _conn: {}, + ) + assert engine.get_execution_options().get("isolation_level") == "AUTOCOMMIT" + + +def test_create_generic_db_connection_respects_explicit_isolation_level(): + engine = create_generic_db_connection( + connection=object(), + get_connection_url_fn=lambda _conn: "sqlite://", + get_connection_args_fn=lambda _conn: {}, + isolation_level="SERIALIZABLE", + ) + with engine.connect() as conn: + assert conn.get_isolation_level() == "SERIALIZABLE" diff --git a/ingestion/tests/unit/test_dbt.py b/ingestion/tests/unit/test_dbt.py index 9a7ad7bc3eea..63524f8a3050 100644 --- a/ingestion/tests/unit/test_dbt.py +++ b/ingestion/tests/unit/test_dbt.py @@ -3462,8 +3462,7 @@ def test_compiled_only_empty_message_is_skipped(self): def test_real_pass_result_is_ingested(self): """ - Real test pass: status=pass, message="Pass". - Must call add_test_case_results exactly once. + Real test pass: status=pass. Ingested, but result stays None (#29645). """ from metadata.ingestion.source.database.dbt.constants import DbtCommonEnum @@ -3483,6 +3482,8 @@ def test_real_pass_result_is_ingested(self): source.add_dbt_test_result(dbt_test) source.metadata.add_test_case_results.assert_called_once() + test_case_result = source.metadata.add_test_case_results.call_args.kwargs["test_results"] + self.assertIsNone(test_case_result.result) def test_real_failure_result_is_ingested(self): """ @@ -3511,6 +3512,8 @@ def test_real_failure_result_is_ingested(self): source.add_dbt_test_result(dbt_test) source.metadata.add_test_case_results.assert_called_once() + test_case_result = source.metadata.add_test_case_results.call_args.kwargs["test_results"] + self.assertEqual(test_case_result.result, "Got 3 results, configured to fail if != 0") def test_real_warn_result_is_ingested(self): """ @@ -3539,6 +3542,8 @@ def test_real_warn_result_is_ingested(self): source.add_dbt_test_result(dbt_test) source.metadata.add_test_case_results.assert_called_once() + test_case_result = source.metadata.add_test_case_results.call_args.kwargs["test_results"] + self.assertEqual(test_case_result.result, "Got 1 result, configured to warn if != 0") class TestRemoveManifestNonRequiredKeys(TestCase): diff --git a/ingestion/tests/unit/test_filter_pattern.py b/ingestion/tests/unit/test_filter_pattern.py index b903901e54f7..34ec212261ad 100644 --- a/ingestion/tests/unit/test_filter_pattern.py +++ b/ingestion/tests/unit/test_filter_pattern.py @@ -22,6 +22,7 @@ filter_by_classifications, filter_by_dashboard, filter_by_fqn, + filter_pattern_enabled, validate_regex, ) @@ -45,6 +46,16 @@ def test_filter(): assert _filter(filter_pattern_both, "potato_tomato") +def test_filter_pattern_enabled(): + """A pattern is enabled only when includes or excludes are configured""" + assert filter_pattern_enabled(None) is False + assert filter_pattern_enabled(FilterPattern()) is False + assert filter_pattern_enabled(FilterPattern(includes=[])) is False + assert filter_pattern_enabled(FilterPattern(excludes=[])) is False + assert filter_pattern_enabled(FilterPattern(includes=["^keep$"])) is True + assert filter_pattern_enabled(FilterPattern(excludes=["^skip$"])) is True + + def test_filter_by_classifications(): """An entity is matched against the full set of its tags: a single matching include tag keeps it, a single matching exclude tag drops it, and exclude diff --git a/ingestion/tests/unit/test_handle_partitions.py b/ingestion/tests/unit/test_handle_partitions.py index 79752410301c..f2277e17d036 100644 --- a/ingestion/tests/unit/test_handle_partitions.py +++ b/ingestion/tests/unit/test_handle_partitions.py @@ -164,7 +164,7 @@ class BigqueryUnitTest(TestCase): @patch("metadata.ingestion.connections.builders.create_generic_db_connection") @patch("metadata.ingestion.source.database.bigquery.metadata.BigquerySource.set_project_id") @patch("metadata.ingestion.source.database.bigquery.metadata.BigquerySource._test_connection") - @patch("metadata.ingestion.source.database.common_db_source.get_connection") + @patch("metadata.ingestion.source.database.common_db_source.create_connection") def __init__( self, methodName, # noqa: N803 diff --git a/ingestion/tests/unit/test_ometa_client_resilience.py b/ingestion/tests/unit/test_ometa_client_resilience.py index 110b81f4ea36..ff729ce2b1d8 100644 --- a/ingestion/tests/unit/test_ometa_client_resilience.py +++ b/ingestion/tests/unit/test_ometa_client_resilience.py @@ -80,13 +80,26 @@ def _handle(self, conn: socket.socket, behavior: str) -> None: if behavior == "hang": time.sleep(_HANG_SECONDS) return - body = json.dumps({"ok": True}).encode() - conn.sendall( - b"HTTP/1.1 200 OK\r\n" - b"Content-Type: application/json\r\n" - b"Content-Length: " + str(len(body)).encode() + b"\r\n" - b"Connection: close\r\n\r\n" + body - ) + if behavior.isdigit(): + # dbt-shaped error: "code" nested under "status", which the client + # cannot classify, so get() drops it to None. + self._send(conn, int(behavior), {"status": {"code": int(behavior)}}) + return + self._send(conn, 200, {"ok": True}) + + @staticmethod + def _send(conn: socket.socket, status: int, payload: dict) -> None: + reason = {200: "OK", 401: "Unauthorized", 504: "Gateway Timeout"}.get(status, "Status") + body = json.dumps(payload).encode() + conn.sendall( + f"HTTP/1.1 {status} {reason}\r\n".encode() + + b"Content-Type: application/json\r\n" + + b"Content-Length: " + + str(len(body)).encode() + + b"\r\n" + + b"Connection: close\r\n\r\n" + + body + ) def _rest(port: int) -> REST: @@ -120,3 +133,17 @@ def test_connection_failure_exhausts_to_transport_error(): with FlakyServer([], tail="close") as srv, pytest.raises(RestTransportError): _rest(srv.port).get("/anything") assert srv.attempts >= 2 + + +def test_get_raw_surfaces_a_status_get_swallows(): + with FlakyServer(["401"]) as srv: + assert _rest(srv.port).get("/x") is None + with FlakyServer(["401"]) as srv: + assert _rest(srv.port).get_raw("/x").status_code == 401 + + +def test_get_raw_still_retries_gateway_5xx(): + with FlakyServer(["504", "ok"]) as srv: + resp = _rest(srv.port).get_raw("/x", retry_wait=0) + assert resp.status_code == 200 + assert srv.attempts >= 2 diff --git a/ingestion/tests/unit/test_progress_registry.py b/ingestion/tests/unit/test_progress_registry.py index fbec7ca92cc3..726d055f680b 100644 --- a/ingestion/tests/unit/test_progress_registry.py +++ b/ingestion/tests/unit/test_progress_registry.py @@ -13,7 +13,7 @@ import threading from unittest.mock import patch -from metadata.utils.progress_registry import ProgressRegistry +from metadata.ingestion.progress.registry import ProgressRegistry def _by_label(snapshot): @@ -353,7 +353,7 @@ def test_none_before_first_open(self): def test_positive_after_first_open(self): reg = ProgressRegistry() - with patch("metadata.utils.progress_registry.time.monotonic") as clock: + with patch("metadata.ingestion.progress.registry.time.monotonic") as clock: clock.return_value = 100.0 reg.open([], "Database", None) clock.return_value = 130.0 @@ -361,7 +361,7 @@ def test_positive_after_first_open(self): def test_marker_set_on_first_open_only(self): reg = ProgressRegistry() - with patch("metadata.utils.progress_registry.time.monotonic") as clock: + with patch("metadata.ingestion.progress.registry.time.monotonic") as clock: clock.return_value = 100.0 reg.open([], "Database", None) clock.return_value = 200.0 diff --git a/ingestion/tests/unit/test_progress_tracking.py b/ingestion/tests/unit/test_progress_tracking.py new file mode 100644 index 000000000000..a8ed829369fd --- /dev/null +++ b/ingestion/tests/unit/test_progress_tracking.py @@ -0,0 +1,40 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Unit tests for the composed ProgressTracking and its attach helper.""" + +from metadata.ingestion.progress.modes import ProgressMode +from metadata.ingestion.progress.registry import ProgressRegistry +from metadata.ingestion.progress.tracking import ProgressTracking, attach_progress_tracking + + +class _Owner: + progress_mode = ProgressMode.AUTO + + +class TestAttachProgressTracking: + def test_lazily_creates_one_tracking(self): + owner = _Owner() + tracking = attach_progress_tracking(owner) + assert isinstance(tracking, ProgressTracking) + assert isinstance(tracking.registry, ProgressRegistry) + assert attach_progress_tracking(owner) is tracking + + def test_caches_under_the_scanned_attribute(self): + owner = _Owner() + tracking = attach_progress_tracking(owner) + assert owner.__dict__.get("_progress_tracking") is tracking + + def test_defaults_to_auto_when_owner_declares_no_mode(self): + class _NoMode: + pass + + tracking = attach_progress_tracking(_NoMode()) + assert tracking.mode is ProgressMode.AUTO diff --git a/ingestion/tests/unit/test_progress_tracking_mixin.py b/ingestion/tests/unit/test_progress_tracking_mixin.py deleted file mode 100644 index 5b68a5bc9701..000000000000 --- a/ingestion/tests/unit/test_progress_tracking_mixin.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2025 Collate -# Licensed under the Collate Community License, Version 1.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Unit tests for the shared ProgressTrackingMixin.""" - -from metadata.utils.progress_registry import ProgressRegistry -from metadata.utils.progress_tracking import ProgressTrackingMixin - - -class _Owner(ProgressTrackingMixin): - pass - - -class TestProgressTrackingMixin: - def test_lazily_creates_one_registry(self): - owner = _Owner() - registry = owner.progress - assert isinstance(registry, ProgressRegistry) - assert owner.progress is registry - - def test_exposes_the_scanned_attribute(self): - owner = _Owner() - _ = owner.progress - assert owner.__dict__.get("_progress_registry") is owner.progress diff --git a/ingestion/tests/unit/test_step_summary.py b/ingestion/tests/unit/test_step_summary.py new file mode 100644 index 000000000000..d4c394065740 --- /dev/null +++ b/ingestion/tests/unit/test_step_summary.py @@ -0,0 +1,93 @@ +# Copyright 2025 Collate +# Licensed under the Collate Community License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Unit tests for Summary.from_step failure reporting: the default 10-failure +display cap versus the report_all_failures opt-out that a step sets when +downstream logic needs the complete failure list. +""" + +from metadata.ingestion.api.models import StackTraceError +from metadata.ingestion.api.step import Step, Summary +from metadata.ingestion.ometa.ometa_api import OpenMetadata + + +class _DummyStep(Step): + """Minimal concrete Step that keeps the default failure cap (report_all_failures=False).""" + + @classmethod + def create( + cls, + config_dict: dict, + metadata: OpenMetadata, + pipeline_name: str | None = None, + ) -> "Step": + return cls() + + @property + def name(self) -> str: + return "dummy" + + def close(self) -> None: + pass + + +class _ReportAllStep(_DummyStep): + """Opts into the complete failure list.""" + + report_all_failures = True + + +def _add_failures(step: Step, count: int) -> None: + for i in range(count): + step.status.failed(StackTraceError(name=f"err-{i}", error=f"boom-{i}", stackTrace="")) + + +def test_default_step_caps_failures_at_ten(): + step = _DummyStep() + _add_failures(step, 25) + + summary = Summary.from_step(step) + + # The error COUNT stays complete; only the displayed list is capped. + assert summary.errors == 25 + assert summary.failures is not None + assert len(summary.failures) == 10 + + +def test_report_all_failures_returns_full_list(): + step = _ReportAllStep() + _add_failures(step, 25) + + summary = Summary.from_step(step) + + assert summary.errors == 25 + # Opt-in => the complete list survives, so downstream logic sees every failure. + assert summary.failures is not None + assert len(summary.failures) == 25 + + +def test_report_all_failures_below_cap_is_unaffected(): + step = _ReportAllStep() + _add_failures(step, 3) + + summary = Summary.from_step(step) + + assert summary.failures is not None + assert len(summary.failures) == 3 + + +def test_no_failures_reports_none(): + step = _DummyStep() + + summary = Summary.from_step(step) + + assert summary.errors == 0 + assert summary.failures is None diff --git a/ingestion/tests/unit/test_usage_progress.py b/ingestion/tests/unit/test_usage_progress.py index 19b64f04a8fb..d2aa7403e19c 100644 --- a/ingestion/tests/unit/test_usage_progress.py +++ b/ingestion/tests/unit/test_usage_progress.py @@ -54,14 +54,14 @@ def test_seeds_ceiling_and_reconciles_to_real_count(self): list(UsageSource._iter(source)) - assert source.progress.global_counters() == [("Queries", 3, 3)] + assert source.progress_tracking.registry.global_counters() == [("Queries", 3, 3)] def test_ceiling_is_result_limit_times_days_before_reconcile(self): captured = {} def batches(): # peek the seeded total after the first batch, before completion - captured["mid"] = source.progress.global_counters() + captured["mid"] = source.progress_tracking.registry.global_counters() yield TableQueries(queries=[_query()]) source = _make_usage_source(batches(), result_limit=1000, start=datetime(2026, 1, 1), end=datetime(2026, 1, 3)) diff --git a/ingestion/tests/unit/topology/dashboard/test_dashboard_group_progress.py b/ingestion/tests/unit/topology/dashboard/test_dashboard_group_progress.py index 2a89a069b5dc..da0b0ab19a0d 100644 --- a/ingestion/tests/unit/topology/dashboard/test_dashboard_group_progress.py +++ b/ingestion/tests/unit/topology/dashboard/test_dashboard_group_progress.py @@ -10,6 +10,7 @@ # limitations under the License. """Reusable per-group progress helpers on DashboardServiceSource.""" +from metadata.ingestion.progress.modes import ProgressMode from metadata.ingestion.source.dashboard.dashboard_service import DashboardServiceSource @@ -19,6 +20,8 @@ class _BareSource(DashboardServiceSource): # Overriding the abstract methods clears __abstractmethods__; __new__ then # skips the heavy __init__. The helpers and the ``progress`` property only # touch ``self.__dict__``, so no further setup is needed. + progress_mode = ProgressMode.MANUAL + def create(self, *args, **kwargs): ... def get_dashboard_details(self, *args, **kwargs): ... def get_dashboard_name(self, *args, **kwargs): ... @@ -39,10 +42,10 @@ def test_helpers_drive_registry_and_prune(self): src._open_group_progress("Sales", {"Dashboard": 3, "Chart": None}) src._advance_group_progress("Sales", "Dashboard") src._advance_group_progress("Sales", "Chart") - assert src.progress.global_counters() == [("Workspaces", 0, 2)] - assert src.progress.assets_ingested() == 2 + assert src.progress_tracking.registry.global_counters() == [("Workspaces", 0, 2)] + assert src.progress_tracking.registry.assets_ingested() == 2 src._close_group_progress("Sales") - assert src.progress.global_counters() == [("Workspaces", 1, 2)] - snapshot = src.progress.snapshot() + assert src.progress_tracking.registry.global_counters() == [("Workspaces", 1, 2)] + snapshot = src.progress_tracking.registry.snapshot() assert snapshot is None or all(child.label != "Sales" for child in snapshot.children) diff --git a/ingestion/tests/unit/topology/dashboard/test_grafana.py b/ingestion/tests/unit/topology/dashboard/test_grafana.py index 0d1273470cac..ba4edde15f94 100644 --- a/ingestion/tests/unit/topology/dashboard/test_grafana.py +++ b/ingestion/tests/unit/topology/dashboard/test_grafana.py @@ -318,9 +318,9 @@ class GrafanaUnitTest(TestCase): Implements the necessary unit tests for the Grafana Dashboard connector """ - @patch("metadata.ingestion.source.dashboard.dashboard_service.DashboardServiceSource.test_connection") - @patch("metadata.ingestion.source.dashboard.grafana.connection.get_connection") - def __init__(self, methodName, get_connection, test_connection) -> None: # noqa: N803 + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def __init__(self, methodName, create_connection, run_test_connection) -> None: # noqa: N803 super().__init__(methodName) # Mock the connection to return a mock client mock_client = MagicMock() @@ -328,8 +328,7 @@ def __init__(self, methodName, get_connection, test_connection) -> None: # noqa mock_client.search_dashboards.return_value = MOCK_SEARCH_RESULTS mock_client.get_dashboard.return_value = MOCK_DASHBOARD_RESPONSE mock_client.get_datasources.return_value = MOCK_DATASOURCES - get_connection.return_value = mock_client - test_connection.return_value = False + create_connection.return_value.client = mock_client self.config = OpenMetadataWorkflowConfig.model_validate(mock_config) # Mock OpenMetadata client to avoid connection attempts diff --git a/ingestion/tests/unit/topology/dashboard/test_hex.py b/ingestion/tests/unit/topology/dashboard/test_hex.py index beb87c70a981..3a64534ecfdc 100644 --- a/ingestion/tests/unit/topology/dashboard/test_hex.py +++ b/ingestion/tests/unit/topology/dashboard/test_hex.py @@ -372,10 +372,11 @@ def test_yield_dashboard_chart(self): result = self.hex_source.yield_dashboard_chart(SAMPLE_PROJECT) self.assertIsNone(result) - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_create_source(self, mock_get_connection): + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_create_source(self, mock_create_connection, mock_run_test_connection): """Test creating HexSource instance""" - mock_get_connection.return_value = MagicMock() + mock_create_connection.return_value.client = MagicMock() config = WorkflowSource.model_validate(MOCK_CONFIG["source"]) metadata = MagicMock() diff --git a/ingestion/tests/unit/topology/dashboard/test_hex_ingestion_flow.py b/ingestion/tests/unit/topology/dashboard/test_hex_ingestion_flow.py index 60de6235b3bf..f172193a50ad 100644 --- a/ingestion/tests/unit/topology/dashboard/test_hex_ingestion_flow.py +++ b/ingestion/tests/unit/topology/dashboard/test_hex_ingestion_flow.py @@ -102,15 +102,15 @@ def setUp(self): }, } - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") @patch.object(OpenMetadata, "__init__", lambda x, y: None) - def test_complete_ingestion_workflow(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + def test_complete_ingestion_workflow(self, mock_create_connection, mock_run_test_connection): """Test complete ingestion workflow from config to metadata storage""" + mock_run_test_connection.return_value = None # Setup mocks mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client sample_projects = create_sample_projects(5) mock_client.get_projects = MagicMock(return_value=sample_projects) @@ -171,11 +171,28 @@ def test_complete_ingestion_workflow(self, mock_get_connection, mock_test_connec f"https://app.hex.tech/app/projects/proj_{i:04d}", ) - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_ingestion_with_filter_pattern(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + @patch.object(OpenMetadata, "__init__", lambda x, y: None) + def test_owned_connection_closed_when_test_connection_fails(self, mock_create_connection, mock_run_test_connection): + """A failing test-connection in __init__ must close the owned connection.""" + mock_run_test_connection.side_effect = RuntimeError("cannot connect") + + metadata = MagicMock() + with self.assertRaises(RuntimeError): + HexSource.create( + config_dict=self.config["source"], + metadata=metadata, + pipeline_name="test_pipeline", + ) + + mock_create_connection.return_value.close.assert_called_once() + + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_ingestion_with_filter_pattern(self, mock_create_connection, mock_run_test_connection): """Test ingestion with dashboard filter pattern""" + mock_run_test_connection.return_value = None # Update config with filter pattern config = self.config.copy() config["source"]["sourceConfig"]["config"]["dashboardFilterPattern"] = { @@ -183,7 +200,7 @@ def test_ingestion_with_filter_pattern(self, mock_get_connection, mock_test_conn } mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # Create projects with specific names projects = [ @@ -221,13 +238,13 @@ def test_ingestion_with_filter_pattern(self, mock_get_connection, mock_test_conn self.assertNotIn("Engineering Metrics", titles) self.assertNotIn("Product Dashboard", titles) - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_ingestion_with_errors(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_ingestion_with_errors(self, mock_create_connection, mock_run_test_connection): """Test ingestion handling errors gracefully""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # Create projects where some will cause errors projects = [ @@ -277,13 +294,13 @@ def mock_url(project): self.assertEqual(len(errors), 1) self.assertIn("API Error", errors[0].error) - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_incremental_ingestion(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_incremental_ingestion(self, mock_create_connection, mock_run_test_connection): """Test incremental ingestion with state management""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # First run - 3 projects initial_projects = create_sample_projects(3) @@ -316,13 +333,13 @@ def test_incremental_ingestion(self, mock_get_connection, mock_test_connection): self.assertEqual(len(new_ids), 2) self.assertEqual(new_ids, {"proj_0003", "proj_0004"}) - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_large_dataset_performance(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_large_dataset_performance(self, mock_create_connection, mock_run_test_connection): """Test performance with large dataset""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # Create 1000 projects large_dataset = create_sample_projects(1000) @@ -360,13 +377,13 @@ def test_large_dataset_performance(self, mock_get_connection, mock_test_connecti # Performance check - should process 1000 dashboards in reasonable time self.assertLess(elapsed_time, 10.0) # Should complete within 10 seconds - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_memory_usage_validation(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_memory_usage_validation(self, mock_create_connection, mock_run_test_connection): """Test memory usage with batch processing""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # Process in batches to validate memory efficiency batch_size = 100 @@ -409,13 +426,13 @@ def test_memory_usage_validation(self, mock_get_connection, mock_test_connection self.assertEqual(total_processed, batch_size * total_batches) - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_owner_and_tag_extraction(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_owner_and_tag_extraction(self, mock_create_connection, mock_run_test_connection): """Test extraction of owners and tags during ingestion""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # Create project with rich metadata project = Project( @@ -492,13 +509,13 @@ def test_owner_and_tag_extraction(self, mock_get_connection, mock_test_connectio # Check we got an error at least self.assertGreater(len(errors), 0) - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_empty_dashboard_list(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_empty_dashboard_list(self, mock_create_connection, mock_run_test_connection): """Test handling of empty dashboard list""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client mock_client.get_projects = MagicMock(return_value=[]) metadata = MagicMock() @@ -510,13 +527,13 @@ def test_empty_dashboard_list(self, mock_get_connection, mock_test_connection): dashboards = list(source.get_dashboards_list()) self.assertEqual(len(dashboards), 0) - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_malformed_api_responses(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_malformed_api_responses(self, mock_create_connection, mock_run_test_connection): """Test handling of malformed API responses""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # Create projects with missing/invalid data malformed_projects = [ @@ -558,13 +575,13 @@ def test_malformed_api_responses(self, mock_get_connection, mock_test_connection # Should handle malformed data gracefully self.assertGreaterEqual(len(successes), 1) # At least the valid one - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_partial_failures_during_batch(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_partial_failures_during_batch(self, mock_create_connection, mock_run_test_connection): """Test partial failures during batch processing""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client projects = create_sample_projects(10) mock_client.get_projects = MagicMock(return_value=projects) @@ -614,13 +631,13 @@ def mock_url(project): class TestHexIngestionWithLineage(TestCase): """Test Hex ingestion with lineage extraction""" - @patch("metadata.ingestion.source.dashboard.dashboard_service.test_connection_common") - @patch("metadata.ingestion.source.dashboard.hex.metadata.get_connection") - def test_ingestion_with_lineage(self, mock_get_connection, mock_test_connection): - mock_test_connection.return_value = None + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def test_ingestion_with_lineage(self, mock_create_connection, mock_run_test_connection): """Test complete ingestion with lineage data""" + mock_run_test_connection.return_value = None mock_client = MagicMock() - mock_get_connection.return_value = mock_client + mock_create_connection.return_value.client = mock_client # Create projects projects = create_sample_projects(3) diff --git a/ingestion/tests/unit/topology/dashboard/test_looker.py b/ingestion/tests/unit/topology/dashboard/test_looker.py index d731815ca029..9d37590832ed 100644 --- a/ingestion/tests/unit/topology/dashboard/test_looker.py +++ b/ingestion/tests/unit/topology/dashboard/test_looker.py @@ -14,8 +14,9 @@ import uuid from datetime import datetime, timedelta +from types import SimpleNamespace from unittest import TestCase -from unittest.mock import patch +from unittest.mock import MagicMock, patch from looker_sdk.sdk.api40.methods import Looker40SDK from looker_sdk.sdk.api40.models import Dashboard as LookerDashboard @@ -47,6 +48,7 @@ from metadata.generated.schema.type.entityLineage import Source as LineageSource from metadata.generated.schema.type.entityReference import EntityReference from metadata.generated.schema.type.entityReferenceList import EntityReferenceList +from metadata.generated.schema.type.filterPattern import FilterPattern from metadata.generated.schema.type.usageDetails import UsageDetails, UsageStats from metadata.generated.schema.type.usageRequest import UsageRequest from metadata.ingestion.api.steps import InvalidSourceException @@ -912,3 +914,177 @@ def test_chart_source_state_populated(self): list(self.looker.yield_dashboard_chart(MOCK_LOOKER_DASHBOARD)) assert len(self.looker.chart_source_state) == 1 assert any("looker_source_test" in fqn for fqn in self.looker.chart_source_state) + + def test_list_datamodels_declares_datamodel_total(self): + """ + Check that list_datamodels declares the DashboardDataModel progress + total from the explore navigation, and marks it reconcilable so + standalone views can grow it later. + """ + models = [ + SimpleNamespace( + name="m1", + project_name="p", + explores=[SimpleNamespace(name="e1"), SimpleNamespace(name="e2")], + ), + SimpleNamespace(name="m2", project_name="p", explores=[SimpleNamespace(name="e3")]), + ] + self.looker.client.all_lookml_models = MagicMock(return_value=models) + self.looker.client.lookml_model_explore = MagicMock(side_effect=Exception("skip detail")) + + list(self.looker.list_datamodels()) + + counter = self.looker.progress_tracking.registry._global["DashboardDataModel"] + self.assertEqual(counter.total, 3) + self.assertTrue(counter.reconcilable) + + def test_list_datamodels_excludes_filtered_models_from_total(self): + """ + Check that list_datamodels excludes explores belonging to models + filtered out by dataModelFilterPattern when computing the + DashboardDataModel progress total, matching what + fetch_lookml_explores actually yields. + """ + models = [ + SimpleNamespace( + name="m1", + project_name="p", + explores=[SimpleNamespace(name="e1"), SimpleNamespace(name="e2")], + ), + SimpleNamespace(name="m2", project_name="p", explores=[SimpleNamespace(name="e3")]), + ] + self.looker.client.all_lookml_models = MagicMock(return_value=models) + self.looker.client.lookml_model_explore = MagicMock(side_effect=Exception("skip detail")) + self.looker.source_config.dataModelFilterPattern = FilterPattern(excludes=["^m2$"]) + + list(self.looker.list_datamodels()) + + counter = self.looker.progress_tracking.registry._global["DashboardDataModel"] + self.assertEqual(counter.total, 2) + + def test_list_datamodels_excludes_filtered_explore_from_total(self): + """ + Check that a dataModelFilterPattern matching an explore's composite + datamodel name (model_explore) excludes only that explore from the + total, mirroring the per-explore filter in yield_bulk_datamodel. + """ + models = [ + SimpleNamespace( + name="m1", + project_name="p", + explores=[SimpleNamespace(name="e1"), SimpleNamespace(name="e2")], + ), + SimpleNamespace(name="m2", project_name="p", explores=[SimpleNamespace(name="e3")]), + ] + self.looker.client.all_lookml_models = MagicMock(return_value=models) + self.looker.client.lookml_model_explore = MagicMock(side_effect=Exception("skip detail")) + self.looker.source_config.dataModelFilterPattern = FilterPattern(excludes=["m1_e2"]) + + list(self.looker.list_datamodels()) + + counter = self.looker.progress_tracking.registry._global["DashboardDataModel"] + self.assertEqual(counter.total, 2) + + def test_get_dashboards_list_declares_dashboard_total(self): + """ + Check that get_dashboards_list declares the Dashboard progress total + from the name-filtered dashboard list. + """ + dashboards = [ + SimpleNamespace(id="1", title="Keep"), + SimpleNamespace(id="2", title="Keep2"), + ] + self.looker.client.all_dashboards = MagicMock(return_value=dashboards) + + result = self.looker.get_dashboards_list() + + self.assertEqual(len(result), 2) + registry = self.looker.progress_tracking.registry + self.assertEqual(registry._global["Dashboard"].total, 2) + + def test_get_dashboards_list_reconcilable_when_project_filtered(self): + """ + projectFilterPattern is applied downstream in the base get_dashboard + (needs per-dashboard project detail), so get_dashboards_list falls back + to a reconcilable running count instead of an unreachable pre-filter + total. + """ + dashboards = [ + SimpleNamespace(id="1", title="Keep"), + SimpleNamespace(id="2", title="Keep2"), + ] + self.looker.client.all_dashboards = MagicMock(return_value=dashboards) + self.looker.source_config.projectFilterPattern = FilterPattern(excludes=["^skip$"]) + + result = self.looker.get_dashboards_list() + + self.assertEqual(len(result), 2) + registry = self.looker.progress_tracking.registry + self.assertTrue(registry._global["Dashboard"].reconcilable) + self.assertIsNone(registry._global["Dashboard"].total) + + def test_yield_bulk_datamodel_tracks_progress(self): + """ + Check that yield_bulk_datamodel advances the DashboardDataModel + counter after successfully yielding the explore request. + """ + self.looker.progress_tracking.manual.set_total("DashboardDataModel", 5) + + mock_explore = LookmlModelExplore( + name="my_explore", + model_name="my_model", + project_name="my_project", + fields=LookmlModelExploreFieldset(dimensions=[], measures=[]), + ) + + with ( + patch.object(LookerSource, "register_record_datamodel", return_value=None), + patch.object(LookerSource, "_build_data_model", return_value=None), + patch.object(LookerSource, "_get_explore_sql", return_value=None), + ): + list(self.looker.yield_bulk_datamodel(mock_explore)) + + counter = self.looker.progress_tracking.registry._global["DashboardDataModel"] + self.assertGreaterEqual(counter.done, 1) + + def test_yield_standalone_datamodels_tracks_progress(self): + """ + Check that yield_standalone_datamodels advances the + DashboardDataModel counter after successfully yielding a view request. + """ + from metadata.ingestion.source.dashboard.looker.models import LookMlView + + self.looker.progress_tracking.manual.set_total("DashboardDataModel", 5) + + mock_view = LookMlView(name="my_view", source_file="views/my_view.view.lkml") + mock_parser = MagicMock() + mock_parser._views_cache = {"my_view": mock_view} + mock_parser.parsed_files = {} + + self.looker._repo_credentials = True + self.looker._project_parsers = {"my_project": mock_parser} + self.looker._views_cache = {} + self.looker._all_lookml_models = [SimpleNamespace(name="my_model")] + + with ( + patch.object(LookerSource, "register_record_datamodel", return_value=None), + patch.object(LookerSource, "_build_data_model", return_value=None), + patch.object(LookerSource, "_add_standalone_view_lineage", return_value=iter([])), + ): + list(self.looker.yield_standalone_datamodels()) + + counter = self.looker.progress_tracking.registry._global["DashboardDataModel"] + self.assertGreaterEqual(counter.done, 1) + + def test_yield_dashboard_tracks_progress(self): + """ + Check that yield_dashboard advances the Dashboard counter after + successfully yielding the dashboard request. + """ + self.looker.progress_tracking.manual.set_total("Dashboard", 5) + + with patch.object(LookerSource, "get_owner_ref", return_value=None): + list(self.looker.yield_dashboard(MOCK_LOOKER_DASHBOARD)) + + counter = self.looker.progress_tracking.registry._global["Dashboard"] + self.assertGreaterEqual(counter.done, 1) diff --git a/ingestion/tests/unit/topology/dashboard/test_metabase.py b/ingestion/tests/unit/topology/dashboard/test_metabase.py index 644202f3f45a..185fe5b5a72c 100644 --- a/ingestion/tests/unit/topology/dashboard/test_metabase.py +++ b/ingestion/tests/unit/topology/dashboard/test_metabase.py @@ -242,12 +242,12 @@ class MetabaseUnitTest(TestCase): Domo Dashboard Unit Test """ - @patch("metadata.ingestion.source.dashboard.dashboard_service.DashboardServiceSource.test_connection") - @patch("metadata.ingestion.source.dashboard.metabase.connection.get_connection") - def __init__(self, methodName, get_connection, test_connection) -> None: # noqa: N803 + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def __init__(self, methodName, create_connection, run_test_connection) -> None: # noqa: N803 super().__init__(methodName) - get_connection.return_value = False - test_connection.return_value = False + create_connection.return_value.client = False + run_test_connection.return_value = False self.config = OpenMetadataWorkflowConfig.model_validate(mock_config) self.metabase: MetabaseSource = MetabaseSource.create( mock_config["source"], diff --git a/ingestion/tests/unit/topology/dashboard/test_microstrategy.py b/ingestion/tests/unit/topology/dashboard/test_microstrategy.py index 1ffa8d1b6dfc..fd6d67878b66 100644 --- a/ingestion/tests/unit/topology/dashboard/test_microstrategy.py +++ b/ingestion/tests/unit/topology/dashboard/test_microstrategy.py @@ -111,11 +111,11 @@ class MicroStrategyUnitTest(TestCase): """ @patch("metadata.ingestion.source.dashboard.microstrategy.metadata.MicrostrategySource.test_connection") - @patch("metadata.ingestion.source.dashboard.microstrategy.connection.get_connection") - def __init__(self, methodName, get_connection, test_connection) -> None: # noqa: N803 + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def __init__(self, methodName, create_connection, test_connection) -> None: # noqa: N803 super().__init__(methodName) test_connection.return_value = False - get_connection.return_value = False + create_connection.return_value.client = False self.config = OpenMetadataWorkflowConfig.model_validate(mock_micro_config) self.microstrategy = MicrostrategySource.create( mock_micro_config["source"], diff --git a/ingestion/tests/unit/topology/dashboard/test_powerbi.py b/ingestion/tests/unit/topology/dashboard/test_powerbi.py index 8f212a02d7ae..7591ad6ff128 100644 --- a/ingestion/tests/unit/topology/dashboard/test_powerbi.py +++ b/ingestion/tests/unit/topology/dashboard/test_powerbi.py @@ -705,10 +705,10 @@ class PowerBIUnitTest(TestCase): """ @patch("metadata.ingestion.source.dashboard.dashboard_service.DashboardServiceSource.test_connection") - @patch("metadata.ingestion.source.dashboard.powerbi.connection.get_connection") - def __init__(self, methodName, get_connection, test_connection) -> None: # noqa: N803 + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def __init__(self, methodName, create_connection, test_connection) -> None: # noqa: N803 super().__init__(methodName) - get_connection.return_value = False + create_connection.return_value.client = False test_connection.return_value = False self.config = OpenMetadataWorkflowConfig.model_validate(mock_config) self.powerbi: PowerbiSource = PowerbiSource.create( @@ -2421,10 +2421,8 @@ def test_upstream_datamart_lineage(self, *_): @pytest.mark.order(55) @patch.object(fqn, "build", side_effect=lambda *args, **kwargs: kwargs.get("chart_name")) def test_yield_dashboard_advances_workspace_progress(self, *_): - from metadata.workflow.progress_render import ProgressReporter - self.powerbi.state = WorkspaceState() - self.powerbi.__dict__.pop("_progress_registry", None) + self.powerbi.__dict__.pop("_progress_tracking", None) for dash in ( PowerBIDashboard(id="dash-1", displayName="One", tiles=[]), @@ -2443,15 +2441,15 @@ def test_yield_dashboard_advances_workspace_progress(self, *_): ) list(self.powerbi.yield_dashboard(Group(id="ws-1", name="Sales"))) - assert self.powerbi.progress.assets_ingested() == 2 - out = ProgressReporter(self.powerbi.progress).cli() + assert self.powerbi.progress_tracking.registry.assets_ingested() == 2 + out = self.powerbi.progress_tracking.registry.render_cli() assert "Sales.Dashboard" in out assert "Dashboard 2" in out @pytest.mark.order(56) def test_get_dashboard_tracks_workspace_group(self): self.powerbi.state = WorkspaceState() - self.powerbi.__dict__.pop("_progress_registry", None) + self.powerbi.__dict__.pop("_progress_tracking", None) ws_a = Group(id="wa", name="Alpha") ws_b = Group(id="wb", name="Beta") @@ -2462,13 +2460,13 @@ def test_get_dashboard_tracks_workspace_group(self): produced = list(self.powerbi.get_dashboard()) assert [w.id for w in produced] == ["wa", "wb"] - assert self.powerbi.progress.global_counters() == [("Workspaces", 2, None)] - assert self.powerbi.progress.snapshot() is None + assert self.powerbi.progress_tracking.registry.global_counters() == [("Workspaces", 2, None)] + assert self.powerbi.progress_tracking.registry.snapshot() is None @pytest.mark.order(56) def test_get_dashboard_does_not_count_workspace_failing_before_open(self): self.powerbi.state = WorkspaceState() - self.powerbi.__dict__.pop("_progress_registry", None) + self.powerbi.__dict__.pop("_progress_tracking", None) ws_ok = Group(id="ok", name="Ok") ws_bad = Group(id="bad", name="Bad") @@ -2479,11 +2477,11 @@ def test_get_dashboard_does_not_count_workspace_failing_before_open(self): produced = list(self.powerbi.get_dashboard()) assert [w.id for w in produced] == ["ok"] - assert self.powerbi.progress.global_counters() == [("Workspaces", 1, None)] + assert self.powerbi.progress_tracking.registry.global_counters() == [("Workspaces", 1, None)] @pytest.mark.order(57) def test_admin_workspace_progress_total_reconciles_to_active_scan_results(self): - self.powerbi.__dict__.pop("_progress_registry", None) + self.powerbi.__dict__.pop("_progress_tracking", None) self.powerbi.pagination_entity_per_page = 100 candidate_workspaces = [Group(id=f"ws-{index}", name=f"Workspace {index}") for index in range(46)] @@ -2503,14 +2501,12 @@ def test_admin_workspace_progress_total_reconciles_to_active_scan_results(self): produced = list(self.powerbi.get_admin_workspace_data()) assert [workspace.id for workspace in produced] == [f"ws-{index}" for index in range(40)] - assert self.powerbi.progress.global_counters() == [("Workspaces", 0, 40)] + assert self.powerbi.progress_tracking.registry.global_counters() == [("Workspaces", 0, 40)] @pytest.mark.order(58) @patch.object(fqn, "build", side_effect=lambda *args, **kwargs: kwargs.get("chart_name")) def test_unnamed_workspace_keys_progress_on_id(self, *_): - from metadata.workflow.progress_render import ProgressReporter - - self.powerbi.__dict__.pop("_progress_registry", None) + self.powerbi.__dict__.pop("_progress_tracking", None) self.powerbi.state.add_filtered_dashboard(PowerBIDashboard(id="dash-1", displayName="One", tiles=[])) @@ -2524,7 +2520,7 @@ def test_unnamed_workspace_keys_progress_on_id(self, *_): self.powerbi._open_group_progress("ws-x", {"Dashboard": None}) list(self.powerbi.yield_dashboard(Group(id="ws-x", name=None))) - out = ProgressReporter(self.powerbi.progress).cli() + out = self.powerbi.progress_tracking.registry.render_cli() assert "ws-x.Dashboard" in out assert "None.Dashboard" not in out diff --git a/ingestion/tests/unit/topology/dashboard/test_sigma.py b/ingestion/tests/unit/topology/dashboard/test_sigma.py index 15931978a9b1..9f9a092e8594 100644 --- a/ingestion/tests/unit/topology/dashboard/test_sigma.py +++ b/ingestion/tests/unit/topology/dashboard/test_sigma.py @@ -236,12 +236,12 @@ class SigmaUnitTest(TestCase): Domo Dashboard Unit Test """ - @patch("metadata.ingestion.source.dashboard.dashboard_service.DashboardServiceSource.test_connection") - @patch("metadata.ingestion.source.dashboard.sigma.connection.get_connection") - def __init__(self, methodName, get_connection, test_connection) -> None: # noqa: N803 + @patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection") + @patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") + def __init__(self, methodName, create_connection, run_test_connection) -> None: # noqa: N803 super().__init__(methodName) - get_connection.return_value = False - test_connection.return_value = False + create_connection.return_value.client = False + run_test_connection.return_value = False self.config = OpenMetadataWorkflowConfig.model_validate(mock_config) self.sigma: SigmaSource = SigmaSource.create( mock_config["source"], diff --git a/ingestion/tests/unit/topology/dashboard/test_ssrs.py b/ingestion/tests/unit/topology/dashboard/test_ssrs.py index d0eafe0d27a3..04a98352ce29 100644 --- a/ingestion/tests/unit/topology/dashboard/test_ssrs.py +++ b/ingestion/tests/unit/topology/dashboard/test_ssrs.py @@ -161,9 +161,10 @@ @pytest.fixture(scope="function") def ssrs_source(): with ( - patch("metadata.ingestion.source.dashboard.dashboard_service.DashboardServiceSource.test_connection"), - patch("metadata.ingestion.source.dashboard.ssrs.connection.get_connection"), + patch("metadata.ingestion.source.dashboard.dashboard_service.run_test_connection"), + patch("metadata.ingestion.source.dashboard.dashboard_service.create_connection") as mock_create, ): + mock_create.return_value.client = SimpleNamespace() config = OpenMetadataWorkflowConfig.model_validate(mock_config) source = SsrsSource.create( mock_config["source"], diff --git a/ingestion/tests/unit/topology/dashboard/test_tableau.py b/ingestion/tests/unit/topology/dashboard/test_tableau.py index 9fc47d48c18e..c570085e127b 100644 --- a/ingestion/tests/unit/topology/dashboard/test_tableau.py +++ b/ingestion/tests/unit/topology/dashboard/test_tableau.py @@ -1046,3 +1046,47 @@ def test_chart_source_state_populated(self): assert len(self.tableau.chart_source_state) == 3 for fqn in self.tableau.chart_source_state: assert "tableau_source_test" in fqn + + def test_get_dashboards_list_declares_totals(self): + self.tableau.client = SimpleNamespace( + get_workbook_count=MagicMock(return_value=7), + get_workbooks=MagicMock(return_value=iter([])), + ) + + list(self.tableau.get_dashboards_list()) + + registry = self.tableau.progress_tracking.registry + assert registry._global["Dashboard"].total == 7 + + def test_get_dashboards_list_reconcilable_when_filtered(self): + self.tableau.client = SimpleNamespace( + get_workbook_count=MagicMock(return_value=7), + get_workbooks=MagicMock(return_value=iter([])), + ) + self.tableau.source_config.dashboardFilterPattern = FilterPattern(excludes=["^skip$"]) + + list(self.tableau.get_dashboards_list()) + + registry = self.tableau.progress_tracking.registry + assert registry._global["Dashboard"].reconcilable is True + assert registry._global["Dashboard"].total is None + self.tableau.client.get_workbook_count.assert_not_called() + + def test_get_dashboards_list_reconcilable_when_count_fails(self): + self.tableau.client = SimpleNamespace( + get_workbook_count=MagicMock(side_effect=Exception("boom")), + get_workbooks=MagicMock(return_value=iter([])), + ) + + list(self.tableau.get_dashboards_list()) + + registry = self.tableau.progress_tracking.registry + assert registry._global["Dashboard"].reconcilable is True + assert registry._global["Dashboard"].total is None + + def test_yield_dashboard_tracks_progress(self): + self.tableau.progress_tracking.manual.set_total(Dashboard.__name__, 3) + + list(self.tableau.yield_dashboard(MOCK_DASHBOARD)) + + assert self.tableau.progress_tracking.registry._global["Dashboard"].done == 1 diff --git a/ingestion/tests/unit/topology/dashboard/test_tableau_client.py b/ingestion/tests/unit/topology/dashboard/test_tableau_client.py index 7135657aa5f0..35b28f796152 100644 --- a/ingestion/tests/unit/topology/dashboard/test_tableau_client.py +++ b/ingestion/tests/unit/topology/dashboard/test_tableau_client.py @@ -226,3 +226,14 @@ def test_test_get_owners_with_include_owners_false(self): with self.assertRaises(TableauOwnersNotFound): self.client.test_get_owners(include_owners=False) + + +def test_get_workbook_count_reads_total_available(): + """Test that get_workbook_count reads total_available from the pagination summary""" + client = TableauClient.__new__(TableauClient) + pagination = SimpleNamespace(total_available=42) + client.tableau_server = SimpleNamespace(workbooks=SimpleNamespace(get=MagicMock(return_value=([], pagination)))) + + assert client.get_workbook_count() == 42 + called_opts = client.tableau_server.workbooks.get.call_args.args[0] + assert called_opts.pagesize == 1 diff --git a/ingestion/tests/unit/topology/database/test_burstiq_connection.py b/ingestion/tests/unit/topology/database/test_burstiq_connection.py index 835890aa5437..a79b1e704951 100644 --- a/ingestion/tests/unit/topology/database/test_burstiq_connection.py +++ b/ingestion/tests/unit/topology/database/test_burstiq_connection.py @@ -18,7 +18,9 @@ from metadata.generated.schema.entity.services.connections.database.burstIQConnection import ( BurstIQConnection, ) -from metadata.ingestion.source.database.burstiq.connection import get_connection +from metadata.ingestion.source.database.burstiq.connection import ( + BurstIQConnection as BurstIQConnectionHandler, +) class TestBurstIQConnection(TestCase): @@ -41,13 +43,13 @@ def setUp(self): @patch("metadata.ingestion.source.database.burstiq.client.requests.post") def test_get_connection(self, mock_post): - """Test get_connection creates BurstIQClient properly""" + """Test the connection handler creates BurstIQClient properly""" mock_response = Mock() mock_response.json.return_value = self.mock_token_response mock_response.raise_for_status = Mock() mock_post.return_value = mock_response - client = get_connection(self.config) + client = BurstIQConnectionHandler(self.config).client # Verify client was created self.assertIsNotNone(client) @@ -196,7 +198,7 @@ def test_connection_invalid_credentials(self, mock_post): mock_post.return_value = mock_response # Should raise exception when authentication is attempted - client = get_connection(self.config) + client = BurstIQConnectionHandler(self.config).client with self.assertRaises(Exception) as context: client.test_authenticate() diff --git a/ingestion/tests/unit/topology/database/test_databricks.py b/ingestion/tests/unit/topology/database/test_databricks.py index cf0c6efd7d9d..18f8939528ca 100644 --- a/ingestion/tests/unit/topology/database/test_databricks.py +++ b/ingestion/tests/unit/topology/database/test_databricks.py @@ -17,6 +17,7 @@ from unittest import TestCase from unittest.mock import MagicMock, Mock, PropertyMock, patch +from metadata.core.connections.lifetime import Borrowed from metadata.generated.schema.api.data.createDatabaseSchema import ( CreateDatabaseSchemaRequest, ) @@ -510,7 +511,7 @@ def test_databricks_engine_wrapper_initialization(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) self.assertEqual(wrapper.engine, mock_engine) self.assertEqual(wrapper.inspector, mock_inspector) @@ -530,7 +531,7 @@ def test_databricks_engine_wrapper_get_schemas_with_non_system_schemas(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) schemas = wrapper.get_schemas() self.assertEqual(schemas, ["information_schema", "test_schema", "performance_schema"]) @@ -552,7 +553,7 @@ def test_databricks_engine_wrapper_get_schemas_with_only_system_schemas(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) schemas = wrapper.get_schemas() self.assertEqual(schemas, ["information_schema", "performance_schema"]) @@ -568,7 +569,7 @@ def test_databricks_engine_wrapper_get_schemas_empty(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) schemas = wrapper.get_schemas() self.assertEqual(schemas, []) @@ -586,7 +587,7 @@ def test_databricks_engine_wrapper_get_tables_with_cached_schema(self): # Mock the connection execute method to return a result mock_result = Mock() - mock_result.fetchall.return_value = [("table1",), ("table2",)] + mock_result.fetchmany.return_value = [("table1",), ("table2",)] mock_connection.execute.return_value = mock_result mock_inspector = Mock() @@ -598,7 +599,7 @@ def test_databricks_engine_wrapper_get_tables_with_cached_schema(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) # Set the first_catalog for the wrapper wrapper.first_catalog = "test_catalog" # First call to get_schemas to set first_schema @@ -606,7 +607,7 @@ def test_databricks_engine_wrapper_get_tables_with_cached_schema(self): # Then call get_tables tables = wrapper.get_tables() - self.assertEqual(tables, mock_result) + self.assertEqual(tables, [("table1",), ("table2",)]) mock_connection.execute.assert_called_once() def test_databricks_engine_wrapper_get_tables_without_cached_schema(self): @@ -620,7 +621,7 @@ def test_databricks_engine_wrapper_get_tables_without_cached_schema(self): # Mock the connection execute method to return a result mock_result = Mock() - mock_result.fetchall.return_value = [("table1",), ("table2",)] + mock_result.fetchmany.return_value = [("table1",), ("table2",)] mock_connection.execute.return_value = mock_result mock_inspector = Mock() @@ -632,13 +633,13 @@ def test_databricks_engine_wrapper_get_tables_without_cached_schema(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) # Set the first_catalog for the wrapper wrapper.first_catalog = "test_catalog" # Call get_tables directly without calling get_schemas first tables = wrapper.get_tables() - self.assertEqual(tables, mock_result) + self.assertEqual(tables, [("table1",), ("table2",)]) # Should have called get_schemas internally mock_inspector.get_schema_names.assert_called_once() mock_connection.execute.assert_called_once() @@ -652,7 +653,7 @@ def test_databricks_engine_wrapper_get_tables_no_schemas(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) tables = wrapper.get_tables() self.assertEqual(tables, []) @@ -669,7 +670,7 @@ def test_databricks_engine_wrapper_get_views_with_cached_schema(self): # Mock the connection execute method to return a result mock_result = Mock() - mock_result.fetchall.return_value = [("view1",), ("view2",)] + mock_result.fetchmany.return_value = [("view1",), ("view2",)] mock_connection.execute.return_value = mock_result mock_inspector = Mock() @@ -681,7 +682,7 @@ def test_databricks_engine_wrapper_get_views_with_cached_schema(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) # Set the first_catalog for the wrapper wrapper.first_catalog = "test_catalog" # First call to get_schemas to set first_schema @@ -689,7 +690,7 @@ def test_databricks_engine_wrapper_get_views_with_cached_schema(self): # Then call get_views views = wrapper.get_views() - self.assertEqual(views, mock_result) + self.assertEqual(views, [("view1",), ("view2",)]) mock_connection.execute.assert_called_once() def test_databricks_engine_wrapper_get_views_without_cached_schema(self): @@ -703,7 +704,7 @@ def test_databricks_engine_wrapper_get_views_without_cached_schema(self): # Mock the connection execute method to return a result mock_result = Mock() - mock_result.fetchall.return_value = [("view1",), ("view2",)] + mock_result.fetchmany.return_value = [("view1",), ("view2",)] mock_connection.execute.return_value = mock_result mock_inspector = Mock() @@ -715,13 +716,13 @@ def test_databricks_engine_wrapper_get_views_without_cached_schema(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) # Set the first_catalog for the wrapper wrapper.first_catalog = "test_catalog" # Call get_views directly without calling get_schemas first views = wrapper.get_views() - self.assertEqual(views, mock_result) + self.assertEqual(views, [("view1",), ("view2",)]) # Should have called get_schemas internally mock_inspector.get_schema_names.assert_called_once() mock_connection.execute.assert_called_once() @@ -735,7 +736,7 @@ def test_databricks_engine_wrapper_get_views_no_schemas(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) views = wrapper.get_views() self.assertEqual(views, []) @@ -753,7 +754,7 @@ def test_databricks_engine_wrapper_caching_behavior(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) # Call get_schemas multiple times schemas1 = wrapper.get_schemas() @@ -767,100 +768,6 @@ def test_databricks_engine_wrapper_caching_behavior(self): # get_schema_names should only be called once due to caching mock_inspector.get_schema_names.assert_called_once() - # pylint: disable=too-many-locals - @patch("metadata.ingestion.source.database.databricks.connection.DatabricksEngineWrapper") - @patch("metadata.ingestion.source.database.databricks.connection.test_connection_steps") - def test_test_connection_function(self, mock_test_connection_steps, mock_engine_wrapper_class): - """Test the test_connection function""" - from metadata.generated.schema.entity.services.connections.database.databricksConnection import ( - DatabricksConnection, - DatabricksScheme, - ) - from metadata.generated.schema.entity.services.connections.testConnectionResult import ( - StatusType, - TestConnectionResult, - TestConnectionStepResult, - ) - - # Mock the test connection result - mock_result = TestConnectionResult( - status=StatusType.Successful, - steps=[ - TestConnectionStepResult( - name="CheckAccess", - mandatory=True, - passed=True, - ), - TestConnectionStepResult( - name="GetSchemas", - mandatory=True, - passed=True, - ), - TestConnectionStepResult( - name="GetTables", - mandatory=True, - passed=True, - ), - TestConnectionStepResult( - name="GetViews", - mandatory=False, - passed=True, - ), - ], - ) - mock_test_connection_steps.return_value = mock_result - - # Create test connection - service_connection = DatabricksConnection( - scheme=DatabricksScheme.databricks, - hostPort="test-host:443", - authType=PersonalAccessToken(token="test-token"), - httpPath="/sql/1.0/warehouses/test", - queryHistoryTable="test_table", - ) - - # Mock the DatabricksEngineWrapper instance to avoid context manager error - mock_wrapper_instance = Mock() - mock_wrapper_instance.get_catalogs.return_value = ["main"] - mock_engine_wrapper_class.return_value = mock_wrapper_instance - - mock_engine = Mock() - mock_engine.connect.return_value = Mock() - mock_metadata = Mock() - - # Test the function - handler = self.DatabricksConnectionHandler(service_connection) - handler._client = mock_engine - result = handler.test_connection(metadata=mock_metadata) - - # Verify the result - self.assertEqual(result, mock_result) - mock_test_connection_steps.assert_called_once() - - # Verify the test_fn dictionary was created with the correct functions - call_args = mock_test_connection_steps.call_args - test_fn = call_args[1]["test_fn"] - - # Check that the test_fn contains the expected keys - expected_keys = [ - "CheckAccess", - "GetSchemas", - "GetTables", - "GetViews", - "GetDatabases", - "GetQueries", - "GetViewDefinitions", - "GetCatalogTags", - "GetSchemaTags", - "GetTableTags", - "GetColumnTags", - "GetTableLineage", - "GetColumnLineage", - ] - for key in expected_keys: - self.assertIn(key, test_fn) - self.assertIsNotNone(test_fn[key]) - def test_databricks_engine_wrapper_system_schema_filtering(self): """Test that system schemas are properly filtered out""" mock_engine = Mock() @@ -879,7 +786,7 @@ def test_databricks_engine_wrapper_system_schema_filtering(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) schemas = wrapper.get_schemas() # Should return all schemas @@ -911,7 +818,7 @@ def test_databricks_engine_wrapper_all_system_schemas(self): with patch("metadata.ingestion.source.database.databricks.connection.inspect") as mock_inspect: mock_inspect.return_value = mock_inspector - wrapper = self.DatabricksEngineWrapper(mock_engine) + wrapper = self.DatabricksEngineWrapper(Borrowed.of(mock_engine)) schemas = wrapper.get_schemas() # Should return all schemas diff --git a/ingestion/tests/unit/topology/database/test_db2.py b/ingestion/tests/unit/topology/database/test_db2.py index 867f3a11dde5..5b398f7958d4 100644 --- a/ingestion/tests/unit/topology/database/test_db2.py +++ b/ingestion/tests/unit/topology/database/test_db2.py @@ -202,7 +202,7 @@ class Db2UnitTest(TestCase): Db2 Unit Test """ - @patch("metadata.ingestion.source.database.common_db_source.get_connection") + @patch("metadata.ingestion.source.database.common_db_source.create_connection") @patch("metadata.ingestion.source.database.common_db_source.CommonDbSourceService.test_connection") def __init__( self, diff --git a/ingestion/tests/unit/topology/database/test_doris.py b/ingestion/tests/unit/topology/database/test_doris.py index 6fa8a101a49c..c33170e6aef7 100644 --- a/ingestion/tests/unit/topology/database/test_doris.py +++ b/ingestion/tests/unit/topology/database/test_doris.py @@ -59,7 +59,7 @@ class DorisUnitTest(TestCase): - @patch("metadata.ingestion.source.database.common_db_source.get_connection") + @patch("metadata.ingestion.source.database.common_db_source.create_connection") @patch("metadata.ingestion.source.database.common_db_source.CommonDbSourceService.test_connection") def __init__(self, methodName, test_connection, get_connection) -> None: # noqa: N803 super().__init__(methodName) diff --git a/ingestion/tests/unit/topology/database/test_exasol.py b/ingestion/tests/unit/topology/database/test_exasol.py index f0d48e701a6a..e61cff5ea0af 100644 --- a/ingestion/tests/unit/topology/database/test_exasol.py +++ b/ingestion/tests/unit/topology/database/test_exasol.py @@ -13,6 +13,8 @@ Test Exasol using the topology """ +from datetime import datetime +from types import SimpleNamespace from unittest import TestCase from unittest.mock import patch @@ -20,6 +22,8 @@ OpenMetadataWorkflowConfig, ) from metadata.ingestion.source.database.exasol.metadata import ExasolSource +from metadata.ingestion.source.database.exasol.queries import EXASOL_SQL_STATEMENT +from metadata.ingestion.source.database.exasol.usage import ExasolUsageSource mock_exasol_config = { "source": { @@ -70,3 +74,23 @@ def __init__(self, methodName, test_connection) -> None: # noqa: N803 def test_close_connection(self, engine, connection): connection.return_value = True self.exasol_source.close() + + +class ExasolUsageTest(TestCase): + def setUp(self): + self.usage_source = ExasolUsageSource.__new__(ExasolUsageSource) + self.usage_source.sql_stmt = EXASOL_SQL_STATEMENT + self.usage_source.filters = "" + self.usage_source.source_config = SimpleNamespace(resultLimit=250, filterCondition=None) + + def test_get_sql_statement(self): + sql = self.usage_source.get_sql_statement( + start_time=datetime(2025, 1, 1, 0, 0, 0), + end_time=datetime(2025, 1, 2, 0, 0, 0), + ) + + assert "EXA_STATISTICS.EXA_DBA_AUDIT_SQL" in sql + assert '"aborted"' not in sql + assert "LIMIT 250" in sql + assert "TO_TIMESTAMP('2025-01-01 00:00:00')" in sql + assert "TO_TIMESTAMP('2025-01-02 00:00:00')" in sql diff --git a/ingestion/tests/unit/topology/database/test_mssql.py b/ingestion/tests/unit/topology/database/test_mssql.py index f4932916b3b7..53925c191814 100644 --- a/ingestion/tests/unit/topology/database/test_mssql.py +++ b/ingestion/tests/unit/topology/database/test_mssql.py @@ -466,6 +466,54 @@ def test_get_encrypted_procedures_handles_error(self): assert result == set() + def test_load_description_maps_degrades_gracefully(self): + """A failing description query is isolated: it is logged, not raised, and the + remaining independent description loads still run so ingestion continues""" + self.mssql.encrypted_procedures_cache = {("db", "dbo"): {"sp"}} + + with ( + patch.object(MssqlSource, "set_schema_description_map", side_effect=Exception("boom")) as schema_map, + patch.object(MssqlSource, "set_database_description_map") as database_map, + patch.object(MssqlSource, "set_stored_procedure_description_map") as procedure_map, + ): + # Must not raise even though the first description query failed + self.mssql._load_description_maps() + + # A failure in one load must not skip the other independent loads + schema_map.assert_called_once() + database_map.assert_called_once() + procedure_map.assert_called_once() + assert self.mssql.encrypted_procedures_cache == {} + + def test_load_description_maps_resets_encrypted_cache(self): + """The per-database encrypted-procedure cache is reset on each database""" + self.mssql.encrypted_procedures_cache = {("db", "dbo"): {"sp"}} + + with ( + patch.object(MssqlSource, "set_schema_description_map"), + patch.object(MssqlSource, "set_database_description_map"), + patch.object(MssqlSource, "set_stored_procedure_description_map"), + ): + self.mssql._load_description_maps() + + assert self.mssql.encrypted_procedures_cache == {} + + def test_failed_database_recorded_in_status(self): + """A database that fails to connect is recorded in status and not yielded""" + self.mssql.config.serviceConnection.root.config.ingestAllDatabases = True + self.mssql.context.get().__dict__["database_service"] = MOCK_DATABASE_SERVICE.name.root + self.mssql.status = MagicMock() + + with ( + patch.object(MssqlSource, "get_database_names_raw", return_value=iter(["bad_db"])), + patch.object(MssqlSource, "_load_description_maps"), + patch.object(MssqlSource, "set_inspector", side_effect=Exception("cannot connect")), + ): + yielded = list(self.mssql.get_database_names()) + + assert yielded == [] + self.mssql.status.failed.assert_called_once() + class MssqlIdentityColumnTest(TestCase): """Regression tests for identity column reflection. diff --git a/ingestion/tests/unit/topology/database/test_redshift_utils.py b/ingestion/tests/unit/topology/database/test_redshift_utils.py index eca3bf47254f..17f9a5a425be 100644 --- a/ingestion/tests/unit/topology/database/test_redshift_utils.py +++ b/ingestion/tests/unit/topology/database/test_redshift_utils.py @@ -14,6 +14,7 @@ import unittest from unittest.mock import MagicMock, Mock +from metadata.ingestion.source.database.column_type_parser import ColumnTypeParser from metadata.ingestion.source.database.redshift.utils import ( _get_all_relation_info, _get_args_and_kwargs, @@ -473,5 +474,39 @@ def test_numeric_with_space_after_comma_falls_back_to_init_args(self): self.assertEqual(kwargs, {}) +class TestRedshiftExternalTableTypeMapping(unittest.TestCase): + """ + Spectrum/Glue external tables emit Hive-style column types via + svv_external_columns. Types like `string` and `double` must resolve to + concrete OpenMetadata types instead of UNKNOWN (issue #29589), otherwise + column-level data quality test selection shows "No data". + """ + + def test_external_hive_types_resolve_to_concrete_types(self): + """Each Spectrum type is registered and maps to the expected type.""" + expected = { + "string": "VARCHAR", + "double": "DOUBLE", + "char": "CHAR", + "tinyint": "TINYINT", + } + + for external_type, expected_om_type in expected.items(): + with self.subTest(external_type=external_type): + self.assertIn( + external_type, + ischema_names, + f"'{external_type}' is not registered in ischema_names", + ) + # Resolve an instantiated type, matching how the dialect passes + # column types into the parser during reflection. + resolved = ColumnTypeParser.get_column_type(ischema_names[external_type]()) + self.assertEqual( + resolved, + expected_om_type, + f"'{external_type}' resolved to {resolved}, expected {expected_om_type}", + ) + + if __name__ == "__main__": unittest.main() diff --git a/ingestion/tests/unit/topology/database/test_snowflake.py b/ingestion/tests/unit/topology/database/test_snowflake.py index 8f947bb277da..b65896e27ed2 100644 --- a/ingestion/tests/unit/topology/database/test_snowflake.py +++ b/ingestion/tests/unit/topology/database/test_snowflake.py @@ -19,6 +19,7 @@ import sqlalchemy.types as sqltypes +from metadata.core.connections.lifetime import Borrowed from metadata.generated.schema.entity.data.database import Database from metadata.generated.schema.entity.data.databaseSchema import DatabaseSchema from metadata.generated.schema.entity.data.table import Table, TableType @@ -993,7 +994,7 @@ def test_test_connection_wires_access_history_and_query_history(): ) checks = SnowflakeChecks( - client=MagicMock(), + db=Borrowed.of(MagicMock()), service_connection=SnowflakeConnectionConfig(username="user", account="acc", warehouse="wh"), ) collected = collect_checks(checks) diff --git a/ingestion/tests/unit/topology/database/test_unity_catalog_connection.py b/ingestion/tests/unit/topology/database/test_unity_catalog_connection.py index 15494825da79..5e1e74598f1b 100644 --- a/ingestion/tests/unit/topology/database/test_unity_catalog_connection.py +++ b/ingestion/tests/unit/topology/database/test_unity_catalog_connection.py @@ -13,7 +13,7 @@ Tests for unitycatalog.connection. """ -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock import pytest from databricks.sdk.service.catalog import TableType @@ -26,7 +26,6 @@ UnityCatalogConnection, ) from metadata.ingestion.connections.test_connections import SourceConnectionException -from metadata.ingestion.source.database.unitycatalog import connection as uc_connection from metadata.ingestion.source.database.unitycatalog.connection import ( VIEW_LISTING_SCAN_LIMIT, get_catalogs, @@ -215,24 +214,3 @@ def test_raises_when_catalog_and_schema_unresolved(self): get_views(client, table_obj) client.tables.list.assert_not_called() - - -class TestTestConnectionWiring: - def test_steps_are_wired_with_configured_catalog_and_schema(self): - service_connection = _connection(catalog="configured_catalog", databaseSchema="configured_schema") - client = MagicMock() - - with ( - patch.object(uc_connection, "get_connection", return_value=client), - patch.object(uc_connection, "get_sqlalchemy_connection"), - patch.object(uc_connection, "test_connection_steps") as mock_steps, - ): - uc_connection.UnityCatalogConnection(service_connection).test_connection(MagicMock()) - - test_fn = mock_steps.call_args.kwargs["test_fn"] - assert test_fn["GetTables"].func is get_tables - assert test_fn["GetViews"].func is get_views - assert test_fn["GetDatabases"].func is get_catalogs - assert test_fn["GetSchemas"].func is get_schemas - assert test_fn["GetDatabases"].args[-1] == "configured_catalog" - assert test_fn["GetSchemas"].args[-1] == "configured_schema" diff --git a/ingestion/tests/unit/topology/database/test_unity_catalog_lineage.py b/ingestion/tests/unit/topology/database/test_unity_catalog_lineage.py index 757a8f23234d..d462859937bc 100644 --- a/ingestion/tests/unit/topology/database/test_unity_catalog_lineage.py +++ b/ingestion/tests/unit/topology/database/test_unity_catalog_lineage.py @@ -73,12 +73,11 @@ def lineage_source(): with ( patch("metadata.ingestion.source.database.unitycatalog.lineage.UnitycatalogLineageSource.test_connection"), patch("metadata.ingestion.ometa.ometa_api.OpenMetadata") as mock_metadata, - patch("metadata.ingestion.source.database.unitycatalog.lineage.get_sqlalchemy_connection") as mock_engine, - patch("metadata.ingestion.source.database.unitycatalog.lineage.get_connection"), + patch("metadata.ingestion.source.database.unitycatalog.lineage.create_connection") as mock_create_connection, ): config = WorkflowSource.model_validate(MOCK_CONFIG["source"]) source = UnitycatalogLineageSource(config, mock_metadata) - source.engine = mock_engine.return_value + source.engine = mock_create_connection.return_value.sql.client yield source diff --git a/ingestion/tests/unit/topology/database/test_unitycatalog_incremental.py b/ingestion/tests/unit/topology/database/test_unitycatalog_incremental.py index f2b8905b9925..c3daf270b400 100644 --- a/ingestion/tests/unit/topology/database/test_unitycatalog_incremental.py +++ b/ingestion/tests/unit/topology/database/test_unitycatalog_incremental.py @@ -142,9 +142,7 @@ def test_init_configures_threads_from_source_config(self): try: with ( - patch(f"{UC_METADATA_MODULE}.get_connection", return_value=Mock()), - patch(f"{UC_METADATA_MODULE}.DatabricksClient", return_value=Mock()), - patch(f"{UC_METADATA_MODULE}.get_sqlalchemy_connection", return_value=Mock()), + patch(f"{UC_METADATA_MODULE}.create_connection", return_value=Mock()), patch.object(UnitycatalogSource, "test_connection", return_value=None), ): source = UnitycatalogSource(config, metadata, incremental) diff --git a/ingestion/tests/unit/topology/pipeline/test_airflowapi.py b/ingestion/tests/unit/topology/pipeline/test_airflowapi.py index bdef0f9272a9..1875c4554521 100644 --- a/ingestion/tests/unit/topology/pipeline/test_airflowapi.py +++ b/ingestion/tests/unit/topology/pipeline/test_airflowapi.py @@ -254,6 +254,78 @@ def test_build_dag_details_with_tasks(self, mock_rest_cls): assert result.tasks[0].class_ref["class_name"] == "PythonOperator" +# ── Client: DAG Count ──────────────────────────────────────────────────── + + +class TestClientGetDagsCount: + @patch("metadata.ingestion.source.pipeline.airflow.api.client.TrackedREST") + def test_returns_total_entries(self, mock_rest_cls): + client, mock_rest = _make_client(mock_rest_cls) + mock_rest.get.return_value = {"dags": [{"dag_id": "d1"}], "total_entries": 42} + + assert client.get_dags_count() == 42 + + @patch("metadata.ingestion.source.pipeline.airflow.api.client.TrackedREST") + def test_returns_none_when_total_entries_absent(self, mock_rest_cls): + client, mock_rest = _make_client(mock_rest_cls) + mock_rest.get.return_value = {"dags": []} + + assert client.get_dags_count() is None + + @patch("metadata.ingestion.source.pipeline.airflow.api.client.TrackedREST") + def test_returns_none_on_request_error(self, mock_rest_cls): + client, mock_rest = _make_client(mock_rest_cls) + mock_rest.get.side_effect = RequestsConnectionError("boom") + + assert client.get_dags_count() is None + + +# ── Source: Progress Totals ────────────────────────────────────────────── + + +class TestDeclareProgressTotals: + def test_sets_pipeline_total_when_count_positive(self): + source = MagicMock() + source.has_pipeline_filter.return_value = False + source.connection.get_dags_count.return_value = 7 + totals = MagicMock() + + AirflowApiSource.declare_progress_totals(source, totals) + + totals.set_total.assert_called_once_with("Pipeline", 7) + + def test_does_not_declare_when_count_none(self): + source = MagicMock() + source.has_pipeline_filter.return_value = False + source.connection.get_dags_count.return_value = None + totals = MagicMock() + + AirflowApiSource.declare_progress_totals(source, totals) + + totals.set_total.assert_not_called() + + def test_does_not_declare_when_count_zero(self): + source = MagicMock() + source.has_pipeline_filter.return_value = False + source.connection.get_dags_count.return_value = 0 + totals = MagicMock() + + AirflowApiSource.declare_progress_totals(source, totals) + + totals.set_total.assert_not_called() + + def test_does_not_declare_when_pipeline_filter_configured(self): + source = MagicMock() + source.has_pipeline_filter.return_value = True + source.connection.get_dags_count.return_value = 7 + totals = MagicMock() + + AirflowApiSource.declare_progress_totals(source, totals) + + totals.set_total.assert_not_called() + source.connection.get_dags_count.assert_not_called() + + # ── Client: Date Field ─────────────────────────────────────────────────── diff --git a/ingestion/tests/unit/topology/pipeline/test_dbtcloud.py b/ingestion/tests/unit/topology/pipeline/test_dbtcloud.py index e5ca2ddf7696..744a0f6b80af 100644 --- a/ingestion/tests/unit/topology/pipeline/test_dbtcloud.py +++ b/ingestion/tests/unit/topology/pipeline/test_dbtcloud.py @@ -533,6 +533,72 @@ def test_get_pipelines_list(self, get_jobs): results = list(self.dbtcloud.get_pipelines_list()) self.assertEqual([EXPECTED_JOB_DETAILS], results) + def test_declare_progress_totals_sets_pipeline_total(self): + totals = MagicMock() + with patch.object(self.dbtcloud.client, "get_jobs_count", return_value=5): + self.dbtcloud.declare_progress_totals(totals) + totals.set_total.assert_called_once_with("Pipeline", 5) + + def test_declare_progress_totals_skips_when_none(self): + totals = MagicMock() + with patch.object(self.dbtcloud.client, "get_jobs_count", return_value=None): + self.dbtcloud.declare_progress_totals(totals) + totals.set_total.assert_not_called() + + def test_declare_progress_totals_skips_when_zero(self): + totals = MagicMock() + with patch.object(self.dbtcloud.client, "get_jobs_count", return_value=0): + self.dbtcloud.declare_progress_totals(totals) + totals.set_total.assert_not_called() + + def test_declare_progress_totals_skips_when_pipeline_filter_configured(self): + totals = MagicMock() + with ( + patch.object(self.dbtcloud, "has_pipeline_filter", return_value=True), + patch.object(self.dbtcloud.client, "get_jobs_count", return_value=5) as get_jobs_count, + ): + self.dbtcloud.declare_progress_totals(totals) + totals.set_total.assert_not_called() + get_jobs_count.assert_not_called() + + def test_get_jobs_count_uses_job_ids_length(self): + client = self.dbtcloud.client + client.job_ids = ["1", "2", "3"] + assert client.get_jobs_count() == 3 + + def test_get_jobs_count_sums_filter_totals(self): + client = self.dbtcloud.client + client.job_ids = None + client.project_ids = ["p1", "p2"] + client.environment_ids = None + with patch.object(client.client, "get", return_value=MOCK_JOB_RESULT) as get: + assert client.get_jobs_count() == 4 + assert get.call_count == 2 + + def test_get_jobs_count_reads_pagination_total(self): + client = self.dbtcloud.client + client.job_ids = None + client.project_ids = None + client.environment_ids = None + with patch.object(client.client, "get", return_value=MOCK_JOB_RESULT): + assert client.get_jobs_count() == 2 + + def test_get_jobs_count_returns_zero_on_error(self): + client = self.dbtcloud.client + client.job_ids = None + client.project_ids = None + client.environment_ids = None + with patch.object(client.client, "get", side_effect=Exception("boom")): + assert client.get_jobs_count() == 0 + + def test_get_jobs_count_continues_when_one_filter_fails(self): + client = self.dbtcloud.client + client.job_ids = None + client.project_ids = ["p1", "p2"] + client.environment_ids = None + with patch.object(client.client, "get", side_effect=[MOCK_JOB_RESULT, Exception("boom")]): + assert client.get_jobs_count() == 2 + def test_pipeline_name(self): assert self.dbtcloud.get_pipeline_name(EXPECTED_JOB_DETAILS) == EXPECTED_PIPELINE_NAME diff --git a/ingestion/tests/unit/topology/pipeline/test_kafkaconnect.py b/ingestion/tests/unit/topology/pipeline/test_kafkaconnect.py index 649dfaf68761..b103423f286f 100644 --- a/ingestion/tests/unit/topology/pipeline/test_kafkaconnect.py +++ b/ingestion/tests/unit/topology/pipeline/test_kafkaconnect.py @@ -13,8 +13,10 @@ Test KafkaConnect client and models """ +from types import SimpleNamespace from unittest import TestCase from unittest.mock import MagicMock, Mock, patch +from uuid import uuid4 from metadata.generated.schema.entity.data.topic import Topic from metadata.generated.schema.entity.services.connections.pipeline.kafkaConnectConnection import ( @@ -1171,3 +1173,414 @@ def test_prefix_search_not_attempted_when_no_container_name(self): source.get_dataset_entity(pipeline, dataset) mock_search.assert_not_called() + + +class TestKafkaConnectTopicRoutingTransforms(TestCase): + """ + Tests for topic-routing SMTs (RegexRouter / TopicRegexRouter and Debezium + outbox EventRouter) that rewrite the destination topic name. + + Regression coverage for the case where a statically-constructed CDC topic + name never matches the real post-transform topic, so lineage is skipped. + See https://github.com/open-metadata/OpenMetadata/issues/27901. + """ + + def _make_source(self): + from metadata.ingestion.source.pipeline.kafkaconnect.metadata import ( + KafkaconnectSource, + ) + + source = object.__new__(KafkaconnectSource) + source._topics_cache = {} + source.metadata = MagicMock() + return source + + @staticmethod + def _topic(name): + topic = SimpleNamespace() + topic.name = SimpleNamespace(root=name) + topic.fullyQualifiedName = SimpleNamespace(root=f'Kafka."{name}"') + return topic + + def test_apply_regex_router_rewrites_topic_name(self): + """RegexRouter must rewrite the constructed topic name deterministically.""" + from metadata.ingestion.source.pipeline.kafkaconnect.client import ( + apply_topic_routing_transforms, + ) + + config = { + "transforms": "route", + "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter", + "transforms.route.regex": r"ecommerce\.sales\.prod\.sales\.(.*)", + "transforms.route.replacement": "prod.global.sales.$1", + } + + result = apply_topic_routing_transforms("ecommerce.sales.prod.sales.outbox", config) + + assert result == "prod.global.sales.outbox" + + def test_apply_confluent_topic_regex_router(self): + """The Confluent Cloud TopicRegexRouter class must be identified and applied.""" + from metadata.ingestion.source.pipeline.kafkaconnect.client import ( + apply_topic_routing_transforms, + ) + + config = { + "transforms": "route", + "transforms.route.type": "io.confluent.connect.cloud.transforms.TopicRegexRouter", + "transforms.route.regex": r"outbox\.event\.(.*)", + "transforms.route.replacement": "prod.global.sales.$1", + } + + result = apply_topic_routing_transforms("outbox.event.orderCreated", config) + + assert result == "prod.global.sales.orderCreated" + + def test_apply_topic_routing_transforms_noop_without_transforms(self): + """With no transforms configured the name is returned unchanged.""" + from metadata.ingestion.source.pipeline.kafkaconnect.client import ( + apply_topic_routing_transforms, + ) + + assert apply_topic_routing_transforms("a.b.c", {}) == "a.b.c" + + def test_apply_regex_router_invalid_regex_returns_original(self): + """An invalid regex must not raise; the original name is preserved.""" + from metadata.ingestion.source.pipeline.kafkaconnect.client import ( + apply_topic_routing_transforms, + ) + + config = { + "transforms": "route", + "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter", + "transforms.route.regex": r"([", # unbalanced group + "transforms.route.replacement": "x", + } + + assert apply_topic_routing_transforms("a.b.c", config) == "a.b.c" + + def test_parse_cdc_topics_applies_regex_router(self): + """CDC topics constructed from table.include.list must have SMTs applied.""" + config = { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "topic.prefix": "ecommerce.sales", + "table.include.list": "prod.sales.outbox", + "transforms": "route", + "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter", + "transforms.route.regex": r"ecommerce\.sales\.prod\.sales\.(.*)", + "transforms.route.replacement": "prod.global.sales.$1", + } + details = KafkaConnectPipelineDetails(name="outbox-connector", type="source", config=config) + source = self._make_source() + + topics = source._parse_cdc_topics_from_config(details, "ecommerce.sales") + + assert [t.name for t in topics] == ["prod.global.sales.outbox"] + + def test_resolve_outbox_topics_matches_ingested_topic(self): + """ + EventRouter routes by a row value (${routedByValue}) unknowable at + ingestion time, so the outbox topic must be matched by pattern against + topics already ingested in the messaging service. + """ + config = { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "topic.prefix": "ecommerce.sales", + "table.include.list": "prod.sales.outbox", + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "prod.global.sales.${routedByValue}_v1", + } + source = self._make_source() + source.metadata.list_all_entities.return_value = [ + self._topic("prod.global.sales.orderCreated_v1"), + self._topic("prod.global.sales.orderCancelled_v1"), + self._topic("unrelated.topic"), + ] + + topics = source._resolve_outbox_topics(connector_config=config, messaging_service_name="Kafka") + + names = sorted(t.name for t in topics) + assert names == [ + "prod.global.sales.orderCancelled_v1", + "prod.global.sales.orderCreated_v1", + ] + assert all(t.fqn for t in topics) + + def test_resolve_outbox_topics_no_messaging_service_returns_empty(self): + """Without a messaging service the outbox topics cannot be matched.""" + config = { + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "prod.global.sales.${routedByValue}_v1", + } + source = self._make_source() + + topics = source._resolve_outbox_topics(connector_config=config, messaging_service_name=None) + + assert topics == [] + + def test_resolve_outbox_topics_composes_following_regex_router(self): + """An EventRouter followed by a RegexRouter must compose into one pattern.""" + config = { + "transforms": "outbox,route", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "outbox.event.${routedByValue}", + "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter", + "transforms.route.regex": r"outbox\.event\.(.*)", + "transforms.route.replacement": "prod.global.sales.$1_v1", + } + source = self._make_source() + source.metadata.list_all_entities.return_value = [ + self._topic("prod.global.sales.orderCreated_v1"), + self._topic("prod.global.other.thing"), + ] + + topics = source._resolve_outbox_topics(connector_config=config, messaging_service_name="Kafka") + + assert [t.name for t in topics] == ["prod.global.sales.orderCreated_v1"] + + def test_apply_regex_router_named_group(self): + """Java named groups (?...) with ${name} replacement convert and apply.""" + from metadata.ingestion.source.pipeline.kafkaconnect.client import ( + apply_topic_routing_transforms, + ) + + config = { + "transforms": "route", + "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter", + "transforms.route.regex": r"outbox\.event\.(?.*)", + "transforms.route.replacement": "prod.global.${agg}_v1", + } + + assert apply_topic_routing_transforms("outbox.event.orderCreated", config) == "prod.global.orderCreated_v1" + + def test_outbox_bare_replacement_is_not_catch_all(self): + """A replacement with no static part must NOT match every topic in the service.""" + config = { + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "${routedByValue}", + } + source = self._make_source() + source.metadata.list_all_entities.return_value = [ + self._topic("some.unrelated.topic"), + self._topic("another.domain.topic"), + ] + + assert source._build_outbox_topic_pattern(config) is None + assert source._resolve_outbox_topics(connector_config=config, messaging_service_name="Kafka") == [] + + def test_outbox_fanout_identifies_outbox_table_by_event_columns(self): + """In a multi-table connector only the table with the full outbox schema fans out.""" + from metadata.generated.schema.entity.data.table import Column, DataType, Table + + config = { + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + } + source = self._make_source() + pipeline = SimpleNamespace(config=config) + outbox = Table.model_construct( + columns=[ + Column(name="id", dataType=DataType.BIGINT), + Column(name="aggregatetype", dataType=DataType.VARCHAR), + Column(name="aggregateid", dataType=DataType.VARCHAR), + Column(name="payload", dataType=DataType.JSON), + ] + ) + # A normal table that happens to share one outbox column must NOT be treated as outbox. + orders = Table.model_construct( + columns=[ + Column(name="id", dataType=DataType.BIGINT), + Column(name="aggregatetype", dataType=DataType.VARCHAR), + Column(name="total", dataType=DataType.BIGINT), + ] + ) + topics = {"prod.global.sales.orderCreated_v1": object()} + + # Multi-table: only the table with the full outbox schema fans out. + assert source._is_outbox_fanout(pipeline, outbox, topics, single_dataset=False) is True + assert source._is_outbox_fanout(pipeline, orders, topics, single_dataset=False) is False + # Single-table connector is unambiguously the outbox. + assert source._is_outbox_fanout(pipeline, orders, topics, single_dataset=True) is True + + def test_outbox_separator_only_replacement_is_not_a_pattern(self): + """A replacement whose static part is only separators must not build a near-catch-all pattern.""" + config = { + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "${routedByValue}.${aggregateid}", + } + source = self._make_source() + + assert source._build_outbox_topic_pattern(config) is None + + +class TestKafkaConnectTransformLineageEdges(TestCase): + """ + End-to-end coverage that transformed topics actually produce lineage edges + (AddLineageRequest) from the source table, not just resolve to Topic entities. + + Drives ``yield_pipeline_lineage_details`` with only the OpenMetadata REST + client and ingestion context mocked; topic resolution, topic-to-dataset + matching, and edge construction all run for real. + See https://github.com/open-metadata/OpenMetadata/issues/27901. + """ + + @staticmethod + def _entity(entity_cls, fqn): + return entity_cls.model_construct( + id=uuid4(), + name=fqn.split(".")[-1].strip('"'), + fullyQualifiedName=fqn, + service=None, + ) + + @staticmethod + def _ingested_topic(name): + return SimpleNamespace( + name=SimpleNamespace(root=name), + fullyQualifiedName=SimpleNamespace(root=f'Kafka."{name}"'), + ) + + def _run_lineage(self, config, ingested_topic_names, pipeline_topics=None): + from metadata.generated.schema.entity.data.table import Table + from metadata.ingestion.source.pipeline.kafkaconnect.metadata import ( + KafkaconnectSource, + ) + + source = object.__new__(KafkaconnectSource) + source._topics_cache = {} + source.lineage_results = [] + source.context = MagicMock() + source.context.get.return_value = SimpleNamespace( + pipeline_service="KafkaConnectSvc", pipeline="outbox-connector" + ) + source._resolve_messaging_service = lambda pipeline_details: "Kafka" + table_entity = self._entity(Table, "PG.db.prod.sales.outbox") + source.get_dataset_entity = lambda **kwargs: table_entity + source.build_column_lineage = lambda **kwargs: None + + pipeline_entity = SimpleNamespace(id=SimpleNamespace(root=uuid4())) + topics_by_fqn = {f'Kafka."{name}"': self._entity(Topic, f'Kafka."{name}"') for name in ingested_topic_names} + + def _get_by_name(entity=None, fqn=None, **kwargs): + entity_name = getattr(entity, "__name__", "") + if entity_name == "Pipeline": + return pipeline_entity + if entity_name == "Topic": + return topics_by_fqn.get(fqn) + return None + + def _fqn_build(entity_type=None, service_name=None, topic_name=None, **kwargs): + entity_name = getattr(entity_type, "__name__", "") + if entity_name == "Topic": + return f'{service_name}."{topic_name}"' + return "KafkaConnectSvc.outbox-connector" + + source.metadata = MagicMock() + source.metadata.get_by_name.side_effect = _get_by_name + source.metadata.list_all_entities.return_value = [self._ingested_topic(name) for name in ingested_topic_names] + + details = KafkaConnectPipelineDetails( + name="outbox-connector", + type="source", + config=config, + topics=[KafkaConnectTopics(name=name) for name in (pipeline_topics or [])], + ) + + with patch( + "metadata.ingestion.source.pipeline.kafkaconnect.metadata.fqn.build", + side_effect=_fqn_build, + ): + results = list(source.yield_pipeline_lineage_details(details)) + + errors = [r.left for r in results if r.left is not None] + assert not errors, f"lineage yielded errors: {errors}" + return table_entity, [r.right for r in results if r.right is not None] + + def test_outbox_event_router_yields_lineage_edges(self): + """Outbox EventRouter must emit table -> topic edges for every routed topic.""" + config = { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "topic.prefix": "ecommerce.sales", + "table.include.list": "prod.sales.outbox", + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "prod.global.sales.${routedByValue}_v1", + } + ingested = [ + "prod.global.sales.orderCreated_v1", + "prod.global.sales.orderCancelled_v1", + "unrelated.topic", + ] + + table_entity, edges = self._run_lineage(config, ingested) + + assert len(edges) == 2 + for edge in edges: + assert edge.edge.fromEntity.type == "table" + assert edge.edge.fromEntity.id.root == table_entity.id + assert edge.edge.toEntity.type == "topic" + + def test_outbox_event_router_yields_edges_from_connector_topics(self): + """ + Live path: Kafka Connect's /topics reports the post-transform topics, so + they arrive pre-populated on the connector rather than via pattern search. + The outbox fan-out must still emit an edge per topic. + """ + config = { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "topic.prefix": "ecommerce.sales", + "table.include.list": "prod.sales.outbox", + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "prod.global.sales.${routedByValue}_v1", + } + routed = ["prod.global.sales.orderCreated_v1", "prod.global.sales.orderCancelled_v1"] + + table_entity, edges = self._run_lineage(config, routed, pipeline_topics=routed) + + assert len(edges) == 2 + for edge in edges: + assert edge.edge.fromEntity.id.root == table_entity.id + assert edge.edge.toEntity.type == "topic" + + def test_multi_table_outbox_connector_does_not_fan_out(self): + """ + A connector capturing several tables cannot attribute routed topics to a + specific table, so it must NOT fan the outbox topics out to every table. + """ + config = { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "topic.prefix": "ecommerce.sales", + "table.include.list": "prod.sales.outbox,prod.sales.orders", + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.route.topic.replacement": "prod.global.sales.${routedByValue}_v1", + } + routed = ["prod.global.sales.orderCreated_v1"] + + _table_entity, edges = self._run_lineage(config, routed) + + assert edges == [] + + def test_regex_router_yields_lineage_edge(self): + """A RegexRouter-renamed CDC topic must still match its table and emit an edge.""" + config = { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "topic.prefix": "ecommerce.sales", + "table.include.list": "prod.sales.outbox", + "transforms": "route", + "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter", + "transforms.route.regex": r"ecommerce\.sales\.prod\.sales\.(.*)", + "transforms.route.replacement": "prod.global.sales.$1", + } + ingested = ["prod.global.sales.outbox"] + + _table_entity, edges = self._run_lineage(config, ingested) + + assert len(edges) == 1 + assert edges[0].edge.fromEntity.type == "table" + assert edges[0].edge.toEntity.type == "topic" diff --git a/ingestion/tests/unit/topology/test_topology_progress_path.py b/ingestion/tests/unit/topology/test_topology_progress_path.py index 725070e769db..aed36e46d14f 100644 --- a/ingestion/tests/unit/topology/test_topology_progress_path.py +++ b/ingestion/tests/unit/topology/test_topology_progress_path.py @@ -19,6 +19,9 @@ from unittest.mock import MagicMock from metadata.ingestion.api.topology_runner import TopologyRunnerMixin +from metadata.ingestion.models.topology import get_topology_node +from metadata.ingestion.progress.modes import ProgressMode +from metadata.ingestion.progress.runner_tracker import NO_OP_NODE_PROGRESS from metadata.ingestion.source.database.database_service import ( DatabaseServiceTopology, ) @@ -37,58 +40,63 @@ def __init__(self, database=None, database_schema=None): class TestGenericProgressPath: def test_database_node_opens_at_root(self): - assert _DBLikeRunner(database="db").current_progress_path("Database") == [] + assert _DBLikeRunner(database="db").progress_tracker.current_path("Database") == [] def test_schema_node_opens_under_its_database(self): runner = _DBLikeRunner(database="db") - assert runner.current_progress_path("DatabaseSchema") == ["db"] + assert runner.progress_tracker.current_path("DatabaseSchema") == ["db"] def test_table_node_opens_under_database_and_schema(self): runner = _DBLikeRunner(database="db", database_schema="sales") - assert runner.current_progress_path("Table") == ["db", "sales"] + assert runner.progress_tracker.current_path("Table") == ["db", "sales"] def test_stored_procedure_opens_under_database_and_schema(self): runner = _DBLikeRunner(database="db", database_schema="sales") - assert runner.current_progress_path("StoredProcedure") == ["db", "sales"] + assert runner.progress_tracker.current_path("StoredProcedure") == ["db", "sales"] def test_schema_node_ignores_stale_sibling_schema_context(self): runner = _DBLikeRunner(database="db2", database_schema="stale_from_db1") - assert runner.current_progress_path("DatabaseSchema") == ["db2"] + assert runner.progress_tracker.current_path("DatabaseSchema") == ["db2"] def test_unknown_entity_type_yields_empty_path(self): - assert _DBLikeRunner(database="db").current_progress_path("Nope") == [] + assert _DBLikeRunner(database="db").progress_tracker.current_path("Nope") == [] def test_none_entity_type_does_not_touch_topology_or_context(self): # The default surface test: no entity type means no path, and the # method must not require topology/context to be set. - assert TopologyRunnerMixin().current_progress_path() == [] + assert TopologyRunnerMixin().progress_tracker.current_path() == [] def test_root_context_keys_derived_from_topology(self): - assert _DBLikeRunner().current_progress_path # smoke: method resolves - assert _DBLikeRunner()._root_context_keys() == {"database_service"} + assert _DBLikeRunner().progress_tracker.current_path # smoke: method resolves + assert _DBLikeRunner().progress_tracker._root_context_keys() == {"database_service"} class TestShouldTrackProgress: - def _runner(self, enabled): - runner = TopologyRunnerMixin() - runner.progress_tracking_enabled = enabled - runner.__dict__["_root_node_ids"] = set() + def _runner(self, mode): + runner = _DBLikeRunner() + runner.progress_mode = mode return runner def test_disabled_never_tracks(self): - assert self._runner(False)._should_track_progress(object(), "Table") is False + runner = self._runner(ProgressMode.OFF) + table_node = get_topology_node("table", runner.topology) + assert runner.progress_tracker.for_node(table_node, is_leaf=True) is NO_OP_NODE_PROGRESS def test_enabled_real_entity_tracks(self): - assert self._runner(True)._should_track_progress(object(), "Table") is True + runner = self._runner(ProgressMode.AUTO) + table_node = get_topology_node("table", runner.topology) + assert runner.progress_tracker.for_node(table_node, is_leaf=True) is not NO_OP_NODE_PROGRESS def test_enabled_but_no_entity_type_does_not_track(self): - assert self._runner(True)._should_track_progress(object(), None) is False + runner = self._runner(ProgressMode.AUTO) + node = SimpleNamespace(stages=[]) + assert runner.progress_tracker.for_node(node, is_leaf=True) is NO_OP_NODE_PROGRESS def test_enabled_root_node_does_not_track(self): - runner = self._runner(True) - root = object() - runner.__dict__["_root_node_ids"] = {id(root)} - assert runner._should_track_progress(root, "Database") is False + runner = self._runner(ProgressMode.AUTO) + root_node = get_topology_node("root", runner.topology) + runner.progress_tracker.on_walk_start([root_node]) + assert runner.progress_tracker.for_node(root_node, is_leaf=False) is NO_OP_NODE_PROGRESS - def test_default_flag_is_false(self): - assert TopologyRunnerMixin.progress_tracking_enabled is False + def test_default_mode_is_auto(self): + assert TopologyRunnerMixin.progress_mode is ProgressMode.AUTO diff --git a/ingestion/tests/unit/topology/test_topology_runner_progress.py b/ingestion/tests/unit/topology/test_topology_runner_progress.py index ad1377e0c4ce..08490334fe05 100644 --- a/ingestion/tests/unit/topology/test_topology_runner_progress.py +++ b/ingestion/tests/unit/topology/test_topology_runner_progress.py @@ -21,24 +21,25 @@ TopologyContextManager, get_topology_node, ) +from metadata.ingestion.progress.modes import ProgressMode +from metadata.ingestion.progress.registry import ProgressRegistry from metadata.ingestion.source.database.database_service import ( DatabaseServiceTopology, ) -from metadata.utils.progress_registry import ProgressRegistry class TestRunnerProgressSurface: def test_progress_is_lazy_per_instance(self): runner = TopologyRunnerMixin() - registry = runner.progress + registry = runner.progress_tracking.registry assert isinstance(registry, ProgressRegistry) - assert runner.progress is registry + assert runner.progress_tracking.registry is registry def test_distinct_instances_distinct_registries(self): - assert TopologyRunnerMixin().progress is not TopologyRunnerMixin().progress + assert TopologyRunnerMixin().progress_tracking.registry is not TopologyRunnerMixin().progress_tracking.registry def test_current_progress_path_default_is_empty(self): - assert TopologyRunnerMixin().current_progress_path() == [] + assert TopologyRunnerMixin().progress_tracker.current_path() == [] def test_declare_totals_is_gone(self): assert not hasattr(TopologyRunnerMixin, "declare_totals") @@ -50,13 +51,14 @@ def test_no_count_pass_in_iter(self): source = inspect.getsource(topology_runner) assert "declare_totals" not in source - def test_root_node_detection_uses_iter_captured_ids(self): - runner = TopologyRunnerMixin() - root, child = object(), object() - assert runner._is_root_node(root) is False # nothing captured yet - runner.__dict__["_root_node_ids"] = {id(root)} - assert runner._is_root_node(root) is True - assert runner._is_root_node(child) is False + +def test_root_node_detection_uses_walk_captured_ids(): + runner = TopologyRunnerMixin() + root, child = object(), object() + assert runner.progress_tracker.is_root_node(root) is False + runner.progress_tracker.on_walk_start([root]) + assert runner.progress_tracker.is_root_node(root) is True + assert runner.progress_tracker.is_root_node(child) is False class _WalkRunner(TopologyRunnerMixin): @@ -65,10 +67,9 @@ class _WalkRunner(TopologyRunnerMixin): topology = DatabaseServiceTopology() - def __init__(self, enabled): - self.progress_tracking_enabled = enabled + def __init__(self, mode=ProgressMode.AUTO): + self.progress_mode = mode self.context = TopologyContextManager(self.topology) - self.__dict__["_root_node_ids"] = set() self.status = MagicMock() def _run_node_producer(self, node): @@ -94,27 +95,39 @@ def _drive_container(runner): def test_disabled_walk_creates_no_registry(): - runner = _WalkRunner(enabled=False) + runner = _WalkRunner(mode=ProgressMode.OFF) + _drive_leaf(runner) + assert "_progress_tracking" not in runner.__dict__ + + +def test_manual_walk_creates_no_registry(): + runner = _WalkRunner(mode=ProgressMode.MANUAL) _drive_leaf(runner) - assert "_progress_registry" not in runner.__dict__ + assert "_progress_tracking" not in runner.__dict__ def test_enabled_walk_records_into_registry(): - runner = _WalkRunner(enabled=True) + runner = _WalkRunner() _drive_leaf(runner) - snapshot = runner.progress.snapshot() + snapshot = runner.progress_tracking.registry.snapshot() assert snapshot.child_type == "Table" assert snapshot.processed == 2 +def test_plain_connector_gets_progress_by_default(): + runner = _WalkRunner() + _drive_leaf(runner) + assert runner.progress_tracking.registry.snapshot().processed == 2 + + def test_container_open_none_through_runner(): """Driving _process_node through the *database* container node must call ``progress.open(parent_path, "Database", None)`` — the lazy branch where no connector pushes a total — so the registry records ``expected=None`` for the Database level.""" - runner = _WalkRunner(enabled=True) + runner = _WalkRunner() _drive_container(runner) - snapshot = runner.progress.snapshot() + snapshot = runner.progress_tracking.registry.snapshot() assert snapshot is not None assert snapshot.child_type == "Database" assert snapshot.expected_by_type.get("Database") is None @@ -123,13 +136,13 @@ def test_container_open_none_through_runner(): @pytest.fixture def progress_runner(): """A _WalkRunner with progress tracking enabled, pre-seeded with a registry.""" - return _WalkRunner(enabled=True) + return _WalkRunner() def test_container_without_push_is_unknown(progress_runner): - # progress_runner: a TopologyRunnerMixin test double with progress_tracking_enabled=True - progress_runner.progress.open(["db1"], "DatabaseSchema", None) - snap = progress_runner.progress.snapshot() + # progress_runner: a TopologyRunnerMixin test double with progress_mode=AUTO + progress_runner.progress_tracking.registry.open(["db1"], "DatabaseSchema", None) + snap = progress_runner.progress_tracking.registry.snapshot() assert snap.children[0].expected is None @@ -143,7 +156,7 @@ def test_runner_has_no_pull_hooks(): class _CtxWalkRunner(_WalkRunner): """Like _WalkRunner but writes each entity into the node's context key, so - consumer-derived paths and _scope_path_for_node resolve to real names.""" + consumer-derived paths and scope_path_for_node resolve to real names.""" def _process_stage(self, stage, node_entity): if getattr(stage, "context", None): @@ -152,23 +165,23 @@ def _process_stage(self, stage, node_entity): def test_scope_path_for_node_appends_context_value(): - runner = _WalkRunner(enabled=True) + runner = _WalkRunner() database_node = get_topology_node("database", runner.topology) key = runner._node_primary_stage(database_node).context setattr(runner.context.get(), key, "salesdb") - assert runner._scope_path_for_node(database_node, []) == ["salesdb"] + assert runner.progress_tracker.scope_path_for_node(database_node, []) == ["salesdb"] def test_scope_path_for_node_is_none_without_context_value(): - runner = _WalkRunner(enabled=True) + runner = _WalkRunner() database_node = get_topology_node("database", runner.topology) - assert runner._scope_path_for_node(database_node, []) is None + assert runner.progress_tracker.scope_path_for_node(database_node, []) is None def test_completed_container_is_closed_through_runner(): - runner = _CtxWalkRunner(enabled=True) + runner = _CtxWalkRunner() closed: list = [] - runner.progress.close = lambda path: closed.append(list(path)) + runner.progress_tracking.registry.close = lambda path: closed.append(list(path)) container = get_topology_node("database", runner.topology) list(runner._process_node(container)) # producer yields "a","b"; each database entity is closed at its own path @@ -183,10 +196,9 @@ class _StatefulLeafRunner(TopologyRunnerMixin): topology = DatabaseServiceTopology() - def __init__(self, enabled): - self.progress_tracking_enabled = enabled + def __init__(self, mode=ProgressMode.AUTO): + self.progress_mode = mode self.context = TopologyContextManager(self.topology) - self.__dict__["_root_node_ids"] = set() self.status = MagicMock() self.state_live_at_stage = [] self._active = None @@ -208,35 +220,73 @@ def _process_stage(self, stage, node_entity): def test_leaf_is_lazy_when_progress_off_preserving_per_yield_state(): - runner = _StatefulLeafRunner(enabled=False) + runner = _StatefulLeafRunner(mode=ProgressMode.OFF) list(runner._process_node(get_topology_node("table", runner.topology))) assert runner.state_live_at_stage == ["a", "b"] -def test_leaf_is_eager_when_progress_on_recording_count(): - runner = _StatefulLeafRunner(enabled=True) +def test_leaf_is_lazy_when_progress_on_preserving_per_yield_state(): + """AUTO-mode leaf producers must still iterate lazily: per-yield producer + state stays live when each stage runs (an eager list()-drain would tear it + down first), while the per-leaf advance keeps the processed count accurate.""" + runner = _StatefulLeafRunner() list(runner._process_node(get_topology_node("table", runner.topology))) - assert runner.state_live_at_stage == [None, None] - assert runner.progress.snapshot().processed == 2 + assert runner.state_live_at_stage == ["a", "b"] + assert runner.progress_tracking.registry.snapshot().processed == 2 + + +class _CtxReadingLeafRunner(TopologyRunnerMixin): + """Mirrors S3 ``get_containers``: the leaf producer reads a context value that + a *stage* of the just-yielded entity populates. Correct only under lazy + iteration — an eager list()-drain runs the producer to completion before any + stage writes the context, so the producer reads ``None``.""" + + topology = DatabaseServiceTopology() + + def __init__(self, mode=ProgressMode.AUTO): + self.progress_mode = mode + self.context = TopologyContextManager(self.topology) + self.status = MagicMock() + self.observed_context = [] + + def _run_node_producer(self, node): + for name in ["t1", "t2"]: + yield name + self.observed_context.append(getattr(self.context.get(), "table", None)) + + def _process_stage(self, stage, node_entity): + if getattr(stage, "context", None): + setattr(self.context.get(), stage.context, node_entity) + return iter(()) + + +def test_leaf_producer_reads_context_written_by_prior_yield_stage(): + """Regression for the S3 ``get_containers`` crash (NoneType fqn / + ``container.id``): a leaf producer that reads context populated by the + just-yielded entity's stage must observe it. An eager list()-drain leaves the + context unset, so the producer would read ``None`` for every entity.""" + runner = _CtxReadingLeafRunner() + list(runner._process_node(get_topology_node("table", runner.topology))) + assert runner.observed_context == ["t1", "t2"] def test_closing_container_tracks_global_done(): - runner = _CtxWalkRunner(enabled=True) - runner.progress.set_total("Database", 5) - runner.progress.set_total("DatabaseSchema", 9) + runner = _CtxWalkRunner() + runner.progress_tracking.registry.set_total("Database", 5) + runner.progress_tracking.registry.set_total("DatabaseSchema", 9) list(runner._process_node(get_topology_node("database", runner.topology))) - counters = {t: (d, total) for t, d, total in runner.progress.global_counters()} + counters = {t: (d, total) for t, d, total in runner.progress_tracking.registry.global_counters()} assert counters["Database"][0] == 2 # 2 databases ("a","b") closed assert counters["DatabaseSchema"][0] == 4 # 2 schemas per database closed def test_reconcilable_container_reconciles_total(): - runner = _CtxWalkRunner(enabled=True) - runner.progress.seed_scope_total("DatabaseSchema", "a", 1) - runner.progress.seed_scope_total("DatabaseSchema", "b", 1) + runner = _CtxWalkRunner() + runner.progress_tracking.registry.seed_scope_total("DatabaseSchema", "a", 1) + runner.progress_tracking.registry.seed_scope_total("DatabaseSchema", "b", 1) # upfront total = 2 (1 seeded per declared database) list(runner._process_node(get_topology_node("database", runner.topology))) - counters = {t: (d, total) for t, d, total in runner.progress.global_counters()} + counters = {t: (d, total) for t, d, total in runner.progress_tracking.registry.global_counters()} # each database actually walks 2 schemas -> reconciled total 2*2=4; done=4 assert counters["DatabaseSchema"] == (4, 4) @@ -247,8 +297,8 @@ class _MultiThreadCtxWalkRunner(_CtxWalkRunner): instead of _process_node. Post-process methods are no-ops because the runner stub does not implement the real connector hooks.""" - def __init__(self, enabled): - super().__init__(enabled) + def __init__(self, mode=ProgressMode.AUTO): + super().__init__(mode) self.context.threads = 2 def _run_node_post_process(self, node): @@ -261,13 +311,55 @@ def test_multithread_schema_node_reconciles_and_tracks_done(): reconcile_scope_total and track are exercised identically to the single-thread reconcile test: seed 1 per declared db, observe 2 per db, final counters show (done=4, total=4).""" - runner = _MultiThreadCtxWalkRunner(enabled=True) - runner.progress.seed_scope_total("DatabaseSchema", "a", 1) - runner.progress.seed_scope_total("DatabaseSchema", "b", 1) + runner = _MultiThreadCtxWalkRunner() + runner.progress_tracking.registry.seed_scope_total("DatabaseSchema", "a", 1) + runner.progress_tracking.registry.seed_scope_total("DatabaseSchema", "b", 1) # upfront total = 2; driving _process_node(database) recurses into # process_nodes([databaseSchema]) which routes to _multithread_process_node # because databaseSchema.threads=True and context.threads=2 list(runner._process_node(get_topology_node("database", runner.topology))) - counters = {t: (d, total) for t, d, total in runner.progress.global_counters()} + counters = {t: (d, total) for t, d, total in runner.progress_tracking.registry.global_counters()} # each database actually walks 2 schemas -> reconciled total 2*2=4; done=4 assert counters["DatabaseSchema"] == (4, 4) + + +class _TotalsWalkRunner(_WalkRunner): + def __init__(self): + super().__init__() + self.declared = 0 + + def declare_progress_totals(self, totals): + self.declared += 1 + totals.set_total("Table", 99) + + +def test_declare_progress_totals_called_once_per_walk(): + runner = _TotalsWalkRunner() + _drive_leaf(runner) + _drive_leaf(runner) + assert runner.declared == 1 + # Two drives of two leaves each advance the leaf-declared global counter's + # done to 4 (see test_leaf_total_advances_global_done). + assert ("Table", 4, 99) in runner.progress_tracking.registry.global_counters() + + +def test_leaf_total_advances_global_done(): + """A total declared on a *leaf* entity type must have its global-counter + ``done`` advanced by leaf processing. Leaves have no container scope, so the + per-leaf ``advance_leaf`` is the only place their ``done`` can move; without + it a leaf-primary connector (e.g. Airflow pipelines) shows a stuck 0/total + denominator while the tree ``processed`` climbs.""" + runner = _TotalsWalkRunner() + _drive_leaf(runner) + counters = {t: (d, total) for t, d, total in runner.progress_tracking.registry.global_counters()} + assert counters["Table"] == (2, 99) + + +def test_leaf_advance_without_total_is_noop_on_global(): + """The added per-leaf ``track`` must stay a no-op for leaf types with no + declared counter (every DB/dashboard connector's leaf), so their counting is + unchanged: the tree ``processed`` advances but no global counter appears.""" + runner = _WalkRunner() + _drive_leaf(runner) + assert runner.progress_tracking.registry.global_counters() == [] + assert runner.progress_tracking.registry.snapshot().processed == 2 diff --git a/ingestion/tests/unit/workflow/test_context_manager.py b/ingestion/tests/unit/workflow/test_context_manager.py index 5c3a40d73721..c29e2ee0d407 100644 --- a/ingestion/tests/unit/workflow/test_context_manager.py +++ b/ingestion/tests/unit/workflow/test_context_manager.py @@ -1,3 +1,9 @@ +import pytest + +from metadata.workflow.context.app_metadata_context import ( + AppMetadataContext, + AppMetadataContextFieldsEnum, +) from metadata.workflow.context.context_manager import ContextManager, ContextsEnum from metadata.workflow.context.workflow_context import ( WorkflowContext, @@ -47,3 +53,25 @@ def set_service_name(name): # The final value should be one of the set values final_value = ContextManager.get_context_attr(ContextsEnum.WORKFLOW, WorkflowContextFieldsEnum.SERVICE_NAME) assert final_value in {f"service_{i}" for i in range(10)} + + +def test_app_metadata_context_registered(): + ctx = ContextManager.get_context(ContextsEnum.APP_METADATA) + assert isinstance(ctx, AppMetadataContext) + + +@pytest.fixture +def reset_app_metadata(): + """ContextManager is a process-wide singleton, so app-metadata state set by one + test would otherwise leak into every test that runs after it.""" + yield + ContextManager.set_context_attr(ContextsEnum.APP_METADATA, AppMetadataContextFieldsEnum.DATA, None) + + +def test_app_metadata_dumps_under_app_metadata_key(reset_app_metadata): + data = {"impact": {"proposed": 9, "autoApplied": 0, "awaitingReview": 9, "rejected": 0}} + ContextManager.set_context_attr(ContextsEnum.APP_METADATA, AppMetadataContextFieldsEnum.DATA, data) + + dumped = ContextManager.dump_contexts() + + assert dumped["appMetadata"]["data"] == data diff --git a/ingestion/tests/unit/workflow/test_progress_rendering.py b/ingestion/tests/unit/workflow/test_progress_rendering.py index 0333f831387f..236271b005c7 100644 --- a/ingestion/tests/unit/workflow/test_progress_rendering.py +++ b/ingestion/tests/unit/workflow/test_progress_rendering.py @@ -16,13 +16,12 @@ ProgressNode, ProgressUpdate, ) -from metadata.utils.progress_registry import ProgressNodeSnapshot, ProgressRegistry -from metadata.workflow.progress_render import ( - ProgressReporter, +from metadata.ingestion.progress import ( format_eta, render_progress_tree, snapshot_to_progress_payload, ) +from metadata.ingestion.progress.registry import ProgressNodeSnapshot, ProgressRegistry def _tree_snapshot(): @@ -46,7 +45,7 @@ def test_counts_all_leaf_types(self): reg.advance(["db", "sch"], "Table") for _ in range(2): reg.advance(["db", "sch"], "StoredProcedure") - assert ProgressReporter(reg).assets_ingested() == 5 + assert reg.assets_ingested() == 5 def test_survives_scope_pruning(self): reg = ProgressRegistry() @@ -56,7 +55,7 @@ def test_survives_scope_pruning(self): reg.advance(["db", "sch"], "Table") reg.close(["db", "sch"]) reg.close(["db"]) - assert ProgressReporter(reg).assets_ingested() == 2 + assert reg.assets_ingested() == 2 class TestProgressRendering: @@ -122,20 +121,20 @@ def _snowflake_like_registry() -> ProgressRegistry: return registry -class TestProgressReporter: +class TestRegistryReporting: def test_cli_header_is_assets_ingested(self): registry = _snowflake_like_registry() - text = ProgressReporter(registry).cli() + text = registry.render_cli() assert text.splitlines()[0] == f"Ingested: {registry.assets_ingested():,} assets" def test_cli_still_shows_active_scope(self): - text = ProgressReporter(_snowflake_like_registry()).cli() + text = _snowflake_like_registry().render_cli() assert "sales.public" in text assert "45/310" in text def test_payload_root_carries_asset_total(self): registry = _snowflake_like_registry() - payload = ProgressReporter(registry).payload() + payload = registry.sse_payload() assert set(payload) == { "label", "entityType", @@ -153,13 +152,13 @@ def test_payload_validates_against_progress_update_model(self): runId="r", timestamp=1, updateType="PROCESSING", - progress=ProgressReporter(_snowflake_like_registry()).payload(), + progress=_snowflake_like_registry().sse_payload(), ) assert update.progress is not None assert update.progress.processed == 45 def test_payload_is_none_before_anything_starts(self): - assert ProgressReporter(ProgressRegistry()).payload() is None + assert ProgressRegistry().sse_payload() is None def test_progress_update_carries_global_counters(self): reg = ProgressRegistry() @@ -167,7 +166,7 @@ def test_progress_update_carries_global_counters(self): reg.track("Workspaces") reg.track("Workspaces") reg.track("Workspaces") - counters = ProgressReporter(reg).global_counters() + counters = reg.global_counters() update = ProgressUpdate( runId="r1", timestamp=1, @@ -189,7 +188,7 @@ def test_header_shows_counters_then_assets(self): for _ in range(12): reg.track("DatabaseSchema") reg.advance([], "Table") - lines = ProgressReporter(reg).cli().splitlines() + lines = reg.render_cli().splitlines() assert lines[0] == "Database 2/4" assert lines[1].startswith("DatabaseSchema 12/45") assert lines[2] == "Ingested: 1 assets" @@ -198,25 +197,25 @@ def test_header_unknown_total_renders_bare_count(self): reg = ProgressRegistry() reg.set_total("Workspaces", None) reg.track("Workspaces") - assert ProgressReporter(reg).cli() == "Workspaces 1" + assert reg.render_cli() == "Workspaces 1" def test_header_renders_with_empty_tree_when_counter_active(self): reg = ProgressRegistry() reg.set_total("Workspaces", 4) for _ in range(4): reg.track("Workspaces") - assert ProgressReporter(reg).cli() == "Workspaces 4/4" + assert reg.render_cli() == "Workspaces 4/4" def test_no_group_keeps_legacy_header(self): reg = ProgressRegistry() reg.open([], "Database", None) reg.open(["x"], "Table", 2) reg.advance(["x"], "Table") - assert ProgressReporter(reg).cli().splitlines()[0] == "Ingested: 1 assets" + assert reg.render_cli().splitlines()[0] == "Ingested: 1 assets" def test_cli_empty_when_no_progress(self): reg = ProgressRegistry() - assert ProgressReporter(reg).cli() == "" + assert reg.render_cli() == "" class TestGlobalCountersOnSseUpdate: @@ -226,7 +225,7 @@ def test_reporter_global_counters_passthrough(self): reg.track("Workspaces") reg.track("Workspaces") reg.track("Workspaces") - assert ProgressReporter(reg).global_counters() == [("Workspaces", 3, 10)] + assert reg.global_counters() == [("Workspaces", 3, 10)] class TestFormatEta: @@ -251,14 +250,14 @@ def test_warmup_done_zero_is_none(self): reg = ProgressRegistry() reg.open([], "Database", None) reg.set_total("DatabaseSchema", 45) - assert ProgressReporter(reg).eta_seconds() is None + assert reg.eta_seconds() is None def test_no_counter_with_total_is_none(self): reg = ProgressRegistry() reg.open([], "Database", None) reg.set_total("Workspaces", None) reg.track("Workspaces") - assert ProgressReporter(reg).eta_seconds() is None + assert reg.eta_seconds() is None def test_complete_is_none(self): reg = ProgressRegistry() @@ -266,32 +265,32 @@ def test_complete_is_none(self): reg.set_total("DatabaseSchema", 4) for _ in range(4): reg.track("DatabaseSchema") - assert ProgressReporter(reg).eta_seconds() is None + assert reg.eta_seconds() is None def test_computable_without_open_when_counter_active(self): reg = ProgressRegistry() - with patch("metadata.utils.progress_registry.time.monotonic") as clock: + with patch("metadata.ingestion.progress.registry.time.monotonic") as clock: clock.return_value = 0.0 reg.set_total("DatabaseSchema", 10) for _ in range(2): reg.track("DatabaseSchema") clock.return_value = 60.0 - assert ProgressReporter(reg).eta_seconds() == 240 + assert reg.eta_seconds() == 240 def test_normal_case_uses_cumulative_rate(self): reg = ProgressRegistry() - with patch("metadata.utils.progress_registry.time.monotonic") as clock: + with patch("metadata.ingestion.progress.registry.time.monotonic") as clock: clock.return_value = 0.0 reg.open([], "Database", None) reg.set_total("DatabaseSchema", 10) for _ in range(2): reg.track("DatabaseSchema") clock.return_value = 60.0 - assert ProgressReporter(reg).eta_seconds() == 240 + assert reg.eta_seconds() == 240 def test_driver_is_last_counter_with_total(self): reg = ProgressRegistry() - with patch("metadata.utils.progress_registry.time.monotonic") as clock: + with patch("metadata.ingestion.progress.registry.time.monotonic") as clock: clock.return_value = 0.0 reg.open([], "Database", None) reg.set_total("Database", 4) @@ -300,13 +299,13 @@ def test_driver_is_last_counter_with_total(self): for _ in range(4): reg.track("DatabaseSchema") clock.return_value = 100.0 - assert ProgressReporter(reg).eta_seconds() == 400 + assert reg.eta_seconds() == 400 class TestEtaInHeader: def test_eta_suffix_on_driver_line_only(self): reg = ProgressRegistry() - with patch("metadata.utils.progress_registry.time.monotonic") as clock: + with patch("metadata.ingestion.progress.registry.time.monotonic") as clock: clock.return_value = 0.0 reg.open([], "Database", None) reg.set_total("Database", 4) @@ -316,7 +315,7 @@ def test_eta_suffix_on_driver_line_only(self): for _ in range(9): reg.track("DatabaseSchema") clock.return_value = 120.0 - lines = ProgressReporter(reg).cli().splitlines() + lines = reg.render_cli().splitlines() assert lines[0] == "Database 2/4" assert lines[1].startswith("DatabaseSchema 9/45") assert "~8m" in lines[1] @@ -326,7 +325,7 @@ def test_no_eta_suffix_when_not_computable(self): reg = ProgressRegistry() reg.open([], "Database", None) reg.set_total("DatabaseSchema", 45) - assert "~" not in ProgressReporter(reg).cli() + assert "~" not in reg.render_cli() class TestHeaderIngestedSuppression: @@ -334,7 +333,7 @@ def test_ingested_line_suppressed_when_no_assets(self): registry = ProgressRegistry() registry.set_total("Queries", 100) registry.track("Queries", 12) - text = ProgressReporter(registry).cli() + text = registry.render_cli() assert "Queries 12/100" in text assert "Ingested:" not in text @@ -342,7 +341,7 @@ def test_totalless_counter_renders_without_denominator_or_eta(self): registry = ProgressRegistry() registry.set_total("LineageRecords", None) registry.track("LineageRecords", 8210) - text = ProgressReporter(registry).cli() + text = registry.render_cli() assert "LineageRecords 8210" in text assert "/" not in text assert "Ingested:" not in text @@ -351,5 +350,5 @@ def test_ingested_line_kept_when_assets_present(self): registry = ProgressRegistry() registry.open(["db", "schema"], "Table", 3) registry.advance(["db", "schema"], "Table") - text = ProgressReporter(registry).cli() + text = registry.render_cli() assert "Ingested: 1 assets" in text diff --git a/ingestion/tests/unit/workflow/test_status_mixin_progress.py b/ingestion/tests/unit/workflow/test_status_mixin_progress.py index 146a62d7ee75..06b6e1a5ac77 100644 --- a/ingestion/tests/unit/workflow/test_status_mixin_progress.py +++ b/ingestion/tests/unit/workflow/test_status_mixin_progress.py @@ -8,7 +8,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""send_progress_update maps ProgressReporter.eta_seconds into the SSE payload.""" +"""send_progress_update maps ProgressRegistry.eta_seconds into the SSE payload.""" from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -16,13 +16,13 @@ from metadata.generated.schema.entity.services.ingestionPipelines.progressUpdate import ( ProgressUpdateType, ) -from metadata.utils.progress_registry import ProgressRegistry +from metadata.ingestion.progress.registry import ProgressRegistry from metadata.workflow.workflow_status_mixin import WorkflowStatusMixin class _FakeStep: def __init__(self, registry: ProgressRegistry) -> None: - self._progress_registry = registry + self._progress_tracking = SimpleNamespace(registry=registry) class _Harness(WorkflowStatusMixin): @@ -46,7 +46,7 @@ class TestEstimatedSecondsRemaining: def test_maps_eta_seconds_into_payload(self): reg = ProgressRegistry() metadata = MagicMock() - with patch("metadata.utils.progress_registry.time.monotonic") as clock: + with patch("metadata.ingestion.progress.registry.time.monotonic") as clock: clock.return_value = 0.0 reg.open([], "Database", None) reg.set_total("DatabaseSchema", 10) diff --git a/openmetadata-clients/openmetadata-java-client/pom.xml b/openmetadata-clients/openmetadata-java-client/pom.xml index d8cd273d73c6..c27b3ab1673b 100644 --- a/openmetadata-clients/openmetadata-java-client/pom.xml +++ b/openmetadata-clients/openmetadata-java-client/pom.xml @@ -89,6 +89,16 @@ msal4j 1.17.2 + + + com.nimbusds + oauth2-oidc-sdk + 11.38.1 + org.projectlombok lombok diff --git a/openmetadata-integration-tests/pom.xml b/openmetadata-integration-tests/pom.xml index f6b3bf6a7d60..6b21e22e8eee 100644 --- a/openmetadata-integration-tests/pom.xml +++ b/openmetadata-integration-tests/pom.xml @@ -216,7 +216,7 @@ org.eclipse.parsson parsson - 1.1.7 + 1.1.8 test contextMemory} relationship a - * memory creates from its sourceEntity. Linking a memory to a page via sourceEntity must make the - * page's memoryCount reflect it (and the relationship-backed sourceEntityId listing return it), - * proving the edge is stored with the page's entity type so the typed {@code findTo} count matches. - */ - @Test - void articleMemoryCountReflectsLinkedMemories(TestNamespace ns) throws HttpResponseException { - RestClient rest = RestClient.admin(); - EntityReference orgRef = getOrganizationRef(); - - Page page = createPage(rest, buildCreateRequest(ns.prefix("pageMemoryCount"), orgRef)); - - CreateContextMemory memoryRequest = - new CreateContextMemory() - .withName(ns.prefix("memCountPill")) - .withQuestion("What does the engagement-weighted CLV metric measure?") - .withAnswer("Customer lifetime value adjusted by an engagement-tier multiplier.") - .withSourceEntity(new EntityReference().withId(page.getId()).withType("page")); - rest.create("v1/contextCenter/memories", memoryRequest, ContextMemory.class); - - Page withCount = getPage(rest, page.getId(), "memoryCount"); - assertEquals( - Integer.valueOf(1), - withCount.getMemoryCount(), - "memoryCount must reflect the MENTIONED_IN-linked memory"); - } - - /** - * The Memory Agent stamps each memory's memoryStats after deriving, loading it via {@code - * getFields("")} (no relationship fields). That machine update must NOT delete the memory's - * sourceEntity MENTIONED_IN edge — a regression that orphaned the pill from its page, zeroing - * memoryCount and the article's derived ontologies. Reproduces the exact stamp path in-process. - */ - @Test - void ontologyStampPreservesMemorySourceLink(TestNamespace ns) throws HttpResponseException { - RestClient rest = RestClient.admin(); - EntityReference orgRef = getOrganizationRef(); - - Page page = createPage(rest, buildCreateRequest(ns.prefix("pageOntologyStamp"), orgRef)); - - CreateContextMemory memoryRequest = - new CreateContextMemory() - .withName(ns.prefix("ontologyStampPill")) - .withQuestion("What engagement multiplier does the CLV metric apply?") - .withAnswer("1.2x engaged, 0.8x occasional, 0.5x dormant.") - .withSourceEntity(new EntityReference().withId(page.getId()).withType("page")); - ContextMemory memory = - rest.create("v1/contextCenter/memories", memoryRequest, ContextMemory.class); - - assertEquals( - Integer.valueOf(1), - getPage(rest, page.getId(), "memoryCount").getMemoryCount(), - "precondition: the memory is linked to its source page"); - - ContextMemoryRepository memoryRepo = - (ContextMemoryRepository) Entity.getEntityRepository(Entity.CONTEXT_MEMORY); - ContextMemory partial = memoryRepo.get(null, memory.getId(), memoryRepo.getFields("")); - memoryRepo.stampMemoryStats( - partial, new MemoryStats().withSourceHash("test-hash").withLastRunAt(1L)); - - assertEquals( - Integer.valueOf(1), - getPage(rest, page.getId(), "memoryCount").getMemoryCount(), - "ontology stamp must preserve the memory's source link (MENTIONED_IN edge)"); - } - @Test void testRelatedEntitiesExcludesDomainsAndDataProducts(TestNamespace ns) throws HttpResponseException { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/SearchSettingsTestHelper.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/SearchSettingsTestHelper.java index e635e4c40ced..1b2f19683184 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/SearchSettingsTestHelper.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/SearchSettingsTestHelper.java @@ -1,6 +1,7 @@ package org.openmetadata.it.search; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -207,6 +208,27 @@ public static void setBoostMode( assetConfig(settings, assetType).setBoostMode(boostMode); } + public static SearchSettings withRankingDisabled( + final SearchSettings settings, final String assetType) { + final JsonNode root = JsonUtils.readTree(JsonUtils.pojoToJson(settings)); + disableRankingNode(root.path("defaultConfiguration")); + + for (JsonNode config : root.path("assetTypeConfigurations")) { + if (assetType.equalsIgnoreCase(config.path("assetType").asText())) { + disableRankingNode(config); + } + } + + return JsonUtils.treeToValue(root, SearchSettings.class); + } + + private static void disableRankingNode(final JsonNode config) { + if (config instanceof ObjectNode configNode + && configNode.path("ranking") instanceof ObjectNode rankingNode) { + rankingNode.put("enabled", false); + } + } + /** * Clears all global and per-asset term/field-value boosts so a scoring test starts from a clean * function-score baseline and only the boosts it adds will fire. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AISettingsResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AISettingsResourceIT.java deleted file mode 100644 index ba8c761668f3..000000000000 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AISettingsResourceIT.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2025 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.it.tests; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.api.parallel.Isolated; -import org.openmetadata.it.util.SdkClients; -import org.openmetadata.it.util.TestNamespaceExtension; -import org.openmetadata.schema.configuration.AIDeletionPolicy; -import org.openmetadata.schema.configuration.AISettings; -import org.openmetadata.schema.configuration.MemoryAgentSettings; -import org.openmetadata.schema.settings.Settings; -import org.openmetadata.schema.settings.SettingsType; -import org.openmetadata.sdk.client.OpenMetadataClient; -import org.openmetadata.sdk.network.HttpMethod; -import org.openmetadata.sdk.network.RequestOptions; - -/** - * Integration tests for the AI Settings REST resource ({@code /system/settings/aiSettings}). - * - *

These tests are fully deterministic: no LLM provider is required. They verify GET default - * values, PUT with changed settings, and reset to defaults via the admin client. - * - *

@Isolated because each test mutates global AI settings; isolation prevents interference with - * concurrently-running tests that read the same settings. - */ -@Isolated -@Execution(ExecutionMode.SAME_THREAD) -@ExtendWith(TestNamespaceExtension.class) -public class AISettingsResourceIT { - - private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final String SETTINGS_PATH = "/v1/system/settings"; - private static final String AI_SETTINGS_PATH = SETTINGS_PATH + "/aiSettings"; - private static final String AI_SETTINGS_RESET_PATH = SETTINGS_PATH + "/reset/aiSettings"; - - @Test - void get_aiSettings_defaultsAreCorrect() throws Exception { - resetToDefaults(); - - AISettings settings = fetchAiSettings(); - - assertNotNull(settings, "AISettings must not be null"); - assertTrue(settings.getEnabled(), "Top-level enabled must default to true"); - assertNotNull(settings.getMemoryAgent(), "memoryAgent must be present in defaults"); - assertTrue(settings.getMemoryAgent().getEnabled(), "memoryAgent.enabled must default to true"); - assertEquals( - AIDeletionPolicy.CASCADE, - settings.getMemoryAgent().getDeletionPolicy(), - "memoryAgent.deletionPolicy must default to cascade"); - } - - @Test - void put_aiSettings_persistsMemoryAgentDisabled() throws Exception { - resetToDefaults(); - - AISettings modified = - new AISettings() - .withEnabled(true) - .withMemoryAgent(new MemoryAgentSettings().withEnabled(false)); - putAiSettings(modified); - - AISettings fetched = fetchAiSettings(); - - assertNotNull(fetched, "Fetched AISettings must not be null"); - assertTrue(fetched.getEnabled(), "Top-level enabled must remain true after partial PUT"); - assertNotNull(fetched.getMemoryAgent(), "memoryAgent must be present after PUT"); - assertEquals( - false, - fetched.getMemoryAgent().getEnabled(), - "memoryAgent.enabled must reflect the PUT value"); - } - - @Test - void put_resetAiSettings_restoresDefaults() throws Exception { - AISettings modified = - new AISettings() - .withEnabled(true) - .withMemoryAgent(new MemoryAgentSettings().withEnabled(false)); - putAiSettings(modified); - - resetToDefaults(); - - AISettings restored = fetchAiSettings(); - - assertNotNull(restored, "Restored AISettings must not be null"); - assertTrue(restored.getEnabled(), "Top-level enabled must be true after reset"); - assertNotNull(restored.getMemoryAgent(), "memoryAgent must be present after reset"); - assertTrue( - restored.getMemoryAgent().getEnabled(), "memoryAgent.enabled must be true after reset"); - assertEquals( - AIDeletionPolicy.CASCADE, - restored.getMemoryAgent().getDeletionPolicy(), - "memoryAgent.deletionPolicy must be cascade after reset"); - } - - private AISettings fetchAiSettings() throws Exception { - OpenMetadataClient client = SdkClients.adminClient(); - String json = - client - .getHttpClient() - .executeForString( - HttpMethod.GET, AI_SETTINGS_PATH, null, RequestOptions.builder().build()); - Settings settings = MAPPER.readValue(json, Settings.class); - assertEquals(SettingsType.AI_SETTINGS, settings.getConfigType()); - return MAPPER.convertValue(settings.getConfigValue(), AISettings.class); - } - - private void putAiSettings(AISettings aiSettings) throws Exception { - OpenMetadataClient client = SdkClients.adminClient(); - Settings payload = - new Settings().withConfigType(SettingsType.AI_SETTINGS).withConfigValue(aiSettings); - String json = MAPPER.writeValueAsString(payload); - client - .getHttpClient() - .executeForString(HttpMethod.PUT, SETTINGS_PATH, json, RequestOptions.builder().build()); - } - - private void resetToDefaults() throws Exception { - OpenMetadataClient client = SdkClients.adminClient(); - client - .getHttpClient() - .executeForString( - HttpMethod.PUT, AI_SETTINGS_RESET_PATH, null, RequestOptions.builder().build()); - } -} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ActivePersonaHeaderIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ActivePersonaHeaderIT.java new file mode 100644 index 000000000000..dfe3e36026b1 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ActivePersonaHeaderIT.java @@ -0,0 +1,249 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.Locale; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.CreateBot; +import org.openmetadata.schema.api.teams.CreatePersona; +import org.openmetadata.schema.api.teams.CreateTeam; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.auth.JWTTokenExpiry; +import org.openmetadata.schema.entity.Bot; +import org.openmetadata.schema.entity.teams.AuthenticationMechanism; +import org.openmetadata.schema.entity.teams.Persona; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.config.OpenMetadataConfig; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class ActivePersonaHeaderIT { + private static final String ACTIVE_PERSONA_HEADER = "X-OpenMetadata-Persona"; + private static final String IMPERSONATE_USER_HEADER = "X-Impersonate-User"; + private static final String MY_PERSONA_CONTEXT_PATH = "/v1/personas/me/context?format=json"; + + @Test + void activePersonaHeaderSelectsAssignedPersonaAndFallsBackToDefault(TestNamespace ns) { + Persona defaultPersona = createPersona(ns, "default"); + Persona selectedPersona = createPersona(ns, "selected"); + Persona unassignedPersona = createPersona(ns, "unassigned"); + User user = + createUser( + ns, + "direct_user", + new CreateUser() + .withPersonas( + List.of( + defaultPersona.getEntityReference(), selectedPersona.getEntityReference())) + .withDefaultPersona(defaultPersona.getEntityReference())); + + assertEquals(defaultPersona.getId().toString(), activePersonaId(user, null)); + assertEquals( + selectedPersona.getId().toString(), + activePersonaId(user, selectedPersona.getId().toString())); + assertEquals( + selectedPersona.getId().toString(), + activePersonaId(user, selectedPersona.getName().toUpperCase(Locale.ROOT))); + assertEquals( + defaultPersona.getId().toString(), + activePersonaId(user, unassignedPersona.getId().toString())); + assertEquals(defaultPersona.getId().toString(), activePersonaId(user, "stale-persona")); + } + + @Test + void activePersonaHeaderSelectsTeamInheritedPersona(TestNamespace ns) { + Persona inheritedPersona = createPersona(ns, "inherited"); + User user = createUser(ns, "inherited_user", new CreateUser()); + ns.trackRoot( + Entity.TEAM, + SdkClients.adminClient() + .teams() + .create( + new CreateTeam() + .withName(ns.shortPrefix("active_persona_team")) + .withTeamType(CreateTeam.TeamType.GROUP) + .withUsers(List.of(user.getId())) + .withDefaultPersona(inheritedPersona.getId()))); + + assertEquals( + inheritedPersona.getId().toString(), + activePersonaId(user, inheritedPersona.getId().toString())); + } + + @Test + void personaSideAssignmentsInvalidateCachedUserContext(TestNamespace ns) { + Persona defaultPersona = createPersona(ns, "cache_default"); + Persona selectedPersona = createPersona(ns, "cache_selected"); + User user = + createUser( + ns, + "cache_user", + new CreateUser() + .withPersonas(List.of(defaultPersona.getEntityReference())) + .withDefaultPersona(defaultPersona.getEntityReference())); + + assertEquals( + defaultPersona.getId().toString(), + activePersonaId(user, selectedPersona.getId().toString())); + + Persona personaWithUsers = + SdkClients.adminClient().personas().get(selectedPersona.getId().toString(), "users"); + personaWithUsers.setUsers(List.of(new EntityReference().withId(user.getId()))); + SdkClients.adminClient() + .personas() + .update(selectedPersona.getId().toString(), personaWithUsers); + assertEquals( + selectedPersona.getId().toString(), + activePersonaId(user, selectedPersona.getId().toString())); + + personaWithUsers = + SdkClients.adminClient().personas().get(selectedPersona.getId().toString(), "users"); + personaWithUsers.setUsers(List.of()); + SdkClients.adminClient() + .personas() + .update(selectedPersona.getId().toString(), personaWithUsers); + assertEquals( + defaultPersona.getId().toString(), + activePersonaId(user, selectedPersona.getId().toString())); + } + + @Test + void userDefaultPersonaChangeInvalidatesCachedUserContext(TestNamespace ns) { + Persona originalDefault = createPersona(ns, "original_default"); + Persona updatedDefault = createPersona(ns, "updated_default"); + User user = + createUser( + ns, + "updated_default_user", + new CreateUser() + .withPersonas( + List.of( + originalDefault.getEntityReference(), updatedDefault.getEntityReference())) + .withDefaultPersona(originalDefault.getEntityReference())); + + assertEquals(originalDefault.getId().toString(), activePersonaId(user, null)); + + User updatedUser = + SdkClients.adminClient().users().get(user.getId().toString(), "personas,defaultPersona"); + updatedUser.setDefaultPersona(updatedDefault.getEntityReference()); + SdkClients.adminClient().users().update(user.getId().toString(), updatedUser); + + assertEquals(updatedDefault.getId().toString(), activePersonaId(user, null)); + } + + @Test + void activePersonaResolvesAgainstImpersonatedUser(TestNamespace ns) { + Persona defaultPersona = createPersona(ns, "impersonated_default"); + Persona selectedPersona = createPersona(ns, "impersonated_selected"); + User targetUser = + createUser( + ns, + "impersonated_user", + new CreateUser() + .withPersonas( + List.of( + defaultPersona.getEntityReference(), selectedPersona.getEntityReference())) + .withDefaultPersona(defaultPersona.getEntityReference())); + User botUser = createBotUser(ns); + Bot bot = + SdkClients.adminClient() + .bots() + .create( + new CreateBot() + .withName(ns.shortPrefix("active_persona_bot")) + .withDescription("Active persona impersonation integration test") + .withBotUser(botUser.getName()) + .withAllowImpersonation(true)); + + try { + JWTAuthMechanism authentication = + SdkClients.adminClient().users().generateToken(botUser.getId(), JWTTokenExpiry.Seven); + assertEquals( + selectedPersona.getId().toString(), + activePersonaId( + authentication.getJWTToken(), + selectedPersona.getId().toString(), + targetUser.getName())); + } finally { + SdkClients.adminClient().bots().delete(bot.getId().toString()); + } + } + + private Persona createPersona(TestNamespace ns, String suffix) { + return ns.trackRoot( + Entity.PERSONA, + SdkClients.adminClient() + .personas() + .create( + new CreatePersona() + .withName(ns.shortPrefix("active_persona_" + suffix)) + .withDescription("Active persona header integration test"))); + } + + private User createUser(TestNamespace ns, String suffix, CreateUser request) { + String name = ns.shortPrefix("active_persona_" + suffix); + request.withName(name).withEmail(name + "@example.com"); + return ns.trackRoot(Entity.USER, SdkClients.adminClient().users().create(request)); + } + + private User createBotUser(TestNamespace ns) { + AuthenticationMechanism authenticationMechanism = + new AuthenticationMechanism() + .withAuthType(AuthenticationMechanism.AuthType.JWT) + .withConfig(new JWTAuthMechanism().withJWTTokenExpiry(JWTTokenExpiry.Unlimited)); + return createUser( + ns, + "bot_user", + new CreateUser().withIsBot(true).withAuthenticationMechanism(authenticationMechanism)); + } + + private String activePersonaId(User user, String requestedPersona) { + String accessToken = + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 3_600); + return activePersonaId(accessToken, requestedPersona, null); + } + + private String activePersonaId( + String accessToken, String requestedPersona, String impersonatedUser) { + OpenMetadataConfig.Builder config = + OpenMetadataConfig.builder().serverUrl(SdkClients.baseUrl()).accessToken(accessToken); + if (requestedPersona != null) { + config.header(ACTIVE_PERSONA_HEADER, requestedPersona); + } + if (impersonatedUser != null) { + config.header(IMPERSONATE_USER_HEADER, impersonatedUser); + } + OpenMetadataClient client = new OpenMetadataClient(config.build()); + JsonNode context = + client + .getHttpClient() + .execute(HttpMethod.GET, MY_PERSONA_CONTEXT_PATH, null, JsonNode.class); + return context.path("persona").path("id").asText(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java index ca6f507999d7..6adc2002edff 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java @@ -3777,6 +3777,7 @@ void test_bulkCreateOrUpdate_async(TestNamespace ns) { assertNotNull(result); assertEquals(5, result.getNumberOfRowsProcessed()); assertEquals(ApiStatus.SUCCESS, result.getStatus()); + awaitAsyncBulkEntitiesPersisted(result); } /** diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BulkAssetChangeEventUserIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BulkAssetChangeEventUserIT.java index e3c989c99688..a143c29a2981 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BulkAssetChangeEventUserIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BulkAssetChangeEventUserIT.java @@ -15,12 +15,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.core.type.TypeReference; import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -56,6 +58,7 @@ import org.openmetadata.sdk.network.HttpClient; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; /** * Integration tests for verifying that bulk asset operations (add/remove) record the correct user @@ -140,9 +143,10 @@ void test_domainBulkRemoveAssets_recordsCorrectUser(TestNamespace ns) throws Exc BulkAssets assets = new BulkAssets().withAssets(List.of(table.getEntityReference())); String addPath = "/v1/domains/" + domain.getFullyQualifiedName() + "/assets/add"; + long timestampBeforeAdd = System.currentTimeMillis(); adminClient.getHttpClient().execute(HttpMethod.PUT, addPath, assets, Void.class); - - Thread.sleep(500); + awaitUpdatedEvent( + adminClient.getHttpClient(), Entity.DOMAIN, domain.getId(), timestampBeforeAdd); long timestampBeforeRemove = System.currentTimeMillis(); @@ -256,9 +260,9 @@ void test_teamBulkRemoveAssets_recordsCorrectUser(TestNamespace ns) throws Excep BulkAssets assets = new BulkAssets().withAssets(List.of(testUser.getEntityReference())); String addPath = "/v1/teams/" + team.getFullyQualifiedName() + "/assets/add"; + long timestampBeforeAdd = System.currentTimeMillis(); adminClient.getHttpClient().execute(HttpMethod.PUT, addPath, assets, Void.class); - - Thread.sleep(500); + awaitUpdatedEvent(adminClient.getHttpClient(), Entity.TEAM, team.getId(), timestampBeforeAdd); long timestampBeforeRemove = System.currentTimeMillis(); @@ -363,6 +367,27 @@ private ListResponse queryChangeEvents( return new ListResponse<>(); } + private void awaitUpdatedEvent( + HttpClient httpClient, String entityType, UUID entityId, long timestamp) throws Exception { + Awaitility.await("Wait for setup bulk-add change event for " + entityType + ":" + entityId) + .pollInterval(Duration.ofMillis(500)) + .atMost(Duration.ofSeconds(30)) + .untilAsserted( + () -> { + ListResponse events = + queryChangeEvents(httpClient, null, entityType, null, null, timestamp); + assertNotNull(events); + assertNotNull(events.getData()); + assertTrue( + events.getData().stream() + .anyMatch( + event -> + entityId.equals(event.getEntityId()) + && event.getEventType() == EventType.ENTITY_UPDATED), + "Setup bulk-add change event was not recorded"); + }); + } + private ListResponse deserializeEventListResponse(String json) throws Exception { if (CommonUtil.nullOrEmpty(json)) { return null; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnCustomPropertiesIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnCustomPropertiesIT.java index 0e280801ac7c..6a06f19db4d4 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnCustomPropertiesIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnCustomPropertiesIT.java @@ -16,10 +16,13 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.factories.DashboardServiceTestFactory; import org.openmetadata.it.factories.DatabaseSchemaTestFactory; import org.openmetadata.it.factories.DatabaseServiceTestFactory; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.CreateDashboardDataModel; @@ -52,6 +55,9 @@ * timeInterval. */ @Execution(ExecutionMode.CONCURRENT) +@ResourceLock( + value = SharedResourceLocks.TABLE_COLUMN_CUSTOM_PROPERTIES, + mode = ResourceAccessMode.READ_WRITE) @ExtendWith(TestNamespaceExtension.class) public class ColumnCustomPropertiesIT { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnGridResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnGridResourceIT.java index 911b3eb676fe..8d597cdbfb50 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnGridResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ColumnGridResourceIT.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -115,7 +116,7 @@ void test_getColumnGrid_aggregatesColumnsAcrossEntityTypes(TestNamespace ns) thr .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); // Poll until both entities are indexed and the column grid shows 2 occurrences await("Wait for column grid to show both occurrences") @@ -172,7 +173,7 @@ void test_getColumnGrid_basic(TestNamespace ns) throws Exception { .withColumns(List.of(col)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid(client, "size=100&entityTypes=table&serviceName=" + service.getName()); @@ -206,7 +207,7 @@ void test_getColumnGrid_withPagination(TestNamespace ns) throws Exception { .execute(); } - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse page1 = getColumnGrid(client, "size=2&entityTypes=table&serviceName=" + service.getName()); @@ -231,7 +232,7 @@ void test_getColumnGrid_withEntityTypeFilter(TestNamespace ns) throws Exception .withColumns(List.of(col)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid(client, "entityTypes=table&serviceName=" + service.getName()); @@ -251,7 +252,7 @@ void test_getColumnGrid_withServiceFilter(TestNamespace ns) throws Exception { DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); Table table = createTableWithColumns(ns, schema, "service_filter_test"); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid(client, "entityTypes=table&serviceName=" + service.getName()); @@ -285,7 +286,7 @@ void test_getColumnGrid_withColumnNamePattern(TestNamespace ns) throws Exception .withColumns(List.of(matchingCol, nonMatchingCol)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -305,7 +306,7 @@ void test_getColumnGrid_withColumnNamePattern(TestNamespace ns) throws Exception void test_getColumnGrid_withMetadataStatusMissing(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); DatabaseService service = createTableWithoutMetadata(ns); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -319,7 +320,7 @@ void test_getColumnGrid_withMetadataStatusMissing(TestNamespace ns) throws Excep void test_getColumnGrid_withMetadataStatusComplete(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); DatabaseService service = createTableWithFullMetadata(ns); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -333,7 +334,7 @@ void test_getColumnGrid_withMetadataStatusComplete(TestNamespace ns) throws Exce void test_getColumnGrid_withMetadataStatusIncomplete(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); DatabaseService service = createTableWithPartialMetadata(ns); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -364,7 +365,7 @@ void test_getColumnGrid_combinedFilters(TestNamespace ns) throws Exception { DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); createTableWithColumns(ns, schema, "combined_filters_test"); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -412,7 +413,7 @@ void test_getColumnGrid_withMetadataStatusInconsistent(TestNamespace ns) throws .withColumns(List.of(col2)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -442,7 +443,7 @@ void test_getColumnGrid_verifyMetadataStatusFieldReturned(TestNamespace ns) thro .withColumns(List.of(colWithDesc)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -477,7 +478,7 @@ void test_getColumnGrid_missingStatusForNoMetadata(TestNamespace ns) throws Exce .withColumns(List.of(colNoMeta)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -513,7 +514,7 @@ void test_getColumnGrid_incompleteStatusForDescriptionOnly(TestNamespace ns) thr .withColumns(List.of(colDescOnly)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -562,7 +563,7 @@ void test_getColumnGrid_inconsistentStatusForVariations(TestNamespace ns) throws .withColumns(List.of(col2)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -586,7 +587,7 @@ void test_getColumnGrid_inconsistentStatusForVariations(TestNamespace ns) throws void test_getColumnGrid_completeStatusWithDescriptionAndTags(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); createTableWithCompleteMetadata(ns); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid(client, "entityTypes=table&metadataStatus=COMPLETE"); @@ -633,7 +634,7 @@ void test_getColumnGrid_crossEntityType_tableAndDashboardDataModel(TestNamespace .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -700,7 +701,7 @@ void test_getColumnGrid_crossEntityType_inconsistentMetadata(TestNamespace ns) t .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -752,7 +753,7 @@ void test_getColumnGrid_crossEntityType_consistentMetadata(TestNamespace ns) thr .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -804,7 +805,7 @@ void test_getColumnGrid_crossEntityType_filterByTableOnly(TestNamespace ns) thro .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse tableOnlyResponse = getColumnGrid(client, "entityTypes=table&columnNamePattern=" + sharedColumnName); @@ -854,7 +855,7 @@ void test_getColumnGrid_crossEntityType_verifyOccurrenceDetails(TestNamespace ns .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -913,7 +914,7 @@ void test_getColumnGrid_withDomainFilter(TestNamespace ns) throws Exception { String queryWithDomain = "entityTypes=table&domainId=" + domain.getId().toString(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); // Verify domain filter returns valid response (may be empty if ES hasn't indexed yet) ColumnGridResponse response = getColumnGrid(client, queryWithDomain); @@ -966,7 +967,7 @@ void test_getColumnGrid_withTagsFilter(TestNamespace ns) throws Exception { String queryWithTags = "entityTypes=table&tags=PII.Sensitive&serviceName=" + service.getName(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid(client, queryWithTags); assertNotNull(response, "Response should not be null"); @@ -1035,7 +1036,7 @@ void test_getColumnGrid_withGlossaryTermsFilter(TestNamespace ns) throws Excepti + "&serviceName=" + service.getName(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid(client, queryWithGlossary); assertNotNull(response, "Response should not be null"); @@ -1110,7 +1111,7 @@ void test_getColumnGrid_tagsFilter_onlyReturnsTaggedOccurrences(TestNamespace ns .withColumns(List.of(untaggedCol)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); ColumnGridResponse response = getColumnGrid( @@ -1190,7 +1191,7 @@ void test_getColumnGrid_tagsFilter_metricsAreCorrect(TestNamespace ns) throws Ex .withColumns(List.of(taggedCol, untaggedCol1, untaggedCol2)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); // Query without tag filter - should return all 3 columns ColumnGridResponse noFilterResponse = @@ -1286,7 +1287,7 @@ void test_getColumnGrid_tagsFilter_crossEntityType_onlyTaggedReturned(TestNamesp .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); // Query with tag filter - use column name pattern to scope to our test column ColumnGridResponse response = @@ -1485,14 +1486,36 @@ private ColumnGridResponse getColumnGrid(OpenMetadataClient client, String query return OBJECT_MAPPER.readValue(response, ColumnGridResponse.class); } - private void waitForSearchIndexRefresh() { - // Minimum delay for ES async indexing. Callers that need stronger guarantees - // should follow this with an Awaitility assertion (see test_getColumnGrid_aggregates*). - await("Wait for search index refresh") - .pollDelay(Duration.ofSeconds(2)) - .atMost(Duration.ofSeconds(10)) - .pollInterval(Duration.ofSeconds(1)) - .until(() -> true); + private void waitForSearchIndexRefresh(TestNamespace ns) { + String namespaceMarker = ns.prefix(""); + await("Wait for a namespace entity to appear in search") + .atMost(Duration.ofSeconds(60)) + .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() + .untilAsserted( + () -> { + String response = + SdkClients.adminClient() + .search() + .query(namespaceMarker) + .index("dataAsset") + .size(100) + .execute(); + JsonNode hits = OBJECT_MAPPER.readTree(response).path("hits").path("hits"); + boolean namespaceEntityFound = false; + for (JsonNode hit : hits) { + if (hit.path("_source") + .path("fullyQualifiedName") + .asText() + .contains(namespaceMarker)) { + namespaceEntityFound = true; + break; + } + } + assertTrue( + namespaceEntityFound, + "Search did not return an entity from namespace " + namespaceMarker); + }); } @Test @@ -1509,7 +1532,7 @@ void test_getColumnGrid_patternSearchIsCaseInsensitive(TestNamespace ns) throws .withColumns(List.of(col)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); await("Wait for lowercase pattern search to find mixed-case column") .atMost(Duration.ofSeconds(30)) @@ -1565,7 +1588,7 @@ void test_getColumnGrid_patternSearchExcludesNonMatching(TestNamespace ns) throw .withColumns(List.of(col1, col2)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); await("Wait for pattern search to exclude non-matching columns") .atMost(Duration.ofSeconds(30)) @@ -1606,7 +1629,7 @@ void test_getColumnGrid_patternSearchWithSpecialChars(TestNamespace ns) throws E .withColumns(List.of(col1, col2)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); // Search for "col.with" — dot should be literal, not wildcard await("Wait for pattern search with special chars") @@ -1675,7 +1698,7 @@ void test_getColumnGrid_patternPlusTagFilter(TestNamespace ns) throws Exception .withColumns(List.of(col3)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); await("Wait for pattern + tag filter result") .atMost(Duration.ofSeconds(30)) @@ -1755,7 +1778,7 @@ void test_getColumnGrid_patternPlusGlossaryFilter(TestNamespace ns) throws Excep .withColumns(List.of(col1, col2)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); await("Wait for pattern + glossary filter result") .atMost(Duration.ofSeconds(30)) @@ -1809,7 +1832,7 @@ void test_getColumnGrid_tagFilterPaginationConsistency(TestNamespace ns) throws .execute(); } - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); // Page through with size=2 — should get 2, 2, 1 // Use serviceName to scope to this test's data, raw pattern prefix to match column names @@ -1904,7 +1927,7 @@ void test_getColumnGrid_glossaryFilter_onlyReturnsGlossaryOccurrences(TestNamesp .withColumns(List.of(withoutGlossary)) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); await("Wait for glossary-filtered column to return the tagged occurrence only") .atMost(Duration.ofSeconds(30)) @@ -1966,7 +1989,7 @@ void test_getColumnGrid_patternSearchAcrossEntityTypesDedupesNames(TestNamespace .withDataModelType(DataModelType.MetabaseDataModel) .execute(); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); await("Wait for both entities to be indexed and dedupe correctly") .atMost(Duration.ofSeconds(30)) @@ -2036,7 +2059,7 @@ void test_getColumnGrid_patternSearchFindsAlphabeticallyLateColumn(TestNamespace .execute(); try { - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); await("Wait for first-page search to surface alphabetically-late match (size=25)") .atMost(Duration.ofSeconds(45)) @@ -2109,7 +2132,7 @@ void test_getColumnGrid_serviceFilterMatchesByDisplayNameAndName(TestNamespace n DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); createTableWithColumns(ns, schema, "svc_displayname_filter_test"); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); waitForColumnToBeIndexed(client, "id", service.getName()); ColumnGridResponse byName = @@ -2158,7 +2181,7 @@ void test_getColumnGrid_databaseFilterMatchesByDisplayNameAndName(TestNamespace .in(database.getFullyQualifiedName()) .execute(); createTableWithColumns(ns, schema, "db_displayname_filter_test"); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); waitForColumnToBeIndexed(client, "id", service.getName()); ColumnGridResponse byName = @@ -2209,7 +2232,7 @@ void test_getColumnGrid_schemaFilterMatchesByDisplayNameAndName(TestNamespace ns .in(database.getFullyQualifiedName()) .execute(); createTableWithColumns(ns, schema, "schema_displayname_filter_test"); - waitForSearchIndexRefresh(); + waitForSearchIndexRefresh(ns); waitForColumnToBeIndexed(client, "id", service.getName()); ColumnGridResponse byName = diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataContractResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataContractResourceIT.java index 6d7719cc9442..748ef7107442 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataContractResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataContractResourceIT.java @@ -42,11 +42,15 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EntityStatus; import org.openmetadata.schema.type.SemanticsRule; +import org.openmetadata.schema.utils.ResultList; +import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.fluent.DataContracts; import org.openmetadata.sdk.fluent.DataContracts.FluentDataContract; import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.models.ListResponse; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; import org.openmetadata.service.resources.data.DataContractResource; /** @@ -654,6 +658,52 @@ void testListDataContracts(TestNamespace ns) { "Expected to find the rejected contract with matching entity and status"); } + @Test + void testSearchDataContracts(TestNamespace ns) { + String searchToken = ns.prefix("contract_search"); + DataContract contractByName = + createEntity( + new CreateDataContract() + .withName(searchToken + "_name") + .withEntity(createTestTable(ns).getEntityReference())); + DataContract contractByDisplayName = + createEntity( + new CreateDataContract() + .withName(ns.prefix("different_name")) + .withDisplayName(searchToken + " Display") + .withEntity(createTestTable(ns).getEntityReference())); + + ResultList matches = searchDataContracts(searchToken); + + assertTrue(matches.getData().stream().anyMatch(c -> c.getId().equals(contractByName.getId()))); + assertTrue( + matches.getData().stream().anyMatch(c -> c.getId().equals(contractByDisplayName.getId()))); + assertEquals( + matches.getData().size(), searchDataContracts(searchToken.toUpperCase()).getData().size()); + assertTrue(searchDataContracts(ns.prefix("no_match")).getData().isEmpty()); + } + + private ResultList searchDataContracts(String query) { + OpenMetadataClient client = SdkClients.adminClient(); + RequestOptions options = + RequestOptions.builder() + .queryParam("q", query) + .queryParam("limit", "50") + .queryParam("offset", "0") + .build(); + + return client + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/dataContracts/search", + null, + DataContractResultList.class, + options); + } + + private static class DataContractResultList extends ResultList {} + @Test void testDataContractWithEntityStatus(TestNamespace ns) { Table table = createTestTable(ns); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataInsightAliasReconciliationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataInsightAliasReconciliationIT.java new file mode 100644 index 000000000000..af50bdc9d889 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataInsightAliasReconciliationIT.java @@ -0,0 +1,90 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Collections; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.search.IndexMapping; +import org.openmetadata.service.Entity; +import org.openmetadata.service.search.SearchClient; +import org.openmetadata.service.search.SearchRepository; + +/** + * Locks down the Data Insights aliases (di-data-assets-*) that custom Data Insights charts read for + * data quality. These aliases point at the live {@code testCaseResolutionStatus} / + * {@code testCaseResult} search indices; if a chart cannot resolve them it silently undercounts + * resolved incidents. + * + *

The aliases are attached on index create, re-attached on the reindex alias swap (covered by + * {@code DefaultRecreateHandlerTest}), and reconciled on startup by + * {@link SearchRepository#createMissingIndexes()} so a cluster that predates the alias — an upgraded + * cluster, or one whose alias a past reindex dropped — gets it back. This exercises that startup + * reconciliation against the live cluster. + */ +public class DataInsightAliasReconciliationIT { + + private static final String DQ_ENTITY = Entity.TEST_CASE_RESOLUTION_STATUS; + + @BeforeAll + static void setup() { + SdkClients.adminClient(); + } + + @Test + void startupReconciliationReattachesDataInsightAlias() { + SearchRepository repo = Entity.getSearchRepository(); + SearchClient client = repo.getSearchClient(); + String clusterAlias = repo.getClusterAlias(); + IndexMapping mapping = repo.getIndexMapping(DQ_ENTITY); + + List dataInsightAliases = mapping.getDataInsightAliases(clusterAlias); + assertFalse( + dataInsightAliases.isEmpty(), DQ_ENTITY + " must declare a Data Insights alias in mapping"); + String dataInsightAlias = dataInsightAliases.getFirst(); + String canonicalIndex = mapping.getIndexName(clusterAlias); + + assertTrue( + client.indexExists(canonicalIndex), canonicalIndex + " should exist after bootstrap"); + + // After a reindex the canonical name is itself an alias onto a *_rebuild_* index, so resolve + // the concrete index (or indices) actually serving this entity. Aliases attach to concrete + // indices, never to another alias. + Set servingIndices = client.getIndicesByAlias(canonicalIndex); + if (servingIndices.isEmpty()) { + servingIndices = Set.of(canonicalIndex); // canonical is still a concrete index + } + + // Simulate a cluster that predates the alias: detach it from the serving index/indices. + for (String servingIndex : servingIndices) { + client.removeAliases(servingIndex, Set.of(dataInsightAlias)); + } + assertTrue( + Collections.disjoint(client.getIndicesByAlias(dataInsightAlias), servingIndices), + "Precondition: Data Insights alias should be detached before reconciliation"); + + // Startup reconciliation must re-attach it. + repo.createMissingIndexes(); + + assertTrue( + client.getIndicesByAlias(dataInsightAlias).containsAll(servingIndices), + "createMissingIndexes must reconcile the Data Insights alias back onto the live index so " + + "custom Data Insights charts resolve it after an upgrade"); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductResourceIT.java index 1f7b53c8f9d2..763f307e70a1 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductResourceIT.java @@ -1259,7 +1259,7 @@ private void assertDomainDetachChangeEvent( Double currentVersion, long eventsSince) { Awaitility.await() - .atMost(Duration.ofSeconds(10)) + .atMost(Duration.ofSeconds(30)) .untilAsserted( () -> { ListResponse events = diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DatabaseSchemaResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DatabaseSchemaResourceIT.java index 614f0b1dbb2d..86799edb8a12 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DatabaseSchemaResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DatabaseSchemaResourceIT.java @@ -7,9 +7,16 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.io.IOException; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.function.Consumer; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @@ -1536,6 +1543,321 @@ void test_importCsv_mutualExclusivityTags_dryRun_fails(TestNamespace ns) { "Schema should not have tags applied in dry run mode"); } + /** + * Reproduces #28523: bulk-editing a table that inherits its domain and has a data product in that + * same domain must not fail "Data Product Domain Validation". The exported CSV carries no explicit + * domain (inherited domains are not exported), so an empty domain column must preserve the + * inherited domain for rule evaluation instead of wiping it. + */ + @Test + void test_importCsv_tableWithInheritedDomainAndDataProduct_succeeds(TestNamespace ns) + throws Exception { + OpenMetadataClient client = SdkClients.adminClient(); + DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + + org.openmetadata.schema.entity.domains.Domain domain = + client + .domains() + .create( + new org.openmetadata.schema.api.domains.CreateDomain() + .withName(ns.prefix("inherited_dp_domain")) + .withDomainType( + org.openmetadata.schema.api.domains.CreateDomain.DomainType.AGGREGATE) + .withDescription("Domain inherited by the table under test")); + + CreateDatabase createDb = new CreateDatabase(); + createDb.setName(ns.prefix("inherited_dp_db")); + createDb.setService(service.getFullyQualifiedName()); + createDb.setDomains(List.of(domain.getFullyQualifiedName())); + Database database = client.databases().create(createDb); + + CreateDatabaseSchema createSchema = new CreateDatabaseSchema(); + createSchema.setName(ns.prefix("inherited_dp_schema")); + createSchema.setDatabase(database.getFullyQualifiedName()); + DatabaseSchema schema = createEntity(createSchema); + + org.openmetadata.schema.entity.domains.DataProduct dataProduct = + client + .dataProducts() + .create( + new org.openmetadata.schema.api.domains.CreateDataProduct() + .withName(ns.prefix("inherited_dp_product")) + .withDescription("Data product sharing the table's inherited domain") + .withDomains(List.of(domain.getFullyQualifiedName()))); + + String tableName = ns.prefix("inherited_dp_table"); + CreateTable createTable = new CreateTable(); + createTable.setName(tableName); + createTable.setDatabaseSchema(schema.getFullyQualifiedName()); + createTable.setColumns( + List.of( + new org.openmetadata.schema.type.Column() + .withName("id") + .withDataType(org.openmetadata.schema.type.ColumnDataType.BIGINT))); + org.openmetadata.schema.entity.data.Table table = client.tables().create(createTable); + + org.openmetadata.schema.type.api.BulkAssets addAsset = + new org.openmetadata.schema.type.api.BulkAssets() + .withAssets(List.of(table.getEntityReference())); + client + .getHttpClient() + .execute( + org.openmetadata.sdk.network.HttpMethod.PUT, + "/v1/dataProducts/" + dataProduct.getFullyQualifiedName() + "/assets/add", + addAsset, + Void.class); + + org.openmetadata.schema.entity.data.Table withDp = + client.tables().get(table.getId().toString(), "domains,dataProducts"); + assertEquals(1, withDp.getDataProducts().size(), "Table should have the data product assigned"); + assertNotNull(withDp.getDomains()); + assertTrue( + withDp.getDomains().stream().anyMatch(d -> Boolean.TRUE.equals(d.getInherited())), + "Table should inherit its domain from the database"); + + String csv = + "name*,displayName,description,owner,tags,glossaryTerms,tiers,certification,retentionPeriod,sourceUrl,domains,extension\n" + + tableName + + ",Bulk Edited Table,Edited via bulk edit,,,,,,,,,"; + + String dryRunRaw = + client.databaseSchemas().importCsv(schema.getFullyQualifiedName(), csv, true, false); + CsvImportResult dryRun = JsonUtils.readValue(dryRunRaw, CsvImportResult.class); + assertEquals( + 0, + dryRun.getNumberOfRowsFailed(), + "Bulk-edit dry run must not fail with an inherited domain: " + dryRunRaw); + assertFalse( + dryRunRaw.contains("Data Product Domain Validation"), + "Inherited domain must satisfy Data Product Domain Validation: " + dryRunRaw); + + String importRaw = + client.databaseSchemas().importCsv(schema.getFullyQualifiedName(), csv, false, false); + CsvImportResult importResult = JsonUtils.readValue(importRaw, CsvImportResult.class); + assertEquals(0, importResult.getNumberOfRowsFailed(), "Bulk edit should pass: " + importRaw); + + org.openmetadata.schema.entity.data.Table afterImport = + client.tables().get(table.getId().toString(), "domains"); + assertTrue( + afterImport.getDomains() == null + || afterImport.getDomains().stream() + .allMatch(d -> Boolean.TRUE.equals(d.getInherited())), + "Inherited domain must not be materialized as a direct domain after import"); + assertEquals("Edited via bulk edit", afterImport.getDescription()); + } + + /** + * Recursive variant of #28523: the recursive dry-run load excludes domains, so an empty domain + * column must still preserve the table's inherited domain for "Data Product Domain Validation". + * Exports the schema recursively, then forces the table row's domain column empty before re-import. + */ + @Test + void test_importCsvRecursive_tableWithInheritedDomainAndDataProduct_succeeds(TestNamespace ns) + throws Exception { + OpenMetadataClient client = SdkClients.adminClient(); + DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + + org.openmetadata.schema.entity.domains.Domain domain = + client + .domains() + .create( + new org.openmetadata.schema.api.domains.CreateDomain() + .withName(ns.prefix("rec_inherited_domain")) + .withDomainType( + org.openmetadata.schema.api.domains.CreateDomain.DomainType.AGGREGATE) + .withDescription("Domain inherited by the recursive table under test")); + + CreateDatabase createDb = new CreateDatabase(); + createDb.setName(ns.prefix("rec_inherited_db")); + createDb.setService(service.getFullyQualifiedName()); + createDb.setDomains(List.of(domain.getFullyQualifiedName())); + Database database = client.databases().create(createDb); + + CreateDatabaseSchema createSchema = new CreateDatabaseSchema(); + createSchema.setName(ns.prefix("rec_inherited_schema")); + createSchema.setDatabase(database.getFullyQualifiedName()); + DatabaseSchema schema = createEntity(createSchema); + + org.openmetadata.schema.entity.domains.DataProduct dataProduct = + client + .dataProducts() + .create( + new org.openmetadata.schema.api.domains.CreateDataProduct() + .withName(ns.prefix("rec_inherited_product")) + .withDescription("Data product sharing the table's inherited domain") + .withDomains(List.of(domain.getFullyQualifiedName()))); + + String tableName = ns.prefix("rec_inherited_table"); + CreateTable createTable = new CreateTable(); + createTable.setName(tableName); + createTable.setDatabaseSchema(schema.getFullyQualifiedName()); + createTable.setDescription("Initial Table Description"); + createTable.setColumns( + List.of( + new org.openmetadata.schema.type.Column() + .withName("id") + .withDataType(org.openmetadata.schema.type.ColumnDataType.BIGINT))); + org.openmetadata.schema.entity.data.Table table = client.tables().create(createTable); + + org.openmetadata.schema.type.api.BulkAssets addAsset = + new org.openmetadata.schema.type.api.BulkAssets() + .withAssets(List.of(table.getEntityReference())); + client + .getHttpClient() + .execute( + org.openmetadata.sdk.network.HttpMethod.PUT, + "/v1/dataProducts/" + dataProduct.getFullyQualifiedName() + "/assets/add", + addAsset, + Void.class); + + String exportedCsv = client.databaseSchemas().exportCsv(schema.getFullyQualifiedName(), true); + String newCsv = + rewriteCsvRows( + exportedCsv, + cols -> { + if (cols.size() > 12 && "table".equals(cols.get(12).trim())) { + cols.set(2, "Recursive Bulk Edited"); + cols.set(10, ""); + } + }); + + String dryRunRaw = + client.databaseSchemas().importCsv(schema.getFullyQualifiedName(), newCsv, true, true); + CsvImportResult dryRun = JsonUtils.readValue(dryRunRaw, CsvImportResult.class); + assertEquals( + 0, + dryRun.getNumberOfRowsFailed(), + "Recursive bulk-edit dry run must not fail with an inherited domain: " + dryRunRaw); + assertFalse( + dryRunRaw.contains("Data Product Domain Validation"), + "Inherited domain must satisfy Data Product Domain Validation: " + dryRunRaw); + + String importRaw = + client.databaseSchemas().importCsv(schema.getFullyQualifiedName(), newCsv, false, true); + CsvImportResult importResult = JsonUtils.readValue(importRaw, CsvImportResult.class); + assertEquals( + 0, importResult.getNumberOfRowsFailed(), "Recursive bulk edit should pass: " + importRaw); + + org.openmetadata.schema.entity.data.Table afterImport = + client.tables().get(table.getId().toString(), "domains"); + assertTrue( + afterImport.getDomains() == null + || afterImport.getDomains().stream() + .allMatch(d -> Boolean.TRUE.equals(d.getInherited())), + "Inherited domain must not be materialized as a direct domain after recursive import"); + assertEquals("Recursive Bulk Edited", afterImport.getDescription()); + } + + /** + * Export→import round-trip for #28523: an inherited domain must not be written to the CSV domains + * column on export. Otherwise re-import reads it back as a plain FQN (the inherited flag is lost in + * serialization), {@code dropInheritedDomains} cannot recognize it, and it gets materialized as a + * direct domain. Asserts the exported table row has an empty domain column, then re-imports the + * export verbatim (only the description edited) and confirms the domain stays inherited. + */ + @Test + void test_exportCsv_inheritedDomainNotExported_roundTripDoesNotMaterialize(TestNamespace ns) + throws Exception { + OpenMetadataClient client = SdkClients.adminClient(); + DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + + org.openmetadata.schema.entity.domains.Domain domain = + client + .domains() + .create( + new org.openmetadata.schema.api.domains.CreateDomain() + .withName(ns.prefix("roundtrip_domain")) + .withDomainType( + org.openmetadata.schema.api.domains.CreateDomain.DomainType.AGGREGATE) + .withDescription("Domain inherited by the round-trip table under test")); + + CreateDatabase createDb = new CreateDatabase(); + createDb.setName(ns.prefix("roundtrip_db")); + createDb.setService(service.getFullyQualifiedName()); + createDb.setDomains(List.of(domain.getFullyQualifiedName())); + Database database = client.databases().create(createDb); + + CreateDatabaseSchema createSchema = new CreateDatabaseSchema(); + createSchema.setName(ns.prefix("roundtrip_schema")); + createSchema.setDatabase(database.getFullyQualifiedName()); + DatabaseSchema schema = createEntity(createSchema); + + org.openmetadata.schema.entity.domains.DataProduct dataProduct = + client + .dataProducts() + .create( + new org.openmetadata.schema.api.domains.CreateDataProduct() + .withName(ns.prefix("roundtrip_product")) + .withDescription("Data product sharing the table's inherited domain") + .withDomains(List.of(domain.getFullyQualifiedName()))); + + String tableName = ns.prefix("roundtrip_table"); + CreateTable createTable = new CreateTable(); + createTable.setName(tableName); + createTable.setDatabaseSchema(schema.getFullyQualifiedName()); + createTable.setDescription("Initial Table Description"); + createTable.setColumns( + List.of( + new org.openmetadata.schema.type.Column() + .withName("id") + .withDataType(org.openmetadata.schema.type.ColumnDataType.BIGINT))); + org.openmetadata.schema.entity.data.Table table = client.tables().create(createTable); + + org.openmetadata.schema.type.api.BulkAssets addAsset = + new org.openmetadata.schema.type.api.BulkAssets() + .withAssets(List.of(table.getEntityReference())); + client + .getHttpClient() + .execute( + org.openmetadata.sdk.network.HttpMethod.PUT, + "/v1/dataProducts/" + dataProduct.getFullyQualifiedName() + "/assets/add", + addAsset, + Void.class); + + String exportedCsv = client.databaseSchemas().exportCsv(schema.getFullyQualifiedName(), true); + boolean[] tableRowFound = {false}; + String newCsv = + rewriteCsvRows( + exportedCsv, + cols -> { + if (cols.size() > 12 && "table".equals(cols.get(12).trim())) { + assertTrue( + cols.get(10).trim().isEmpty(), + "Export must not write the inherited domain to the CSV domains column: " + + cols); + cols.set(2, "Round Trip Edited"); + tableRowFound[0] = true; + } + }); + assertTrue(tableRowFound[0], "Exported CSV should contain the table row"); + + String dryRunRaw = + client.databaseSchemas().importCsv(schema.getFullyQualifiedName(), newCsv, true, true); + CsvImportResult dryRun = JsonUtils.readValue(dryRunRaw, CsvImportResult.class); + assertEquals( + 0, + dryRun.getNumberOfRowsFailed(), + "Round-trip dry run must not fail with an inherited domain: " + dryRunRaw); + assertFalse( + dryRunRaw.contains("Data Product Domain Validation"), + "Inherited domain must satisfy Data Product Domain Validation: " + dryRunRaw); + + String importRaw = + client.databaseSchemas().importCsv(schema.getFullyQualifiedName(), newCsv, false, true); + CsvImportResult importResult = JsonUtils.readValue(importRaw, CsvImportResult.class); + assertEquals( + 0, importResult.getNumberOfRowsFailed(), "Round-trip import should pass: " + importRaw); + + org.openmetadata.schema.entity.data.Table afterImport = + client.tables().get(table.getId().toString(), "domains"); + assertTrue( + afterImport.getDomains() == null + || afterImport.getDomains().stream() + .allMatch(d -> Boolean.TRUE.equals(d.getInherited())), + "Inherited domain must not be materialized as a direct domain after round-trip import"); + assertEquals("Round Trip Edited", afterImport.getDescription()); + } + /** * Test that importing a table with APPROVED glossary terms as tags succeeds. */ @@ -1772,6 +2094,29 @@ private String formatDomainsForCsv(List> rowEditor) + throws IOException { + CSVFormat format = CSVFormat.DEFAULT.builder().setRecordSeparator('\n').build(); + StringBuilder rewritten = new StringBuilder(); + try (CSVParser parser = CSVParser.parse(csv, format); + CSVPrinter printer = new CSVPrinter(rewritten, format)) { + boolean isHeader = true; + for (CSVRecord csvRecord : parser) { + List cols = new ArrayList<>(csvRecord.toList()); + if (!isHeader) { + rowEditor.accept(cols); + } + isHeader = false; + printer.printRecord(cols); + } + } + return rewritten.toString(); + } + private String formatExtensionForCsv(Object extension) { if (extension == null) { return ""; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DirectoryResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DirectoryResourceIT.java index ba9b6d020f50..6dc6ac19ec1d 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DirectoryResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DirectoryResourceIT.java @@ -564,6 +564,64 @@ void test_listReturnsServiceParentAndStats_excludesDeletedFromTotalSize(TestName "Parent reference must match on the list path"); } + /** + * A nested directory must inherit its domain from its parent directory (not the drive service) + * on the bulk list path, even when the parent field is not requested: the parent reference is + * needed internally for inheritance and must not leak into the response. + */ + @Test + void test_listInheritsDomainFromParentDirectoryWithoutParentField(TestNamespace ns) { + DriveService driveService = DriveServiceTestFactory.createGoogleDrive(ns); + + org.openmetadata.schema.entity.domains.Domain parentDomain = + SdkClients.adminClient() + .domains() + .create( + new org.openmetadata.schema.api.domains.CreateDomain() + .withName(ns.prefix("dir_parent_domain")) + .withDomainType( + org.openmetadata.schema.api.domains.CreateDomain.DomainType.AGGREGATE) + .withDescription("Domain assigned to the parent directory")); + + Directory parentDir = + getDirectoryService() + .create( + new CreateDirectory() + .withName(ns.prefix("domain_parent")) + .withService(driveService.getFullyQualifiedName()) + .withDomains(java.util.List.of(parentDomain.getFullyQualifiedName()))); + + Directory nestedDir = + getDirectoryService() + .create( + new CreateDirectory() + .withName(ns.prefix("domain_nested")) + .withService(driveService.getFullyQualifiedName()) + .withParent(parentDir.getFullyQualifiedName())); + + ListParams params = + new ListParams() + .setService(driveService.getFullyQualifiedName()) + .setFields("domains") + .setLimit(1000); + Directory listedNested = findInList(params, nestedDir.getId()); + assertNotNull(listedNested, "Nested directory must be present in the list response"); + assertTrue( + listedNested.getParent() == null, + "Parent was not requested and must not be returned on the list path"); + assertNotNull( + listedNested.getDomains(), + "Nested directory must inherit a domain on the list path even without the parent field"); + assertEquals(1, listedNested.getDomains().size()); + assertEquals( + parentDomain.getFullyQualifiedName(), + listedNested.getDomains().getFirst().getFullyQualifiedName(), + "Nested directory must inherit its domain from the parent directory, not the drive service"); + assertTrue( + Boolean.TRUE.equals(listedNested.getDomains().getFirst().getInherited()), + "The domain must be marked inherited"); + } + private Directory findInList(ListParams params, UUID id) { ListResponse response = listEntities(params); Directory match = null; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DomainIsolationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DomainIsolationIT.java index 4b3cb38f9e47..a48c02b1f8f6 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DomainIsolationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DomainIsolationIT.java @@ -17,9 +17,12 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.factories.DatabaseSchemaTestFactory; import org.openmetadata.it.factories.DatabaseServiceTestFactory; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.CreateTable; @@ -50,6 +53,7 @@ */ @Execution(ExecutionMode.CONCURRENT) @ExtendWith(TestNamespaceExtension.class) +@ResourceLock(value = SharedResourceLocks.SEARCH_SETTINGS, mode = ResourceAccessMode.READ_WRITE) public class DomainIsolationIT { private static final ObjectMapper MAPPER = new ObjectMapper(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/FeedResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/FeedResourceIT.java index 895dded83857..8f5d0c01d917 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/FeedResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/FeedResourceIT.java @@ -21,6 +21,7 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.openmetadata.it.factories.DatabaseServiceTestFactory; +import org.openmetadata.it.factories.ShortStackFactory; import org.openmetadata.it.factories.TableTestFactory; import org.openmetadata.it.factories.UserTestFactory; import org.openmetadata.it.util.SdkClients; @@ -31,12 +32,14 @@ import org.openmetadata.schema.api.feed.CreatePost; import org.openmetadata.schema.api.feed.CreateThread; import org.openmetadata.schema.api.feed.ResolveTask; +import org.openmetadata.schema.api.tests.CreateTestCase; import org.openmetadata.schema.entity.data.Database; import org.openmetadata.schema.entity.data.DatabaseSchema; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.feed.Thread; import org.openmetadata.schema.entity.services.DatabaseService; import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.tests.TestCase; import org.openmetadata.schema.type.AnnouncementDetails; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Post; @@ -45,8 +48,10 @@ import org.openmetadata.schema.type.TaskStatus; import org.openmetadata.schema.type.TaskType; import org.openmetadata.schema.type.ThreadType; +import org.openmetadata.sdk.exceptions.InvalidRequestException; import org.openmetadata.sdk.fluent.DatabaseSchemas; import org.openmetadata.sdk.fluent.Databases; +import org.openmetadata.sdk.fluent.builders.TestCaseBuilder; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.sdk.network.RequestOptions; @@ -340,6 +345,192 @@ void post_validTaskAndList_200(TestNamespace ns) throws Exception { deleteThread(taskThread.getId()); } + @Test + void post_requestApprovalTaskForColumn_400AndDoesNotBreakTaskList(TestNamespace ns) + throws Exception { + Table table = createTestTable(ns); + String about = + String.format("<#E::table::%s::columns::%s>", table.getFullyQualifiedName(), "id"); + + User assigneeUser = SdkClients.adminClient().users().getByName("admin"); + EntityReference assignee = assigneeUser.getEntityReference(); + + CreateTaskDetails approvalDetails = + new CreateTaskDetails() + .withType(TaskType.RequestApproval) + .withAssignees(List.of(assignee)) + .withOldValue("this is a test suggestion") + .withSuggestion("this is a different test suggestion2"); + + CreateThread invalidApprovalTask = + new CreateThread() + .withMessage("this is a test, I am a very good programmer") + .withAbout(about) + .withType(ThreadType.Task) + .withTaskDetails(approvalDetails); + + InvalidRequestException exception = + assertThrows(InvalidRequestException.class, () -> createThread(invalidApprovalTask)); + assertEquals(400, exception.getStatusCode()); + + CreateTaskDetails descriptionDetails = + new CreateTaskDetails() + .withType(TaskType.RequestDescription) + .withAssignees(List.of(assignee)) + .withOldValue("old description") + .withSuggestion("new description"); + + Thread validTask = null; + try { + validTask = + createThread( + new CreateThread() + .withMessage("Please update description") + .withAbout(about) + .withType(ThreadType.Task) + .withTaskDetails(descriptionDetails)); + + ThreadList tasks = listTasks(about); + assertTrue(threadListContainsTask(tasks, validTask)); + assertFalse( + tasks.getData().stream() + .anyMatch( + thread -> + thread.getTask() != null + && thread.getTask().getType() == TaskType.RequestApproval)); + } finally { + if (validTask != null) { + deleteThread(validTask.getId()); + } + } + } + + @Test + void post_tagTaskWithInvalidSuggestionJson_400(TestNamespace ns) throws Exception { + Table table = createTestTable(ns); + String about = String.format("<#E::table::%s>", table.getFullyQualifiedName()); + + User assigneeUser = SdkClients.adminClient().users().getByName("admin"); + EntityReference assignee = assigneeUser.getEntityReference(); + + CreateTaskDetails taskDetails = + new CreateTaskDetails() + .withType(TaskType.RequestTag) + .withAssignees(List.of(assignee)) + .withOldValue("[]") + .withSuggestion("this is a different test suggestion2"); + + CreateThread invalidTagTask = + new CreateThread() + .withMessage("Please update tags") + .withAbout(about) + .withType(ThreadType.Task) + .withTaskDetails(taskDetails); + + InvalidRequestException exception = + assertThrows(InvalidRequestException.class, () -> createThread(invalidTagTask)); + assertEquals(400, exception.getStatusCode()); + } + + @Test + void post_tagTaskWithBlankValues_200(TestNamespace ns) throws Exception { + Table table = createTestTable(ns); + String about = String.format("<#E::table::%s>", table.getFullyQualifiedName()); + + User assigneeUser = SdkClients.adminClient().users().getByName("admin"); + EntityReference assignee = assigneeUser.getEntityReference(); + + CreateTaskDetails taskDetails = + new CreateTaskDetails() + .withType(TaskType.RequestTag) + .withAssignees(List.of(assignee)) + .withOldValue("") + .withSuggestion(" \n\t"); + + Thread taskThread = null; + try { + taskThread = + createThread( + new CreateThread() + .withMessage("Please update tags") + .withAbout(about) + .withType(ThreadType.Task) + .withTaskDetails(taskDetails)); + + assertNotNull(taskThread); + assertNotNull(taskThread.getTask()); + assertEquals(TaskStatus.Open, taskThread.getTask().getStatus()); + assertTrue(threadListContainsTask(listTasks(about), taskThread)); + } finally { + if (taskThread != null) { + deleteThread(taskThread.getId()); + } + } + } + + @Test + void post_testCaseFailureResolutionTask_200(TestNamespace ns) throws Exception { + TestCase testCase = createTestCase(ns); + String about = String.format("<#E::testCase::%s>", testCase.getFullyQualifiedName()); + + User assigneeUser = SdkClients.adminClient().users().getByName("admin"); + EntityReference assignee = assigneeUser.getEntityReference(); + + CreateTaskDetails taskDetails = + new CreateTaskDetails() + .withType(TaskType.RequestTestCaseFailureResolution) + .withAssignees(List.of(assignee)) + .withOldValue("Test case failed") + .withSuggestion("Investigate and resolve the failure"); + + Thread taskThread = null; + try { + taskThread = + createThread( + new CreateThread() + .withMessage("Please resolve the test case failure") + .withAbout(about) + .withType(ThreadType.Task) + .withTaskDetails(taskDetails)); + + assertNotNull(taskThread); + assertNotNull(taskThread.getTask()); + assertEquals(TaskType.RequestTestCaseFailureResolution, taskThread.getTask().getType()); + assertEquals(TaskStatus.Open, taskThread.getTask().getStatus()); + assertTrue(threadListContainsTask(listTasks(about), taskThread)); + } finally { + if (taskThread != null) { + deleteThread(taskThread.getId()); + } + } + } + + @Test + void post_unsupportedLegacyFeedTaskType_400(TestNamespace ns) throws Exception { + Table table = createTestTable(ns); + String about = String.format("<#E::table::%s>", table.getFullyQualifiedName()); + + User assigneeUser = SdkClients.adminClient().users().getByName("admin"); + EntityReference assignee = assigneeUser.getEntityReference(); + + CreateTaskDetails taskDetails = + new CreateTaskDetails() + .withType(TaskType.Generic) + .withAssignees(List.of(assignee)) + .withSuggestion("{}"); + + CreateThread unsupportedTask = + new CreateThread() + .withMessage("Please process custom task") + .withAbout(about) + .withType(ThreadType.Task) + .withTaskDetails(taskDetails); + + InvalidRequestException exception = + assertThrows(InvalidRequestException.class, () -> createThread(unsupportedTask)); + assertEquals(400, exception.getStatusCode()); + } + @Test void put_resolveTaskByUser_description_200(TestNamespace ns) throws Exception { Table table = createTestTable(ns); @@ -1457,6 +1648,19 @@ private Table createTestTable(TestNamespace ns) throws Exception { return TableTestFactory.createSimple(ns, schema.getFullyQualifiedName()); } + private TestCase createTestCase(TestNamespace ns) throws Exception { + Table table = ShortStackFactory.table(ns); + CreateTestCase createTestCase = + TestCaseBuilder.create(SdkClients.adminClient()) + .name(ns.prefix("testcase")) + .description("Test case created by feed integration test") + .forTable(table) + .testDefinition("tableRowCountToEqual") + .parameter("value", "100") + .build(); + return SdkClients.adminClient().testCases().create(createTestCase); + } + private Thread createThread(CreateThread createThread) throws Exception { return SdkClients.adminClient() .getHttpClient() @@ -1520,6 +1724,20 @@ private ThreadList listTasks() throws Exception { return MAPPER.readValue(response, ThreadList.class); } + private ThreadList listTasks(String entityLink) throws Exception { + RequestOptions options = + RequestOptions.builder() + .queryParam("entityLink", entityLink) + .queryParam("type", ThreadType.Task.toString()) + .build(); + + String response = + SdkClients.adminClient() + .getHttpClient() + .executeForString(HttpMethod.GET, "/v1/feed", null, options); + return MAPPER.readValue(response, ThreadList.class); + } + private ThreadList listTasksByUserFilter(UUID userId, String filterType) throws Exception { return listTasksByUserFilter(userId, filterType, null); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryCsvRelationTypesIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryCsvRelationTypesIT.java index 3e5d34856949..615eca62e759 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryCsvRelationTypesIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryCsvRelationTypesIT.java @@ -42,7 +42,9 @@ import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.factories.GlossaryTermTestFactory; import org.openmetadata.it.factories.GlossaryTestFactory; +import org.openmetadata.it.util.NamespaceCleanup; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.entity.data.Glossary; @@ -432,7 +434,8 @@ void testFqnWithColonIsNotMisinterpreted(TestNamespace ns) throws Exception { * that mutates these settings must use the same key on a {@link ResourceLock} so JUnit serialises * across classes; a class-local synchronized block would only guard intra-class concurrency. */ - private static final String SETTINGS_RESOURCE_KEY = "glossaryTermRelationSettings"; + private static final String SETTINGS_RESOURCE_KEY = + SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS; @Test void testImportPreservesMixedRelationsViaApi(TestNamespace ns) throws Exception { @@ -595,6 +598,7 @@ void testRoundTripWithCustomRelationType(TestNamespace ns) throws Exception { imported.getRelatedTerms().get(0).getRelationType(), "Custom relation type should be preserved through CSV import"); } finally { + NamespaceCleanup.deleteRoots(ns.drainTrackedRoots()); cleanupCustomTypes(customType, inverseType); } } @@ -652,31 +656,26 @@ private void addCustomRelationTypePair(String customType, String inverseType) th putRelationSettings(payload); } - private void cleanupCustomTypes(String... customTypes) { - try { - JsonNode current = getRelationSettings(); - ArrayNode types = (ArrayNode) current.get("config_value").get("relationTypes"); - ArrayNode filtered = OBJECT_MAPPER.createArrayNode(); - for (JsonNode type : types) { - String name = type.get("name").asText(); - boolean drop = false; - for (String custom : customTypes) { - if (custom.equals(name)) { - drop = true; - break; - } - } - if (!drop) { - filtered.add(type); + private void cleanupCustomTypes(String... customTypes) throws Exception { + JsonNode current = getRelationSettings(); + ArrayNode types = (ArrayNode) current.get("config_value").get("relationTypes"); + ArrayNode filtered = OBJECT_MAPPER.createArrayNode(); + for (JsonNode type : types) { + String name = type.get("name").asText(); + boolean drop = false; + for (String custom : customTypes) { + if (custom.equals(name)) { + drop = true; + break; } } - ObjectNode payload = OBJECT_MAPPER.createObjectNode(); - payload.set("relationTypes", filtered); - putRelationSettings(payload); - } catch (Exception e) { - LOG.warn( - "Failed to cleanup custom relation types {}: {}", List.of(customTypes), e.getMessage()); + if (!drop) { + filtered.add(type); + } } + ObjectNode payload = OBJECT_MAPPER.createObjectNode(); + payload.set("relationTypes", filtered); + putRelationSettings(payload); } private JsonNode getRelationSettings() throws Exception { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryRdfImportIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryRdfImportIT.java index 2269049abdda..b1a1f9d94ad9 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryRdfImportIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryRdfImportIT.java @@ -21,21 +21,28 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIf; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.auth.JwtAuthProvider; import org.openmetadata.it.factories.GlossaryTestFactory; import org.openmetadata.it.factories.UserTestFactory; +import org.openmetadata.it.util.NamespaceCleanup; import org.openmetadata.it.util.RdfTestUtils; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.CreateGlossaryTerm; @@ -52,11 +59,15 @@ */ @Execution(ExecutionMode.CONCURRENT) @ExtendWith(TestNamespaceExtension.class) +@ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) public class GlossaryRdfImportIT { private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private ObjectNode originalRelationSettings; private static final String ONTOLOGY = """ @@ -89,6 +100,34 @@ public class GlossaryRdfImportIT { rdfs:range xsd:string . """; + @BeforeEach + void captureRelationSettings() throws Exception { + HttpResponse response = + get(SdkClients.getServerUrl() + "/v1/system/settings/glossaryTermRelationSettings"); + assertEquals(200, response.statusCode(), response.body()); + originalRelationSettings = + (ObjectNode) OBJECT_MAPPER.readTree(response.body()).path("config_value").deepCopy(); + } + + @AfterEach + void restoreRelationSettings(TestNamespace ns) throws Exception { + NamespaceCleanup.deleteRoots(ns.drainTrackedRoots()); + + ObjectNode payload = OBJECT_MAPPER.createObjectNode(); + payload.put("config_type", "glossaryTermRelationSettings"); + payload.set("config_value", originalRelationSettings); + HttpRequest request = + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + "/v1/system/settings")) + .header("Authorization", "Bearer " + SdkClients.getAdminToken()) + .header("Content-Type", "application/json") + .timeout(Duration.ofSeconds(30)) + .PUT(HttpRequest.BodyPublishers.ofString(OBJECT_MAPPER.writeValueAsString(payload))) + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertEquals(200, response.statusCode(), response.body()); + } + @Test void importsOwlOntologyIntoGlossary(TestNamespace ns) throws Exception { Glossary glossary = GlossaryTestFactory.createSimple(ns); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermMoveApprovalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermMoveApprovalIT.java index ceb03f14cf72..a80c7863d9c2 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermMoveApprovalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermMoveApprovalIT.java @@ -98,9 +98,14 @@ public class GlossaryTermMoveApprovalIT { private static final String WORKFLOW_STATUS_FINISHED = "FINISHED"; private static final Set TERMINAL_WORKFLOW_STATUSES = Set.of("FINISHED", "EXCEPTION", "FAILURE"); - private static final Duration TASK_TIMEOUT = Duration.ofMinutes(3); - private static final Duration MOVE_TIMEOUT = Duration.ofMinutes(2); - private static final Duration STATUS_TIMEOUT = Duration.ofMinutes(2); + // Every wait below is gated on the async Flowable job executor (BPMN trigger → approval task → + // status transition → workflow completion), which contends with the rest of the concurrent + // suite. Under nightly load any one of these could lose the race first, so all budgets are + // generous rather than only the approval-task wait that happened to time out. (main already + // raised TASK_TIMEOUT to 5 min; this keeps that and extends the same headroom to move/status.) + private static final Duration TASK_TIMEOUT = Duration.ofMinutes(5); + private static final Duration MOVE_TIMEOUT = Duration.ofMinutes(3); + private static final Duration STATUS_TIMEOUT = Duration.ofMinutes(3); private static final Duration POLL_INTERVAL = Duration.ofSeconds(2); protected SharedEntities shared() { @@ -332,11 +337,32 @@ private void tagTermOntoNewTable(TestNamespace ns, GlossaryTerm term) { private Task waitForOpenApprovalTask(String aboutFqn) { Map filters = Map.of("limit", "100", "status", TaskEntityStatus.Open.value(), "aboutEntity", aboutFqn); - Awaitility.await("wait for open glossary approval task for " + aboutFqn) + long deadline = System.nanoTime() + TASK_TIMEOUT.toNanos(); + Awaitility.await("wait for glossary approval workflow instance for " + aboutFqn) .atMost(TASK_TIMEOUT) .pollInterval(POLL_INTERVAL) .ignoreExceptions() - .until(() -> !listTasks(filters).isEmpty()); + .untilAsserted( + () -> + assertFalse( + approvalWorkflowStatuses(aboutFqn).isEmpty(), + "The glossary change event has not started an approval workflow for " + + aboutFqn)); + Duration remaining = + Duration.ofNanos( + Math.max(POLL_INTERVAL.multipliedBy(2).toNanos(), deadline - System.nanoTime())); + Awaitility.await("wait for open glossary approval task for " + aboutFqn) + .atMost(remaining) + .pollInterval(POLL_INTERVAL) + .ignoreExceptions() + .untilAsserted( + () -> + assertFalse( + listTasks(filters).isEmpty(), + "Approval workflow exists with statuses " + + approvalWorkflowStatuses(aboutFqn) + + " but no open task was created for " + + aboutFqn)); List tasks = listTasks(filters); assertFalse(tasks.isEmpty(), "Expected an open approval task for " + aboutFqn); Task task = tasks.get(0); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationSettingsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationSettingsIT.java index f0a192f38ec0..5a990e434075 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationSettingsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationSettingsIT.java @@ -21,9 +21,12 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.factories.GlossaryTermTestFactory; import org.openmetadata.it.factories.GlossaryTestFactory; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.entity.data.Glossary; @@ -48,9 +51,11 @@ public class GlossaryTermRelationSettingsIT { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); - private static final Object SETTINGS_LOCK = new Object(); @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ) void test_glossaryTermRelationSettingsExist() throws Exception { OpenMetadataClient client = SdkClients.adminClient(); @@ -110,6 +115,9 @@ void test_glossaryTermRelationSettingsExist() throws Exception { } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ) void test_relationTypesHaveColors() throws Exception { OpenMetadataClient client = SdkClients.adminClient(); @@ -169,304 +177,306 @@ void test_usageCountsApiReturnsValidData() throws Exception { } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void test_deleteRelationTypeProtection(TestNamespace ns) throws Exception { - synchronized (SETTINGS_LOCK) { - String customTypeName = "testCustomType" + System.currentTimeMillis(); - - JsonNode currentSettings = getSettings(); - ArrayNode relationTypes = - (ArrayNode) currentSettings.get("config_value").get("relationTypes"); - - ObjectNode newType = MAPPER.createObjectNode(); - newType.put("name", customTypeName); - newType.put("displayName", "Test Custom Type"); - newType.put("description", "A test custom relation type for delete protection testing"); - newType.put("isSymmetric", true); - newType.put("isTransitive", false); - newType.put("isCrossGlossaryAllowed", true); - newType.put("category", "associative"); - newType.put("isSystemDefined", false); - newType.put("color", "#ff5733"); - relationTypes.add(newType); - - ObjectNode newSettings = MAPPER.createObjectNode(); - newSettings.set("relationTypes", relationTypes); - updateSettings(newSettings); - LOG.info("Created custom relation type: {}", customTypeName); + String customTypeName = "testCustomType" + System.currentTimeMillis(); + + JsonNode currentSettings = getSettings(); + ArrayNode relationTypes = (ArrayNode) currentSettings.get("config_value").get("relationTypes"); + + ObjectNode newType = MAPPER.createObjectNode(); + newType.put("name", customTypeName); + newType.put("displayName", "Test Custom Type"); + newType.put("description", "A test custom relation type for delete protection testing"); + newType.put("isSymmetric", true); + newType.put("isTransitive", false); + newType.put("isCrossGlossaryAllowed", true); + newType.put("category", "associative"); + newType.put("isSystemDefined", false); + newType.put("color", "#ff5733"); + relationTypes.add(newType); + + ObjectNode newSettings = MAPPER.createObjectNode(); + newSettings.set("relationTypes", relationTypes); + updateSettings(newSettings); + LOG.info("Created custom relation type: {}", customTypeName); + + Glossary glossary = GlossaryTestFactory.createSimple(ns); + GlossaryTerm term1 = GlossaryTermTestFactory.createWithName(ns, glossary, "termA"); + GlossaryTerm term2 = GlossaryTermTestFactory.createWithName(ns, glossary, "termB"); + + GlossaryTerm updatedTerm = + addTermRelation(term1.getId().toString(), term2.getId().toString(), customTypeName); + assertNotNull(updatedTerm, "Should successfully add relation with custom type"); + LOG.info( + "Created relation between {} and {} with type {}", + term1.getName(), + term2.getName(), + customTypeName); + + JsonNode settingsWithRelationInUse = getSettings(); + ArrayNode typesWithRelationInUse = + (ArrayNode) settingsWithRelationInUse.get("config_value").get("relationTypes"); - Glossary glossary = GlossaryTestFactory.createSimple(ns); - GlossaryTerm term1 = GlossaryTermTestFactory.createWithName(ns, glossary, "termA"); - GlossaryTerm term2 = GlossaryTermTestFactory.createWithName(ns, glossary, "termB"); - - GlossaryTerm updatedTerm = - addTermRelation(term1.getId().toString(), term2.getId().toString(), customTypeName); - assertNotNull(updatedTerm, "Should successfully add relation with custom type"); - LOG.info( - "Created relation between {} and {} with type {}", - term1.getName(), - term2.getName(), - customTypeName); - - JsonNode settingsWithRelationInUse = getSettings(); - ArrayNode typesWithRelationInUse = - (ArrayNode) settingsWithRelationInUse.get("config_value").get("relationTypes"); - - ArrayNode typesWithoutCustom = MAPPER.createArrayNode(); - for (JsonNode type : typesWithRelationInUse) { - if (!customTypeName.equals(type.get("name").asText())) { - typesWithoutCustom.add(type); - } + ArrayNode typesWithoutCustom = MAPPER.createArrayNode(); + for (JsonNode type : typesWithRelationInUse) { + if (!customTypeName.equals(type.get("name").asText())) { + typesWithoutCustom.add(type); } + } - ObjectNode settingsWithoutCustomType = MAPPER.createObjectNode(); - settingsWithoutCustomType.set("relationTypes", typesWithoutCustom); + ObjectNode settingsWithoutCustomType = MAPPER.createObjectNode(); + settingsWithoutCustomType.set("relationTypes", typesWithoutCustom); - int deleteStatusCode = updateSettingsAndGetStatus(settingsWithoutCustomType); - LOG.info("Delete attempt status code: {}", deleteStatusCode); + int deleteStatusCode = updateSettingsAndGetStatus(settingsWithoutCustomType); + LOG.info("Delete attempt status code: {}", deleteStatusCode); - assertTrue( - deleteStatusCode >= 400, - "Delete should fail when relation type is in use. Got status: " + deleteStatusCode); + assertTrue( + deleteStatusCode >= 400, + "Delete should fail when relation type is in use. Got status: " + deleteStatusCode); - removeTermRelation(term1.getId().toString(), term2.getId().toString(), customTypeName); - removeTermRelation(term2.getId().toString(), term1.getId().toString(), customTypeName); - LOG.info( - "Removed relation between {} and {} (both directions)", term1.getName(), term2.getName()); + removeTermRelation(term1.getId().toString(), term2.getId().toString(), customTypeName); + removeTermRelation(term2.getId().toString(), term1.getId().toString(), customTypeName); + LOG.info( + "Removed relation between {} and {} (both directions)", term1.getName(), term2.getName()); - int deleteAfterRemovalStatusCode = updateSettingsAndGetStatus(settingsWithoutCustomType); - LOG.info("Delete after removal status code: {}", deleteAfterRemovalStatusCode); + int deleteAfterRemovalStatusCode = updateSettingsAndGetStatus(settingsWithoutCustomType); + LOG.info("Delete after removal status code: {}", deleteAfterRemovalStatusCode); - assertEquals( - 200, deleteAfterRemovalStatusCode, "Delete should succeed after relations are removed"); - - JsonNode finalSettings = getSettings(); - ArrayNode finalTypes = (ArrayNode) finalSettings.get("config_value").get("relationTypes"); - boolean customTypeExists = false; - for (JsonNode type : finalTypes) { - if (customTypeName.equals(type.get("name").asText())) { - customTypeExists = true; - break; - } + assertEquals( + 200, deleteAfterRemovalStatusCode, "Delete should succeed after relations are removed"); + + JsonNode finalSettings = getSettings(); + ArrayNode finalTypes = (ArrayNode) finalSettings.get("config_value").get("relationTypes"); + boolean customTypeExists = false; + for (JsonNode type : finalTypes) { + if (customTypeName.equals(type.get("name").asText())) { + customTypeExists = true; + break; } - assertFalse(customTypeExists, "Custom type should be deleted from settings"); - LOG.info("Successfully verified delete protection for relation type: {}", customTypeName); } + assertFalse(customTypeExists, "Custom type should be deleted from settings"); + LOG.info("Successfully verified delete protection for relation type: {}", customTypeName); } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void test_oneToManyCardinalityConstraints(TestNamespace ns) throws Exception { - synchronized (SETTINGS_LOCK) { - String customTypeName = "oneToMany" + System.currentTimeMillis(); - - JsonNode currentSettings = getSettings(); - ArrayNode relationTypes = - (ArrayNode) currentSettings.get("config_value").get("relationTypes"); - - ObjectNode newType = MAPPER.createObjectNode(); - newType.put("name", customTypeName); - newType.put("displayName", "One To Many Type"); - newType.put("description", "Source can relate to many targets, each target only one source"); - newType.put("isSymmetric", false); - newType.put("isTransitive", false); - newType.put("isCrossGlossaryAllowed", true); - newType.put("category", "associative"); - newType.put("isSystemDefined", false); - newType.put("color", "#22c55e"); - newType.put("cardinality", "ONE_TO_MANY"); - relationTypes.add(newType); - - ObjectNode newSettings = MAPPER.createObjectNode(); - newSettings.set("relationTypes", relationTypes); - updateSettings(newSettings); - - try { - Glossary glossary = GlossaryTestFactory.createSimple(ns); - GlossaryTerm source = GlossaryTermTestFactory.createWithName(ns, glossary, "source"); - GlossaryTerm targetA = GlossaryTermTestFactory.createWithName(ns, glossary, "targetA"); - GlossaryTerm targetB = GlossaryTermTestFactory.createWithName(ns, glossary, "targetB"); - GlossaryTerm source2 = GlossaryTermTestFactory.createWithName(ns, glossary, "source2"); - - int status1 = - addTermRelationAndGetStatus( - source.getId().toString(), targetA.getId().toString(), customTypeName); - assertEquals(200, status1, "Source to targetA should succeed"); - - int status2 = - addTermRelationAndGetStatus( - source.getId().toString(), targetB.getId().toString(), customTypeName); - assertEquals( - 200, status2, "Source to targetB should succeed (ONE_TO_MANY allows multiple targets)"); + String customTypeName = "oneToMany" + System.currentTimeMillis(); + + JsonNode currentSettings = getSettings(); + ArrayNode relationTypes = (ArrayNode) currentSettings.get("config_value").get("relationTypes"); + + ObjectNode newType = MAPPER.createObjectNode(); + newType.put("name", customTypeName); + newType.put("displayName", "One To Many Type"); + newType.put("description", "Source can relate to many targets, each target only one source"); + newType.put("isSymmetric", false); + newType.put("isTransitive", false); + newType.put("isCrossGlossaryAllowed", true); + newType.put("category", "associative"); + newType.put("isSystemDefined", false); + newType.put("color", "#22c55e"); + newType.put("cardinality", "ONE_TO_MANY"); + relationTypes.add(newType); + + ObjectNode newSettings = MAPPER.createObjectNode(); + newSettings.set("relationTypes", relationTypes); + updateSettings(newSettings); - int status3 = - addTermRelationAndGetStatus( - source2.getId().toString(), targetA.getId().toString(), customTypeName); - assertTrue( - status3 >= 400, - "Second source to same target should be rejected (target max=1). Got: " + status3); + try { + Glossary glossary = GlossaryTestFactory.createSimple(ns); + GlossaryTerm source = GlossaryTermTestFactory.createWithName(ns, glossary, "source"); + GlossaryTerm targetA = GlossaryTermTestFactory.createWithName(ns, glossary, "targetA"); + GlossaryTerm targetB = GlossaryTermTestFactory.createWithName(ns, glossary, "targetB"); + GlossaryTerm source2 = GlossaryTermTestFactory.createWithName(ns, glossary, "source2"); - removeTermRelation(source.getId().toString(), targetA.getId().toString(), customTypeName); - removeTermRelation(source.getId().toString(), targetB.getId().toString(), customTypeName); - } finally { - cleanupCustomType(customTypeName); - } + int status1 = + addTermRelationAndGetStatus( + source.getId().toString(), targetA.getId().toString(), customTypeName); + assertEquals(200, status1, "Source to targetA should succeed"); + + int status2 = + addTermRelationAndGetStatus( + source.getId().toString(), targetB.getId().toString(), customTypeName); + assertEquals( + 200, status2, "Source to targetB should succeed (ONE_TO_MANY allows multiple targets)"); + + int status3 = + addTermRelationAndGetStatus( + source2.getId().toString(), targetA.getId().toString(), customTypeName); + assertTrue( + status3 >= 400, + "Second source to same target should be rejected (target max=1). Got: " + status3); + + removeTermRelation(source.getId().toString(), targetA.getId().toString(), customTypeName); + removeTermRelation(source.getId().toString(), targetB.getId().toString(), customTypeName); + } finally { + cleanupCustomType(customTypeName); } } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void test_manyToOneCardinalityConstraints(TestNamespace ns) throws Exception { - synchronized (SETTINGS_LOCK) { - String customTypeName = "manyToOne" + System.currentTimeMillis(); - - JsonNode currentSettings = getSettings(); - ArrayNode relationTypes = - (ArrayNode) currentSettings.get("config_value").get("relationTypes"); - - ObjectNode newType = MAPPER.createObjectNode(); - newType.put("name", customTypeName); - newType.put("displayName", "Many To One Type"); - newType.put("description", "Many sources can relate to one target, source limited to one"); - newType.put("isSymmetric", false); - newType.put("isTransitive", false); - newType.put("isCrossGlossaryAllowed", true); - newType.put("category", "associative"); - newType.put("isSystemDefined", false); - newType.put("color", "#f59e0b"); - newType.put("cardinality", "MANY_TO_ONE"); - relationTypes.add(newType); - - ObjectNode newSettings = MAPPER.createObjectNode(); - newSettings.set("relationTypes", relationTypes); - updateSettings(newSettings); - - try { - Glossary glossary = GlossaryTestFactory.createSimple(ns); - GlossaryTerm sourceA = GlossaryTermTestFactory.createWithName(ns, glossary, "srcA"); - GlossaryTerm sourceB = GlossaryTermTestFactory.createWithName(ns, glossary, "srcB"); - GlossaryTerm target = GlossaryTermTestFactory.createWithName(ns, glossary, "target"); - GlossaryTerm target2 = GlossaryTermTestFactory.createWithName(ns, glossary, "target2"); - - int status1 = - addTermRelationAndGetStatus( - sourceA.getId().toString(), target.getId().toString(), customTypeName); - assertEquals(200, status1, "sourceA to target should succeed"); - - int status2 = - addTermRelationAndGetStatus( - sourceB.getId().toString(), target.getId().toString(), customTypeName); - assertEquals( - 200, - status2, - "sourceB to same target should succeed (MANY_TO_ONE allows multiple sources)"); + String customTypeName = "manyToOne" + System.currentTimeMillis(); + + JsonNode currentSettings = getSettings(); + ArrayNode relationTypes = (ArrayNode) currentSettings.get("config_value").get("relationTypes"); + + ObjectNode newType = MAPPER.createObjectNode(); + newType.put("name", customTypeName); + newType.put("displayName", "Many To One Type"); + newType.put("description", "Many sources can relate to one target, source limited to one"); + newType.put("isSymmetric", false); + newType.put("isTransitive", false); + newType.put("isCrossGlossaryAllowed", true); + newType.put("category", "associative"); + newType.put("isSystemDefined", false); + newType.put("color", "#f59e0b"); + newType.put("cardinality", "MANY_TO_ONE"); + relationTypes.add(newType); + + ObjectNode newSettings = MAPPER.createObjectNode(); + newSettings.set("relationTypes", relationTypes); + updateSettings(newSettings); - int status3 = - addTermRelationAndGetStatus( - sourceA.getId().toString(), target2.getId().toString(), customTypeName); - assertTrue( - status3 >= 400, - "sourceA to second target should be rejected (source max=1). Got: " + status3); + try { + Glossary glossary = GlossaryTestFactory.createSimple(ns); + GlossaryTerm sourceA = GlossaryTermTestFactory.createWithName(ns, glossary, "srcA"); + GlossaryTerm sourceB = GlossaryTermTestFactory.createWithName(ns, glossary, "srcB"); + GlossaryTerm target = GlossaryTermTestFactory.createWithName(ns, glossary, "target"); + GlossaryTerm target2 = GlossaryTermTestFactory.createWithName(ns, glossary, "target2"); - removeTermRelation(sourceA.getId().toString(), target.getId().toString(), customTypeName); - removeTermRelation(sourceB.getId().toString(), target.getId().toString(), customTypeName); - } finally { - cleanupCustomType(customTypeName); - } + int status1 = + addTermRelationAndGetStatus( + sourceA.getId().toString(), target.getId().toString(), customTypeName); + assertEquals(200, status1, "sourceA to target should succeed"); + + int status2 = + addTermRelationAndGetStatus( + sourceB.getId().toString(), target.getId().toString(), customTypeName); + assertEquals( + 200, + status2, + "sourceB to same target should succeed (MANY_TO_ONE allows multiple sources)"); + + int status3 = + addTermRelationAndGetStatus( + sourceA.getId().toString(), target2.getId().toString(), customTypeName); + assertTrue( + status3 >= 400, + "sourceA to second target should be rejected (source max=1). Got: " + status3); + + removeTermRelation(sourceA.getId().toString(), target.getId().toString(), customTypeName); + removeTermRelation(sourceB.getId().toString(), target.getId().toString(), customTypeName); + } finally { + cleanupCustomType(customTypeName); } } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void test_customCardinalityConstraints(TestNamespace ns) throws Exception { - synchronized (SETTINGS_LOCK) { - String customTypeName = "customCard" + System.currentTimeMillis(); - - JsonNode currentSettings = getSettings(); - ArrayNode relationTypes = - (ArrayNode) currentSettings.get("config_value").get("relationTypes"); - - ObjectNode newType = MAPPER.createObjectNode(); - newType.put("name", customTypeName); - newType.put("displayName", "Custom Cardinality Type"); - newType.put("description", "Custom cardinality with sourceMax=2, targetMax=2"); - newType.put("isSymmetric", false); - newType.put("isTransitive", false); - newType.put("isCrossGlossaryAllowed", true); - newType.put("category", "associative"); - newType.put("isSystemDefined", false); - newType.put("color", "#8b5cf6"); - newType.put("cardinality", "CUSTOM"); - newType.put("sourceMax", 2); - newType.put("targetMax", 2); - relationTypes.add(newType); - - ObjectNode newSettings = MAPPER.createObjectNode(); - newSettings.set("relationTypes", relationTypes); - updateSettings(newSettings); - - try { - Glossary glossary = GlossaryTestFactory.createSimple(ns); - GlossaryTerm src = GlossaryTermTestFactory.createWithName(ns, glossary, "src"); - GlossaryTerm tgtA = GlossaryTermTestFactory.createWithName(ns, glossary, "tgtA"); - GlossaryTerm tgtB = GlossaryTermTestFactory.createWithName(ns, glossary, "tgtB"); - GlossaryTerm tgtC = GlossaryTermTestFactory.createWithName(ns, glossary, "tgtC"); - - int s1 = - addTermRelationAndGetStatus( - src.getId().toString(), tgtA.getId().toString(), customTypeName); - assertEquals(200, s1, "First relation should succeed (within sourceMax=2)"); - - int s2 = - addTermRelationAndGetStatus( - src.getId().toString(), tgtB.getId().toString(), customTypeName); - assertEquals(200, s2, "Second relation should succeed (at sourceMax=2)"); - - int s3 = - addTermRelationAndGetStatus( - src.getId().toString(), tgtC.getId().toString(), customTypeName); - assertTrue( - s3 >= 400, "Third relation should be rejected (exceeds sourceMax=2). Got: " + s3); + String customTypeName = "customCard" + System.currentTimeMillis(); + + JsonNode currentSettings = getSettings(); + ArrayNode relationTypes = (ArrayNode) currentSettings.get("config_value").get("relationTypes"); + + ObjectNode newType = MAPPER.createObjectNode(); + newType.put("name", customTypeName); + newType.put("displayName", "Custom Cardinality Type"); + newType.put("description", "Custom cardinality with sourceMax=2, targetMax=2"); + newType.put("isSymmetric", false); + newType.put("isTransitive", false); + newType.put("isCrossGlossaryAllowed", true); + newType.put("category", "associative"); + newType.put("isSystemDefined", false); + newType.put("color", "#8b5cf6"); + newType.put("cardinality", "CUSTOM"); + newType.put("sourceMax", 2); + newType.put("targetMax", 2); + relationTypes.add(newType); + + ObjectNode newSettings = MAPPER.createObjectNode(); + newSettings.set("relationTypes", relationTypes); + updateSettings(newSettings); - removeTermRelation(src.getId().toString(), tgtA.getId().toString(), customTypeName); - removeTermRelation(src.getId().toString(), tgtB.getId().toString(), customTypeName); - } finally { - cleanupCustomType(customTypeName); - } + try { + Glossary glossary = GlossaryTestFactory.createSimple(ns); + GlossaryTerm src = GlossaryTermTestFactory.createWithName(ns, glossary, "src"); + GlossaryTerm tgtA = GlossaryTermTestFactory.createWithName(ns, glossary, "tgtA"); + GlossaryTerm tgtB = GlossaryTermTestFactory.createWithName(ns, glossary, "tgtB"); + GlossaryTerm tgtC = GlossaryTermTestFactory.createWithName(ns, glossary, "tgtC"); + + int s1 = + addTermRelationAndGetStatus( + src.getId().toString(), tgtA.getId().toString(), customTypeName); + assertEquals(200, s1, "First relation should succeed (within sourceMax=2)"); + + int s2 = + addTermRelationAndGetStatus( + src.getId().toString(), tgtB.getId().toString(), customTypeName); + assertEquals(200, s2, "Second relation should succeed (at sourceMax=2)"); + + int s3 = + addTermRelationAndGetStatus( + src.getId().toString(), tgtC.getId().toString(), customTypeName); + assertTrue(s3 >= 400, "Third relation should be rejected (exceeds sourceMax=2). Got: " + s3); + + removeTermRelation(src.getId().toString(), tgtA.getId().toString(), customTypeName); + removeTermRelation(src.getId().toString(), tgtB.getId().toString(), customTypeName); + } finally { + cleanupCustomType(customTypeName); } } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void test_systemDefinedRelationTypeCannotBeDeleted() throws Exception { - synchronized (SETTINGS_LOCK) { - JsonNode currentSettings = getSettings(); - ArrayNode relationTypes = - (ArrayNode) currentSettings.get("config_value").get("relationTypes"); - - ArrayNode withoutRelatedTo = MAPPER.createArrayNode(); - boolean foundRelatedTo = false; - for (JsonNode type : relationTypes) { - if ("relatedTo".equals(type.get("name").asText())) { - foundRelatedTo = true; - JsonNode isSystemDefined = type.get("isSystemDefined"); - assertTrue( - isSystemDefined != null && isSystemDefined.asBoolean(), - "'relatedTo' should be system-defined"); - } else { - withoutRelatedTo.add(type); - } + JsonNode currentSettings = getSettings(); + ArrayNode relationTypes = (ArrayNode) currentSettings.get("config_value").get("relationTypes"); + + ArrayNode withoutRelatedTo = MAPPER.createArrayNode(); + boolean foundRelatedTo = false; + for (JsonNode type : relationTypes) { + if ("relatedTo".equals(type.get("name").asText())) { + foundRelatedTo = true; + JsonNode isSystemDefined = type.get("isSystemDefined"); + assertTrue( + isSystemDefined != null && isSystemDefined.asBoolean(), + "'relatedTo' should be system-defined"); + } else { + withoutRelatedTo.add(type); } - assertTrue(foundRelatedTo, "relatedTo should exist in default settings"); + } + assertTrue(foundRelatedTo, "relatedTo should exist in default settings"); - ObjectNode settingsWithoutRelatedTo = MAPPER.createObjectNode(); - settingsWithoutRelatedTo.set("relationTypes", withoutRelatedTo); + ObjectNode settingsWithoutRelatedTo = MAPPER.createObjectNode(); + settingsWithoutRelatedTo.set("relationTypes", withoutRelatedTo); - int status = updateSettingsAndGetStatus(settingsWithoutRelatedTo); - LOG.info("Attempt to delete system-defined 'relatedTo' status: {}", status); + int status = updateSettingsAndGetStatus(settingsWithoutRelatedTo); + LOG.info("Attempt to delete system-defined 'relatedTo' status: {}", status); - assertTrue( - status >= 400, - "Should not be able to remove system-defined relation type 'relatedTo'. Got: " + status); - } + assertTrue( + status >= 400, + "Should not be able to remove system-defined relation type 'relatedTo'. Got: " + status); } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ) void test_systemDefinedRelationTypesHaveCorrectDesignSystemColors() throws Exception { JsonNode settings = getSettings(); JsonNode relationTypes = settings.get("config_value").get("relationTypes"); @@ -515,6 +525,9 @@ void test_systemDefinedRelationTypesHaveCorrectDesignSystemColors() throws Excep } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ) void test_defaultRelationTypesHaveExpectedProperties() throws Exception { JsonNode settings = getSettings(); JsonNode relationTypes = settings.get("config_value").get("relationTypes"); @@ -547,73 +560,73 @@ void test_defaultRelationTypesHaveExpectedProperties() throws Exception { } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void test_cardinalityConstraints(TestNamespace ns) throws Exception { - synchronized (SETTINGS_LOCK) { - String customTypeName = "cardinalityType" + System.currentTimeMillis(); - - JsonNode currentSettings = getSettings(); - ArrayNode relationTypes = - (ArrayNode) currentSettings.get("config_value").get("relationTypes"); - - ObjectNode newType = MAPPER.createObjectNode(); - newType.put("name", customTypeName); - newType.put("displayName", "Cardinality Type"); - newType.put("description", "Relation type with cardinality constraints"); - newType.put("isSymmetric", false); - newType.put("isTransitive", false); - newType.put("isCrossGlossaryAllowed", true); - newType.put("category", "associative"); - newType.put("isSystemDefined", false); - newType.put("color", "#4f46e5"); - newType.put("cardinality", "ONE_TO_ONE"); - relationTypes.add(newType); - - ObjectNode newSettings = MAPPER.createObjectNode(); - newSettings.set("relationTypes", relationTypes); - updateSettings(newSettings); - - Glossary glossary = GlossaryTestFactory.createSimple(ns); - GlossaryTerm term1 = GlossaryTermTestFactory.createWithName(ns, glossary, "cardA"); - GlossaryTerm term2 = GlossaryTermTestFactory.createWithName(ns, glossary, "cardB"); - GlossaryTerm term3 = GlossaryTermTestFactory.createWithName(ns, glossary, "cardC"); - - int status1 = - addTermRelationAndGetStatus( - term1.getId().toString(), term2.getId().toString(), customTypeName); - assertEquals(200, status1, "First relation should succeed"); - - int status2 = - addTermRelationAndGetStatus( - term1.getId().toString(), term3.getId().toString(), customTypeName); - assertTrue(status2 >= 400, "Should reject source cardinality violation"); + String customTypeName = "cardinalityType" + System.currentTimeMillis(); + + JsonNode currentSettings = getSettings(); + ArrayNode relationTypes = (ArrayNode) currentSettings.get("config_value").get("relationTypes"); + + ObjectNode newType = MAPPER.createObjectNode(); + newType.put("name", customTypeName); + newType.put("displayName", "Cardinality Type"); + newType.put("description", "Relation type with cardinality constraints"); + newType.put("isSymmetric", false); + newType.put("isTransitive", false); + newType.put("isCrossGlossaryAllowed", true); + newType.put("category", "associative"); + newType.put("isSystemDefined", false); + newType.put("color", "#4f46e5"); + newType.put("cardinality", "ONE_TO_ONE"); + relationTypes.add(newType); + + ObjectNode newSettings = MAPPER.createObjectNode(); + newSettings.set("relationTypes", relationTypes); + updateSettings(newSettings); + + Glossary glossary = GlossaryTestFactory.createSimple(ns); + GlossaryTerm term1 = GlossaryTermTestFactory.createWithName(ns, glossary, "cardA"); + GlossaryTerm term2 = GlossaryTermTestFactory.createWithName(ns, glossary, "cardB"); + GlossaryTerm term3 = GlossaryTermTestFactory.createWithName(ns, glossary, "cardC"); + + int status1 = + addTermRelationAndGetStatus( + term1.getId().toString(), term2.getId().toString(), customTypeName); + assertEquals(200, status1, "First relation should succeed"); + + int status2 = + addTermRelationAndGetStatus( + term1.getId().toString(), term3.getId().toString(), customTypeName); + assertTrue(status2 >= 400, "Should reject source cardinality violation"); + + int status3 = + addTermRelationAndGetStatus( + term3.getId().toString(), term2.getId().toString(), customTypeName); + assertTrue(status3 >= 400, "Should reject target cardinality violation"); + + removeTermRelation(term1.getId().toString(), term2.getId().toString(), customTypeName); + + int status4 = + addTermRelationAndGetStatus( + term3.getId().toString(), term2.getId().toString(), customTypeName); + assertEquals(200, status4, "Should allow relation after previous one is removed"); + + removeTermRelation(term3.getId().toString(), term2.getId().toString(), customTypeName); - int status3 = - addTermRelationAndGetStatus( - term3.getId().toString(), term2.getId().toString(), customTypeName); - assertTrue(status3 >= 400, "Should reject target cardinality violation"); - - removeTermRelation(term1.getId().toString(), term2.getId().toString(), customTypeName); - - int status4 = - addTermRelationAndGetStatus( - term3.getId().toString(), term2.getId().toString(), customTypeName); - assertEquals(200, status4, "Should allow relation after previous one is removed"); - - removeTermRelation(term3.getId().toString(), term2.getId().toString(), customTypeName); - - JsonNode settingsAfter = getSettings(); - ArrayNode typesAfter = (ArrayNode) settingsAfter.get("config_value").get("relationTypes"); - ArrayNode typesWithoutCustom = MAPPER.createArrayNode(); - for (JsonNode type : typesAfter) { - if (!customTypeName.equals(type.get("name").asText())) { - typesWithoutCustom.add(type); - } + JsonNode settingsAfter = getSettings(); + ArrayNode typesAfter = (ArrayNode) settingsAfter.get("config_value").get("relationTypes"); + ArrayNode typesWithoutCustom = MAPPER.createArrayNode(); + for (JsonNode type : typesAfter) { + if (!customTypeName.equals(type.get("name").asText())) { + typesWithoutCustom.add(type); } - - ObjectNode settingsWithoutCustomType = MAPPER.createObjectNode(); - settingsWithoutCustomType.set("relationTypes", typesWithoutCustom); - updateSettings(settingsWithoutCustomType); } + + ObjectNode settingsWithoutCustomType = MAPPER.createObjectNode(); + settingsWithoutCustomType.set("relationTypes", typesWithoutCustom); + updateSettings(settingsWithoutCustomType); } private JsonNode getSettings() throws Exception { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationsIT.java index 5808cce4dd1e..8e851497901a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryTermRelationsIT.java @@ -18,15 +18,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; import java.util.List; import java.util.Map; +import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; @@ -52,9 +46,6 @@ public class GlossaryTermRelationsIT { private static final Logger LOG = LoggerFactory.getLogger(GlossaryTermRelationsIT.class); - private static final HttpClient HTTP_CLIENT = - HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Test void testAddTermRelationWithSynonymType(TestNamespace ns) throws Exception { @@ -255,128 +246,26 @@ void testGetTermRelationGraphFilteredByType(TestNamespace ns) throws Exception { LOG.debug("Filtered graph has {} edges of type synonym", edges.size()); } - private GlossaryTerm addTermRelation(String fromTermId, String toTermId, String relationType) - throws Exception { - String baseUrl = SdkClients.getServerUrl(); - String token = SdkClients.getAdminToken(); - - String url = String.format("%s/v1/glossaryTerms/%s/relations", baseUrl, fromTermId); - - String jsonBody = - String.format( - "{\"term\":{\"id\":\"%s\",\"type\":\"glossaryTerm\"},\"relationType\":\"%s\"}", - toTermId, relationType); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(url)) - .header("Authorization", "Bearer " + token) - .header("Content-Type", "application/json") - .timeout(Duration.ofSeconds(30)) - .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) - .build(); - - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - LOG.warn( - "Failed to add term relation: status={}, body={}", - response.statusCode(), - response.body()); - return null; - } - - return OBJECT_MAPPER.readValue(response.body(), GlossaryTerm.class); + private GlossaryTerm addTermRelation(String fromTermId, String toTermId, String relationType) { + return SdkClients.adminClient() + .glossaryTerms() + .addRelation(UUID.fromString(fromTermId), UUID.fromString(toTermId), relationType); } - private GlossaryTerm removeTermRelation(String fromTermId, String toTermId, String relationType) - throws Exception { - String baseUrl = SdkClients.getServerUrl(); - String token = SdkClients.getAdminToken(); - - String url = - String.format( - "%s/v1/glossaryTerms/%s/relations/%s?relationType=%s", - baseUrl, fromTermId, toTermId, relationType); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(url)) - .header("Authorization", "Bearer " + token) - .timeout(Duration.ofSeconds(30)) - .DELETE() - .build(); - - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - LOG.warn( - "Failed to remove term relation: status={}, body={}", - response.statusCode(), - response.body()); - return null; - } - - return OBJECT_MAPPER.readValue(response.body(), GlossaryTerm.class); + private GlossaryTerm removeTermRelation(String fromTermId, String toTermId, String relationType) { + return SdkClients.adminClient() + .glossaryTerms() + .removeRelation(UUID.fromString(fromTermId), UUID.fromString(toTermId), relationType); } - private Map getRelationTypeUsageCounts() throws Exception { - String baseUrl = SdkClients.getServerUrl(); - String token = SdkClients.getAdminToken(); - - String url = String.format("%s/v1/glossaryTerms/relationTypes/usage", baseUrl); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(url)) - .header("Authorization", "Bearer " + token) - .header("Accept", "application/json") - .timeout(Duration.ofSeconds(30)) - .GET() - .build(); - - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - LOG.warn( - "Failed to get relation type usage counts: status={}, body={}", - response.statusCode(), - response.body()); - return Map.of(); - } - - return OBJECT_MAPPER.readValue(response.body(), new TypeReference>() {}); + private Map getRelationTypeUsageCounts() { + return SdkClients.adminClient().glossaryTerms().relationTypeUsage(); } - private Map getTermRelationGraph(String termId, int depth, String relationTypes) - throws Exception { - String baseUrl = SdkClients.getServerUrl(); - String token = SdkClients.getAdminToken(); - - String url = - String.format( - "%s/v1/glossaryTerms/%s/relationsGraph?depth=%d%s", - baseUrl, termId, depth, relationTypes != null ? "&relationTypes=" + relationTypes : ""); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(url)) - .header("Authorization", "Bearer " + token) - .header("Accept", "application/json") - .timeout(Duration.ofSeconds(30)) - .GET() - .build(); - - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - LOG.warn( - "Failed to get term relation graph: status={}, body={}", - response.statusCode(), - response.body()); - return Map.of(); - } - - return OBJECT_MAPPER.readValue(response.body(), new TypeReference>() {}); + private Map getTermRelationGraph(String termId, int depth, String relationTypes) { + List types = relationTypes != null ? List.of(relationTypes.split(",")) : null; + return SdkClients.adminClient() + .glossaryTerms() + .relationGraph(UUID.fromString(termId), depth, types); } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndexTemplateIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndexTemplateIT.java index 5fe07fef1ffa..d19778c08b67 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndexTemplateIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndexTemplateIT.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import es.co.elastic.clients.transport.rest5_client.low_level.Request; import es.co.elastic.clients.transport.rest5_client.low_level.Response; import es.co.elastic.clients.transport.rest5_client.low_level.Rest5Client; @@ -15,6 +16,8 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.io.entity.StringEntity; import org.junit.jupiter.api.Test; @@ -32,6 +35,8 @@ public class IndexTemplateIT { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String CLUSTER_ALIAS = "openmetadata"; + private static final List READ_ONLY_INDEX_TEMPLATE_FIELDS = + List.of("created_date", "created_date_millis", "modified_date", "modified_date_millis"); @Test void testIndexTemplatesExist(TestNamespace ns) throws Exception { @@ -117,10 +122,16 @@ void testTemplatePatternMatchesRebuildIndices(TestNamespace ns) throws Exception @Test void testAutoCreatedIndexFromTemplateHasProperMappings(TestNamespace ns) throws Exception { Rest5Client searchClient = TestSuiteBootstrap.createSearchClient(); - String testIndexName = CLUSTER_ALIAS + "_table_search_index_rebuild_test_template_it"; + String testTemplateName = uniqueTestResourceName("table_mapping"); + String testIndexName = testTemplateName + "_index"; try { deleteIndexIfExists(searchClient, testIndexName); + copyTemplateForIndex( + searchClient, + "om_" + CLUSTER_ALIAS + "_table_search_index", + testTemplateName, + testIndexName); String doc = "{\"name\":\"test_table\",\"fullyQualifiedName\":\"db.schema.test_table\"," @@ -145,16 +156,23 @@ void testAutoCreatedIndexFromTemplateHasProperMappings(TestNamespace ns) throws } finally { deleteIndexIfExists(searchClient, testIndexName); + deleteTemplateIfExists(searchClient, testTemplateName); } } @Test void testAutoCreatedIndexHasAnalyzers(TestNamespace ns) throws Exception { Rest5Client searchClient = TestSuiteBootstrap.createSearchClient(); - String testIndexName = CLUSTER_ALIAS + "_table_search_index_rebuild_test_analyzer_it"; + String testTemplateName = uniqueTestResourceName("table_analyzer"); + String testIndexName = testTemplateName + "_index"; try { deleteIndexIfExists(searchClient, testIndexName); + copyTemplateForIndex( + searchClient, + "om_" + CLUSTER_ALIAS + "_table_search_index", + testTemplateName, + testIndexName); String doc = "{\"name\":\"analyzer_test\",\"entityType\":\"table\",\"deleted\":false}"; Request indexRequest = new Request("POST", "/" + testIndexName + "/_doc"); @@ -175,17 +193,24 @@ void testAutoCreatedIndexHasAnalyzers(TestNamespace ns) throws Exception { } finally { deleteIndexIfExists(searchClient, testIndexName); + deleteTemplateIfExists(searchClient, testTemplateName); } } @Test void testDocUpdateOnDeletedIndexUsesTemplateNotAutoInference(TestNamespace ns) throws Exception { Rest5Client searchClient = TestSuiteBootstrap.createSearchClient(); - String testIndexName = CLUSTER_ALIAS + "_tag_search_index_rebuild_it_doc_update"; + String testTemplateName = uniqueTestResourceName("tag_mapping"); + String testIndexName = testTemplateName + "_index"; deleteIndexIfExists(searchClient, testIndexName); try { + copyTemplateForIndex( + searchClient, + "om_" + CLUSTER_ALIAS + "_tag_search_index", + testTemplateName, + testIndexName); String doc = "{\"name\":\"test_tag\",\"fullyQualifiedName\":\"Classification.test_tag\"," + "\"entityType\":\"tag\",\"deleted\":false," @@ -243,6 +268,7 @@ void testDocUpdateOnDeletedIndexUsesTemplateNotAutoInference(TestNamespace ns) t "Auto-created index should have om_analyzer from template"); } finally { deleteIndexIfExists(searchClient, testIndexName); + deleteTemplateIfExists(searchClient, testTemplateName); } } @@ -379,6 +405,43 @@ private JsonNode getSettingsForIndex(Rest5Client client, String indexName) throw return indexNode.get("settings").get("index"); } + private void copyTemplateForIndex( + Rest5Client client, String sourceTemplateName, String testTemplateName, String testIndexName) + throws Exception { + Request getRequest = new Request("GET", "/_index_template/" + sourceTemplateName); + Response getResponse = client.performRequest(getRequest); + assertEquals(200, getResponse.getStatusCode()); + JsonNode response = + MAPPER.readTree( + new String( + getResponse.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8)); + ObjectNode template = + (ObjectNode) response.path("index_templates").get(0).path("index_template").deepCopy(); + template.remove(READ_ONLY_INDEX_TEMPLATE_FIELDS); + template.set("index_patterns", MAPPER.createArrayNode().add(testIndexName)); + + Request putRequest = new Request("PUT", "/_index_template/" + testTemplateName); + putRequest.setEntity( + new StringEntity(MAPPER.writeValueAsString(template), ContentType.APPLICATION_JSON)); + Response putResponse = client.performRequest(putRequest); + int putStatus = putResponse.getStatusCode(); + String putResponseBody = + putResponse.getEntity() == null + ? "" + : new String( + putResponse.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8); + assertTrue( + putStatus == 200 || putStatus == 201, + "Test index template should be created successfully. HTTP " + + putStatus + + ": " + + putResponseBody); + } + + private static String uniqueTestResourceName(String label) { + return "zz_indextemplate_it_" + label + "_" + UUID.randomUUID().toString().replace("-", ""); + } + private void deleteIndexIfExists(Rest5Client client, String indexName) { try { Request deleteRequest = new Request("DELETE", "/" + indexName); @@ -387,4 +450,13 @@ private void deleteIndexIfExists(Rest5Client client, String indexName) { // Index may not exist } } + + private void deleteTemplateIfExists(Rest5Client client, String templateName) { + try { + Request deleteRequest = new Request("DELETE", "/_index_template/" + templateName); + client.performRequest(deleteRequest); + } catch (Exception ignored) { + // Template may not exist + } + } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/K8sOMJobOperatorIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/K8sOMJobOperatorIT.java index c53509701580..e32fac6d9971 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/K8sOMJobOperatorIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/K8sOMJobOperatorIT.java @@ -40,7 +40,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -138,10 +137,6 @@ static void setupCluster() throws Exception { // TODO: we need to fix this, it's giving us 422 error // installCRDs(); - // Setup Awaitility defaults for operator tests - Awaitility.setDefaultTimeout(TIMEOUT.toSeconds(), TimeUnit.SECONDS); - Awaitility.setDefaultPollInterval(5, TimeUnit.SECONDS); - LOG.info("K3s cluster setup complete with namespace: {}", TEST_NAMESPACE); } @@ -289,6 +284,7 @@ void testSuccessfulJobWithExitHandler() { // Wait for main pod to be created Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -310,6 +306,7 @@ void testSuccessfulJobWithExitHandler() { // Wait for main pod to complete Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -321,6 +318,7 @@ void testSuccessfulJobWithExitHandler() { // Wait for exit handler to be created Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -342,6 +340,7 @@ void testSuccessfulJobWithExitHandler() { // Wait for exit handler to complete Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -373,6 +372,7 @@ void testFailedJobWithExitHandler() { // Wait for main pod to fail Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -393,6 +393,7 @@ void testFailedJobWithExitHandler() { // Wait for exit handler to be created Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -414,6 +415,7 @@ void testFailedJobWithExitHandler() { // Wait for exit handler to complete Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -450,6 +452,7 @@ void testRaceConditionHandling() { jobs.forEach( (jobName, omJob) -> { Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT.multipliedBy(2)) .until( () -> { @@ -484,6 +487,7 @@ void testPodDeletionDuringExecution() { // Wait for main pod to be created and running Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -516,6 +520,7 @@ void testPodDeletionDuringExecution() { // Wait for operator to detect pod deletion and handle it Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -545,6 +550,7 @@ void testTTLCleanup() { // Wait for job to complete Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(TIMEOUT) .until( () -> { @@ -631,6 +637,7 @@ void testCronOMJobCreatesOMJobsOnSchedule() { // Wait for the CronOMJob to create at least one OMJob Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(Duration.ofMinutes(2)) .until( () -> { @@ -718,6 +725,7 @@ void testCronOMJobWithStartingDeadline() { // Wait for at least one schedule Awaitility.await() + .pollInterval(Duration.ofSeconds(5)) .atMost(Duration.ofMinutes(6)) .until( () -> { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MemoryAgentIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MemoryAgentIT.java deleted file mode 100644 index 601c94ebe5fe..000000000000 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MemoryAgentIT.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright 2025 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.it.tests; - -import static org.awaitility.Awaitility.await; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.openmetadata.it.util.SdkClients; -import org.openmetadata.it.util.TestNamespace; -import org.openmetadata.it.util.TestNamespaceExtension; -import org.openmetadata.schema.api.context.CreateContextMemory; -import org.openmetadata.schema.api.data.CreateGlossary; -import org.openmetadata.schema.configuration.AIDeletionPolicy; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.entity.data.Glossary; -import org.openmetadata.schema.entity.data.GlossaryTerm; -import org.openmetadata.schema.entity.data.Metric; -import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.type.ProviderType; -import org.openmetadata.schema.type.Relationship; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.sdk.client.OpenMetadataClient; -import org.openmetadata.sdk.services.context.ContextMemoryService; -import org.openmetadata.sdk.services.glossary.GlossaryService; -import org.openmetadata.service.Entity; -import org.openmetadata.service.drive.memory.MemoryAction; -import org.openmetadata.service.drive.memory.MemoryDerivation; -import org.openmetadata.service.drive.memory.MemoryReconciler; -import org.openmetadata.service.drive.memory.MemoryVerdict; -import org.openmetadata.service.jdbi3.GlossaryRepository; -import org.openmetadata.service.jdbi3.GlossaryTermRepository; -import org.openmetadata.service.jdbi3.MetricRepository; -import org.openmetadata.service.util.MemoryOwnership; - -/** - * Integration tests for the Memory Agent lifecycle. - * - *

These tests are FULLY DETERMINISTIC: no LLM provider is needed. Rather than triggering the - * actual agent derivation pipeline (which requires an LLM), we seed the derived state directly via - * the in-process repository ({@code Entity.getEntityRepository}) — exactly replicating what the - * reconciler's CREATE path produces — and then drive the rest of the lifecycle through the PUBLIC - * REST API so the real cascade and adopt-on-touch hooks fire. - * - *

Scenario A — CASCADE on hard delete: hard-delete a memory whose term is AUTOMATION-owned - * → the term must disappear (404). - * - *

Scenario B — Adopt-on-touch releases the term, survives delete: a human PATCH to the - * term's description must flip {@code provider} to {@code user}; hard-delete the memory → the term - * must survive. - * - *

Scenario C — derivedFrom / derivedEntities projections: the 11a fields must expose the - * edge in both directions. - * - *

Scenario D — full pipeline with a stub LLM: SKIPPED because the - * {@link org.openmetadata.service.drive.memory.MemoryProcessingEngine} singleton is built once - * with the server's quiet-period (default 5 min) and {@link - * org.openmetadata.service.llm.LLMClientHolder} uses a static field. Resetting the singleton in an - * integration environment that is already serving requests races with the production path: any memory - * created concurrently by another test or background job could be ingested by the stub, producing - * non-deterministic side-effects. Scenarios A, B, C cover the catalog-critical lifecycle end-to-end - * through the public API hooks; the unit tests in ContextMemoryReconcilerTest and MemoryExtractorTest - * cover the LLM derivation path with full determinism. - */ -@Execution(ExecutionMode.CONCURRENT) -@ExtendWith(TestNamespaceExtension.class) -public class MemoryAgentIT { - - // ═══════════════════════════════════════════════════════════════════ - // Scenario A — CASCADE hard delete removes the automation-owned term - // ═══════════════════════════════════════════════════════════════════ - - @Test - void scenarioA_cascadeHardDelete_removesAutomationOwnedTerm(TestNamespace ns) throws Exception { - OpenMetadataClient client = SdkClients.adminClient(); - - ContextMemory memory = createMemory(client, ns.prefix("mem-cascade")); - Glossary glossary = createGlossary(client, ns.prefix("gl-cascade")); - GlossaryTerm term = createAutomationTerm(ns.prefix("term-cascade"), glossary); - seedDerivedFromEdge(term.getId(), memory.getId()); - - hardDeleteMemory(client, memory.getId()); - - await() - .pollInterval(Duration.ofMillis(300)) - .atMost(Duration.ofSeconds(20)) - .untilAsserted( - () -> { - boolean gone = isGone(client, term.getId()); - assertTrue( - gone, - "Automation-owned term must be deleted (cascade) when memory is hard-deleted"); - }); - } - - // ═══════════════════════════════════════════════════════════════════ - // Scenario B — Adopt-on-touch: human PATCH → provider=user → survives delete - // ═══════════════════════════════════════════════════════════════════ - - @Test - void scenarioB_adoptOnTouch_termSurvivesMemoryDelete(TestNamespace ns) throws Exception { - OpenMetadataClient client = SdkClients.adminClient(); - - ContextMemory memory = createMemory(client, ns.prefix("mem-adopt")); - Glossary glossary = createGlossary(client, ns.prefix("gl-adopt")); - GlossaryTerm term = createAutomationTerm(ns.prefix("term-adopt"), glossary); - seedDerivedFromEdge(term.getId(), memory.getId()); - - GlossaryTerm fetched = client.glossaryTerms().get(term.getId().toString()); - GlossaryTerm toUpdate = JsonUtils.deepCopy(fetched, GlossaryTerm.class); - toUpdate.setDescription("Human-edited description triggering adoption"); - client.glossaryTerms().update(term.getId().toString(), toUpdate); - - GlossaryTerm afterPatch = client.glossaryTerms().get(term.getId().toString()); - assertEquals( - ProviderType.USER, - afterPatch.getProvider(), - "provider must flip to USER after a human PATCH on an automation-owned term"); - - hardDeleteMemory(client, memory.getId()); - - await() - .pollInterval(Duration.ofMillis(300)) - .atMost(Duration.ofSeconds(20)) - .untilAsserted( - () -> { - boolean alive = isAlive(client, term.getId()); - assertTrue( - alive, "Human-adopted term must survive when its source memory is deleted"); - }); - - GlossaryService glossaryService = new GlossaryService(client.getHttpClient()); - client.glossaryTerms().delete(term.getId().toString(), hardDeleteParams()); - glossaryService.delete(glossary.getId().toString(), hardDeleteParams()); - } - - // ═══════════════════════════════════════════════════════════════════ - // Scenario C — derivedFrom / derivedEntities projections expose the edge - // ═══════════════════════════════════════════════════════════════════ - - @Test - void scenarioC_projections_exposeDerivedEdgeInBothDirections(TestNamespace ns) throws Exception { - OpenMetadataClient client = SdkClients.adminClient(); - - ContextMemory memory = createMemory(client, ns.prefix("mem-proj")); - Glossary glossary = createGlossary(client, ns.prefix("gl-proj")); - GlossaryTerm term = createAutomationTerm(ns.prefix("term-proj"), glossary); - seedDerivedFromEdge(term.getId(), memory.getId()); - - GlossaryTerm termWithDerivedFrom = - client.glossaryTerms().get(term.getId().toString(), "derivedFrom"); - assertNotNull( - termWithDerivedFrom.getDerivedFrom(), "derivedFrom must be populated on the term"); - assertEquals( - memory.getId(), - termWithDerivedFrom.getDerivedFrom().getId(), - "derivedFrom must point to the seeded source memory"); - - ContextMemoryService memoryService = new ContextMemoryService(client.getHttpClient()); - ContextMemory memoryWithDerived = - memoryService.get(memory.getId().toString(), "derivedEntities"); - assertNotNull( - memoryWithDerived.getDerivedEntities(), "derivedEntities must be populated on the memory"); - boolean termPresent = - memoryWithDerived.getDerivedEntities().stream() - .anyMatch(ref -> ref.getId().equals(term.getId())); - assertTrue(termPresent, "derivedEntities must include the seeded term reference"); - - GlossaryService glossaryService = new GlossaryService(client.getHttpClient()); - hardDeleteMemory(client, memory.getId()); - glossaryService.delete(glossary.getId().toString(), hardDeleteParams()); - } - - // ═══════════════════════════════════════════════════════════════════ - // Scenario E — axis-toggle: deriveMetrics=false skips metric CREATE, - // leaves pre-existing owned metric untouched (no mass-retire) - // - // Fully deterministic: passes the axis flags directly to reconcile(), - // bypassing the settings cache to avoid race conditions in concurrent runs. - // - // Setup: one AUTOMATION-owned metric seeded with a DERIVED_FROM edge. - // Action: reconcile with deriveMetrics=false and CREATE verdict for metric. - // Assert: metric axis gated → 0 new metrics created, 0 retired, owned metric alive. - // ═══════════════════════════════════════════════════════════════════ - - @Test - void scenarioE_deriveMetricsDisabled_skipsMetricAndPreservesExistingOwnedMetric(TestNamespace ns) - throws Exception { - OpenMetadataClient client = SdkClients.adminClient(); - - ContextMemory memory = createMemory(client, ns.prefix("mem-toggle")); - Metric existingOwnedMetric = createAutomationMetric(ns.prefix("owned-metric")); - seedDerivedFromMetricEdge(existingOwnedMetric.getId(), memory.getId()); - - MemoryReconciler reconciler = buildReconciler(); - MemoryVerdict createMetricVerdict = - new MemoryVerdict( - MemoryAction.CREATE, - null, - null, - null, - ns.prefix("new-m"), - "NewM", - "desc", - "COUNT", - null, - null); - MemoryVerdict skipTermVerdict = - new MemoryVerdict(MemoryAction.SKIP, null, null, null, null, null, null, null, null, null); - MemoryReconciler.ReconcileResult result = - reconciler.reconcile( - memory, - new MemoryDerivation(skipTermVerdict, createMetricVerdict), - null, - AIDeletionPolicy.CASCADE, - true, - false); - - assertEquals(0, result.createdMetrics(), "metric axis disabled: no metrics must be created"); - assertEquals(0, result.retired(), "disabled axis must NOT retire pre-existing owned metric"); - boolean metricStillAlive = isMetricAlive(existingOwnedMetric.getId()); - assertTrue( - metricStillAlive, "pre-existing owned metric must survive when metric axis is disabled"); - - MetricRepository metricRepo = (MetricRepository) Entity.getEntityRepository(Entity.METRIC); - metricRepo.delete(MemoryOwnership.MEMORY_BOT_NAME, existingOwnedMetric.getId(), false, true); - hardDeleteMemory(client, memory.getId()); - } - - // ═══════════════════════════════════════════════════════════════════ - // Private helpers - // ═══════════════════════════════════════════════════════════════════ - - private ContextMemory createMemory(OpenMetadataClient client, String name) { - ContextMemoryService svc = new ContextMemoryService(client.getHttpClient()); - CreateContextMemory req = - new CreateContextMemory() - .withName(name) - .withQuestion("What is " + name + "?") - .withAnswer("Answer for " + name + "."); - return svc.create(req); - } - - private Glossary createGlossary(OpenMetadataClient client, String name) { - GlossaryService svc = new GlossaryService(client.getHttpClient()); - CreateGlossary req = new CreateGlossary().withName(name).withDescription("Test glossary"); - return svc.create(req); - } - - /** - * Creates a GlossaryTerm with {@code provider=AUTOMATION} via the in-process repository, - * exactly replicating the path {@code MemoryReconciler.createTerm} takes. The public REST - * {@code CreateGlossaryTerm} API does not expose {@code provider}, so we bypass it and call - * {@code createInternal} directly — the same call the reconciler uses — so the stored JSON - * carries {@code "provider":"automation"} and the cascade / adopt-on-touch hooks see the correct - * value when they read back from the DB. - */ - private GlossaryTerm createAutomationTerm(String name, Glossary glossary) { - GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - GlossaryTerm term = - new GlossaryTerm() - .withId(UUID.randomUUID()) - .withName(name) - .withDescription("Automation-derived term for " + name) - .withGlossary(glossary.getEntityReference()) - .withProvider(ProviderType.AUTOMATION) - .withUpdatedBy(MemoryOwnership.MEMORY_BOT_NAME) - .withUpdatedAt(System.currentTimeMillis()); - return termRepo.createInternal(term); - } - - private Metric createAutomationMetric(String name) { - MetricRepository metricRepo = (MetricRepository) Entity.getEntityRepository(Entity.METRIC); - Metric metric = - new Metric() - .withId(UUID.randomUUID()) - .withName(name) - .withDescription("Automation-derived metric for " + name) - .withProvider(ProviderType.AUTOMATION) - .withUpdatedBy(MemoryOwnership.MEMORY_BOT_NAME) - .withUpdatedAt(System.currentTimeMillis()); - return metricRepo.createInternal(metric); - } - - /** - * Seeds the {@code DERIVED_FROM} edge that the Memory Agent's CREATE path produces: - * {@code from=term → to=memory} via {@link Relationship#DERIVED_FROM}. - * - *

This uses the in-process repository directly (the same call as - * {@code MemoryReconciler.addDerivedFromEdge}) so the edge is queryable through the real - * relationship table, and all subsequent REST calls (GET, DELETE) exercise the real hooks. - */ - private void seedDerivedFromEdge(UUID termId, UUID memoryId) { - GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - termRepo.addRelationship( - termId, - memoryId, - Entity.GLOSSARY_TERM, - Entity.CONTEXT_MEMORY, - Relationship.DERIVED_FROM, - false); - } - - private void seedDerivedFromMetricEdge(UUID metricId, UUID memoryId) { - MetricRepository metricRepo = (MetricRepository) Entity.getEntityRepository(Entity.METRIC); - metricRepo.addRelationship( - metricId, memoryId, Entity.METRIC, Entity.CONTEXT_MEMORY, Relationship.DERIVED_FROM, false); - } - - private void hardDeleteMemory(OpenMetadataClient client, UUID memoryId) { - ContextMemoryService svc = new ContextMemoryService(client.getHttpClient()); - svc.delete(memoryId.toString(), hardDeleteParams()); - } - - private Map hardDeleteParams() { - Map params = new HashMap<>(); - params.put("hardDelete", "true"); - return params; - } - - private boolean isGone(OpenMetadataClient client, UUID termId) { - try { - GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - GlossaryTerm term = termRepo.find(termId, Include.ALL); - return term == null || term.getDeleted() != null && term.getDeleted(); - } catch (Exception e) { - return true; - } - } - - private boolean isAlive(OpenMetadataClient client, UUID termId) { - try { - GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - GlossaryTerm term = termRepo.find(termId, Include.NON_DELETED); - return term != null && (term.getDeleted() == null || !term.getDeleted()); - } catch (Exception e) { - return false; - } - } - - private boolean isMetricAlive(UUID metricId) { - try { - MetricRepository metricRepo = (MetricRepository) Entity.getEntityRepository(Entity.METRIC); - Metric metric = metricRepo.find(metricId, Include.NON_DELETED); - return metric != null && (metric.getDeleted() == null || !metric.getDeleted()); - } catch (Exception e) { - return false; - } - } - - private MemoryReconciler buildReconciler() { - GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - MetricRepository metricRepo = (MetricRepository) Entity.getEntityRepository(Entity.METRIC); - GlossaryRepository glossaryRepo = - (GlossaryRepository) Entity.getEntityRepository(Entity.GLOSSARY); - return new MemoryReconciler(termRepo, metricRepo, glossaryRepo); - } -} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MultiDomainHasDomainIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MultiDomainHasDomainIT.java index 39c77389af44..b5b7a5eaf330 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MultiDomainHasDomainIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/MultiDomainHasDomainIT.java @@ -12,9 +12,12 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.factories.DatabaseSchemaTestFactory; import org.openmetadata.it.factories.DatabaseServiceTestFactory; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.CreateTable; @@ -57,6 +60,7 @@ */ @Execution(ExecutionMode.CONCURRENT) @ExtendWith(TestNamespaceExtension.class) +@ResourceLock(value = SharedResourceLocks.SEARCH_SETTINGS, mode = ResourceAccessMode.READ_WRITE) public class MultiDomainHasDomainIT { private static final ObjectMapper MAPPER = new ObjectMapper(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java index 620b3b7adb4b..b46f245486fb 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java @@ -32,6 +32,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -60,6 +62,7 @@ */ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @ExtendWith(TestNamespaceExtension.class) +@Execution(ExecutionMode.SAME_THREAD) public class OpenLineageLineageResolutionIT { private static final ObjectMapper MAPPER = new ObjectMapper(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrphanIngestionPipelineCleanupIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrphanIngestionPipelineCleanupIT.java new file mode 100644 index 000000000000..6026554e7b56 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrphanIngestionPipelineCleanupIT.java @@ -0,0 +1,104 @@ +/* + * Copyright 2025 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Date; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.bootstrap.SharedEntities; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.services.ingestionPipelines.CreateIngestionPipeline; +import org.openmetadata.schema.entity.services.ingestionPipelines.AirflowConfig; +import org.openmetadata.schema.entity.services.ingestionPipelines.IngestionPipeline; +import org.openmetadata.schema.entity.services.ingestionPipelines.PipelineType; +import org.openmetadata.schema.metadataIngestion.DatabaseServiceMetadataPipeline; +import org.openmetadata.schema.metadataIngestion.SourceConfig; +import org.openmetadata.schema.type.Relationship; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.util.OrphanIngestionPipelineCleanup; + +/** + * End-to-end test for {@link OrphanIngestionPipelineCleanup} (the Data Retention cleanup of + * ingestion pipelines whose container {@code service -> pipeline} CONTAINS row is missing). Verifies + * that a pipeline with no container is hard-deleted, while a healthy pipeline is left untouched — the + * cleanup is selective, not a blanket wipe. + */ +@Execution(ExecutionMode.SAME_THREAD) +@ExtendWith(TestNamespaceExtension.class) +public class OrphanIngestionPipelineCleanupIT { + + private static final int BATCH = 10_000; + + @Test + void missingContainer_deletesPipeline_keepsHealthy(TestNamespace ns) throws Exception { + IngestionPipeline healthy = createPipeline("healthyPipe_" + ns.uniqueShortId()); + IngestionPipeline broken = createPipeline("brokenPipe_" + ns.uniqueShortId()); + + assertEquals(1, pipelineRowCount(broken.getId().toString()), "broken pipeline should exist"); + assertEquals(1, pipelineRowCount(healthy.getId().toString()), "healthy pipeline should exist"); + + // Break the broken pipeline: remove its service -> pipeline CONTAINS relationship row (leaving + // the service intact) — the exact data-drift state the cleanup targets. + Entity.getCollectionDAO() + .relationshipDAO() + .deleteTo(broken.getId(), Entity.INGESTION_PIPELINE, Relationship.CONTAINS.ordinal()); + + OrphanIngestionPipelineCleanup.Result result = + new OrphanIngestionPipelineCleanup(Entity.getCollectionDAO(), false).performCleanup(BATCH); + + assertTrue(result.getOrphansDeleted() >= 1, "the broken pipeline must be counted as an orphan"); + + // Broken pipeline is gone; healthy pipeline survives — the cleanup is selective. + assertEquals(0, pipelineRowCount(broken.getId().toString()), "broken pipeline must be deleted"); + assertEquals(1, pipelineRowCount(healthy.getId().toString()), "healthy pipeline must survive"); + } + + private IngestionPipeline createPipeline(String name) { + OpenMetadataClient client = SdkClients.adminClient(); + SourceConfig sourceConfig = + new SourceConfig() + .withConfig( + new DatabaseServiceMetadataPipeline() + .withMarkDeletedTables(true) + .withIncludeViews(true)); + return client + .ingestionPipelines() + .create( + new CreateIngestionPipeline() + .withName(name) + .withPipelineType(PipelineType.METADATA) + .withService(SharedEntities.get().MYSQL_SERVICE.getEntityReference()) + .withSourceConfig(sourceConfig) + .withAirflowConfig(new AirflowConfig().withStartDate(new Date()))); + } + + private int pipelineRowCount(String id) { + return TestSuiteBootstrap.getJdbi() + .withHandle( + handle -> + handle + .createQuery("SELECT COUNT(*) FROM ingestion_pipeline_entity WHERE id = :id") + .bind("id", id) + .mapTo(Integer.class) + .one()); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/PatchTableEmbeddingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/PatchTableEmbeddingIT.java index 1044ef576b76..03c9d2a43896 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/PatchTableEmbeddingIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/PatchTableEmbeddingIT.java @@ -59,7 +59,8 @@ void testPatchTableDescriptionUpdatesEmbeddingForSemanticSearch(TestNamespace ns searchRepo.initializeVectorSearchService(); Assumptions.assumeTrue( - searchRepo.isVectorEmbeddingEnabled(), "Vector embedding could not be initialized"); + searchRepo.getVectorIndexService() != null, + "Vector embedding could not be initialized: " + searchRepo.getVectorServiceInitError()); try { runEmbeddingTest(ns, searchRepo); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfGlossaryGraphIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfGlossaryGraphIT.java index b59b079ee9b2..3d8b6ddc7ed0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfGlossaryGraphIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfGlossaryGraphIT.java @@ -36,10 +36,14 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.api.parallel.Isolated; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.bootstrap.TestSuiteBootstrap; import org.openmetadata.it.factories.GlossaryTermTestFactory; import org.openmetadata.it.factories.GlossaryTestFactory; +import org.openmetadata.it.util.NamespaceCleanup; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.configuration.rdf.RdfConfiguration; @@ -393,6 +397,9 @@ void sameTermPairCanHoldMultipleRelationTypesIndependently(TestNamespace ns) thr } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void customRdfPredicateRelationSurfacesInGraphEndpoint(TestNamespace ns) throws Exception { // Regression: GlossaryTermRelationSettings lets operators define custom // relation types with arbitrary rdfPredicate URIs (e.g. "Enrolls In" with @@ -433,11 +440,15 @@ void customRdfPredicateRelationSurfacesInGraphEndpoint(TestNamespace ns) throws // term — exactly the customer's symptom. awaitEdgeBetween(glossary.getId(), a.getId(), b.getId(), customTypeName); } finally { + NamespaceCleanup.deleteRoots(ns.drainTrackedRoots()); removeCustomRelationTypeFromSettings(customTypeName); } } @Test + @ResourceLock( + value = SharedResourceLocks.GLOSSARY_TERM_RELATION_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) void customRelationWithNullRdfPredicateSurfacesInGraphEndpoint(TestNamespace ns) throws Exception { // Companion to customRdfPredicateRelationSurfacesInGraphEndpoint covering @@ -465,6 +476,7 @@ void customRelationWithNullRdfPredicateSurfacesInGraphEndpoint(TestNamespace ns) // this edge (written as om:regressionNullPredRel) is filtered out. awaitEdgeBetween(glossary.getId(), a.getId(), b.getId(), customTypeName); } finally { + NamespaceCleanup.deleteRoots(ns.drainTrackedRoots()); removeCustomRelationTypeFromSettings(customTypeName); } } @@ -488,6 +500,13 @@ private void addCustomRelationTypeToSettings(String name, URI rdfPredicate) thro } com.fasterxml.jackson.databind.node.ObjectNode custom = MAPPER.createObjectNode(); custom.put("name", name); + custom.put("displayName", name); + custom.put("isSymmetric", false); + custom.put("isTransitive", false); + custom.put("isCrossGlossaryAllowed", true); + custom.put("category", "associative"); + custom.put("isSystemDefined", false); + custom.put("color", "#4f46e5"); if (rdfPredicate != null) { custom.put("rdfPredicate", rdfPredicate.toString()); } @@ -509,35 +528,35 @@ private void addCustomRelationTypeToSettings(String name, URI rdfPredicate) thro () -> "PUT settings failed: " + response.statusCode() + " " + response.body()); } - private void removeCustomRelationTypeFromSettings(String name) { - try { - JsonNode existing = fetchGlossaryTermRelationSettings(); - if (existing == null || !existing.has("relationTypes")) { - return; - } - com.fasterxml.jackson.databind.node.ObjectNode payload = MAPPER.createObjectNode(); - payload.put("config_type", "glossaryTermRelationSettings"); - com.fasterxml.jackson.databind.node.ObjectNode value = MAPPER.createObjectNode(); - com.fasterxml.jackson.databind.node.ArrayNode kept = MAPPER.createArrayNode(); - for (JsonNode t : existing.get("relationTypes")) { - if (!name.equals(t.path("name").asText(null))) { - kept.add(t); - } + private void removeCustomRelationTypeFromSettings(String name) throws Exception { + JsonNode existing = fetchGlossaryTermRelationSettings(); + if (existing == null || !existing.has("relationTypes")) { + return; + } + com.fasterxml.jackson.databind.node.ObjectNode payload = MAPPER.createObjectNode(); + payload.put("config_type", "glossaryTermRelationSettings"); + com.fasterxml.jackson.databind.node.ObjectNode value = MAPPER.createObjectNode(); + com.fasterxml.jackson.databind.node.ArrayNode kept = MAPPER.createArrayNode(); + for (JsonNode t : existing.get("relationTypes")) { + if (!name.equals(t.path("name").asText(null))) { + kept.add(t); } - value.set("relationTypes", kept); - payload.set("config_value", value); - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(SdkClients.getServerUrl() + "/v1/system/settings")) - .header("Authorization", "Bearer " + SdkClients.getAdminToken()) - .header("Content-Type", "application/json") - .timeout(Duration.ofSeconds(30)) - .PUT(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload))) - .build(); - HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (Exception e) { - LOG.warn("Failed to remove custom relation type {} from settings", name, e); } + value.set("relationTypes", kept); + payload.set("config_value", value); + HttpRequest request = + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + "/v1/system/settings")) + .header("Authorization", "Bearer " + SdkClients.getAdminToken()) + .header("Content-Type", "application/json") + .timeout(Duration.ofSeconds(30)) + .PUT(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload))) + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertEquals( + 200, + response.statusCode(), + () -> "PUT settings failed: " + response.statusCode() + " " + response.body()); } private JsonNode fetchGlossaryTermRelationSettings() throws Exception { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java index 6b8fbcd35987..717d5b7630ad 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java @@ -383,7 +383,7 @@ void testRecoverStaleDoesNotAffectRecentClaims(TestNamespace ns) { // --------------------------------------------------------------------------- @Test - void testUpdateFailureAndRetryCountIncrementsCount(TestNamespace ns) { + void testUpdateFailureAndRetryCountIncrementsCountAndRetainsAttemptTime(TestNamespace ns) { String entityId = UUID.randomUUID().toString(); String entityFqn = ns.prefix("rq") + ".entity"; @@ -400,7 +400,40 @@ void testUpdateFailureAndRetryCountIncrementsCount(TestNamespace ns) { records.stream().filter(r -> r.getEntityId().equals(entityId)).findFirst().orElseThrow(); assertEquals(1, record.getRetryCount()); assertEquals("retry 1 failed", record.getFailureReason()); - assertNull(record.getClaimedAt()); + assertNotNull(record.getClaimedAt()); + + retryQueueDAO.deleteByEntity(entityId, entityFqn); + } + + @Test + void testClaimPendingHonorsRetryBackoff(TestNamespace ns) { + String entityId = UUID.randomUUID().toString(); + String entityFqn = ns.prefix("rq") + ".backoff"; + + retryQueueDAO.upsert( + entityId, entityFqn, "initial", SearchIndexRetryQueue.STATUS_PENDING, "table"); + retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING); + retryQueueDAO.updateFailureAndRetryCount( + entityId, entityFqn, "retry 1 failed", SearchIndexRetryQueue.STATUS_PENDING_RETRY_1); + + List delayedFirstRetry = retryQueueDAO.claimPending(1000, 3600, 7200); + assertTrue( + delayedFirstRetry.stream().noneMatch(record -> record.getEntityId().equals(entityId))); + + List eligibleFirstRetry = retryQueueDAO.claimPending(1000, 0, 0); + assertTrue( + eligibleFirstRetry.stream().anyMatch(record -> record.getEntityId().equals(entityId))); + + retryQueueDAO.updateFailureAndRetryCount( + entityId, entityFqn, "retry 2 failed", SearchIndexRetryQueue.STATUS_PENDING_RETRY_2); + + List delayedSecondRetry = retryQueueDAO.claimPending(1000, 0, 7200); + assertTrue( + delayedSecondRetry.stream().noneMatch(record -> record.getEntityId().equals(entityId))); + + List eligibleSecondRetry = retryQueueDAO.claimPending(1000, 0, 0); + assertTrue( + eligibleSecondRetry.stream().anyMatch(record -> record.getEntityId().equals(entityId))); retryQueueDAO.deleteByEntity(entityId, entityFqn); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java index 9bbb341389d1..13326d756009 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SystemResourceIT.java @@ -29,6 +29,7 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; @@ -37,6 +38,7 @@ import org.openmetadata.api.configuration.LogoConfiguration; import org.openmetadata.api.configuration.ThemeConfiguration; import org.openmetadata.api.configuration.UiThemePreference; +import org.openmetadata.common.utils.CommonUtil; import org.openmetadata.it.util.SdkClients; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; @@ -69,9 +71,12 @@ import org.openmetadata.schema.system.TestLoginTokenRequest; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.SemanticsRule; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.util.EntityUtil; /** * Integration tests for System Resource endpoints. @@ -91,6 +96,26 @@ public class SystemResourceIT { private static final ObjectMapper MAPPER = new ObjectMapper(); + @AfterEach + void resetSearchSettingsAfterTest() throws Exception { + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.PUT, + "/v1/system/settings/reset/" + SettingsType.SEARCH_SETTINGS.value(), + null, + RequestOptions.builder().build()); + } + + private SearchSettings loadCanonicalSearchSettings() throws Exception { + List resources = + EntityUtil.getJsonDataResources(".*json/data/settings/searchSettings.json$"); + String json = + CommonUtil.getResourceAsStream( + EntityRepository.class.getClassLoader(), resources.getFirst()); + return JsonUtils.readValue(json, SearchSettings.class); + } + @Test void test_getSystemVersion() throws Exception { OpenMetadataClient client = SdkClients.adminClient(); @@ -703,6 +728,7 @@ void test_updateLoginConfiguration() throws Exception { @Test void test_getDefaultSearchSettings() throws Exception { OpenMetadataClient client = SdkClients.adminClient(); + SearchSettings canonicalSearchSettings = loadCanonicalSearchSettings(); // Ensure deterministic baseline even when other tests mutate search settings. client @@ -727,9 +753,15 @@ void test_getDefaultSearchSettings() throws Exception { MAPPER.convertValue(settings.getConfigValue(), SearchSettings.class); assertNotNull(searchConfig.getGlobalSettings()); - assertEquals(10000, searchConfig.getGlobalSettings().getMaxAggregateSize()); - assertEquals(10000, searchConfig.getGlobalSettings().getMaxResultHits()); - assertEquals(1000, searchConfig.getGlobalSettings().getMaxAnalyzedOffset()); + assertEquals( + canonicalSearchSettings.getGlobalSettings().getMaxAggregateSize(), + searchConfig.getGlobalSettings().getMaxAggregateSize()); + assertEquals( + canonicalSearchSettings.getGlobalSettings().getMaxResultHits(), + searchConfig.getGlobalSettings().getMaxResultHits()); + assertEquals( + canonicalSearchSettings.getGlobalSettings().getMaxAnalyzedOffset(), + searchConfig.getGlobalSettings().getMaxAnalyzedOffset()); assertNotNull(searchConfig.getGlobalSettings().getAggregations()); assertFalse(searchConfig.getGlobalSettings().getAggregations().isEmpty()); @@ -751,6 +783,7 @@ void test_getDefaultSearchSettings() throws Exception { @Test void test_defaultSearchRankingBoostConfiguration() throws Exception { OpenMetadataClient client = SdkClients.adminClient(); + SearchSettings canonicalSearchSettings = loadCanonicalSearchSettings(); client .getHttpClient() @@ -778,54 +811,82 @@ void test_defaultSearchRankingBoostConfiguration() throws Exception { .filter(conf -> "table".equalsIgnoreCase(conf.getAssetType())) .findFirst() .orElseThrow(() -> new AssertionError("Table configuration not found")); + AssetTypeConfiguration canonicalTableConfig = + canonicalSearchSettings.getAssetTypeConfigurations().stream() + .filter(conf -> "table".equalsIgnoreCase(conf.getAssetType())) + .findFirst() + .orElseThrow(() -> new AssertionError("Canonical table configuration not found")); assertEquals( - AssetTypeConfiguration.BoostMode.MULTIPLY, + canonicalTableConfig.getBoostMode(), tableConfig.getBoostMode(), - "Table boost mode should be multiply for tiebreaker scoring"); + "Table boost mode should match the canonical search settings"); assertNotNull(tableConfig.getFieldValueBoosts()); - assertEquals(2, tableConfig.getFieldValueBoosts().size()); - - FieldValueBoost usageCountBoost = - tableConfig.getFieldValueBoosts().stream() - .filter(b -> "usageSummary.monthlyStats.count".equals(b.getField())) - .findFirst() - .orElseThrow(() -> new AssertionError("Usage count field value boost not found")); - assertEquals(0.002, usageCountBoost.getFactor(), 1e-6); - - FieldValueBoost percentileBoost = - tableConfig.getFieldValueBoosts().stream() - .filter(b -> "usageSummary.monthlyStats.percentileRank".equals(b.getField())) - .findFirst() - .orElseThrow(() -> new AssertionError("Percentile rank field value boost not found")); - assertEquals(0.0005, percentileBoost.getFactor(), 1e-6); + assertNotNull(canonicalTableConfig.getFieldValueBoosts()); + assertEquals( + canonicalTableConfig.getFieldValueBoosts().size(), + tableConfig.getFieldValueBoosts().size()); + for (FieldValueBoost canonicalBoost : canonicalTableConfig.getFieldValueBoosts()) { + FieldValueBoost actualBoost = + tableConfig.getFieldValueBoosts().stream() + .filter(boost -> canonicalBoost.getField().equals(boost.getField())) + .findFirst() + .orElseThrow( + () -> + new AssertionError( + "Field value boost not found: " + canonicalBoost.getField())); + assertEquals(canonicalBoost.getField(), actualBoost.getField()); + assertEquals(canonicalBoost.getFactor(), actualBoost.getFactor(), 1e-12); + assertTrue(actualBoost.getFactor() > 0, "Field value boost factors must be positive"); + } List globalTermBoosts = searchConfig.getGlobalSettings().getTermBoosts(); + List canonicalGlobalTermBoosts = + canonicalSearchSettings.getGlobalSettings().getTermBoosts(); assertNotNull(globalTermBoosts); - assertEquals(3, globalTermBoosts.size()); + assertNotNull(canonicalGlobalTermBoosts); + assertEquals(canonicalGlobalTermBoosts.size(), globalTermBoosts.size()); + for (TermBoost canonicalBoost : canonicalGlobalTermBoosts) { + TermBoost actualBoost = + globalTermBoosts.stream() + .filter( + boost -> + canonicalBoost.getField().equals(boost.getField()) + && canonicalBoost.getValue().equals(boost.getValue())) + .findFirst() + .orElseThrow( + () -> + new AssertionError( + "Term boost not found: " + + canonicalBoost.getField() + + "=" + + canonicalBoost.getValue())); + assertEquals(canonicalBoost.getField(), actualBoost.getField()); + assertEquals(canonicalBoost.getValue(), actualBoost.getValue()); + assertEquals(canonicalBoost.getBoost(), actualBoost.getBoost(), 1e-12); + } TermBoost tier1Boost = globalTermBoosts.stream() .filter(t -> "Tier.Tier1".equals(t.getValue())) .findFirst() .orElseThrow(() -> new AssertionError("Tier1 term boost not found")); - assertEquals("tier.tagFQN", tier1Boost.getField()); - assertEquals(0.05, tier1Boost.getBoost(), 1e-6); TermBoost tier2Boost = globalTermBoosts.stream() .filter(t -> "Tier.Tier2".equals(t.getValue())) .findFirst() .orElseThrow(() -> new AssertionError("Tier2 term boost not found")); - assertEquals(0.03, tier2Boost.getBoost(), 1e-6); TermBoost tier3Boost = globalTermBoosts.stream() .filter(t -> "Tier.Tier3".equals(t.getValue())) .findFirst() .orElseThrow(() -> new AssertionError("Tier3 term boost not found")); - assertEquals(0.01, tier3Boost.getBoost(), 1e-6); + assertTrue(tier1Boost.getBoost() > tier2Boost.getBoost()); + assertTrue(tier2Boost.getBoost() > tier3Boost.getBoost()); + assertTrue(tier3Boost.getBoost() > 0); } @Test @@ -1676,29 +1737,46 @@ private SecurityConfiguration buildBasicSecurityConfig() { @Test void test_updateSecurityConfig() throws Exception { OpenMetadataClient client = SdkClients.adminClient(); - - SecurityConfiguration securityConfig = buildBasicSecurityConfig(); - - String securityConfigJson = MAPPER.writeValueAsString(securityConfig); - String updatedJson = + String originalSecurityConfigJson = client .getHttpClient() .executeForString( - HttpMethod.PUT, + HttpMethod.GET, "/v1/system/security/config", - securityConfigJson, + null, RequestOptions.builder().build()); - assertNotNull(updatedJson); - SecurityConfiguration updated = MAPPER.readValue(updatedJson, SecurityConfiguration.class); - - assertNotNull(updated); - assertEquals( - securityConfig.getAuthenticationConfiguration().getProvider(), - updated.getAuthenticationConfiguration().getProvider()); - assertEquals( - securityConfig.getAuthorizerConfiguration().getClassName(), - updated.getAuthorizerConfiguration().getClassName()); + try { + SecurityConfiguration securityConfig = buildBasicSecurityConfig(); + String securityConfigJson = MAPPER.writeValueAsString(securityConfig); + String updatedJson = + client + .getHttpClient() + .executeForString( + HttpMethod.PUT, + "/v1/system/security/config", + securityConfigJson, + RequestOptions.builder().build()); + + assertNotNull(updatedJson); + SecurityConfiguration updated = MAPPER.readValue(updatedJson, SecurityConfiguration.class); + + assertNotNull(updated); + assertEquals( + securityConfig.getAuthenticationConfiguration().getProvider(), + updated.getAuthenticationConfiguration().getProvider()); + assertEquals( + securityConfig.getAuthorizerConfiguration().getClassName(), + updated.getAuthorizerConfiguration().getClassName()); + } finally { + client + .getHttpClient() + .executeForString( + HttpMethod.PUT, + "/v1/system/security/config", + originalSecurityConfigJson, + RequestOptions.builder().build()); + } } @Test diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TableResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TableResourceIT.java index 7c6162843e9b..76c3d9da40a5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TableResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TableResourceIT.java @@ -22,6 +22,9 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.awaitility.Awaitility; @@ -1561,7 +1564,6 @@ void test_patchTable_removeColumnWithUniqueConstraint(TestNamespace ns) { // TODO: Migrate put_tableJoinsInvalidColumnName_4xx - Requires SDK table joins validation // TODO: Migrate put_tableSampleData_200 - Requires SDK sample data support // TODO: Migrate put_tableInvalidSampleData_4xx - Requires SDK sample data validation - // TODO: Migrate put_schemaDefinition_200 - Requires SDK schema definition support // TODO: Migrate put_profileConfig_200 - Requires SDK profiler config support // TODO: Migrate put_tableProfile_200 - Requires SDK table profile support // TODO: Migrate create_profilerWrongTimestamp - Requires SDK profile timestamp validation @@ -2372,7 +2374,6 @@ void create_profilerWrongTimestamp(TestNamespace ns) { void put_schemaDefinition_200(TestNamespace ns) { OpenMetadataClient client = SdkClients.adminClient(); - // Create a view table with schema definition String query = """ sales_vw @@ -2384,16 +2385,29 @@ void put_schemaDefinition_200(TestNamespace ns) { """; CreateTable createRequest = createRequest(ns.prefix("view_table"), ns); - createRequest.setTableType(org.openmetadata.schema.type.TableType.View); + createRequest.setTableType(TableType.View); createRequest.setSchemaDefinition(query); Table table = createEntity(createRequest); assertNotNull(table); - assertEquals(org.openmetadata.schema.type.TableType.View, table.getTableType()); + assertEquals(TableType.View, table.getTableType()); - // Fetch with schemaDefinition field + // Verify schemaDefinition persisted on create Table fetched = client.tables().get(table.getId().toString(), "schemaDefinition"); assertEquals(query, fetched.getSchemaDefinition()); + + // Verify schemaDefinition is updated via PUT + String updatedQuery = + """ + sales_vw + create view sales_vw as + select * from public.sales; + """; + createRequest.setSchemaDefinition(updatedQuery); + client.tables().createOrUpdate(createRequest); + + Table fetchedAfterUpdate = client.tables().get(table.getId().toString(), "schemaDefinition"); + assertEquals(updatedQuery, fetchedAfterUpdate.getSchemaDefinition()); } // =================================================================== @@ -3738,11 +3752,10 @@ void test_concurrentColumnUpdates_reproduceDataLoss(TestNamespace ns) throws Exc Table baseState = client.tables().get(table.getId().toString(), "columns,tags"); // Simulate concurrent updates - java.util.concurrent.CountDownLatch startLatch = new java.util.concurrent.CountDownLatch(1); - java.util.concurrent.CountDownLatch completionLatch = - new java.util.concurrent.CountDownLatch(2); - java.util.concurrent.atomic.AtomicReference errorRef = - new java.util.concurrent.atomic.AtomicReference<>(); + CountDownLatch startLatch = new CountDownLatch(1); + CountDownLatch firstUpdateCompleted = new CountDownLatch(1); + CountDownLatch completionLatch = new CountDownLatch(2); + AtomicReference errorRef = new AtomicReference<>(); // Thread A: Update column description Thread threadA = @@ -3758,6 +3771,7 @@ void test_concurrentColumnUpdates_reproduceDataLoss(TestNamespace ns) throws Exc } catch (Exception e) { errorRef.set(e); } finally { + firstUpdateCompleted.countDown(); completionLatch.countDown(); } }); @@ -3768,7 +3782,9 @@ void test_concurrentColumnUpdates_reproduceDataLoss(TestNamespace ns) throws Exc () -> { try { startLatch.await(); - Thread.sleep(50); // Small delay + if (!firstUpdateCompleted.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("First column update did not complete"); + } Table tableB = client.tables().get(baseState.getId().toString(), "columns"); Column col = tableB.getColumns().get(0); col.setDisplayName("Display Name B"); @@ -3784,11 +3800,13 @@ void test_concurrentColumnUpdates_reproduceDataLoss(TestNamespace ns) throws Exc threadA.start(); threadB.start(); startLatch.countDown(); - completionLatch.await(10, java.util.concurrent.TimeUnit.SECONDS); + assertTrue(completionLatch.await(45, TimeUnit.SECONDS), "Concurrent updates did not complete"); + assertNull(errorRef.get(), "Concurrent column update failed"); - // Verify - at least one update should succeed Table finalTable = client.tables().get(table.getId().toString(), "columns"); - assertNotNull(finalTable); + Column finalColumn = finalTable.getColumns().get(0); + assertEquals("Description A", finalColumn.getDescription()); + assertEquals("Display Name B", finalColumn.getDisplayName()); } // =================================================================== diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index c89038559af8..8a1fec7cfe74 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.function.BiFunction; import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -83,6 +84,9 @@ import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.ContainerDataModel; +import org.openmetadata.schema.type.DataAccessPermission; +import org.openmetadata.schema.type.DataAccessRequestPayload; +import org.openmetadata.schema.type.DataAccessType; import org.openmetadata.schema.type.EntityHistory; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Field; @@ -1809,6 +1813,80 @@ void testGetCountByAboutEntityWithResolvedTasks(TestNamespace ns) { assertEquals(1, countByAbout.getOpen(), "One task should still be open"); } + /** + * The count SQL buckets rows row-aware on {@code type} so {@code Approved} lands in Open for + * DataAccessRequest (non-terminal — awaiting grant) and in Completed for non-DAR task types + * where it is terminal. This keeps openCount + completedCount = total across a mixed inbox + * and was the regression that produced Open(10) + Closed(4) > All(13) when the UI mapped + * Open to the {@code active} bucket. See ListFilter.buildTaskStatusGroupCondition and + * CollectionDAO.TaskDAO#getTaskCountSummary. + */ + @Test + void testGetCount_ApprovedDarInOpenBucket_ApprovedGlossaryInClosedBucket(TestNamespace ns) { + DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); + Table table = TableTestFactory.createSimple(ns, schema.getFullyQualifiedName()); + String tableFqn = table.getFullyQualifiedName(); + String tableLink = entityLink("table", tableFqn); + + Task glossaryTask = + createEntity( + new CreateTask() + .withName(ns.prefix("bucket-glossary-approved")) + .withCategory(TaskCategory.Approval) + .withType(TaskEntityType.GlossaryApproval) + .withAbout(tableLink)); + + DataAccessRequestPayload darPayload = + new DataAccessRequestPayload() + .withAccessType(DataAccessType.FullAccess) + .withRequestedAccess(DataAccessPermission.Read) + .withReason("integration-test") + .withDuration("P14D"); + + Task darTask = + SdkClients.adminClient() + .tasks() + .create( + new CreateTask() + .withName(ns.prefix("bucket-dar-approved")) + .withCategory(TaskCategory.DataAccess) + .withType(TaskEntityType.DataAccessRequest) + .withAbout(tableLink) + .withPayload(darPayload)); + + ResolveTask approve = + new ResolveTask() + .withResolutionType(TaskResolutionType.Approved) + .withComment("Approved for bucket test"); + + Task resolvedGlossary = + SdkClients.adminClient().tasks().resolve(glossaryTask.getId().toString(), approve); + Task resolvedDar = + SdkClients.adminClient().tasks().resolve(darTask.getId().toString(), approve); + + assertEquals(TaskEntityStatus.Approved, resolvedGlossary.getStatus()); + assertEquals(TaskEntityStatus.Approved, resolvedDar.getStatus()); + + TaskCount count = SdkClients.adminClient().tasks().getCountByAboutEntity(tableFqn); + + assertEquals(2, count.getTotal(), "Both tasks are about the same table"); + assertEquals(1, count.getOpen(), "DAR row with status=Approved must land in the open bucket"); + assertEquals( + 1, + count.getCompleted(), + "Glossary row with status=Approved must land in the completed bucket"); + assertEquals( + count.getTotal(), + count.getOpen() + count.getCompleted(), + "openCount + completedCount must reconcile with total for a mixed inbox"); + assertEquals( + 2, + count.getApproved(), + "approvedCount is a raw status counter — both rows have status=Approved and land here" + + " regardless of the row-aware open/completed bucket routing"); + } + @Test void testTaskAboutFqnHashIsStoredCorrectly(TestNamespace ns) { DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); @@ -2057,6 +2135,84 @@ void testVisibleEndpointAndAllViewCountReturnVisibleTaskUnion(TestNamespace ns) assertEquals(3, visibleCount.getOpen(), "All-view open count should match visible open tasks"); } + @Test + void testScopedTaskEndpointsHonorTimeRange(TestNamespace ns) { + SharedEntities shared = SharedEntities.get(); + Domain domain = createDomain(ns, "time-range-domain"); + Table ownedTable = + createTableWithDomainAndOwners(ns, domain.getEntityReference(), List.of(shared.USER1_REF)); + + Task assignedTask = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "time-range-assigned", ownedTable) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName()))); + Task createdTask = + SdkClients.user1Client() + .tasks() + .create(createTaskRequestAboutTable(ns, "time-range-created", ownedTable)); + + // assignedTask is visible to user1 both via /visible and /owned (about a + // user1-owned table); createdTask exercises /created (createdBy user1). + assertTimeRangeFilters( + (startTs, endTs) -> + SdkClients.user1Client() + .tasks() + .listVisible(null, null, null, "assignees,about", 1000, startTs, endTs), + assignedTask.getId(), + assignedTask.getCreatedAt()); + assertTimeRangeFilters( + (startTs, endTs) -> + SdkClients.user1Client() + .tasks() + .listOwned(null, null, null, "about", 1000, startTs, endTs), + assignedTask.getId(), + assignedTask.getCreatedAt()); + assertTimeRangeFilters( + (startTs, endTs) -> + SdkClients.user1Client() + .tasks() + .listCreated(null, null, null, "about", 1000, startTs, endTs), + createdTask.getId(), + createdTask.getCreatedAt()); + + assertThrows( + InvalidRequestException.class, + () -> + SdkClients.user1Client() + .tasks() + .listVisible(null, null, null, null, null, 2000L, 1000L), + "Inverted startTs > endTs should return 400"); + } + + private void assertTimeRangeFilters( + BiFunction> lister, UUID taskId, long createdAt) { + ListResponse inRange = lister.apply(createdAt - 1000, createdAt + 1000); + assertTrue( + inRange.getData().stream().anyMatch(t -> t.getId().equals(taskId)), + "Task should appear when its createdAt is inside the window"); + assertEquals( + inRange.getData().size(), + inRange.getTotal(), + "paging.total must reflect the time-filtered rows, not an unfiltered count"); + + ListResponse boundary = lister.apply(createdAt, createdAt); + assertTrue( + boundary.getData().stream().anyMatch(t -> t.getId().equals(taskId)), + "Task should appear when the window bounds equal its createdAt (bounds are inclusive)"); + + ListResponse pastRange = lister.apply(createdAt - 5000, createdAt - 1000); + assertFalse( + pastRange.getData().stream().anyMatch(t -> t.getId().equals(taskId)), + "Task should be excluded when the window ends before its createdAt (endTs upper bound)"); + + ListResponse futureRange = lister.apply(createdAt + 1000, createdAt + 5000); + assertFalse( + futureRange.getData().stream().anyMatch(t -> t.getId().equals(taskId)), + "Task should be excluded when the window starts after its createdAt (startTs lower bound)"); + } + // ==================== Entity Change Application Tests ==================== @Test diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java index f1efb466fd49..2137209f7494 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java @@ -74,6 +74,9 @@ public class TestCaseResourceIT extends BaseEntityIT { private static final Logger LOG = LoggerFactory.getLogger(TestCaseResourceIT.class); private static final ObjectMapper MAPPER = new ObjectMapper(); + // Search converges synchronously post-commit, but a transient ES write failure falls back to the + // async retry queue — allow generous headroom so heavy parallel runs don't trip the happy path. + private static final Duration SEARCH_CONVERGENCE_TIMEOUT = Duration.ofSeconds(120); private static final RetryConfig DEADLOCK_RETRY_CONFIG = RetryConfig.custom() .maxAttempts(3) @@ -1393,8 +1396,9 @@ void test_putPreservesLogicalSuiteSearchMembership(TestNamespace ns) throws Exce try (Rest5Client searchClient = TestSuiteBootstrap.createSearchClient()) { Awaitility.await("logical suite membership indexed before PUT") - .atMost(Duration.ofSeconds(60)) + .atMost(SEARCH_CONVERGENCE_TIMEOUT) .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() .untilAsserted( () -> assertSearchDocContainsTestSuite( @@ -1406,14 +1410,25 @@ void test_putPreservesLogicalSuiteSearchMembership(TestNamespace ns) throws Exce client.testCases().upsert(createRequest); TestCase fetched = client.testCases().get(testCase.getId().toString(), "testSuites"); + // Read-your-write (DB + sync cache) is immediately consistent, so assert the PUT actually + // applied here — this pins the failure to search propagation rather than a dropped update. + assertEquals( + updatedDescription, + fetched.getDescription(), + "PUT should apply the new description at the API level"); assertTrue( fetched.getTestSuites().stream() .anyMatch(suite -> suite.getId().equals(logicalSuite.getId())), "PUT should preserve the logical suite graph relationship"); + // Search indexing runs synchronously post-commit, BUT a transient ES write failure falls back + // to the async SearchIndexRetryQueue, so convergence is eventually-consistent, not strictly + // bounded by the write returning. Poll generously (and ignore transient query hiccups) rather + // than assuming the sync drain always wins on the first sample under heavy parallel load. Awaitility.await("PUT preserves logical suite membership in search") - .atMost(Duration.ofSeconds(60)) + .atMost(SEARCH_CONVERGENCE_TIMEOUT) .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() .untilAsserted( () -> { JsonNode source = queryTestCaseSearchSource(searchClient, testCase.getId()); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TypeResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TypeResourceIT.java index aa5b67537b67..385b912f1a42 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TypeResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TypeResourceIT.java @@ -22,7 +22,10 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.SharedResourceLocks; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.CreateType; @@ -835,6 +838,9 @@ void test_concurrentCustomPropertyAdditions(TestNamespace ns) throws Exception { } @Test + @ResourceLock( + value = SharedResourceLocks.TABLE_COLUMN_CUSTOM_PROPERTIES, + mode = ResourceAccessMode.READ_WRITE) void test_addCustomPropertyToTableColumn(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); @@ -856,6 +862,9 @@ void test_addCustomPropertyToTableColumn(TestNamespace ns) throws Exception { } @Test + @ResourceLock( + value = SharedResourceLocks.TABLE_COLUMN_CUSTOM_PROPERTIES, + mode = ResourceAccessMode.READ_WRITE) void test_addCustomPropertyToDashboardDataModelColumn(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); @@ -879,6 +888,9 @@ void test_addCustomPropertyToDashboardDataModelColumn(TestNamespace ns) throws E } @Test + @ResourceLock( + value = SharedResourceLocks.TABLE_COLUMN_CUSTOM_PROPERTIES, + mode = ResourceAccessMode.READ_WRITE) void test_columnCustomPropertiesAreIsolated(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); @@ -928,6 +940,9 @@ void test_columnCustomPropertiesAreIsolated(TestNamespace ns) throws Exception { } @Test + @ResourceLock( + value = SharedResourceLocks.TABLE_COLUMN_CUSTOM_PROPERTIES, + mode = ResourceAccessMode.READ_WRITE) void test_getAllCustomPropertiesIncludesColumnTypes(TestNamespace ns) throws Exception { OpenMetadataClient client = SdkClients.adminClient(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java index 968ca9084865..1fbe3f984ce8 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java @@ -45,6 +45,7 @@ import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.services.teams.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -211,9 +212,6 @@ void testUserMetricsWithRealActivity() throws Exception { Map initialMetrics = getUserMetrics(); LOG.info("Initial metrics: {}", initialMetrics); - int initialTotalUsers = (Integer) initialMetrics.get("total_users"); - int initialBotUsers = (Integer) initialMetrics.get("bot_users"); - String userName = ns.prefix("metricsuser"); String email = "metricsuser_" + ns.shortPrefix() + "@test.openmetadata.org"; CreateUser createUser = new CreateUser().withName(userName).withEmail(email).withIsBot(false); @@ -230,25 +228,23 @@ void testUserMetricsWithRealActivity() throws Exception { .pollDelay(Duration.ofMillis(500)) .pollInterval(Duration.ofSeconds(1)) .ignoreExceptions() - .until( + .untilAsserted( () -> { + assertNotNull(usersApi.getByName(newUser.getName())); Map m = getUserMetrics(); int total = (Integer) m.get("total_users"); - return total > initialTotalUsers; + assertTrue( + total >= listUserTotal(usersApi), + "Metrics should include every visible user while the created user exists"); }); Map updatedMetrics = getUserMetrics(); LOG.info("Updated metrics after activity: {}", updatedMetrics); int updatedTotalUsers = (Integer) updatedMetrics.get("total_users"); - // In parallel test execution, other tests may create/delete users, so verify the user exists assertTrue( - updatedTotalUsers >= initialTotalUsers, - "Total users should not decrease: initial=" - + initialTotalUsers - + ", updated=" - + updatedTotalUsers); - // Verify our created user exists by fetching it + updatedTotalUsers > 0, + "Metrics should report at least one user while the created user exists"); User fetchedUser = usersApi.getByName(newUser.getName()); assertNotNull(fetchedUser, "Created user should exist"); @@ -275,6 +271,12 @@ void testUserMetricsWithRealActivity() throws Exception { } } + private int listUserTotal(UserService usersApi) { + ListParams params = new ListParams(); + params.setLimit(1); + return usersApi.list(params).getPaging().getTotal(); + } + @Test void testUserMetricsWithBotUser() throws Exception { Map initialMetrics = getUserMetrics(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpChatResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpChatResourceIT.java deleted file mode 100644 index da159340e0d9..000000000000 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpChatResourceIT.java +++ /dev/null @@ -1,293 +0,0 @@ -package org.openmetadata.it.tests.mcp; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.fasterxml.jackson.databind.JsonNode; -import java.net.http.HttpResponse; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.openmetadata.it.auth.JwtAuthProvider; -import org.openmetadata.schema.configuration.LLMBedrockConfig; -import org.openmetadata.schema.configuration.LLMConfiguration; -import org.openmetadata.schema.configuration.LLMProvider; -import org.openmetadata.schema.entity.chat.McpConversation; -import org.openmetadata.schema.security.credentials.AWSBaseConfig; -import org.openmetadata.schema.utils.JsonUtils; - -@Execution(ExecutionMode.SAME_THREAD) -public class McpChatResourceIT extends McpTestBase { - - private static final String MCP_CLIENT_PATH = "mcp-client"; - - @BeforeAll - static void setUp() throws Exception { - initAuth(); - ensureMcpChatEnabled(); - } - - private static void ensureMcpChatEnabled() throws Exception { - Map mcpChat = new HashMap<>(); - mcpChat.put("enabled", true); - mcpChat.put("systemPrompt", "Test prompt"); - Map aiSettings = new HashMap<>(); - aiSettings.put("enabled", true); - aiSettings.put("mcpChat", mcpChat); - Map settings = new HashMap<>(); - settings.put("config_type", "aiSettings"); - settings.put("config_value", aiSettings); - - put("system/settings", settings, Object.class); - } - - @Test - void testMcpChatEnabledInSettings() throws Exception { - JsonNode settings = get("system/settings/aiSettings", JsonNode.class); - JsonNode mcpChat = settings.get("config_value").get("mcpChat"); - - assertThat(mcpChat.get("enabled").asBoolean()).isTrue(); - assertThat(mcpChat.get("systemPrompt").asText()).isEqualTo("Test prompt"); - } - - @Test - void testLlmConfigurationDeserialization() throws Exception { - LLMConfiguration config = - new LLMConfiguration() - .withEnabled(true) - .withProvider(LLMProvider.BEDROCK) - .withBedrock( - new LLMBedrockConfig() - .withModelId("anthropic.claude-sonnet-4-20250514-v1:0") - .withAwsConfig(new AWSBaseConfig().withRegion("us-east-1"))); - - String json = JsonUtils.pojoToJson(config); - LLMConfiguration deserialized = JsonUtils.readValue(json, LLMConfiguration.class); - - assertThat(deserialized.getProvider()).isEqualTo(LLMProvider.BEDROCK); - assertThat(deserialized.getBedrock()).isNotNull(); - assertThat(deserialized.getBedrock().getAwsConfig().getRegion()).isEqualTo("us-east-1"); - } - - @Test - void testCreateConversation() throws Exception { - McpConversation conversation = createConversation(); - - assertThat(conversation).isNotNull(); - assertThat(conversation.getId()).isNotNull(); - assertThat(conversation.getMessageCount()).isZero(); - } - - @Test - void testListConversations() throws Exception { - McpConversation created = createConversation(); - - JsonNode result = get(MCP_CLIENT_PATH + "/conversations?limit=50", JsonNode.class); - - assertThat(result.has("data")).isTrue(); - assertThat(result.get("data").isArray()).isTrue(); - - boolean found = false; - for (JsonNode conv : result.get("data")) { - if (conv.get("id").asText().equals(created.getId().toString())) { - found = true; - break; - } - } - assertThat(found).isTrue(); - } - - @Test - void testGetConversationById() throws Exception { - McpConversation created = createConversation(); - - McpConversation fetched = - get(MCP_CLIENT_PATH + "/conversations/" + created.getId(), McpConversation.class); - - assertThat(fetched.getId()).isEqualTo(created.getId()); - assertThat(fetched.getMessageCount()).isZero(); - } - - @Test - void testGetConversationMessages_empty() throws Exception { - McpConversation created = createConversation(); - - JsonNode result = - get(MCP_CLIENT_PATH + "/conversations/" + created.getId() + "/messages", JsonNode.class); - - assertThat(result.has("data")).isTrue(); - assertThat(result.get("data").isArray()).isTrue(); - assertThat(result.get("data").size()).isZero(); - } - - @Test - void testDeleteConversation() throws Exception { - McpConversation created = createConversation(); - - HttpResponse deleteResp = - deleteResponse(MCP_CLIENT_PATH + "/conversations/" + created.getId()); - assertThat(deleteResp.statusCode()).isEqualTo(204); - - HttpResponse getResp = - getResponse(MCP_CLIENT_PATH + "/conversations/" + created.getId(), authToken); - assertThat(getResp.statusCode()).isGreaterThanOrEqualTo(400); - } - - @Nested - class ConversationIsolation { - - private static String otherUserToken; - - @BeforeAll - static void setUpOtherUser() { - otherUserToken = - "Bearer " - + JwtAuthProvider.tokenFor( - "test@open-metadata.org", "test@open-metadata.org", new String[] {}, 3600); - } - - @Test - void getConversationByIdIsBlockedForOtherUser() throws Exception { - McpConversation created = createConversation(); - - HttpResponse resp = - getResponse(MCP_CLIENT_PATH + "/conversations/" + created.getId(), otherUserToken); - - assertThat(resp.statusCode()).isGreaterThanOrEqualTo(400); - } - - @Test - void listConversationsDoesNotExposeOtherUsersData() throws Exception { - McpConversation adminConversation = createConversation(); - - HttpResponse resp = - getResponse(MCP_CLIENT_PATH + "/conversations?limit=100", otherUserToken); - assertThat(resp.statusCode()).isEqualTo(200); - - JsonNode result = OBJECT_MAPPER.readTree(resp.body()); - assertThat(result.has("data")).isTrue(); - - for (JsonNode conv : result.get("data")) { - assertThat(conv.get("id").asText()) - .as("Other user should never see admin's conversation") - .isNotEqualTo(adminConversation.getId().toString()); - } - } - - @Test - void getMessagesIsBlockedForOtherUser() throws Exception { - McpConversation created = createConversation(); - - HttpResponse resp = - getResponse( - MCP_CLIENT_PATH + "/conversations/" + created.getId() + "/messages", otherUserToken); - - assertThat(resp.statusCode()).isGreaterThanOrEqualTo(400); - } - - @Test - void deleteConversationIsBlockedForOtherUser() throws Exception { - McpConversation created = createConversation(); - - HttpResponse deleteResp = - deleteResponse(MCP_CLIENT_PATH + "/conversations/" + created.getId(), otherUserToken); - - assertThat(deleteResp.statusCode()).isGreaterThanOrEqualTo(400); - - McpConversation stillExists = - get(MCP_CLIENT_PATH + "/conversations/" + created.getId(), McpConversation.class); - assertThat(stillExists.getId()).isEqualTo(created.getId()); - } - - @Test - void chatOnExistingConversationIsBlockedForOtherUser() throws Exception { - McpConversation created = createConversation(); - - Map chatRequest = new HashMap<>(); - chatRequest.put("conversationId", created.getId().toString()); - chatRequest.put("message", "Hello from another user"); - - HttpResponse resp = - postResponse(MCP_CLIENT_PATH + "/chat", chatRequest, otherUserToken); - - assertThat(resp.statusCode()).isGreaterThanOrEqualTo(400); - } - - @Test - void eachUserSeesOnlyOwnConversations() throws Exception { - McpConversation adminConversation = createConversation(); - - HttpResponse otherCreateResp = - postResponse(MCP_CLIENT_PATH + "/conversations", new HashMap<>(), otherUserToken); - assertThat(otherCreateResp.statusCode()).isIn(200, 201); - McpConversation otherConversation = - OBJECT_MAPPER.readValue(otherCreateResp.body(), McpConversation.class); - - JsonNode adminList = get(MCP_CLIENT_PATH + "/conversations?limit=100", JsonNode.class); - boolean adminSeesOwn = false; - boolean adminSeesOther = false; - for (JsonNode conv : adminList.get("data")) { - String id = conv.get("id").asText(); - if (id.equals(adminConversation.getId().toString())) { - adminSeesOwn = true; - } - if (id.equals(otherConversation.getId().toString())) { - adminSeesOther = true; - } - } - assertThat(adminSeesOwn).as("Admin should see own conversation").isTrue(); - assertThat(adminSeesOther).as("Admin should not see other user's conversation").isFalse(); - - HttpResponse otherListResp = - getResponse(MCP_CLIENT_PATH + "/conversations?limit=100", otherUserToken); - JsonNode otherList = OBJECT_MAPPER.readTree(otherListResp.body()); - boolean otherSeesOwn = false; - boolean otherSeesAdmin = false; - for (JsonNode conv : otherList.get("data")) { - String id = conv.get("id").asText(); - if (id.equals(otherConversation.getId().toString())) { - otherSeesOwn = true; - } - if (id.equals(adminConversation.getId().toString())) { - otherSeesAdmin = true; - } - } - assertThat(otherSeesOwn).as("Other user should see own conversation").isTrue(); - assertThat(otherSeesAdmin).as("Other user should not see admin's conversation").isFalse(); - - deleteResponse( - MCP_CLIENT_PATH + "/conversations/" + otherConversation.getId(), otherUserToken); - } - } - - @Test - void testChatSucceedsWhenLlmConfigured() throws Exception { - Map chatRequest = new HashMap<>(); - chatRequest.put("message", "Hello"); - - HttpResponse resp = postResponse(MCP_CLIENT_PATH + "/chat", chatRequest, authToken); - - // The embedded suite configures an in-JVM stub LLM (see TestSuiteBootstrap / LlmStubServer), - // so chat is enabled end to end and returns a completion, rather than the 500 raised by - // requireChatEnabled() when llmConfiguration is absent. - assertThat(resp.statusCode()).isEqualTo(200); - } - - @Test - void testGetNonExistentConversation() throws Exception { - UUID randomId = UUID.randomUUID(); - - HttpResponse resp = - getResponse(MCP_CLIENT_PATH + "/conversations/" + randomId, authToken); - - assertThat(resp.statusCode()).isGreaterThanOrEqualTo(400); - } - - private McpConversation createConversation() throws Exception { - return post(MCP_CLIENT_PATH + "/conversations", new HashMap<>(), McpConversation.class); - } -} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpIntegrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpIntegrationIT.java index 3f578fd55b54..c10b0d1e3aaa 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpIntegrationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpIntegrationIT.java @@ -7,6 +7,7 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -17,6 +18,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.openmetadata.it.auth.JwtAuthProvider; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.service.Entity; @@ -298,4 +300,91 @@ void testComprehensiveMcpToolsLoadTest() throws Exception { assertThat(allCompleted).isTrue(); assertThat(successfulRequests.get()).isGreaterThan(totalRequests / 2); } + + @Test + void getEntityDetailsIsDeniedByTagBasedPolicy() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String tagFqn = createRestrictedTag(suffix); + Table restricted = createServiceDatabaseSchemaTable("mcp_authz_" + suffix); + tagTable(restricted.getId().toString(), tagFqn); + String deniedToken = createUserDeniedByTag(suffix, tagFqn); + + Map call = + McpTestUtils.createGetEntityToolCall(Entity.TABLE, restricted.getFullyQualifiedName()); + + // Admin bypasses the policy and sees the table — proves the denial below is real, not a fluke. + assertThat(executeMcpRequest(call).toString()).contains("created_at"); + + // The non-admin is hit by the tag Deny: no entity data must come back. + assertThat(executeMcpRequest(call, deniedToken).toString()).doesNotContain("created_at"); + } + + private String createRestrictedTag(String suffix) throws Exception { + String classification = "McpAuthz" + suffix; + post( + "classifications", + Map.of("name", classification, "description", "mcp authz"), + JsonNode.class); + JsonNode tag = + post( + "tags", + Map.of("classification", classification, "name", "Restricted", "description", "mcp"), + JsonNode.class); + return tag.get("fullyQualifiedName").asText(); + } + + private void tagTable(String tableId, String tagFqn) throws Exception { + patch( + "tables/" + tableId, + String.format( + "[{\"op\":\"add\",\"path\":\"/tags/0\",\"value\":{\"tagFQN\":\"%s\",\"source\":" + + "\"Classification\",\"labelType\":\"Manual\",\"state\":\"Confirmed\"}}]", + tagFqn)); + } + + private String createUserDeniedByTag(String suffix, String tagFqn) throws Exception { + String prefix = "mcpauthz_" + suffix; + JsonNode policy = + post( + "policies", + Map.of( + "name", + prefix + "_policy", + "rules", + List.of( + Map.of( + "name", prefix + "_rule", + "resources", List.of("table"), + "operations", List.of("ViewAll"), + "effect", "deny", + "condition", String.format("matchAnyTag('%s')", tagFqn)))), + JsonNode.class); + JsonNode role = + post( + "roles", + Map.of( + "name", + prefix + "_role", + "policies", + List.of(policy.get("fullyQualifiedName").asText())), + JsonNode.class); + JsonNode dataConsumer = get("roles/name/DataConsumer", JsonNode.class); + JsonNode team = + post( + "teams", + Map.of( + "name", + prefix + "_team", + "teamType", + "Group", + "defaultRoles", + List.of(dataConsumer.get("id").asText(), role.get("id").asText())), + JsonNode.class); + String email = prefix + "_u@test.openmetadata.org"; + post( + "users", + Map.of("name", prefix + "_u", "email", email, "teams", List.of(team.get("id").asText())), + JsonNode.class); + return "Bearer " + JwtAuthProvider.tokenFor(email, email, new String[] {}, 3_600); + } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpOAuthIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpOAuthIT.java index 1fff75755740..ae6e75838bbb 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpOAuthIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpOAuthIT.java @@ -16,8 +16,11 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@Execution(ExecutionMode.SAME_THREAD) public class McpOAuthIT extends McpTestBase { private static String registeredClientId; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpTestBase.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpTestBase.java index 618123112584..284aed4a577b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpTestBase.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpTestBase.java @@ -236,13 +236,18 @@ protected String getMcpUrl(String path) { } protected JsonNode executeMcpRequest(java.util.Map mcpRequest) throws Exception { + return executeMcpRequest(mcpRequest, authToken); + } + + protected JsonNode executeMcpRequest(java.util.Map mcpRequest, String token) + throws Exception { String requestBody = OBJECT_MAPPER.writeValueAsString(mcpRequest); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(getMcpUrl("/mcp"))) .header("Content-Type", "application/json") .header("Accept", "application/json, text/event-stream") - .header("Authorization", authToken) + .header("Authorization", token) .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .timeout(Duration.ofSeconds(30)) .build(); @@ -250,9 +255,7 @@ protected JsonNode executeMcpRequest(java.util.Map mcpRequest) t HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).isEqualTo(200); - String responseBody = response.body(); - String jsonContent = extractJsonFromResponse(responseBody); - return OBJECT_MAPPER.readTree(jsonContent); + return OBJECT_MAPPER.readTree(extractJsonFromResponse(response.body())); } protected static String extractJsonFromResponse(String responseBody) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpToolsValidationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpToolsValidationIT.java index a41e4c40d2cd..c8e4ecdaea6a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpToolsValidationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpToolsValidationIT.java @@ -18,6 +18,8 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import org.openmetadata.schema.api.data.CreateDatabase; import org.openmetadata.schema.api.data.CreateDatabaseSchema; import org.openmetadata.schema.api.data.CreateGlossary; @@ -36,6 +38,7 @@ import org.openmetadata.service.Entity; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@Execution(ExecutionMode.SAME_THREAD) public class McpToolsValidationIT extends McpTestBase { private static Table testTable; @@ -150,10 +153,16 @@ private JsonNode executeToolCall(Map toolCallRequest) throws Exc @Test @Order(1) void testSearchMetadataTool() throws Exception { - Map toolCall = - McpTestUtils.createSearchMetadataToolCall("mcp_val_table", 5, Entity.TABLE); - JsonNode result = executeToolCall(toolCall); - validateSearchMetadataResponse(result, "mcp_val_table"); + Awaitility.await("MCP search should find the newly indexed validation table") + .atMost(Duration.ofSeconds(60)) + .pollInterval(Duration.ofSeconds(2)) + .untilAsserted( + () -> { + Map toolCall = + McpTestUtils.createSearchMetadataToolCall("mcp_val_table", 5, Entity.TABLE); + JsonNode result = executeToolCall(toolCall); + validateSearchMetadataResponse(result, "mcp_val_table"); + }); } @Test @@ -196,7 +205,7 @@ void testGetEntityDetailsWideTableIsPaginatedNotDiscarded() throws Exception { @Test @Order(3) void testCreateGlossaryTool() throws Exception { - String randomGlossaryName = "randomGlossary"; + String randomGlossaryName = "randomGlossary_" + UUID.randomUUID().toString().substring(0, 8); Map toolCall = McpTestUtils.createGlossaryToolCall( randomGlossaryName, "Test glossary created for validation testing"); @@ -573,36 +582,33 @@ private void validateSearchMetadataResponse(JsonNode result, String expectedQuer assertThat(result.has("content")).isTrue(); JsonNode content = result.get("content"); assertThat(content.isArray()).isTrue(); + assertThat(content).isNotEmpty(); + JsonNode firstResult = content.get(0); + assertThat(firstResult.has("text")).isTrue(); + JsonNode response = OBJECT_MAPPER.readTree(firstResult.get("text").asText()); - if (content.size() > 0) { - JsonNode firstResult = content.get(0); - assertThat(firstResult.has("text")).isTrue(); - JsonNode response = OBJECT_MAPPER.readTree(firstResult.get("text").asText()); + assertThat(response.has("query")).isTrue(); + assertEquals(response.get("query").asText(), expectedQuery); + + Set matchingEntities = new HashSet<>(); + response + .get("results") + .forEach( + r -> { + assertThat(r.has("name")).isTrue(); + assertThat(r.has("fullyQualifiedName")).isTrue(); + assertThat(r.has("entityType")).isTrue(); + assertThat(r.has("deleted")) + .withFailMessage("Missing 'deleted' field in search result for: " + r.get("name")) + .isTrue(); + matchingEntities.add(r.get("name").asText()); + }); - assertThat(response.has("query")).isTrue(); - assertEquals(response.get("query").asText(), expectedQuery); - - Set matchingEntities = new HashSet<>(); - response - .get("results") - .forEach( - r -> { - assertThat(r.has("name")).isTrue(); - assertThat(r.has("fullyQualifiedName")).isTrue(); - assertThat(r.has("entityType")).isTrue(); - assertThat(r.has("deleted")) - .withFailMessage( - "Missing 'deleted' field in search result for: " + r.get("name")) - .isTrue(); - matchingEntities.add(r.get("name").asText()); - }); - - assertThat(matchingEntities.stream().anyMatch(name -> name.contains(expectedQuery))) - .withFailMessage( - "Expected at least one entity name containing '%s' but got: %s", - expectedQuery, matchingEntities) - .isTrue(); - } + assertThat(matchingEntities.stream().anyMatch(name -> name.contains(expectedQuery))) + .withFailMessage( + "Expected at least one entity name containing '%s' but got: %s", + expectedQuery, matchingEntities) + .isTrue(); } private JsonNode readEntityText(JsonNode result) throws Exception { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java new file mode 100644 index 000000000000..44357a078379 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java @@ -0,0 +1,216 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.it.tests.mcp; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.schema.api.teams.CreatePersona; +import org.openmetadata.schema.api.teams.CreateTeam; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.teams.Persona; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.PersonaContextDefinition; +import org.openmetadata.schema.type.personaContext.ContextRule; +import org.openmetadata.schema.type.personaContext.ContextSection; +import org.openmetadata.service.Entity; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class PersonaAIContextIT extends McpTestBase { + private static Persona persona; + private static Table table; + private static String directMemberToken; + private static String inheritedMemberToken; + private static String nonMemberToken; + private static String botToken; + + @BeforeAll + static void setup() throws Exception { + initAuth(); + String suffix = UUID.randomUUID().toString().substring(0, 8); + table = createServiceDatabaseSchemaTable("persona_context_" + suffix); + + User directMember = createUser("persona_direct_" + suffix); + User inheritedMember = createUser("persona_inherited_" + suffix); + User nonMember = createUser("persona_non_member_" + suffix); + User bot = get("users/name/profiler-bot", User.class); + + persona = + post( + "personas", + new CreatePersona() + .withName("persona_context_" + suffix) + .withDescription("Persona AI context integration test") + .withUsers(List.of(directMember.getId())), + Persona.class); + + post( + "teams", + new CreateTeam() + .withName("persona_context_team_" + suffix) + .withTeamType(CreateTeam.TeamType.GROUP) + .withUsers(List.of(inheritedMember.getId())) + .withDefaultPersona(persona.getId()), + JsonNode.class); + + directMemberToken = tokenFor(directMember); + inheritedMemberToken = tokenFor(inheritedMember); + nonMemberToken = tokenFor(nonMember); + botToken = tokenFor(bot); + + put( + contextPath(), + new PersonaContextDefinition() + .withEnabled(true) + .withCharacterBudget(400_000) + .withCacheTtlMinutes(30), + PersonaContextDefinition.class); + post(contextPath() + "/rules", tableRule("Baseline tables"), PersonaContextDefinition.class); + } + + @Test + void ruleCrudPreviewDocumentCacheAndMcpRoundTrip() throws Exception { + ContextRule requested = tableRule("CRUD tables"); + PersonaContextDefinition created = + post(contextPath() + "/rules", requested, PersonaContextDefinition.class); + ContextRule createdRule = + created.getRules().stream() + .filter(rule -> requested.getName().equals(rule.getName())) + .findFirst() + .orElseThrow(); + assertThat(createdRule.getId()).isNotNull(); + assertThat(createdRule.getSections()) + .contains(ContextSection.DESCRIPTION, ContextSection.JOINS, ContextSection.METRICS); + + JsonNode preview = post(contextPath() + "/rules/preview", requested, JsonNode.class); + assertThat(preview.get("matchedCount").asInt()).isGreaterThanOrEqualTo(1); + assertThat(preview.get("sampleNames").isArray()).isTrue(); + + HttpResponse duplicate = + postResponse(contextPath() + "/rules", tableRule(" crud TABLES "), authToken); + assertThat(duplicate.statusCode()).isEqualTo(400); + + ContextRule updatedRule = tableRule("Updated CRUD tables").withMaxAssets(2); + PersonaContextDefinition updated = + put( + contextPath() + "/rules/" + createdRule.getId(), + updatedRule, + PersonaContextDefinition.class); + assertThat(updated.getRules()).anyMatch(rule -> updatedRule.getName().equals(rule.getName())); + + HttpResponse firstDocument = getResponse(contextPath() + "/document", authToken); + HttpResponse secondDocument = getResponse(contextPath() + "/document", authToken); + assertThat(firstDocument.statusCode()).isEqualTo(200); + assertThat(secondDocument.statusCode()).isEqualTo(200); + assertThat(firstDocument.headers().firstValue("X-Cache")).isPresent(); + assertThat(secondDocument.headers().firstValue("X-Cache")).isPresent(); + assertThat(secondDocument.headers().firstValue("X-Cache").orElseThrow()).isIn("HIT", "BYPASS"); + JsonNode document = OBJECT_MAPPER.readTree(secondDocument.body()); + assertThat(document.get("markdown").asText()).contains(table.getFullyQualifiedName()); + + HttpResponse refreshed = + postResponse(contextPath() + "/document:refresh", Map.of(), authToken); + assertThat(refreshed.statusCode()).isEqualTo(200); + assertThat(refreshed.headers().firstValue("X-Cache").orElseThrow()).isEqualTo("BYPASS"); + + JsonNode mcp = + executeMcp( + McpTestUtils.createToolCallRequest( + "get_persona_context", + Map.of("personaName", persona.getFullyQualifiedName(), "format", "json")), + directMemberToken); + assertThat(mcp.path("result").path("isError").asBoolean(false)).isFalse(); + assertThat(mcp.toString()).contains(persona.getFullyQualifiedName()); + + HttpResponse deleted = + deleteResponse(contextPath() + "/rules/" + createdRule.getId(), authToken); + assertThat(deleted.statusCode()).isEqualTo(200); + } + + @Test + void enforcesMemberInheritedBotAdminAndRefreshAuthorization() throws Exception { + String personaContextPath = + "personas/name/" + persona.getFullyQualifiedName() + "/context?format=json"; + assertThat(getResponse(personaContextPath, directMemberToken).statusCode()).isEqualTo(200); + assertThat(getResponse(personaContextPath, inheritedMemberToken).statusCode()).isEqualTo(200); + assertThat(getResponse(personaContextPath, nonMemberToken).statusCode()).isEqualTo(403); + assertThat(getResponse(contextPath(), directMemberToken).statusCode()).isEqualTo(403); + assertThat(getResponse(personaContextPath + "&refresh=true", directMemberToken).statusCode()) + .isEqualTo(403); + assertThat(getResponse(personaContextPath + "&refresh=true", botToken).statusCode()) + .isEqualTo(200); + + JsonNode deniedMcp = + executeMcp( + McpTestUtils.createToolCallRequest( + "get_persona_context", Map.of("personaName", persona.getFullyQualifiedName())), + nonMemberToken); + assertThat(deniedMcp.toString()).contains("not assigned to persona"); + } + + private JsonNode executeMcp(Map requestBody, String token) throws Exception { + HttpRequest request = + HttpRequest.newBuilder() + .uri(URI.create(getMcpUrl("/mcp"))) + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .header("Authorization", token) + .POST( + HttpRequest.BodyPublishers.ofString(OBJECT_MAPPER.writeValueAsString(requestBody))) + .timeout(Duration.ofSeconds(30)) + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).isEqualTo(200); + return OBJECT_MAPPER.readTree(extractJsonFromResponse(response.body())); + } + + private static User createUser(String name) throws Exception { + return post( + "users", new CreateUser().withName(name).withEmail(name + "@example.com"), User.class); + } + + private static String tokenFor(User user) { + return "Bearer " + + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 3_600); + } + + private static ContextRule tableRule(String name) { + return new ContextRule() + .withName(name) + .withEntityType(Entity.TABLE) + .withQueryFilter( + "{\"query\":{\"term\":{\"fullyQualifiedName\":\"" + + table.getFullyQualifiedName() + + "\"}}}") + .withSections(Set.of()) + .withMaxAssets(1) + .withEnabled(true); + } + + private static String contextPath() { + return "personas/" + persona.getId() + "/aiContext"; + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntityRankingSeeders.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntityRankingSeeders.java new file mode 100644 index 000000000000..9b2252330401 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntityRankingSeeders.java @@ -0,0 +1,831 @@ +package org.openmetadata.it.tests.search; + +import java.net.URI; +import java.util.List; +import org.openmetadata.it.factories.DatabaseServiceTestFactory; +import org.openmetadata.it.tests.search.EntitySeeder.Placement; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.CreateAPICollection; +import org.openmetadata.schema.api.data.CreateAPIEndpoint; +import org.openmetadata.schema.api.data.CreateChart; +import org.openmetadata.schema.api.data.CreateContainer; +import org.openmetadata.schema.api.data.CreateDashboard; +import org.openmetadata.schema.api.data.CreateDashboardDataModel; +import org.openmetadata.schema.api.data.CreateDashboardDataModel.DashboardServiceType; +import org.openmetadata.schema.api.data.CreateDirectory; +import org.openmetadata.schema.api.data.CreateGlossary; +import org.openmetadata.schema.api.data.CreateGlossaryTerm; +import org.openmetadata.schema.api.data.CreateMetric; +import org.openmetadata.schema.api.data.CreateMlModel; +import org.openmetadata.schema.api.data.CreatePipeline; +import org.openmetadata.schema.api.data.CreateQuery; +import org.openmetadata.schema.api.data.CreateSearchIndex; +import org.openmetadata.schema.api.data.CreateStoredProcedure; +import org.openmetadata.schema.api.data.CreateTable; +import org.openmetadata.schema.api.data.CreateTopic; +import org.openmetadata.schema.api.data.StoredProcedureCode; +import org.openmetadata.schema.api.services.CreateApiService; +import org.openmetadata.schema.api.services.CreateDashboardService; +import org.openmetadata.schema.api.services.CreateDriveService; +import org.openmetadata.schema.api.services.CreateDriveService.DriveServiceType; +import org.openmetadata.schema.api.services.CreateMessagingService; +import org.openmetadata.schema.api.services.CreateMessagingService.MessagingServiceType; +import org.openmetadata.schema.api.services.CreateMlModelService; +import org.openmetadata.schema.api.services.CreatePipelineService; +import org.openmetadata.schema.api.services.CreatePipelineService.PipelineServiceType; +import org.openmetadata.schema.api.services.CreateSearchService; +import org.openmetadata.schema.api.services.CreateStorageService; +import org.openmetadata.schema.entity.services.ApiService; +import org.openmetadata.schema.entity.services.DashboardService; +import org.openmetadata.schema.entity.services.SearchService; +import org.openmetadata.schema.security.credentials.AWSCredentials; +import org.openmetadata.schema.services.connections.dashboard.CustomDashboardConnection; +import org.openmetadata.schema.services.connections.dashboard.CustomDashboardConnection.CustomDashboardType; +import org.openmetadata.schema.services.connections.dashboard.LookerConnection; +import org.openmetadata.schema.services.connections.drive.GoogleDriveConnection; +import org.openmetadata.schema.services.connections.messaging.KafkaConnection; +import org.openmetadata.schema.services.connections.mlmodel.SklearnConnection; +import org.openmetadata.schema.services.connections.pipeline.AirflowConnection; +import org.openmetadata.schema.services.connections.storage.S3Connection; +import org.openmetadata.schema.type.APISchema; +import org.openmetadata.schema.type.ChartType; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.ContainerDataModel; +import org.openmetadata.schema.type.DashboardConnection; +import org.openmetadata.schema.type.DataModelType; +import org.openmetadata.schema.type.DriveConnection; +import org.openmetadata.schema.type.Field; +import org.openmetadata.schema.type.FieldDataType; +import org.openmetadata.schema.type.MessageSchema; +import org.openmetadata.schema.type.MessagingConnection; +import org.openmetadata.schema.type.MlFeature; +import org.openmetadata.schema.type.MlFeatureDataType; +import org.openmetadata.schema.type.MlModelConnection; +import org.openmetadata.schema.type.PipelineConnection; +import org.openmetadata.schema.type.SchemaType; +import org.openmetadata.schema.type.SearchIndexDataType; +import org.openmetadata.schema.type.SearchIndexField; +import org.openmetadata.schema.type.StorageConnection; +import org.openmetadata.schema.type.StoredProcedureLanguage; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.schema.type.Task; +import org.openmetadata.sdk.client.OpenMetadataClient; + +/** Registry of one {@link EntitySeeder} per searchable asset type. */ +final class EntityRankingSeeders { + + private EntityRankingSeeders() {} + + static List all() { + return List.of( + new TableSeeder(), + new DashboardSeeder(), + new TopicSeeder(), + new PipelineSeeder(), + new MlModelSeeder(), + new ContainerSeeder(), + new DashboardDataModelSeeder(), + new QuerySeeder(), + new StoredProcedureSeeder(), + new SearchIndexSeeder(), + new GlossaryTermSeeder(), + new MetricSeeder(), + new ApiEndpointSeeder(), + new DirectorySeeder()); + } + + static final class TableSeeder implements EntitySeeder { + @Override + public String entityType() { + return "table"; + } + + @Override + public String index() { + return "table_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // columns.name + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + return RankingSupport.createSchemaFqn(ns); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateTable create = + new CreateTable() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withDatabaseSchema(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withColumns( + List.of( + new Column() + .withName(EntitySeeder.distinctiveFor(ns, token, placement)) + .withDataType(ColumnDataType.VARCHAR) + .withDataLength(64))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.tables().create(create).getName(); + } + } + + static final class DashboardSeeder implements EntitySeeder { + @Override + public String entityType() { + return "dashboard"; + } + + @Override + public String index() { + return "dashboard_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // charts.name (chart created + attached via withCharts) + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + DashboardConnection connection = + new DashboardConnection() + .withConfig( + new CustomDashboardConnection().withType(CustomDashboardType.CUSTOM_DASHBOARD)); + CreateDashboardService createService = + new CreateDashboardService() + .withName(ns.prefix("dash_svc_" + ns.shortPrefix())) + .withServiceType(DashboardServiceType.CustomDashboard) + .withConnection(connection); + return client.dashboardServices().create(createService).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateDashboard create = + new CreateDashboard() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)); + if (placement == Placement.DISTINCTIVE) { + create.withCharts(List.of(createChart(client, ns, parent, token, placement))); + } + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.dashboards().create(create).getName(); + } + + private String createChart( + OpenMetadataClient client, + TestNamespace ns, + String service, + String token, + Placement placement) { + CreateChart createChart = + new CreateChart() + .withName(EntitySeeder.distinctiveFor(ns, token, placement)) + .withService(service) + .withChartType(ChartType.Other); + return client.charts().create(createChart).getFullyQualifiedName(); + } + } + + static final class TopicSeeder implements EntitySeeder { + @Override + public String entityType() { + return "topic"; + } + + @Override + public String index() { + return "topic_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // messageSchema.schemaFields.name + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + KafkaConnection kafkaConn = new KafkaConnection().withBootstrapServers("localhost:9092"); + CreateMessagingService service = + new CreateMessagingService() + .withName(ns.prefix("msg-svc-" + ns.shortPrefix())) + .withServiceType(MessagingServiceType.Kafka) + .withConnection(new MessagingConnection().withConfig(kafkaConn)); + return client.messagingServices().create(service).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + MessageSchema schema = + new MessageSchema() + .withSchemaType(SchemaType.JSON) + .withSchemaFields( + List.of( + new Field() + .withName(EntitySeeder.distinctiveFor(ns, token, placement)) + .withDataType(FieldDataType.STRING))); + CreateTopic create = + new CreateTopic() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withPartitions(1) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withMessageSchema(schema); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.topics().create(create).getName(); + } + } + + static final class PipelineSeeder implements EntitySeeder { + @Override + public String entityType() { + return "pipeline"; + } + + @Override + public String index() { + return "pipeline_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // tasks.name + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + AirflowConnection airflow = + new AirflowConnection().withHostPort(URI.create("http://localhost:8080")); + CreatePipelineService service = + new CreatePipelineService() + .withName(ns.prefix("pipelineService_" + ns.uniqueShortId())) + .withServiceType(PipelineServiceType.Airflow) + .withConnection(new PipelineConnection().withConfig(airflow)) + .withDescription("Test Airflow service"); + return client.pipelineServices().create(service).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreatePipeline create = + new CreatePipeline() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withTasks( + List.of(new Task().withName(EntitySeeder.distinctiveFor(ns, token, placement)))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.pipelines().create(create).getName(); + } + } + + static final class MlModelSeeder implements EntitySeeder { + @Override + public String entityType() { + return "mlmodel"; + } + + @Override + public String index() { + return "mlmodel_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // mlFeatures.name + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + SklearnConnection config = + new SklearnConnection().withType(SklearnConnection.SklearnType.SKLEARN); + CreateMlModelService service = + new CreateMlModelService() + .withName(ns.prefix("mlsvc-" + ns.uniqueShortId())) + .withServiceType(CreateMlModelService.MlModelServiceType.Sklearn) + .withConnection(new MlModelConnection().withConfig(config)); + return client.mlModelServices().create(service).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateMlModel create = + new CreateMlModel() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withAlgorithm("regression") + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withMlFeatures( + List.of( + new MlFeature() + .withName(EntitySeeder.distinctiveFor(ns, token, placement)) + .withDataType(MlFeatureDataType.Numerical))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.mlModels().create(create).getName(); + } + } + + static final class ContainerSeeder implements EntitySeeder { + @Override + public String entityType() { + return "container"; + } + + @Override + public String index() { + return "container_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // dataModel.columns.name + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + AWSCredentials awsCreds = new AWSCredentials().withAwsRegion("us-east-1"); + S3Connection s3Conn = new S3Connection().withAwsConfig(awsCreds); + CreateStorageService service = + new CreateStorageService() + .withName(ns.prefix("search_storage_svc")) + .withServiceType(CreateStorageService.StorageServiceType.S3) + .withConnection(new StorageConnection().withConfig(s3Conn)); + return client.storageServices().create(service).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateContainer create = + new CreateContainer() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withDataModel( + new ContainerDataModel() + .withColumns( + List.of( + new Column() + .withName(EntitySeeder.distinctiveFor(ns, token, placement)) + .withDataType(ColumnDataType.VARCHAR) + .withDataLength(64)))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.containers().create(create).getName(); + } + } + + static final class DashboardDataModelSeeder implements EntitySeeder { + @Override + public String entityType() { + return "dashboardDataModel"; + } + + @Override + public String index() { + return "dashboard_data_model_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // columns.name + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + LookerConnection lookerConn = + new LookerConnection() + .withHostPort(URI.create("http://localhost:9999")) + .withClientId("test-client"); + CreateDashboardService request = + new CreateDashboardService() + .withName(ns.prefix("lookerService-" + ns.uniqueShortId())) + .withServiceType(DashboardServiceType.Looker) + .withConnection(new DashboardConnection().withConfig(lookerConn)) + .withDescription("Test Looker service"); + DashboardService service = client.dashboardServices().create(request); + return service.getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateDashboardDataModel create = + new CreateDashboardDataModel() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withDataModelType(DataModelType.LookMlView) + .withColumns( + List.of( + new Column() + .withName(EntitySeeder.distinctiveFor(ns, token, placement)) + .withDataType(ColumnDataType.VARCHAR) + .withDataLength(64))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.dashboardDataModels().create(create).getName(); + } + } + + static final class QuerySeeder implements EntitySeeder { + @Override + public String entityType() { + return "query"; + } + + @Override + public String index() { + return "query_search_index"; + } + + @Override + public boolean hasDistinctive() { + return false; // queryText/SQL not matched by the default query-index search; + // ranking still covers name/displayName/description/tier + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + return DatabaseServiceTestFactory.createPostgres(ns).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateQuery create = + new CreateQuery() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withService(parent) + .withQuery("SELECT " + EntitySeeder.distinctiveFor(ns, token, placement) + " FROM t"); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.queries().create(create).getName(); + } + } + + static final class StoredProcedureSeeder implements EntitySeeder { + @Override + public String entityType() { + return "storedProcedure"; + } + + @Override + public String index() { + return "stored_procedure_search_index"; + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + return RankingSupport.createSchemaFqn(ns); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateStoredProcedure create = + new CreateStoredProcedure() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withDatabaseSchema(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withStoredProcedureCode( + new StoredProcedureCode() + .withLanguage(StoredProcedureLanguage.SQL) + .withCode("SELECT 1;")); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.storedProcedures().create(create).getName(); + } + } + + static final class SearchIndexSeeder implements EntitySeeder { + @Override + public String entityType() { + return "searchIndex"; + } + + @Override + public String index() { + return "search_entity_search_index"; + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + CreateSearchService service = + new CreateSearchService() + .withName(ns.prefix("search-svc-" + ns.uniqueShortId())) + .withServiceType(CreateSearchService.SearchServiceType.ElasticSearch); + SearchService created = client.searchServices().create(service); + return created.getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateSearchIndex create = + new CreateSearchIndex() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withFields( + List.of( + new SearchIndexField() + .withName(RankingSupport.uniqueTerm(ns)) + .withDataType(SearchIndexDataType.TEXT))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.searchIndexes().create(create).getName(); + } + } + + static final class GlossaryTermSeeder implements EntitySeeder { + @Override + public String entityType() { + return "glossaryTerm"; + } + + @Override + public String index() { + return "glossary_term_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // synonyms[] + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + CreateGlossary glossary = + new CreateGlossary() + .withName(ns.prefix("glossary-" + ns.uniqueShortId())) + .withDescription("ranking suite glossary " + ns.shortPrefix()); + return client.glossaries().create(glossary).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateGlossaryTerm create = + new CreateGlossaryTerm() + .withGlossary(parent) + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withSynonyms(List.of(EntitySeeder.distinctiveFor(ns, token, placement))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.glossaryTerms().create(create).getName(); + } + } + + static final class MetricSeeder implements EntitySeeder { + @Override + public String entityType() { + return "metric"; + } + + @Override + public String index() { + return "metric_search_index"; + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + // Metric is a top-level entity with no parent service; seed() ignores this value. + return ns.prefix("metrics"); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateMetric create = + new CreateMetric() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.metrics().create(create).getName(); + } + } + + static final class ApiEndpointSeeder implements EntitySeeder { + @Override + public String entityType() { + return "apiEndpoint"; + } + + @Override + public String index() { + return "api_endpoint_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // requestSchema.schemaFields.name + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + CreateApiService service = + new CreateApiService() + .withName(ns.prefix("apiService_" + ns.uniqueShortId())) + .withServiceType(CreateApiService.ApiServiceType.Rest); + ApiService created = client.apiServices().create(service); + CreateAPICollection collection = + new CreateAPICollection() + .withName(ns.prefix("apiCollection_" + ns.uniqueShortId())) + .withService(created.getFullyQualifiedName()); + return client.apiCollections().create(collection).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateAPIEndpoint create = + new CreateAPIEndpoint() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withApiCollection(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withRequestSchema( + new APISchema() + .withSchemaFields( + List.of( + new Field() + .withName(EntitySeeder.distinctiveFor(ns, token, placement)) + .withDataType(FieldDataType.STRING)))); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.apiEndpoints().create(create).getName(); + } + } + + static final class DirectorySeeder implements EntitySeeder { + @Override + public String entityType() { + return "directory"; + } + + @Override + public String index() { + return "directory_search_index"; + } + + @Override + public boolean hasDistinctive() { + return true; // path + } + + @Override + public String setup(OpenMetadataClient client, TestNamespace ns) { + CreateDriveService service = + new CreateDriveService() + .withName(ns.prefix("drive-" + ns.uniqueShortId())) + .withServiceType(DriveServiceType.GoogleDrive) + .withConnection(new DriveConnection().withConfig(new GoogleDriveConnection())); + return client.driveServices().create(service).getFullyQualifiedName(); + } + + @Override + public String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1) { + CreateDirectory create = + new CreateDirectory() + .withName(EntitySeeder.nameFor(ns, token, placement)) + .withService(parent) + .withDisplayName(EntitySeeder.displayNameFor(ns, token, placement)) + .withDescription(EntitySeeder.descriptionFor(ns, token, placement)) + .withPath("/" + EntitySeeder.distinctiveFor(ns, token, placement)); + List tags = EntitySeeder.tierTags(tier1); + if (tags != null) { + create.withTags(tags); + } + return client.directories().create(create).getName(); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntitySeeder.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntitySeeder.java new file mode 100644 index 000000000000..3cf527db42d9 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntitySeeder.java @@ -0,0 +1,91 @@ +package org.openmetadata.it.tests.search; + +import java.util.List; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.sdk.client.OpenMetadataClient; + +/** + * Seeds one entity type for the data-driven ranking suite ({@link SearchEntityRankingIT}). A seeder + * knows how to create a parent container once ({@link #setup}) and then create entities into it with + * a search token placed in exactly one field ({@link #seed}), so the ranking tests can isolate how + * each field of that entity type's search config contributes to the score. + * + *

Placement contract — the token appears in only the named field; every other searchable + * field is generic (token-free), so a query for the token isolates that field: + * + *

    + *
  • {@code NAME} — the entity name (token is the leading, clean sub-token). + *
  • {@code DISPLAY_NAME_EXACT} — displayName equals the token exactly (hits {@code + * displayName.keyword}, boost 20/exact). + *
  • {@code DISPLAY_NAME_PHRASE} — displayName contains the token in a longer phrase (hits {@code + * displayName}, boost 10/phrase — but not the exact keyword field). + *
  • {@code DESCRIPTION} — the description mentions the token (boost 2/standard). + *
  • {@code DISTINCTIVE} — the entity's distinctive nested field (columns / charts / tasks / + * queryText / synonyms / …); only when {@link #hasDistinctive()}. + *
+ * + * {@code tier1=true} additionally tags the entity {@code Tier.Tier1} (global term boost) for the + * text-tie ranking check. + */ +interface EntitySeeder { + + enum Placement { + NAME, + DISPLAY_NAME_EXACT, + DISPLAY_NAME_PHRASE, + DESCRIPTION, + DISTINCTIVE + } + + String entityType(); + + String index(); + + default boolean hasDistinctive() { + return false; + } + + /** Create the parent container (service / glossary / schema …) once; returns its FQN. */ + String setup(OpenMetadataClient client, TestNamespace ns); + + /** Create an entity with the token placed per {@code placement}; returns the indexed name. */ + String seed( + OpenMetadataClient client, + TestNamespace ns, + String parent, + String token, + Placement placement, + boolean tier1); + + // --- shared placement helpers so every seeder builds identical field content --------------- + + /** Unique entity name; the token is the leading clean sub-token only for {@code NAME}. */ + static String nameFor(TestNamespace ns, String token, Placement placement) { + String lead = placement == Placement.NAME ? token : RankingSupport.uniqueTerm(ns); + return ns.prefix(lead + "-" + ns.uniqueShortId()); + } + + static String displayNameFor(TestNamespace ns, String token, Placement placement) { + return switch (placement) { + case DISPLAY_NAME_EXACT -> token; + case DISPLAY_NAME_PHRASE -> token + " reporting warehouse"; + default -> "gd " + RankingSupport.uniqueTerm(ns); + }; + } + + static String descriptionFor(TestNamespace ns, String token, Placement placement) { + return placement == Placement.DESCRIPTION + ? "this asset mentions " + token + " once in prose" + : "generic description body " + RankingSupport.uniqueTerm(ns); + } + + /** The token to write into the distinctive nested field, or a generic value for other placements. */ + static String distinctiveFor(TestNamespace ns, String token, Placement placement) { + return placement == Placement.DISTINCTIVE ? token : "generic_" + RankingSupport.uniqueTerm(ns); + } + + static List tierTags(boolean tier1) { + return tier1 ? List.of(RankingSupport.classificationTag(RankingSupport.TIER1_TAG)) : null; + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/LiveIndexRetryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/LiveIndexRetryIT.java index e35f21edcd10..d28826e0af1b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/LiveIndexRetryIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/LiveIndexRetryIT.java @@ -53,7 +53,12 @@ class LiveIndexRetryIT { // just block-then-succeed on resume and never enqueue anything. private static final Duration FAILURE_TIMEOUT = Duration.ofSeconds(120); private static final Duration OUTAGE_BACKSTOP = Duration.ofSeconds(180); - private static final Duration DRAIN_TIMEOUT = Duration.ofMinutes(2); + // Drain budget after resume. The retry worker polls every 5s but, having seen the engine + // unavailable during the outage, backs off exponentially up to 60s before it re-checks a resumed + // engine — so the first post-resume claim can land ~a minute late, then cascade-reindex + + // bulk flushAndAwait(60) + engine refresh follow. Under concurrent full-suite load 2 min was too + // tight (nightly flake). Matches the 3-5 min budgets of the sibling ReindexOutageRecoveryIT. + private static final Duration DRAIN_TIMEOUT = Duration.ofMinutes(4); private static ServerHandle server; private static SearchAssertions search; @@ -82,14 +87,18 @@ void liveIndexEnqueuesRetriesDuringEsOutageAndDrainsAfter(final TestNamespace ns Awaitility.await("blocked live-index write times out and enqueues a retry row") .atMost(FAILURE_TIMEOUT) .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() .until(() -> pendingRetryCount() > 0); } finally { EsOutageInjector.unpause(); } + // ignoreExceptions: the first polls run right as the engine resumes, so a transient + // search/DB read can throw before the cluster is fully serving — retry rather than fail. Awaitility.await("retry queue drains and table appears in index") .atMost(DRAIN_TIMEOUT) .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() .untilAsserted( () -> { assertThat(pendingRetryCount()).as("retry queue must drain to zero pending").isZero(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/RankingSupport.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/RankingSupport.java new file mode 100644 index 000000000000..c5413dfa5965 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/RankingSupport.java @@ -0,0 +1,136 @@ +package org.openmetadata.it.tests.search; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalInt; +import java.util.concurrent.Callable; +import org.awaitility.Awaitility; +import org.awaitility.core.ConditionTimeoutException; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.search.RelevancyFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.sdk.client.OpenMetadataClient; + +/** + * Minimal search helpers for the per-entity-type ranking suite ({@link SearchEntityRankingIT}): + * runs a lexical query through the SDK ({@code client.search().query(q).index(idx).execute()}), + * parses the raw Elasticsearch/OpenSearch response into a small ranked view, and provides the + * token / tier-tag / schema fixtures the seeders need. + * + *

Ranking-knob mechanics (tier, field, usage boosts) are already covered on tables by + * {@code SearchRelevancyPreviewIT} via {@code /v1/search/preview}; this suite adds the missing + * per-entity-type coverage, so it only needs read-back ordering — no settings mutation. + */ +final class RankingSupport { + + private RankingSupport() {} + + static final String TIER1_TAG = "Tier.Tier1"; + private static final Duration INDEX_WAIT = Duration.ofSeconds(30); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** A hit's name + fqn + score — enough to assert relative ranking. */ + record Hit(String name, String fqn, double score) { + boolean matches(String token) { + return contains(name, token) || contains(fqn, token); + } + } + + /** Parsed, score-descending view of a search response. */ + record SearchResult(List hits) { + + List names() { + return hits.stream().map(Hit::name).toList(); + } + + boolean contains(String token) { + return hits.stream().anyMatch(hit -> hit.matches(token)); + } + + /** 0-based rank (position in score-descending order) of the first hit matching {@code token}. */ + OptionalInt rankOf(String token) { + OptionalInt rank = OptionalInt.empty(); + for (int i = 0; i < hits.size() && rank.isEmpty(); i++) { + if (hits.get(i).matches(token)) { + rank = OptionalInt.of(i); + } + } + return rank; + } + } + + /** Run {@code query} against {@code index} via the SDK and parse the ranked hits. */ + static SearchResult search(OpenMetadataClient client, String index, String query) { + try { + String body = client.search().query(query).index(index).from(0).size(50).execute(); + return parse(body); + } catch (Exception e) { + throw new IllegalStateException("search failed for index=" + index + " q=" + query, e); + } + } + + private static SearchResult parse(String body) throws Exception { + JsonNode hitsNode = OBJECT_MAPPER.readTree(body).path("hits").path("hits"); + List hits = new ArrayList<>(); + for (JsonNode hit : hitsNode) { + JsonNode source = hit.path("_source"); + hits.add( + new Hit( + text(source, "name"), + text(source, "fullyQualifiedName"), + hit.path("_score").asDouble(0.0))); + } + return new SearchResult(hits); + } + + /** Poll (never sleep) until {@code condition} holds; returns {@code false} on timeout. */ + static boolean awaitTrue(Callable condition) { + try { + Awaitility.await() + .atMost(INDEX_WAIT) + .pollInterval(Duration.ofMillis(500)) + .ignoreExceptions() + .until(condition); + return true; + } catch (ConditionTimeoutException timeout) { + return false; + } + } + + /** Create a database service + database + schema and return the schema FQN entities hang off. */ + static String createSchemaFqn(TestNamespace ns) { + return DatabaseSchemaTestFactory.createSimple(ns).getFullyQualifiedName(); + } + + /** + * A unique, hex-free search term (letters g–v). OpenMetadata embeds a hex run-id in every + * entity name, so a hex query token ngram-matches those names and adds variable text score that + * breaks controlled score-ties. Mapping each hex digit into g–v yields a token that cannot collide + * with the hex names, keeping the text match exactly equal across seeded entities. + */ + static String uniqueTerm(TestNamespace ns) { + String hex = ns.uniqueShortId(); + StringBuilder term = new StringBuilder("zz"); + for (int i = 0; i < hex.length(); i++) { + term.append((char) ('g' + Character.digit(hex.charAt(i), 16))); + } + return term.toString(); + } + + static TagLabel classificationTag(String tagFqn) { + return RelevancyFixtures.tierLabel(tagFqn); + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.path(field); + return value.isMissingNode() || value.isNull() ? null : value.asText(); + } + + private static boolean contains(String value, String token) { + return value != null && token != null && value.contains(token); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchEntityRankingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchEntityRankingIT.java new file mode 100644 index 000000000000..ae6cabeca1d3 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchEntityRankingIT.java @@ -0,0 +1,164 @@ +package org.openmetadata.it.tests.search; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.it.tests.search.EntitySeeder.Placement; +import org.openmetadata.it.tests.search.RankingSupport.SearchResult; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.sdk.client.OpenMetadataClient; + +/** + * End-to-end ranking coverage per searchable entity type. Every asset type shares the same + * common-field boosts (name/displayName over description) and the same global term / value boosts, + * so the ranking paths are asserted uniformly, driven by one {@link EntitySeeder} per type that + * knows how to place a token in each field: + * + *

    + *
  1. a name match outranks a description-only match (higher field boost), + *
  2. a displayName match outranks a description-only match, + *
  3. an exact displayName match ranks at least as high as a partial one ({@code + * displayName.keyword} exact vs {@code displayName} phrase), + *
  4. on a text tie (identical displayName) a {@code Tier.Tier1}-tagged entity outranks an + * untagged one (global term boost), + *
  5. the entity's distinctive nested field (columns / charts / tasks / synonyms / …) is itself + * searchable. + *
+ * + * Each entity is one parameterized case; every failure across the checks is collected and reported + * together. Seeding uses {@link SdkClients#adminClient()} so any entity type is reachable. + */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class SearchEntityRankingIT { + + private record Case( + Placement high, + boolean tierHigh, + Placement low, + boolean tierLow, + boolean allowEqual, + String label) {} + + private static final List CASES = + List.of( + new Case( + Placement.NAME, false, Placement.DESCRIPTION, false, false, "name > description"), + new Case( + Placement.DISPLAY_NAME_PHRASE, + false, + Placement.DESCRIPTION, + false, + false, + "displayName > description"), + new Case( + Placement.DISPLAY_NAME_EXACT, + false, + Placement.DISPLAY_NAME_PHRASE, + false, + true, + "exact displayName >= partial"), + new Case( + Placement.DISPLAY_NAME_EXACT, + true, + Placement.DISPLAY_NAME_EXACT, + false, + false, + "Tier1 > untagged on a text tie")); + + static Stream seeders() { + return EntityRankingSeeders.all().stream() + .map(seeder -> Arguments.of(Named.of(seeder.entityType(), seeder))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("seeders") + void entityRanking(EntitySeeder seeder, TestNamespace ns) { + OpenMetadataClient client = SdkClients.adminClient(); + String parent = seeder.setup(client, ns); + + List failures = new ArrayList<>(); + for (Case testCase : CASES) { + evaluateCase(client, ns, seeder, parent, testCase, failures); + } + if (seeder.hasDistinctive()) { + evaluateDistinctive(client, ns, seeder, parent, failures); + } + assertTrue( + failures.isEmpty(), + seeder.entityType() + " ranking failures:\n - " + String.join("\n - ", failures)); + } + + private void evaluateCase( + OpenMetadataClient client, + TestNamespace ns, + EntitySeeder seeder, + String parent, + Case testCase, + List failures) { + String term = RankingSupport.uniqueTerm(ns); + String high = seeder.seed(client, ns, parent, term, testCase.high(), testCase.tierHigh()); + String low = seeder.seed(client, ns, parent, term, testCase.low(), testCase.tierLow()); + boolean bothIndexed = + RankingSupport.awaitTrue( + () -> { + SearchResult polled = RankingSupport.search(client, seeder.index(), term); + return polled.contains(high) && polled.contains(low); + }); + if (!bothIndexed) { + failures.add(testCase.label() + ": both documents were not indexed in time"); + return; + } + SearchResult result = RankingSupport.search(client, seeder.index(), term); + int rankHigh = result.rankOf(high).orElse(Integer.MAX_VALUE); + int rankLow = result.rankOf(low).orElse(Integer.MAX_VALUE); + boolean ok = testCase.allowEqual() ? rankHigh <= rankLow : rankHigh < rankLow; + if (!ok) { + failures.add( + testCase.label() + + ": expected [" + + high + + "] " + + (testCase.allowEqual() ? ">=" : ">") + + " [" + + low + + "] but ranks were " + + rankHigh + + " vs " + + rankLow + + " -> " + + result.names()); + } + } + + private void evaluateDistinctive( + OpenMetadataClient client, + TestNamespace ns, + EntitySeeder seeder, + String parent, + List failures) { + String term = RankingSupport.uniqueTerm(ns); + String name = seeder.seed(client, ns, parent, term, Placement.DISTINCTIVE, false); + boolean found = + RankingSupport.awaitTrue( + () -> RankingSupport.search(client, seeder.index(), term).contains(name)); + if (!found) { + failures.add( + "distinctive field: [" + + name + + "] not found by its nested-field token -> " + + RankingSupport.search(client, seeder.index(), term).names()); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java index fcbb80cd677f..25a167dbe5c0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import java.time.Duration; +import java.util.ArrayList; import java.util.List; import org.awaitility.Awaitility; import org.junit.jupiter.api.BeforeAll; @@ -47,6 +48,7 @@ class SearchRelevancyPreviewIT { private static final String NAME_FIELD = "name"; private static final String DESCRIPTION_FIELD = "description"; private static final String USAGE_COUNT_FIELD = "usageSummary.weeklyStats.count"; + private static final double USAGE_SIGNAL_FACTOR = 0.001; private static final Duration INDEXED_TIMEOUT = ReindexHelpers.searchPropagationTimeout(); private static final Duration RANK_POLL = Duration.ofSeconds(3); @@ -91,7 +93,8 @@ void fieldValueBoostRanksByNumericUsage(final TestNamespace ns) { awaitIndexed(marker, 2); final SearchSettings boosted = SearchSettingsTestHelper.copyOf(currentSettings()); - SearchSettingsTestHelper.addGlobalFieldValueBoost(boosted, USAGE_COUNT_FIELD, 50.0); + SearchSettingsTestHelper.addGlobalFieldValueBoost( + boosted, USAGE_COUNT_FIELD, USAGE_SIGNAL_FACTOR); // Usage rolls into usageSummary asynchronously, so poll until the numeric boost takes effect. Awaitility.await("usage field-value boost ranks the heavily-used table first") @@ -118,15 +121,17 @@ void searchFieldsSelectWhichFieldMatches(final TestNamespace ns) { final SearchSettings base = currentSettings(); - final SearchSettings nameOnly = SearchSettingsTestHelper.copyOf(base); + SearchSettings nameOnly = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.setOnlySearchField(nameOnly, TABLE_INDEX, NAME_FIELD, 5.0); + nameOnly = SearchSettingsTestHelper.withRankingDisabled(nameOnly, TABLE_INDEX); assertThat(SearchSettingsTestHelper.previewIds(server, query, TABLE_INDEX, nameOnly, 10)) .as("searching only 'name' must return only the table whose name carries the token") .containsExactly(tokenInName.getId().toString()); - final SearchSettings descriptionOnly = SearchSettingsTestHelper.copyOf(base); + SearchSettings descriptionOnly = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.setOnlySearchField( descriptionOnly, TABLE_INDEX, DESCRIPTION_FIELD, 5.0); + descriptionOnly = SearchSettingsTestHelper.withRankingDisabled(descriptionOnly, TABLE_INDEX); assertThat(SearchSettingsTestHelper.previewIds(server, query, TABLE_INDEX, descriptionOnly, 10)) .as("searching only 'description' must return only the table whose description carries it") .containsExactly(tokenInDescription.getId().toString()); @@ -136,8 +141,10 @@ void searchFieldsSelectWhichFieldMatches(final TestNamespace ns) { void maxResultHitsClampsTheReturnedHits(final TestNamespace ns) { final String marker = ns.uniqueShortId(); final DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns); + final List seededIds = new ArrayList<>(); for (int i = 0; i < 4; i++) { - RelevancyFixtures.createTable(schema, marker + i, marker, null); + seededIds.add( + RelevancyFixtures.createTable(schema, marker + i, marker, null).getId().toString()); } awaitIndexed(marker, 4); @@ -149,11 +156,15 @@ void maxResultHitsClampsTheReturnedHits(final TestNamespace ns) { .as("maxResultHits=2 must cap the hit list at 2 even when size=10") .hasSize(2); + // The marker is a fuzzy query (name.ngram), so on the shared cluster a concurrent run's + // ngram-colliding table can appear as an extra hit. Assert the whole seeded cohort is present + // rather than an exact size, which such a foreign hit would inflate. Clamp above is size-exact + // because maxResultHits=2 caps the total regardless of how many tables match. final SearchSettings wide = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.setMaxResultHits(wide, 50); assertThat(SearchSettingsTestHelper.previewIds(server, marker, TABLE_INDEX, wide, 10)) .as("a wide maxResultHits must return the whole seeded cohort") - .hasSize(4); + .containsAll(seededIds); } @Test @@ -187,16 +198,18 @@ void matchTypeExactRequiresTheFullKeyword(final TestNamespace ns) { final SearchSettings base = currentSettings(); - final SearchSettings exact = SearchSettingsTestHelper.copyOf(base); + SearchSettings exact = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.setOnlySearchField( exact, TABLE_INDEX, NAME_FIELD, 5.0, FieldBoost.MatchType.EXACT); + exact = SearchSettingsTestHelper.withRankingDisabled(exact, TABLE_INDEX); assertThat(SearchSettingsTestHelper.previewIds(server, exactName, TABLE_INDEX, exact, 10)) .as("matchType=exact must match only the whole-keyword name, not the prefixed sibling") .containsExactly(exactTable.getId().toString()); - final SearchSettings standard = SearchSettingsTestHelper.copyOf(base); + SearchSettings standard = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.setOnlySearchField( standard, TABLE_INDEX, NAME_FIELD, 5.0, FieldBoost.MatchType.STANDARD); + standard = SearchSettingsTestHelper.withRankingDisabled(standard, TABLE_INDEX); assertThat(SearchSettingsTestHelper.previewIds(server, exactName, TABLE_INDEX, standard, 10)) .as("matchType=standard must match both the exact and the prefixed name") .hasSize(2); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchScoringIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchScoringIT.java index e4f4887d6070..3807df7b237a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchScoringIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchScoringIT.java @@ -153,9 +153,10 @@ void explanationExposesTheConfiguredBoostFunction(final TestNamespace ns) { RelevancyFixtures.createTable(schema, marker + "a", marker, null); awaitIndexed(marker, 1); - final SearchSettings settings = + SearchSettings settings = SearchSettingsTestHelper.copyOf(SearchSettingsTestHelper.currentSettings(server)); SearchSettingsTestHelper.clearBoosts(settings, TABLE_INDEX); + settings = SearchSettingsTestHelper.withRankingDisabled(settings, TABLE_INDEX); SearchSettingsTestHelper.addAssetFieldValueBoost( settings, TABLE_INDEX, USAGE_COUNT_FIELD, 7.0, null, 5.0); @@ -176,8 +177,9 @@ void explanationExposesTheConfiguredBoostFunction(final TestNamespace ns) { private static SearchSettings twoBoostSettings( final SearchSettings base, final AssetTypeConfiguration.ScoreMode scoreMode) { - final SearchSettings settings = SearchSettingsTestHelper.copyOf(base); + SearchSettings settings = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.clearBoosts(settings, TABLE_INDEX); + settings = SearchSettingsTestHelper.withRankingDisabled(settings, TABLE_INDEX); SearchSettingsTestHelper.addAssetTermBoost( settings, TABLE_INDEX, TIER_FIELD, TIER_1, TERM_BOOST); SearchSettingsTestHelper.addAssetFieldValueBoost( @@ -190,8 +192,9 @@ private static SearchSettings twoBoostSettings( private static SearchSettings tierOnly( final SearchSettings base, final AssetTypeConfiguration.BoostMode boostMode) { - final SearchSettings settings = SearchSettingsTestHelper.copyOf(base); + SearchSettings settings = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.clearBoosts(settings, TABLE_INDEX); + settings = SearchSettingsTestHelper.withRankingDisabled(settings, TABLE_INDEX); SearchSettingsTestHelper.addAssetTermBoost( settings, TABLE_INDEX, TIER_FIELD, TIER_1, TERM_BOOST); SearchSettingsTestHelper.setScoreMode( @@ -206,8 +209,9 @@ private static double usageScoreGap( final FieldValueBoost.Modifier modifier, final String highId, final String lowId) { - final SearchSettings settings = SearchSettingsTestHelper.copyOf(base); + SearchSettings settings = SearchSettingsTestHelper.copyOf(base); SearchSettingsTestHelper.clearBoosts(settings, TABLE_INDEX); + settings = SearchSettingsTestHelper.withRankingDisabled(settings, TABLE_INDEX); SearchSettingsTestHelper.addAssetFieldValueBoost( settings, TABLE_INDEX, USAGE_COUNT_FIELD, 1.0, modifier, 0.0); SearchSettingsTestHelper.setScoreMode( diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/TestCaseStaleDefinitionReindexIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/TestCaseStaleDefinitionReindexIT.java index cad0b9d0dbfa..518df9f774d7 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/TestCaseStaleDefinitionReindexIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/TestCaseStaleDefinitionReindexIT.java @@ -37,14 +37,15 @@ *

When a test case's {@code testDefinition} relationship row is missing (a deleted definition or * data drift), building both the {@code testCase} doc and its {@code testCaseResult} docs fails * (the testCaseResult build resolves the parent test case with the {@code testDefinition} field, - * which throws "does not have expected relationship"). The reindex must report those as - * failures and keep the job stats balanced — it must NOT silently drop the records (read but + * which throws "does not have expected relationship"). The reindex must report those (as a + * failure or a stale-reference warning) and keep the job stats balanced — it must NOT + * silently drop the records (read but * never indexed, never failed), which is what previously emptied the data-quality page while the * run reported success. * - *

Asserts the invariant that catches the regression: {@code totalRecords == successRecords + - * failedRecords + warningRecords} (everything read is accounted for), and that the broken records - * surface as failures rather than vanishing. + *

Asserts the invariant that catches the regression: every read record is accounted for by + * success, failure, or warning counters, and the broken records surface (as failures or warnings) + * rather than vanishing. * *

Embedded-only: the relationship-row surgery needs the in-JVM DAO; the REST API would reject or * cascade it. @@ -91,13 +92,17 @@ void brokenTestDefinitionRelationshipIsReportedNotSilentlyDropped(final TestName assertThat(stats).as("run must carry stats").isNotNull(); // The broken test case and its result fail to build — they must be REPORTED, not masked. - assertThat(sumOrZero(stats.getJobStats().getFailedRecords())) - .as("a broken testCase->testDefinition relationship must surface as a reported failure") + // ReindexingUtil classifies a missing testCase->testDefinition relationship as a + // stale-reference *warning* (still accounted, not dropped), so accept failed or warning. + final long reported = + sumOrZero(stats.getJobStats().getFailedRecords()) + + sumOrZero(stats.getJobStats().getWarningRecords()); + assertThat(reported) + .as("a broken testCase->testDefinition relationship must surface as failed or warning") .isPositive(); - // The invariant the silent-drop regression violated: everything read is accounted for. - assertBalanced(stats.getJobStats(), "jobStats"); - assertBalanced(stats.getReaderStats(), "readerStats"); + assertNoRecordsDropped(stats.getJobStats(), "jobStats"); + assertNoRecordsDropped(stats.getReaderStats(), "readerStats"); } finally { try { Entity.getCollectionDAO().testCaseDAO().delete(broken.getId()); @@ -107,20 +112,22 @@ void brokenTestDefinitionRelationshipIsReportedNotSilentlyDropped(final TestName } } - private static void assertBalanced(final StepStats s, final String label) { - if (s == null) { + private static void assertNoRecordsDropped(final StepStats stats, final String label) { + if (stats == null) { return; } - final long total = sumOrZero(s.getTotalRecords()); - final long accounted = - sumOrZero(s.getSuccessRecords()) - + sumOrZero(s.getFailedRecords()) - + sumOrZero(s.getWarningRecords()); + final long total = sumOrZero(stats.getTotalRecords()); + final long completed = + sumOrZero(stats.getSuccessRecords()) + sumOrZero(stats.getFailedRecords()); + final long accounted = completed + sumOrZero(stats.getWarningRecords()); + assertThat(completed) + .as("%s success+failed must not exceed total(%d)", label, total) + .isLessThanOrEqualTo(total); assertThat(accounted) .as( - "%s must balance: total(%d) == success+failed+warning — no record silently dropped", + "%s must account for total(%d) records using success+failed plus warnings", label, total) - .isEqualTo(total); + .isGreaterThanOrEqualTo(total); } private static TestCase testCase(final TestNamespace ns, final Table table, final String name) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/scale/ServiceDeleteSearchCleanupScaleIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/scale/ServiceDeleteSearchCleanupScaleIT.java index 312c193e56f9..a7144aa7f4d3 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/scale/ServiceDeleteSearchCleanupScaleIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/scale/ServiceDeleteSearchCleanupScaleIT.java @@ -18,9 +18,7 @@ import com.fasterxml.jackson.databind.JsonNode; import java.time.Duration; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -34,6 +32,7 @@ import org.junit.jupiter.api.parallel.ExecutionMode; import org.openmetadata.it.factories.DatabaseSchemaTestFactory; import org.openmetadata.it.factories.DatabaseServiceTestFactory; +import org.openmetadata.it.search.IndexAliasInspector; import org.openmetadata.it.search.SearchClient; import org.openmetadata.it.server.ServerHandle; import org.openmetadata.it.util.OssTestServer; @@ -46,6 +45,7 @@ import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.service.Entity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,16 +84,16 @@ class ServiceDeleteSearchCleanupScaleIT { // -Dscale.workers. private static final int LOAD_WORKERS = Integer.getInteger("scale.workers", 8); private static final int CREATE_TIMEOUT_SECONDS = 300; - private static final String TABLE_INDEX = "table_search_index"; - private static final String COLUMN_INDEX = "column_search_index"; private static ServerHandle server; private static SearchClient search; + private static IndexAliasInspector indexAliases; @BeforeAll static void setup() { server = OssTestServer.defaultHandle(); search = new SearchClient(server); + indexAliases = new IndexAliasInspector(server); } @Test @@ -106,10 +106,12 @@ void recursiveServiceHardDelete_clearsTableAndColumnDocsAtScale(final TestNamesp final DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); final String serviceId = service.getId().toString(); - // Resolve the logical index names to the cluster-prefixed aliases the running server actually - // created (e.g. openmetadata_column_search_index) so counts work regardless of clusterAlias. - final String tableIndex = Entity.getSearchRepository().getIndexOrAliasName(TABLE_INDEX); - final String columnIndex = Entity.getSearchRepository().getIndexOrAliasName(COLUMN_INDEX); + // Resolve the entity indexes via the server (IndexAliasInspector), not the in-JVM + // Entity.getSearchRepository() — that static is null in external mode, where the OM service + // runs in a separate JVM. indexNameFor is cluster-alias-aware (e.g. + // openmetadata_column_search_index) so counts work regardless of clusterAlias. + final String tableIndex = indexAliases.indexNameFor(Entity.TABLE); + final String columnIndex = indexAliases.indexNameFor(Entity.TABLE_COLUMN); final long seedStart = System.currentTimeMillis(); seedTables(ns, client, schema.getFullyQualifiedName(), tableCount); @@ -130,12 +132,12 @@ void recursiveServiceHardDelete_clearsTableAndColumnDocsAtScale(final TestNamesp final long deleteStart = System.currentTimeMillis(); recursiveHardDelete(client, serviceId); - final long deleteMs = System.currentTimeMillis() - deleteStart; - awaitCount(tableIndex, serviceId, 0); awaitCount(columnIndex, serviceId, 0); + final long deleteMs = System.currentTimeMillis() - deleteStart; LOG.info( - "Recursive hard delete of {} tables cleared search in {} ms — table docs=0, column docs=0", + "Recursive async hard delete of {} tables cleared search in {} ms — table docs=0," + + " column docs=0", tableCount, deleteMs); } @@ -183,10 +185,18 @@ private List buildColumns() { } private void recursiveHardDelete(final OpenMetadataClient client, final String serviceId) { - final Map params = new HashMap<>(); - params.put("hardDelete", "true"); - params.put("recursive", "true"); - client.databaseServices().delete(serviceId, params); + // Mirror the UI's service delete: hit the async endpoint (DELETE /databaseServices/async/{id}) + // so the recursive hard delete runs on the server's background executor instead of blocking the + // request thread — a synchronous 100k-table delete can exceed a proxied cluster's gateway + // timeout. The endpoint returns 202 immediately; the awaitCount(...) assertions confirm the + // delete's search cascade actually cleared both indexes. + client + .getHttpClient() + .execute( + HttpMethod.DELETE, + "/v1/services/databaseServices/async/" + serviceId + "?hardDelete=true&recursive=true", + null, + Object.class); } private void awaitCount(final String index, final String serviceId, final long expected) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ExternalTokenRefresher.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ExternalTokenRefresher.java index 6f0cf02eea5a..b123a47a47b7 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ExternalTokenRefresher.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/ExternalTokenRefresher.java @@ -29,7 +29,13 @@ public final class ExternalTokenRefresher implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(ExternalTokenRefresher.class); - private static final Duration EXPIRY_BUFFER = Duration.ofMinutes(2); + // Renew this far ahead of expiry so a flaky login endpoint has room for several 60s retries + // before the token actually dies (login TTL is ~1h, so 10m early is safe). + private static final Duration EXPIRY_BUFFER = Duration.ofMinutes(10); + // Bounds BOTH the connect and the read phase of each login. Without a read timeout a slow or + // half-open gateway would block http.send() forever on the single-thread scheduler, and the + // token would never renew for the rest of the run. + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(30); private static final long FALLBACK_REFRESH_SECONDS = Duration.ofMinutes(30).toSeconds(); private final ScheduledExecutorService scheduler = @@ -39,7 +45,7 @@ public final class ExternalTokenRefresher implements AutoCloseable { t.setDaemon(true); return t; }); - private final HttpClient http = HttpClient.newBuilder().connectTimeout(EXPIRY_BUFFER).build(); + private final HttpClient http = HttpClient.newBuilder().connectTimeout(REQUEST_TIMEOUT).build(); private final ObjectMapper mapper = new ObjectMapper(); private final String loginUrl; private final String email; @@ -99,6 +105,7 @@ private String login() { http.send( HttpRequest.newBuilder(URI.create(loginUrl)) .header("Content-Type", "application/json") + .timeout(REQUEST_TIMEOUT) .POST(HttpRequest.BodyPublishers.ofString(body)) .build(), HttpResponse.BodyHandlers.ofString()); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java new file mode 100644 index 000000000000..cb7c97da3e67 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/SharedResourceLocks.java @@ -0,0 +1,9 @@ +package org.openmetadata.it.util; + +public final class SharedResourceLocks { + public static final String GLOSSARY_TERM_RELATION_SETTINGS = "glossaryTermRelationSettings"; + public static final String SEARCH_SETTINGS = "searchSettings"; + public static final String TABLE_COLUMN_CUSTOM_PROPERTIES = "customProperties:tableColumn"; + + private SharedResourceLocks() {} +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespace.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespace.java index dcbaaec0df7c..39311cc13407 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespace.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespace.java @@ -45,6 +45,12 @@ public List trackedRoots() { return Collections.unmodifiableList(roots); } + public List drainTrackedRoots() { + List trackedRoots = List.copyOf(roots); + roots.clear(); + return trackedRoots; + } + public void setMethodId(String methodId) { this.methodId = methodId; // Reset cached short prefix when method changes diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespaceExtension.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespaceExtension.java index be6232542e6a..2f12fb14e30b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespaceExtension.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/TestNamespaceExtension.java @@ -38,7 +38,7 @@ public void beforeEach(ExtensionContext context) { public void afterEach(ExtensionContext context) { TestNamespace ns = context.getStore(NAMESPACE).get(NS_KEY, TestNamespace.class); if (ns != null) { - NamespaceCleanup.deleteRoots(ns.trackedRoots()); + NamespaceCleanup.deleteRoots(ns.drainTrackedRoots()); } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/search/reindex/SelectiveFieldReindexUIIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/search/reindex/SelectiveFieldReindexUIIT.java index a086b1e9862a..33b401f63750 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/search/reindex/SelectiveFieldReindexUIIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/search/reindex/SelectiveFieldReindexUIIT.java @@ -197,7 +197,14 @@ private static void assertTableSearchableByColumnName( () -> { final ExplorePage explore = ExplorePage.openWithSearch(ui, Tab.TABLES, fixtures.tableColumnMarker); - explore.assertCountForTab(Tab.TABLES, 1); + // Assert the seeded table itself surfaces for the column-name query, not that it's the + // ONLY hit: the Explore filter-count is a global fuzzy total, so on the shared cluster a + // concurrent run's ngram-colliding table would inflate an == 1 count. Presence of the + // seeded table still fails if the reindex drops columns from _source (the regression). + PlaywrightAssertions.assertThat(explore.firstResultByName(fixtures.tableName)) + .isVisible( + new LocatorAssertions.IsVisibleOptions() + .setTimeout(INNER_ASSERT_TIMEOUT.toMillis())); }); } @@ -231,7 +238,12 @@ private static void assertWorksheetSearchableByColumnName( () -> { final ExplorePage explore = ExplorePage.openWithSearch(ui, Tab.WORKSHEETS, fixtures.worksheetColumnMarker); - explore.assertCountForTab(Tab.WORKSHEETS, 1); + // Presence of the seeded worksheet, not an == 1 global fuzzy count — see the rationale in + // assertTableSearchableByColumnName. + PlaywrightAssertions.assertThat(explore.firstResultByName(fixtures.worksheetName)) + .isVisible( + new LocatorAssertions.IsVisibleOptions() + .setTimeout(INNER_ASSERT_TIMEOUT.toMillis())); }); } @@ -354,14 +366,16 @@ private static SeededFixtures seed(final TestNamespace ns) { final DriveService driveService = createShortDriveService(shortId); final String worksheetColumnMarker = "wcol" + shortId; - createWorksheetWithColumnMarker( - shortId, driveService.getFullyQualifiedName(), worksheetColumnMarker); + final String worksheetName = + createWorksheetWithColumnMarker( + shortId, driveService.getFullyQualifiedName(), worksheetColumnMarker); return new SeededFixtures( table.getFullyQualifiedName(), table.getName(), tableColumnMarker, worksheetColumnMarker, + worksheetName, testCaseSeed.testCaseName, testCaseSeed.testSuiteName); } @@ -495,7 +509,7 @@ private static DriveService createShortDriveService(final String shortId) { } } - private static void createWorksheetWithColumnMarker( + private static String createWorksheetWithColumnMarker( final String shortId, final String driveServiceFqn, final String columnMarker) { final Spreadsheet spreadsheet = SdkClients.adminClient() @@ -508,7 +522,7 @@ private static void createWorksheetWithColumnMarker( .withName("ws_" + shortId) .withSpreadsheet(spreadsheet.getFullyQualifiedName()) .withColumns(List.of(markerColumn)); - SdkClients.adminClient().worksheets().create(request); + return SdkClients.adminClient().worksheets().create(request).getName(); } private record SeededFixtures( @@ -516,6 +530,7 @@ private record SeededFixtures( String tableName, String tableColumnMarker, String worksheetColumnMarker, + String worksheetName, String testCaseName, String testSuiteName) {} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java index 7dcba59f004c..1fd249ddbe64 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java @@ -41,7 +41,7 @@ public static BundleTestSuitePage openCreateForm(final UiSession ui) { */ public BundleTestSuitePage fillNameDescriptionAndAttach( final String suiteName, final String description, final String testCaseName) { - page.locator("[data-testid='test-suite-name']").fill(suiteName); + page.locator("[data-testid='test-suite-name'] input").fill(suiteName); page.locator("[data-testid='editor'] [contenteditable='true']").first().fill(description); // The selection card and its searchbar render after the create form opens; allow diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/IncidentManagerPage.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/IncidentManagerPage.java index f46ddee14fd5..ad5c2faa2936 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/IncidentManagerPage.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/IncidentManagerPage.java @@ -6,7 +6,9 @@ import com.microsoft.playwright.assertions.PlaywrightAssertions; import com.microsoft.playwright.options.AriaRole; import com.microsoft.playwright.options.WaitForSelectorState; +import java.time.Duration; import java.util.regex.Pattern; +import org.awaitility.Awaitility; import org.openmetadata.playwright.ui.UiSession; /** @@ -28,6 +30,12 @@ public final class IncidentManagerPage extends PageObject { private static final String API_TASK_RESOLVE_REGEX = ".*/api/v1/tasks/.+/resolve"; private static final String API_INCIDENT_STATUS_REGEX = ".*/api/v1/dataQuality/testCases/testCaseIncidentStatus.*"; + private static final Pattern PAGE_SIZE_50_OPTION = + Pattern.compile("50.*page", Pattern.CASE_INSENSITIVE); + private static final Duration PAGE_SIZE_RETRY_TIMEOUT = Duration.ofSeconds(60); + private static final Duration PAGE_SIZE_RETRY_INTERVAL = Duration.ofSeconds(2); + private static final double PAGE_SIZE_CLICK_TIMEOUT_MS = 5_000; + private static final double PAGE_SIZE_RESPONSE_TIMEOUT_MS = 15_000; private IncidentManagerPage(final Page page, final UiSession session) { super(page, session); @@ -207,20 +215,36 @@ public IncidentManagerPage clickPrevious() { /** Open page size dropdown, click the {@code 50 / Page} option, await list with limit=50. */ public IncidentManagerPage selectPageSize50() { - // Scope to the OPEN dropdown panel: Ant Design keeps closed panels in the DOM tagged - // .ant-dropdown-hidden, and a page-wide getByRole("50 / page") can resolve a stale/closing one - // — the click then burns its full timeout on an element that is "not stable" / "not visible". + // The incident list refetches after a reindex; while it loads, paging.total briefly drops and + // the pagination bar (which owns this dropdown) unmounts, collapsing the panel between + // resolving + // the "50 / page" item and clicking it — " intercepts pointer events", then the item goes + // not-visible. Re-open and re-click as one unit until the list actually reloads at limit=50. + Awaitility.await("incident list page size set to 50") + .atMost(PAGE_SIZE_RETRY_TIMEOUT) + .pollInterval(PAGE_SIZE_RETRY_INTERVAL) + .pollDelay(Duration.ZERO) + .ignoreExceptions() + .untilAsserted(this::openDropdownAndSelectPageSize50); + return this; + } + + private void openDropdownAndSelectPageSize50() { + // Reset any panel a previous attempt left half-open — Ant toggles on trigger click, so opening + // a + // stuck-open menu would instead close it. Escape is a no-op when nothing is open. + page.keyboard().press("Escape"); final Locator menu = page.locator(".ant-dropdown:not(.ant-dropdown-hidden) .ant-dropdown-menu"); openMenu(byTestId("page-size-selection-dropdown"), menu); + // Click the visible menuitem page-wide (getByRole excludes the hidden/closed panels Ant leaves + // in the DOM). Bounded click + response timeouts so a collapse fails this attempt fast and the + // outer retry re-opens, instead of burning the full default timeout on a detached panel. final Locator option = - menu.getByRole( - AriaRole.MENUITEM, - new Locator.GetByRoleOptions() - .setName(Pattern.compile("50.*page", Pattern.CASE_INSENSITIVE))); - option.scrollIntoViewIfNeeded(); + page.getByRole(AriaRole.MENUITEM, new Page.GetByRoleOptions().setName(PAGE_SIZE_50_OPTION)); page.waitForResponse( - r -> r.url().matches(API_LIST_REGEX) && r.url().contains("limit=50"), () -> option.click()); - return this; + r -> r.url().matches(API_LIST_REGEX) && r.url().contains("limit=50"), + new Page.WaitForResponseOptions().setTimeout(PAGE_SIZE_RESPONSE_TIMEOUT_MS), + () -> option.click(new Locator.ClickOptions().setTimeout(PAGE_SIZE_CLICK_TIMEOUT_MS))); } /** diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/PageObject.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/PageObject.java index 6f825ffd6895..c817445a3725 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/PageObject.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/PageObject.java @@ -2,7 +2,6 @@ import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; -import com.microsoft.playwright.TimeoutError; import com.microsoft.playwright.options.WaitForSelectorState; import org.openmetadata.playwright.ui.UiSession; @@ -38,30 +37,21 @@ protected PageObject(final Page page, final UiSession session) { this.session = session; } - private static final double MENU_OPEN_PROBE_MS = 3_000; - /** Convenience accessor for {@code data-testid} locators — prefer over text/CSS. */ protected final Locator byTestId(final String testId) { return page.getByTestId(testId); } /** - * Open an Ant Design dropdown/menu reliably. A single {@code trigger.click()} can be swallowed - * when the panel re-renders mid-click, leaving the menu closed and any follow-up wait on a menu - * item burning its full timeout. Click once, and if the menu panel hasn't appeared within a short - * probe window, click the trigger again before waiting on it for the full default timeout. + * Open an Ant Design dropdown/menu. Ant triggers TOGGLE on click, so we click exactly once and + * wait for the panel. A speculative second click (to guard against a "swallowed" first click) + * would instead close a menu the first click already opened slowly, and any follow-up item click + * then burns its full timeout on the collapsing panel. Matches the single-click pattern the + * source {@code *.spec.ts} files use for these same dropdowns. */ protected final void openMenu(final Locator trigger, final Locator menu) { trigger.click(); - try { - menu.waitFor( - new Locator.WaitForOptions() - .setState(WaitForSelectorState.VISIBLE) - .setTimeout(MENU_OPEN_PROBE_MS)); - } catch (final TimeoutError firstClickSwallowed) { - trigger.click(); - menu.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE)); - } + menu.waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE)); } /** Override to wait for a page-specific readiness signal after navigation. */ diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/TableDataQualityPage.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/TableDataQualityPage.java index 9a5f624bdf1d..09ec1e9e31ab 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/TableDataQualityPage.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/TableDataQualityPage.java @@ -73,20 +73,36 @@ public TableDataQualityPage selectColumnLevel(final String columnName) { && r.url().contains("entityType=COLUMN"), () -> { page.locator("[id='root\\/column']").click(); - page.locator("[title='" + columnName + "']").click(); + page.getByRole(AriaRole.OPTION) + .filter(new Locator.FilterOptions().setHasText(columnName)) + .first() + .click(); }); return this; } + /** + * Select a test definition in the type combobox by its display name. The migrated + * react-hook-form field renders options as {@code role=option} with no per-option testid, + * so filter by the visible label (mirrors the {@code selectTestType} TS helper). + */ + private void selectTestType(final String displayName) { + page.locator("[id='root\\/testType']").click(); + page.locator("[id='root\\/testType']").fill(displayName); + page.getByRole(AriaRole.OPTION) + .filter(new Locator.FilterOptions().setHasText(displayName)) + .first() + .click(); + } + /** * Fill the column-level form for {@code columnValueLengthsToBeBetween} and submit. * Drawer detaches when create completes. */ public TableDataQualityPage submitColumnValueLengthsToBeBetween( final String testCaseName, final String minLength, final String maxLength) { - byTestId("test-case-name").fill(testCaseName); - page.locator("[id='root\\/testType']").click(); - byTestId("columnValueLengthsToBeBetween").click(); + byTestId("test-case-name").locator("input").fill(testCaseName); + selectTestType("Column Value Lengths To Be Between"); page.locator("#testCaseFormV1_params_minLength").fill(minLength); page.locator("#testCaseFormV1_params_maxLength").fill(maxLength); @@ -104,9 +120,8 @@ public TableDataQualityPage submitColumnValueLengthsToBeBetween( */ public TableDataQualityPage submitColumnValuesToBeInSet( final String testCaseName, final java.util.List allowedValues) { - byTestId("test-case-name").fill(testCaseName); - page.locator("[id='root\\/testType']").click(); - byTestId("columnValuesToBeInSet").click(); + byTestId("test-case-name").locator("input").fill(testCaseName); + selectTestType("Column Values To Be In Set"); // Fill each allowed-value row. UI renders one row by default; click "+" for extras. for (int i = 0; i < allowedValues.size(); i++) { if (i > 0) { @@ -129,9 +144,8 @@ public TableDataQualityPage submitColumnValuesToBeInSet( */ public TableDataQualityPage submitTableColumnNameToExist( final String testCaseName, final String columnName) { - byTestId("test-case-name").fill(testCaseName); - page.locator("[id='root\\/testType']").click(); - byTestId("tableColumnNameToExist").click(); + byTestId("test-case-name").locator("input").fill(testCaseName); + selectTestType("Table Column Name To Exist"); page.locator("#testCaseFormV1_params_columnName").fill(columnName); page.waitForResponse( @@ -162,29 +176,29 @@ public TableDataQualityPage assertTestCaseGone(final String testCaseName) { } /** - * Opens the action-dropdown for the named test case and clicks Edit. Waits for - * the edit drawer title — works regardless of test type (table or column). + * Opens the action-dropdown for the named test case and clicks Edit. Waits for the + * prefetched form body, which works regardless of test type (table or column). */ public TableDataQualityPage openEditDrawer(final String testCaseName) { byTestId("action-dropdown-" + testCaseName).click(); page.waitForResponse( r -> r.url().matches(API_TEST_DEFINITION_REGEX), () -> byTestId("edit-" + testCaseName).click()); - byTestId("edit-test-case-drawer-title") + byTestId("test-case-form-v1") .waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE)); return this; } - /** Update a single param field (id starts with {@code tableTestForm_params_}) and save. */ + /** Update a single param field (id starts with {@code testCaseFormV1_params_}) and save. */ public TableDataQualityPage updateParamAndSave(final String paramName, final String newValue) { - final String selector = "#tableTestForm_params_" + paramName; + final String selector = "#testCaseFormV1_params_" + paramName; page.locator(selector).clear(); page.locator(selector).fill(newValue); page.waitForResponse( r -> r.url().matches(API_TEST_CASE_UPDATE_REGEX) && (r.request().method().equals("PUT") || r.request().method().equals("PATCH")), - () -> byTestId("update-btn").click()); + () -> byTestId("create-btn").click()); byTestId("test-case-form-v1") .waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.DETACHED)); return this; @@ -193,10 +207,10 @@ public TableDataQualityPage updateParamAndSave(final String paramName, final Str /** * Read an array-shaped param at a given index from the OPEN edit drawer (caller * already invoked {@link #openEditDrawer}). Form field id pattern: - * {@code #tableTestForm_params___value}. + * {@code #testCaseFormV1_params___value}. */ public String readArrayParamValue(final String paramName, final int index) { - final String selector = "#tableTestForm_params_" + paramName + "_" + index + "_value"; + final String selector = "#testCaseFormV1_params_" + paramName + "_" + index + "_value"; page.locator(selector) .waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE)); return page.locator(selector).inputValue(); @@ -205,14 +219,14 @@ public String readArrayParamValue(final String paramName, final int index) { /** Update an array-shaped param at a given index in the OPEN edit drawer and save. */ public TableDataQualityPage updateArrayParamAndSave( final String paramName, final int index, final String newValue) { - final String selector = "#tableTestForm_params_" + paramName + "_" + index + "_value"; + final String selector = "#testCaseFormV1_params_" + paramName + "_" + index + "_value"; page.locator(selector).clear(); page.locator(selector).fill(newValue); page.waitForResponse( r -> r.url().matches(API_TEST_CASE_UPDATE_REGEX) && (r.request().method().equals("PUT") || r.request().method().equals("PATCH")), - () -> byTestId("update-btn").click()); + () -> byTestId("create-btn").click()); byTestId("test-case-form-v1") .waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.DETACHED)); return this; @@ -229,7 +243,7 @@ public TableDataQualityPage cancelEditDrawer() { /** Re-open the edit drawer, read a param input value, then close (Cancel). */ public String readParam(final String testCaseName, final String paramName) { openEditDrawer(testCaseName); - final String selector = "#tableTestForm_params_" + paramName; + final String selector = "#testCaseFormV1_params_" + paramName; page.locator(selector) .waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE)); final String value = page.locator(selector).inputValue(); @@ -239,11 +253,12 @@ public String readParam(final String testCaseName, final String paramName) { return value; } - /** Deletes the test case through the action menu + "DELETE" confirm dialog. */ + /** Deletes the test case through the action menu and confirmation button. */ public TableDataQualityPage deleteTestCase(final String testCaseName) { byTestId("action-dropdown-" + testCaseName).click(); byTestId("delete-" + testCaseName).click(); - page.locator("#deleteTextInput").fill("DELETE"); + byTestId("confirm-button") + .waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE)); page.waitForResponse( r -> r.url().contains("/api/v1/dataQuality/testCases/") diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java index b6d1c308511c..01390e83b29c 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java @@ -5,10 +5,7 @@ import io.modelcontextprotocol.server.McpStatelessServerFeatures; import io.modelcontextprotocol.server.McpStatelessSyncServer; import io.modelcontextprotocol.spec.McpSchema; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.openmetadata.mcp.prompts.DefaultPromptsContext; @@ -24,7 +21,6 @@ import org.openmetadata.service.apps.McpServerProvider; import org.openmetadata.service.apps.bundles.mcp.McpAppConstants; import org.openmetadata.service.limits.Limits; -import org.openmetadata.service.resources.mcpclient.McpClientResource; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.ImpersonationContext; import org.openmetadata.service.security.JwtFilter; @@ -71,67 +67,6 @@ public void initializeMcpServer( List tools = getTools(); List prompts = getPrompts(); addStatelessTransport(contextHandler, tools, prompts, config); - - registerMcpClientToolExecutor(); - } - - @SuppressWarnings("unchecked") - private void registerMcpClientToolExecutor() { - try { - McpClientResource mcpClientResource = McpClientResource.getInstance(); - if (mcpClientResource == null) { - LOG.warn("McpClientResource not found — MCP Client chat will not have tool access."); - return; - } - - String json = McpUtils.getJsonFromFile("json/data/mcp/tools.json"); - List> rawTools = McpUtils.loadDefinitionsFromJson(json); - List> llmToolDefs = new ArrayList<>(); - for (Map rawTool : rawTools) { - Map functionDef = new HashMap<>(); - functionDef.put("name", rawTool.get("name")); - functionDef.put("description", rawTool.get("description")); - if (rawTool.containsKey("parameters")) { - Map params = (Map) rawTool.get("parameters"); - Map cleanParams = new HashMap<>(params); - cleanParams.remove("examples"); - functionDef.put("parameters", cleanParams); - } - Map tool = new HashMap<>(); - tool.put("type", "function"); - tool.put("function", functionDef); - llmToolDefs.add(tool); - } - - mcpClientResource.registerToolExecutor( - (secCtx, toolName, arguments) -> { - Map args = - (arguments != null && !arguments.isBlank()) - ? JsonUtils.readValue(arguments, Map.class) - : new HashMap<>(); - McpSchema.CallToolRequest request = new McpSchema.CallToolRequest(toolName, args, null); - McpSchema.CallToolResult callResult = - toolContext.callTool(authorizer, limits, toolName, secCtx, request); - return extractToolResultContent(callResult); - }, - llmToolDefs); - LOG.info("Registered MCP tool executor with McpClientResource."); - } catch (Exception e) { - LOG.warn("Failed to register MCP Client tool executor: {}", e.getMessage()); - } - } - - private static String extractToolResultContent(McpSchema.CallToolResult result) { - if (result.content() == null || result.content().isEmpty()) { - return "{}"; - } - StringBuilder sb = new StringBuilder(); - for (McpSchema.Content content : result.content()) { - if (content instanceof McpSchema.TextContent textContent) { - sb.append(textContent.text()); - } - } - return sb.length() > 0 ? sb.toString() : "{}"; } protected List getTools() { diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpUtils.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpUtils.java index c93ef39dbdd0..a57eb1c3d76d 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpUtils.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpUtils.java @@ -83,17 +83,8 @@ public static List getToolProperties(String jsonFilePath) { throw new RuntimeException("Failed to load tool definitions"); } LOG.debug("Successfully loaded {} tool definitions", cachedTools.size()); - for (int i = 0; i < cachedTools.size(); i++) { - Map toolDef = cachedTools.get(i); - String name = (String) toolDef.get("name"); - String description = (String) toolDef.get("description"); - Map schema = JsonUtils.getMap(toolDef.get("parameters")); - result.add( - McpSchema.Tool.builder() - .name(name) - .description(description) - .inputSchema(JSON_MAPPER, JsonUtils.pojoToJson(schema)) - .build()); + for (Map toolDef : cachedTools) { + result.add(buildTool(toolDef)); } return result; } catch (Exception e) { @@ -102,6 +93,45 @@ public static List getToolProperties(String jsonFilePath) { } } + private static McpSchema.Tool buildTool(Map toolDef) { + String name = (String) toolDef.get("name"); + String title = (String) toolDef.get("title"); + String description = (String) toolDef.get("description"); + Map schema = JsonUtils.getMap(toolDef.get("parameters")); + McpSchema.Tool.Builder builder = + McpSchema.Tool.builder() + .name(name) + .title(title) + .description(description) + .inputSchema(JSON_MAPPER, JsonUtils.pojoToJson(schema)); + McpSchema.ToolAnnotations annotations = buildToolAnnotations(toolDef, title); + if (annotations != null) { + builder.annotations(annotations); + } + return builder.build(); + } + + @SuppressWarnings("unchecked") + private static McpSchema.ToolAnnotations buildToolAnnotations( + Map toolDef, String title) { + // openWorldHint defaults to true per the MCP spec when omitted, which would mislabel every + // tool here as reaching external/public systems. All tools only read/write our own + // OpenMetadata catalog, so tools.json sets it to false explicitly for each tool. + McpSchema.ToolAnnotations result = null; + Map annotations = (Map) toolDef.get("annotations"); + if (annotations != null) { + result = + new McpSchema.ToolAnnotations( + title, + (Boolean) annotations.get("readOnlyHint"), + (Boolean) annotations.get("destructiveHint"), + (Boolean) annotations.get("idempotentHint"), + (Boolean) annotations.get("openWorldHint"), + (Boolean) annotations.get("returnDirect")); + } + return result; + } + public static List getPrompts(String jsonFilePath) { try { String json = getJsonFromFile(jsonFilePath); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateClassificationTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateClassificationTool.java index 854f353867ac..789f5a93fb45 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateClassificationTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateClassificationTool.java @@ -62,6 +62,8 @@ public Map execute( repo.prepareInternal(entity, false); final String userName = CommonUtils.principal(securityContext); + // createOrUpdate silently overwrites an existing classification with this name — + // tools.json marks this tool destructiveHint:true for that reason. final RestUtil.PutResponse response = repo.createOrUpdate(null, entity, userName, ImpersonationContext.getImpersonatedBy()); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateContextMemoryTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateContextMemoryTool.java index 9bb52f936030..16fe8030b06a 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateContextMemoryTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateContextMemoryTool.java @@ -57,6 +57,9 @@ public Map execute( repo.prepareInternal(entity, false); final String userName = CommonUtils.principal(securityContext); + // createOrUpdate overwrites an existing memory with this name (the tool description + // documents this as intentional reuse) — tools.json still marks this tool + // destructiveHint:true since the prior content is discarded. final RestUtil.PutResponse response = repo.createOrUpdate(null, entity, userName, ImpersonationContext.getImpersonatedBy()); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDataProductTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDataProductTool.java index da7a5c64757c..012e7c4c4a72 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDataProductTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDataProductTool.java @@ -74,6 +74,8 @@ public Map execute( repo.prepareInternal(entity, false); final String userName = CommonUtils.principal(securityContext); + // createOrUpdate silently overwrites an existing data product with this name — + // tools.json marks this tool destructiveHint:true for that reason. final RestUtil.PutResponse response = repo.createOrUpdate(null, entity, userName, ImpersonationContext.getImpersonatedBy()); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDomainTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDomainTool.java index 6041fbb7b494..ef9b60c59ab5 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDomainTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateDomainTool.java @@ -73,6 +73,8 @@ public Map execute( repo.prepareInternal(entity, false); final String userName = CommonUtils.principal(securityContext); + // createOrUpdate silently overwrites an existing domain with this name — tools.json + // marks this tool destructiveHint:true for that reason. final RestUtil.PutResponse response = repo.createOrUpdate(null, entity, userName, ImpersonationContext.getImpersonatedBy()); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateMetricTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateMetricTool.java index dee11eb09338..a40d3aee35f2 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateMetricTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateMetricTool.java @@ -184,6 +184,8 @@ public Map execute( String userName = securityContext.getUserPrincipal().getName(); String impersonatedBy = ImpersonationContext.getImpersonatedBy(); + // createOrUpdate silently overwrites an existing metric with this name — tools.json + // marks this tool destructiveHint:true for that reason. RestUtil.PutResponse response = repo.createOrUpdate(null, metric, userName, impersonatedBy); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTagTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTagTool.java index 31e3644b5bad..5e0b641ea86c 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTagTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTagTool.java @@ -73,6 +73,8 @@ public Map execute( repo.prepareInternal(entity, false); final String userName = CommonUtils.principal(securityContext); + // createOrUpdate silently overwrites an existing tag at this FQN — tools.json marks + // this tool destructiveHint:true for that reason. final RestUtil.PutResponse response = repo.createOrUpdate(null, entity, userName, ImpersonationContext.getImpersonatedBy()); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTestCaseTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTestCaseTool.java index 9b0d2b2d7b5b..4265746018dd 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTestCaseTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CreateTestCaseTool.java @@ -116,6 +116,8 @@ public Map execute( testDefinitionName, fqn); String impersonatedBy = ImpersonationContext.getImpersonatedBy(); + // createOrUpdate silently overwrites an existing test case with this name — tools.json + // marks this tool destructiveHint:true for that reason. RestUtil.PutResponse response = repository.createOrUpdate(null, testCase, updatedBy, impersonatedBy); McpChangeEventUtil.publishChangeEvent( diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java index b280cccf118f..05a0b3f4c1af 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java @@ -88,6 +88,9 @@ public CallToolOutcome callToolWithMetadata( case "get_asset_context": result = new GetAssetContextTool().execute(authorizer, securityContext, params); break; + case "get_persona_context": + result = new GetPersonaContextTool().execute(authorizer, securityContext, params); + break; case "find_context": result = new FindContextTool().execute(authorizer, securityContext, params); break; diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindContextTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindContextTool.java index b016b657cf47..3e796642e8f5 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindContextTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindContextTool.java @@ -1,10 +1,6 @@ package org.openmetadata.mcp.tools; -import static org.openmetadata.schema.type.MetadataOperation.VIEW_ALL; -import static org.openmetadata.schema.type.MetadataOperation.VIEW_BASIC; - import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; @@ -12,15 +8,13 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.aicontext.AIContextFinder; -import org.openmetadata.service.aicontext.AIContextFinder.CandidateAsset; import org.openmetadata.service.aicontext.AIContextFinder.FoundContext; +import org.openmetadata.service.aicontext.AIContextFinderAccess; import org.openmetadata.service.aicontext.AIContextMarkdown; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; import org.openmetadata.service.security.auth.CatalogSecurityContext; -import org.openmetadata.service.security.policyevaluator.OperationContext; -import org.openmetadata.service.security.policyevaluator.ResourceContext; import org.openmetadata.service.security.policyevaluator.SubjectContext; /** @@ -40,8 +34,6 @@ public class FindContextTool implements McpTool { private static final int MAX_SIZE = 50; private static final String FORMAT_JSON = "json"; private static final String NO_RESULTS_MESSAGE = "No company knowledge found for this query."; - private static final List KNOWLEDGE_TYPES = - List.of(Entity.GLOSSARY_TERM, Entity.METRIC, Entity.PAGE); @Override public Map execute( @@ -57,61 +49,19 @@ public Map execute( "error", "Semantic search is not enabled. Configure vector embeddings in the OpenMetadata server settings."); } else { - authorizeKnowledgeAccess(authorizer, securityContext); + AIContextFinderAccess.authorizeKnowledgeAccess(authorizer, securityContext); String format = (String) params.getOrDefault("format", "markdown"); int size = Math.min(Math.max(McpParams.getInt(params, "size", DEFAULT_SIZE), 1), MAX_SIZE); LOG.info("Finding company context for query: {}, format: {}", query, format); SubjectContext subjectContext = DefaultAuthorizer.getSubjectContext(securityContext); FoundContext found = new AIContextFinder(subjectContext).find(query, size); - result = render(filterCandidates(found, authorizer, securityContext), format); + result = + render( + AIContextFinderAccess.filterCandidates(found, authorizer, securityContext), format); } return result; } - private void authorizeKnowledgeAccess( - Authorizer authorizer, CatalogSecurityContext securityContext) { - for (String knowledgeType : KNOWLEDGE_TYPES) { - authorizer.authorize( - securityContext, - new OperationContext(knowledgeType, VIEW_ALL), - new ResourceContext<>(knowledgeType)); - } - } - - /** - * Drops candidate assets the caller cannot view. Glossary-routed candidates are already - * RBAC-filtered by the subject-scoped search; this guards the relationship-routed ones - * (metric APPLIED_TO, page HAS), which are read straight from the entity-relationship table. - */ - private FoundContext filterCandidates( - FoundContext found, Authorizer authorizer, CatalogSecurityContext securityContext) { - List visible = new ArrayList<>(); - for (CandidateAsset asset : found.candidateAssets()) { - if (canView(asset, authorizer, securityContext)) { - visible.add(asset); - } - } - return new FoundContext(found.items(), visible); - } - - private boolean canView( - CandidateAsset asset, Authorizer authorizer, CatalogSecurityContext securityContext) { - boolean visible = false; - try { - authorizer.authorize( - securityContext, - new OperationContext(asset.entityType(), VIEW_BASIC), - new ResourceContext<>(asset.entityType(), null, asset.fullyQualifiedName())); - visible = true; - } catch (Exception e) { - LOG.debug( - "Dropping candidate asset {} not viewable by caller: {}", - asset.fullyQualifiedName(), - e.getMessage()); - } - return visible; - } - private Map render(FoundContext found, String format) { Map result; if (FORMAT_JSON.equalsIgnoreCase(format)) { diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java index 3204ec951c3b..c111cc2c9a44 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java @@ -103,10 +103,12 @@ public Map execute( throws IOException { String entityType = (String) params.get("entityType"); String fqn = (String) params.get("fqn"); + // Authorize by FQN so entity-scoped tag/owner/domain policies are evaluated, not just the + // resource-type permission. authorizer.authorize( securityContext, new OperationContext(entityType, VIEW_ALL), - new ResourceContext<>(entityType)); + new ResourceContext<>(entityType, null, fqn)); LOG.info("Getting details for entity type: {}, FQN: {}", entityType, fqn); int columnOffset = Math.max(0, McpParams.getInt(params, COLUMN_OFFSET_PARAM, DEFAULT_COLUMN_OFFSET)); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetPersonaContextTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetPersonaContextTool.java new file mode 100644 index 000000000000..41c08f5cfe9e --- /dev/null +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetPersonaContextTool.java @@ -0,0 +1,145 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.mcp.tools; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.openmetadata.mcp.util.McpResponseTrim; +import org.openmetadata.schema.entity.teams.Persona; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.aicontext.PersonaContextAccess; +import org.openmetadata.service.aicontext.PersonaContextBuilder; +import org.openmetadata.service.aicontext.PersonaContextCache; +import org.openmetadata.service.limits.Limits; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.auth.CatalogSecurityContext; + +/** Returns one deterministic, line-bounded part of a persona's shared AI context document. */ +public class GetPersonaContextTool implements McpTool { + private static final int PART_RESPONSE_BUDGET = McpResponseTrim.MAX_RESPONSE_CHARS - 10_000; + + @Override + public Map execute( + Authorizer authorizer, CatalogSecurityContext securityContext, Map params) + throws IOException { + Persona persona = resolvePersona(securityContext, stringParam(params, "personaName")); + PersonaContextAccess.authorize(securityContext, persona); + PersonaContextBuilder.MaterializedPersonaContext materialized = + PersonaContextCache.getInstance().get(persona, false).value(); + String format = stringParam(params, "format"); + String content = + "json".equalsIgnoreCase(format) + ? JsonUtils.pojoToJson(materialized.context()) + : materialized.markdown(); + List parts = split(content); + int requestedPart = intParam(params.get("part"), 1); + if (requestedPart < 1 || requestedPart > parts.size()) { + return Map.of( + McpResponseTrim.ERROR_KEY, + "part must be between 1 and " + parts.size(), + McpResponseTrim.STATUS_CODE_KEY, + 400); + } + + Map result = new LinkedHashMap<>(); + result.put("format", "json".equalsIgnoreCase(format) ? "json" : "markdown"); + result.put("content", parts.get(requestedPart - 1)); + result.put("part", requestedPart); + result.put("totalParts", parts.size()); + result.put(McpResponseTrim.HAS_MORE_KEY, requestedPart < parts.size()); + result.put("fingerprint", materialized.context().getFingerprint()); + return result; + } + + @Override + public Map execute( + Authorizer authorizer, + Limits limits, + CatalogSecurityContext securityContext, + Map params) + throws IOException { + throw new UnsupportedOperationException( + "GetPersonaContextTool does not require limit validation."); + } + + private static Persona resolvePersona( + CatalogSecurityContext securityContext, String personaName) { + return personaName == null || personaName.isBlank() + ? PersonaContextAccess.activePersona(securityContext) + : Entity.getEntityByName( + Entity.PERSONA, personaName, "contextDefinition,users", Include.NON_DELETED); + } + + static List split(String content) { + List parts = new ArrayList<>(); + if (content == null || content.isEmpty()) { + return List.of(""); + } + int start = 0; + while (start < content.length()) { + int candidateEnd = largestSerializableEnd(content, start); + int end = candidateEnd; + if (candidateEnd < content.length()) { + int lineEnd = content.lastIndexOf('\n', candidateEnd); + if (lineEnd > start) { + end = lineEnd + 1; + } + } + parts.add(content.substring(start, end)); + start = end; + } + return parts; + } + + private static int largestSerializableEnd(String content, int start) { + int low = start + 1; + int high = content.length(); + int result = low; + while (low <= high) { + int midpoint = low + (high - low) / 2; + int serializedLength = + McpResponseTrim.serializedLength(Map.of("content", content.substring(start, midpoint))); + if (serializedLength <= PART_RESPONSE_BUDGET) { + result = midpoint; + low = midpoint + 1; + } else { + high = midpoint - 1; + } + } + return result; + } + + private static String stringParam(Map params, String key) { + Object value = params.get(key); + return value == null ? null : String.valueOf(value); + } + + private static int intParam(Object value, int defaultValue) { + if (value instanceof Number number) { + return number.intValue(); + } + if (value != null) { + try { + return Integer.parseInt(String.valueOf(value)); + } catch (NumberFormatException ignored) { + return -1; + } + } + return defaultValue; + } +} diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTermTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTermTool.java index d3cf7aa8892b..cdcbb8a503b6 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTermTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTermTool.java @@ -63,6 +63,8 @@ public Map execute( String impersonatedBy = ImpersonationContext.getImpersonatedBy(); String userName = securityContext.getUserPrincipal().getName(); + // createOrUpdate silently overwrites an existing term at this FQN — tools.json marks + // this tool destructiveHint:true for that reason. RestUtil.PutResponse response = glossaryTermRepository.createOrUpdate(null, glossaryTerm, userName, impersonatedBy); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTool.java index 14c700ed2e46..d0d29c6dcf06 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GlossaryTool.java @@ -71,6 +71,8 @@ public Map execute( String impersonatedBy = ImpersonationContext.getImpersonatedBy(); String userName = securityContext.getUserPrincipal().getName(); + // createOrUpdate silently overwrites an existing glossary at this name — tools.json + // marks this tool destructiveHint:true for that reason. RestUtil.PutResponse response = glossaryRepository.createOrUpdate(null, glossary, userName, impersonatedBy); McpChangeEventUtil.publishChangeEvent(response.getEntity(), response.getChangeType(), userName); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/usage/McpUsageRecorder.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/usage/McpUsageRecorder.java index f2188a224be7..884f9e2992e0 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/usage/McpUsageRecorder.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/usage/McpUsageRecorder.java @@ -13,10 +13,13 @@ package org.openmetadata.mcp.usage; +import org.openmetadata.schema.entity.app.App; import org.openmetadata.schema.entity.app.AppExtension; import org.openmetadata.schema.entity.app.mcp.McpToolCallUsage; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.AbstractNativeApplication; +import org.openmetadata.service.apps.ApplicationContext; import org.openmetadata.service.apps.bundles.mcp.McpAppConstants; import org.openmetadata.service.jdbi3.CollectionDAO; import org.slf4j.Logger; @@ -58,10 +61,16 @@ public static void record( McpToolCallUsage.ErrorCategory errorCategory, String clientName) { try { + App app = resolveMcpApp(); + if (app == null) { + LOG.debug( + "McpApplication not initialized, skipping MCP usage record for tool {}", toolName); + return; + } McpToolCallUsage usage = new McpToolCallUsage() - .withAppId(McpAppConstants.MCP_APP_ID) - .withAppName(McpAppConstants.MCP_APP_NAME) + .withAppId(app.getId()) + .withAppName(app.getName()) .withTimestamp(System.currentTimeMillis()) .withExtension(AppExtension.ExtensionType.LIMITS) .withToolName(toolName) @@ -89,6 +98,12 @@ public static void record(String toolName, String userName, boolean success) { record(toolName, userName, success, null, null, null); } + private static App resolveMcpApp() { + AbstractNativeApplication app = + ApplicationContext.getInstance().getAppIfExists(McpAppConstants.MCP_APP_NAME); + return app != null ? app.getApp() : null; + } + private static CollectionDAO.AppExtensionTimeSeries getDao() { return Entity.getCollectionDAO().appExtensionTimeSeriesDao(); } diff --git a/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json b/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json index ddff20959203..8bf950592c27 100644 --- a/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json +++ b/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json @@ -2,6 +2,12 @@ "tools": [ { "name": "search_company_context", + "title": "Search Company Context", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Semantic search over Company Context knowledge pills extracted from Context Center files. Returns each pill's title, question, answer, summary, and source file in one call. Use this to answer questions from company documents, runbooks, FAQs, and policies.", "parameters": { "description": "Provide a natural-language 'query'. Returns the most semantically relevant knowledge pills.", @@ -33,6 +39,12 @@ }, { "name": "get_company_context", + "title": "Get Company Context", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Fetch a single Company Context knowledge pill, returning its full title, question, answer, summary, and source file. Pass the 'fullyQualifiedName' (or 'name') from a search_company_context result, exactly as returned.", "parameters": { "description": "Provide the 'fqn' of the knowledge pill to fetch.", @@ -50,6 +62,12 @@ }, { "name": "search_metadata", + "title": "Search Metadata", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Keyword-based search for data assets and data quality entities in OpenMetadata. Best when you know specific names, owners, tags, tiers, services, or column names. Use this for exact lookups (e.g., 'find table X', 'tables owned by team Y'), filtering by metadata properties, counting assets, and aggregations. Also searches data quality test cases and test suites when entityType is 'testCase' or 'testSuite' — these are NOT part of the default search scope, so always set entityType explicitly for data quality questions. Supports pagination and advanced OpenSearch DSL queries. Choose this over semantic_search when the query targets known identifiers or structured attributes. Results include 'fullyQualifiedName' and 'entityType' — pass these directly to get_entity_details for full entity information.", "parameters": { "description": "Use 'query' for keyword search or 'queryFilter' for advanced OpenSearch DSL. Best for exact matches and filtering by metadata properties.", @@ -173,6 +191,12 @@ }, { "name": "semantic_search", + "title": "Semantic Search", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Meaning-based discovery of data assets using vector embeddings. Best for exploratory or vague queries where you don't know exact names — it finds conceptually related assets even when no keywords match. Use this when the user describes what data they need in plain language (e.g., 'tables about customer spending behavior', 'anything related to revenue forecasting'). Returns entity summaries with name, columns, description, and metadata. Choose this over search_metadata when the query is about meaning or concepts rather than specific identifiers or attributes. Results include 'fullyQualifiedName' and 'entityType' — pass these directly to get_entity_details for full entity information.", "parameters": { "description": "Use 'query' to describe what you're looking for in plain language. The system finds conceptually similar assets using vector similarity. Optionally filter by entity type, service, or tags.", @@ -251,6 +275,12 @@ }, { "name": "get_entity_details", + "title": "Get Entity Details", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Get detailed information about a specific entity by its fully qualified name, including its custom properties (returned under the 'extension' field). IMPORTANT: Use the 'fullyQualifiedName' and 'entityType' values directly from search_metadata or semantic_search results — do not construct the FQN manually. Response is optimized for LLM context: verbose index/noise metadata fields are excluded. Descriptions (entity-level and per-column) are returned in FULL and are never truncated — total response size is bounded by column pagination instead. Only the raw schema DDL and dbt model SQL carry a large safety cap (~30000 characters, flagged with 'schemaDefinitionTruncated' or 'sqlTruncated' inside 'dataModel') to keep the response retrievable; realistic DDL/SQL is well under this. For wide entities (many columns), the 'columns' array is paginated: when it is capped the response sets 'columnsTruncated' with 'totalColumns', 'returnedColumns', 'columnOffset' and 'hasMoreColumns'. When 'hasMoreColumns' is true, fetch the next page by calling again with 'columnOffset' set to the previous 'columnOffset' + 'returnedColumns'; when it is false there are no further columns to retrieve.", "parameters": { "description": "Use 'fullyQualifiedName' and 'entityType' from search results directly.", @@ -281,6 +311,12 @@ }, { "name": "get_asset_context", + "title": "Get Asset Context", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Get the full AI Context (Context Profile) for a single data asset in one call: the business knowledge attached to it (approved glossary term definitions, Context Center articles) plus the type-specific structural context. For tables this includes the column schema, primary key, foreign keys (with the referenced columns and cardinality), and the columns most frequently joined with other tables — the strong, deterministic signals needed for SQL generation. Returns a compact, LLM-friendly markdown document by default. Prefer this over get_entity_details when you have already selected the asset(s) and need their business rules and join keys. Use the 'fullyQualifiedName' and 'entityType' values directly from search_metadata or semantic_search results.", "parameters": { "description": "Use 'fullyQualifiedName' and 'entityType' from search results directly.", @@ -314,8 +350,49 @@ ] } }, + { + "name": "get_persona_context", + "title": "Get Persona Context", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, + "description": "Get the shared AI context document curated for a persona. With no personaName, uses the caller's active persona. The document can contain many assets and is returned in deterministic parts; call again with part=2, part=3, and so on while hasMore is true. Access is limited to persona members, admins, and bots.", + "parameters": { + "type": "object", + "properties": { + "personaName": { + "type": "string", + "description": "Optional persona fully qualified name. Omit to use the caller's active persona." + }, + "format": { + "type": "string", + "description": "Output format to page: markdown (default) or json.", + "enum": [ + "markdown", + "json" + ], + "default": "markdown" + }, + "part": { + "type": "integer", + "description": "One-based document part to return. Start at 1 and continue while hasMore is true.", + "minimum": 1, + "default": 1 + } + }, + "required": [] + } + }, { "name": "find_context", + "title": "Find Context", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "For a business question when no specific asset has been chosen yet: semantically searches the company-knowledge layer (glossary term definitions, metric definitions, Context Center articles) and returns the relevant definitions PLUS the candidate data assets each concept points to (glossary terms → the tables tagged with them, metrics → the assets they apply to, articles → the assets they are about). Use this to bootstrap a data question from business concepts into candidate tables, then call get_asset_context on those candidate fullyQualifiedNames. Returns LLM-friendly markdown by default.", "parameters": { "description": "Provide a natural-language 'query' using the business terms or concepts from the user's request.", @@ -347,6 +424,12 @@ }, { "name": "get_knowledge_content", + "title": "Get Knowledge Content", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Progressive disclosure for attached knowledge. get_asset_context and find_context return bounded EXCERPTS of long glossary definitions, metric definitions, and Context Center articles (each marked contentTruncated) so a bundle never overwhelms the context window. When you need the full detail of one specific item, call this with that item's type and fullyQualifiedName. Without a 'query' it returns the full body; with a 'query' it returns only the passages of a long article most relevant to that query. Returns LLM-friendly markdown by default.", "parameters": { "description": "Provide the knowledge item's 'entityType' and 'fqn' (as given in the get_asset_context/find_context result). Optionally pass a 'query' to retrieve only the relevant passages of a long article.", @@ -393,6 +476,12 @@ }, { "name": "create_glossary_term", + "title": "Create Glossary Term", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a new Glossary Term. Note that a glossary term must be part of a Glossary, so the glossary must be specified in the parameters. If you can't find the right glossary to use, respond back to the user to create a new Glossary first. Note that you can help the user to create the Glossary as well. If you don't find any Glossary that could be related, please list to the user the available Glossaries so users can choose if they want to create or reuse something. Also, note that glossary terms can be hierarchical: for example, a glossary term 'Accounts' can have a child term 'Credit Account', 'Savings Account', etc. So if you find any terms that can be related, it might make sense to create a new term as a child of an existing term.", "parameters": { "type": "object", @@ -437,6 +526,12 @@ }, { "name": "create_glossary", + "title": "Create Glossary", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a new Glossary. A Glossary is a collection of terms that are used to define the business vocabulary of an organization. Typically, similar terms are grouped together in a Glossary. For example, a Glossary names 'Marketing' could contain terms like 'Campaign', 'Lead', 'Opportunity', etc.", "parameters": { "type": "object", @@ -478,6 +573,12 @@ }, { "name": "patch_entity", + "title": "Patch Entity", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Patches an Entity based on a JSONPatch. Beforehand the Entity should be validated by finding it and creating a proper patch. IMPORTANT field naming rules: all array/list fields use PLURAL names in the JSON body — use 'domains' (not 'domain'), 'owners' (not 'owner'), 'tags' (not 'tag'), 'reviewers' (not 'reviewer'). Domain values must be entity reference objects: {\"id\": \"\", \"type\": \"domain\"}. Owner values must be entity reference objects: {\"id\": \"\", \"type\": \"user\" or \"team\"}. To add a domain: [{\"op\": \"add\", \"path\": \"/domains/0\", \"value\": {\"id\": \"\", \"type\": \"domain\", \"name\": \"\"}}]. To replace description: [{\"op\": \"add\", \"path\": \"/description\", \"value\": \"new description\"}]. Always look up entity UUIDs using search or get tools before patching.", "parameters": { "type": "object", @@ -504,6 +605,12 @@ }, { "name": "get_entity_lineage", + "title": "Get Entity Lineage", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Get a compact lineage graph (upstream/downstream dependencies) of a specific entity. Use this for root cause (upstream entities) or impact (downstream entities) analysis and explaining dependencies between entities. By default the response is table-level and optimized for size: each edge carries the connected assets' names, FQNs, types and relationship info (pipeline or sql), with long SQL truncated. Set includeColumnLineage=true only when the user explicitly asks about column-level lineage.", "parameters": { "description": "Fqn is the fully qualified name of the entity. Entity type could be table, topic etc.", @@ -541,6 +648,12 @@ }, { "name": "create_lineage", + "title": "Create Lineage", + "annotations": { + "readOnlyHint": false, + "destructiveHint": false, + "openWorldHint": false + }, "description": "This tool can be used to create lineage between two assets. It takes the source and target asset details and creates a lineage relationship between them.", "parameters": { "description": "Required to create lineage between two assets.", @@ -591,6 +704,12 @@ }, { "name": "get_test_definitions", + "title": "Get Test Definitions", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "This tool can be used to get all the test definitions in the OpenMetadata. It returns a list of test definitions. These test definition can be used to create a test case for a table or a table's column. While creating column test for entity, column data type should be in supportedDataTypes of parameterDefinition.", "parameters": { "description": "These test definition are required to create a test case for table or a table's column.", @@ -624,6 +743,12 @@ }, { "name": "create_test_case", + "title": "Create Test Case", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "This tool can be used to create a test case for a table or a table's column. It needs test definitions. These test definition can be found using the get_test_definitions tool. If this fails do not do other operations.", "parameters": { "description": "This tool can be used to create a test case for a table or a table's column. It requires the test definition and the entity (table or column) to be tested.", @@ -686,6 +811,12 @@ }, { "name": "create_metric", + "title": "Create Metric", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a new Metric entity in OpenMetadata. A Metric represents a measurable business or technical KPI (e.g. daily revenue, error rate). Use this to register new metrics with optional expression, type, granularity, and unit of measurement. Metric can be expressed in SQL, Python, Java, or JavaScript.", "parameters": { "type": "object", @@ -813,6 +944,12 @@ }, { "name": "create_classification", + "title": "Create Classification", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a new Classification in OpenMetadata. A Classification is a top-level container that groups related Tags (e.g. 'PII', 'Tier'). The 'name' becomes the root segment of every tag FQN under it. The 'mutuallyExclusive' flag is immutable once the classification exists: if you set it on an existing classification it is ignored and a '_warning' is returned. Owner and reviewer names must already exist in OpenMetadata. Any domain FQNs must already exist.", "parameters": { "type": "object", @@ -863,6 +1000,12 @@ }, { "name": "create_tag", + "title": "Create Tag", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a new Tag inside a Classification in OpenMetadata. The tag FQN is 'Classification.TagName' (e.g. 'PII.Sensitive'). At least one of 'classification' or 'parent' MUST be provided. Provide 'classification' (the root classification name, which must already exist), and optionally 'parent' for a nested tag (the parent tag FQN, e.g. 'PII.PersonalData', which must already exist). If only 'parent' is given, the classification is derived from its root segment. If both are given, 'classification' must equal the root segment of 'parent'. Owner and reviewer names must already exist.", "parameters": { "type": "object", @@ -921,6 +1064,12 @@ }, { "name": "create_domain", + "title": "Create Domain", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a new Domain in OpenMetadata. A Domain is a top-level governance grouping of data assets. To create a child domain, set 'parent' to the FQN of an existing parent domain (it must already exist). 'domainType' must be one of Source-aligned, Consumer-aligned, or Aggregate; it defaults to 'Aggregate' if omitted. 'experts' are OpenMetadata login names that must already exist. Owner names must also already exist.", "parameters": { "type": "object", @@ -980,6 +1129,12 @@ }, { "name": "create_data_product", + "title": "Create Data Product", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a new Data Product in OpenMetadata. A Data Product groups data assets that deliver business value and must belong to at least one Domain. Provide 'domains' as a list of existing domain FQNs (required, at least one; each must already exist). 'experts' are OpenMetadata login names that must already exist. Owner and reviewer names must also already exist.", "parameters": { "type": "object", @@ -1041,6 +1196,12 @@ }, { "name": "root_cause_analysis", + "title": "Root Cause Analysis", + "annotations": { + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": false + }, "description": "Performs comprehensive root cause analysis via data quality lineage. First identifies upstream failures that may be causing issues for the specified asset. If failures are found, automatically analyzes downstream impact to show which assets may be affected. Returns both upstream root causes and downstream impact analysis. In the response 'status' indicates whether upstream failures were found. If 'status' is 'failed', the 'upstreamAnalysis' can be used to identify the nodes and edges leading to failures and downstreamAnalysis can tell what all nodes in downstream are impacted. If 'status' is 'success', it means no upstream failures were found, and downstream impact analysis was not performed. Responses are compact and table-level by default: node and edge details are trimmed and SQL queries truncated to keep the payload within LLM context limits. Set 'includeColumnLineage' to true only when column-level lineage is needed.", "parameters": { "type": "object", @@ -1086,6 +1247,12 @@ }, { "name": "create_context_memory", + "title": "Create Context Memory", + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": false + }, "description": "Creates a reusable Context Center memory in OpenMetadata — a piece of knowledge the assistant should retain across conversations (e.g. a team preference, a recurring instruction, a runbook step, or an answer to a frequently asked question). Memories created here are recorded as an explicit 'remember this' request and, when the Memory Agent is enabled, may be used to derive glossary terms and metrics. Use this when the user explicitly asks you to remember, note, or store something for later reuse.", "parameters": { "type": "object", diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/McpSdkUpgradeTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/McpSdkUpgradeTest.java index 1babce8f3509..3bd5e2b0df93 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/McpSdkUpgradeTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/McpSdkUpgradeTest.java @@ -174,6 +174,94 @@ void testMcpUtilsGetToolPropertiesLoadsTools() { assertThat(searchTool.inputSchema()).isNotNull(); } + @Test + void testMcpUtilsGetToolPropertiesSetsTitleAndReadOnlyAnnotation() { + // Anthropic's Claude Connectors Directory requires every tool to carry a title plus + // readOnlyHint/destructiveHint. Verify a read-only tool is annotated correctly. + List tools = McpUtils.getToolProperties("json/data/mcp/tools.json"); + + McpSchema.Tool searchTool = + tools.stream().filter(t -> "search_metadata".equals(t.name())).findFirst().orElse(null); + + assertThat(searchTool).isNotNull(); + assertThat(searchTool.title()).isEqualTo("Search Metadata"); + assertThat(searchTool.annotations()).isNotNull(); + assertThat(searchTool.annotations().readOnlyHint()).isTrue(); + assertThat(searchTool.annotations().destructiveHint()).isFalse(); + } + + @Test + void testMcpUtilsGetToolPropertiesMarksPatchEntityAsDestructive() { + List tools = McpUtils.getToolProperties("json/data/mcp/tools.json"); + + McpSchema.Tool patchTool = + tools.stream().filter(t -> "patch_entity".equals(t.name())).findFirst().orElse(null); + + assertThat(patchTool).isNotNull(); + assertThat(patchTool.annotations()).isNotNull(); + assertThat(patchTool.annotations().readOnlyHint()).isFalse(); + assertThat(patchTool.annotations().destructiveHint()).isTrue(); + } + + private static final List UPSERT_CAPABLE_CREATE_TOOLS = + List.of( + "create_glossary_term", + "create_glossary", + "create_tag", + "create_metric", + "create_classification", + "create_domain", + "create_data_product", + "create_test_case", + "create_context_memory"); + + @Test + void testMcpUtilsGetToolPropertiesMarksUpsertCapableCreateToolsAsDestructive() { + // These tools call repository.createOrUpdate(), so an existing entity with the requested + // name/FQN is silently overwritten instead of producing a create conflict. destructiveHint + // must be true so MCP clients require confirmation before the overwrite. + List tools = McpUtils.getToolProperties("json/data/mcp/tools.json"); + + assertThat(tools) + .filteredOn(tool -> UPSERT_CAPABLE_CREATE_TOOLS.contains(tool.name())) + .hasSize(UPSERT_CAPABLE_CREATE_TOOLS.size()) + .allSatisfy( + tool -> + assertThat(tool.annotations().destructiveHint()) + .as("destructiveHint for tool %s", tool.name()) + .isTrue()); + } + + @Test + void testMcpUtilsGetToolPropertiesEveryToolHasTitleAndAnnotations() { + // Regression guard: a new tool added to tools.json without title/annotations would fail + // Claude Connectors Directory review. Fail the build instead of failing review. + List tools = McpUtils.getToolProperties("json/data/mcp/tools.json"); + + assertThat(tools) + .allSatisfy( + tool -> { + assertThat(tool.title()).as("title for tool %s", tool.name()).isNotBlank(); + assertThat(tool.annotations()).as("annotations for tool %s", tool.name()).isNotNull(); + }); + } + + @Test + void testMcpUtilsGetToolPropertiesEveryToolHasExplicitOpenWorldHintFalse() { + // Regression guard: openWorldHint defaults to true when omitted, which would mislabel + // every tool as reaching external/public systems and fail OpenAI Apps SDK review + // ("incorrect or missing action labels"). All tools only touch our own OpenMetadata + // catalog, so every tool must set this explicitly to false. + List tools = McpUtils.getToolProperties("json/data/mcp/tools.json"); + + assertThat(tools) + .allSatisfy( + tool -> + assertThat(tool.annotations().openWorldHint()) + .as("openWorldHint for tool %s", tool.name()) + .isFalse()); + } + @Test void testServerCapabilitiesDoNotAdvertiseLogging() { // The stateless MCP server has no handler for logging/setLevel. diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/GetPersonaContextToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/GetPersonaContextToolTest.java new file mode 100644 index 000000000000..2466d324a917 --- /dev/null +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/GetPersonaContextToolTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.mcp.tools; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.openmetadata.mcp.util.McpResponseTrim; + +class GetPersonaContextToolTest { + + @Test + void splitsLargeDocumentsDeterministicallyAtLineBoundaries() { + String content = "a".repeat(84_999) + "\n" + "b".repeat(90_000) + "\nend"; + + List parts = GetPersonaContextTool.split(content); + + assertEquals(content, String.join("", parts)); + assertTrue( + parts.stream() + .allMatch( + part -> + McpResponseTrim.serializedLength(Map.of("content", part)) + <= McpResponseTrim.MAX_RESPONSE_CHARS - 10_000)); + assertTrue(parts.getFirst().endsWith("\n")); + } + + @Test + void budgetsJsonEscapingInsideTheMcpEnvelope() { + String content = "{\"line\":\"\\\\quoted\\nvalue\"}\n".repeat(10_000); + + List parts = GetPersonaContextTool.split(content); + + assertEquals(content, String.join("", parts)); + assertTrue(parts.size() > 1); + assertTrue( + parts.stream() + .allMatch( + part -> + McpResponseTrim.serializedLength(Map.of("content", part)) + <= McpResponseTrim.MAX_RESPONSE_CHARS - 10_000)); + } + + @Test + void representsAnEmptyDocumentAsOnePart() { + assertEquals(List.of(""), GetPersonaContextTool.split("")); + } +} diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/usage/McpUsageRecorderTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/usage/McpUsageRecorderTest.java index 3108a678288b..0f406344ba43 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/usage/McpUsageRecorderTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/usage/McpUsageRecorderTest.java @@ -18,20 +18,25 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.UUID; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.openmetadata.schema.entity.app.App; import org.openmetadata.schema.entity.app.AppExtension; import org.openmetadata.schema.entity.app.mcp.McpToolCallUsage; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.AbstractNativeApplication; +import org.openmetadata.service.apps.ApplicationContext; import org.openmetadata.service.apps.bundles.mcp.McpAppConstants; import org.openmetadata.service.jdbi3.CollectionDAO; @@ -39,6 +44,8 @@ class McpUsageRecorderTest { private CollectionDAO.AppExtensionTimeSeries dao; private MockedStatic entityStatic; + private MockedStatic appContextStatic; + private ApplicationContext appContext; @BeforeEach void setUp() { @@ -48,15 +55,23 @@ void setUp() { entityStatic = Mockito.mockStatic(Entity.class); entityStatic.when(Entity::getCollectionDAO).thenReturn(collectionDAO); + + appContext = mock(ApplicationContext.class); + appContextStatic = Mockito.mockStatic(ApplicationContext.class); + appContextStatic.when(ApplicationContext::getInstance).thenReturn(appContext); } @AfterEach void tearDown() { entityStatic.close(); + appContextStatic.close(); } @Test - void recordWritesUsageRowWithMcpIdentity() { + void recordWritesUsageRowWhenAppRegistered() { + UUID appId = UUID.randomUUID(); + stubMcpApp(appId, McpAppConstants.MCP_APP_NAME); + long before = System.currentTimeMillis(); McpUsageRecorder.record("search_metadata", "alice", true); long after = System.currentTimeMillis(); @@ -67,7 +82,7 @@ void recordWritesUsageRowWithMcpIdentity() { assertThat(ext.getValue()).isEqualTo("limits"); McpToolCallUsage decoded = JsonUtils.readValue(json.getValue(), McpToolCallUsage.class); - assertThat(decoded.getAppId()).isEqualTo(McpAppConstants.MCP_APP_ID); + assertThat(decoded.getAppId()).isEqualTo(appId); assertThat(decoded.getAppName()).isEqualTo(McpAppConstants.MCP_APP_NAME); assertThat(decoded.getToolName()).isEqualTo("search_metadata"); assertThat(decoded.getUserName()).isEqualTo("alice"); @@ -85,6 +100,8 @@ void recordWritesUsageRowWithMcpIdentity() { */ @Test void serializedJsonContainsGeneratedColumnFieldNames() { + stubMcpApp(UUID.randomUUID(), McpAppConstants.MCP_APP_NAME); + McpUsageRecorder.record("any_tool", "alice", true); ArgumentCaptor json = ArgumentCaptor.forClass(String.class); @@ -96,8 +113,18 @@ void serializedJsonContainsGeneratedColumnFieldNames() { assertThat(raw).contains("\"extension\":\"limits\""); } + @Test + void recordSkipsWhenMcpApplicationNotInitialized() { + when(appContext.getAppIfExists(McpAppConstants.MCP_APP_NAME)).thenReturn(null); + + McpUsageRecorder.record("any_tool", "alice", true); + + verify(dao, never()).insert(anyString(), anyString()); + } + @Test void recordSwallowsDaoException() { + stubMcpApp(UUID.randomUUID(), McpAppConstants.MCP_APP_NAME); doThrow(new RuntimeException("db down")).when(dao).insert(anyString(), eq("limits")); McpUsageRecorder.record("create_glossary", "alice", false); @@ -107,6 +134,8 @@ void recordSwallowsDaoException() { @Test void recordCapturesFailureFlag() { + stubMcpApp(UUID.randomUUID(), McpAppConstants.MCP_APP_NAME); + McpUsageRecorder.record("patch_entity", "bob", false); ArgumentCaptor json = ArgumentCaptor.forClass(String.class); @@ -117,6 +146,8 @@ void recordCapturesFailureFlag() { @Test void recordCapturesPhase3Metadata() { + stubMcpApp(UUID.randomUUID(), McpAppConstants.MCP_APP_NAME); + McpUsageRecorder.record( "create_glossary", "bob", @@ -135,6 +166,8 @@ void recordCapturesPhase3Metadata() { @Test void legacy3ArgOverloadOmitsPhase3Fields() { + stubMcpApp(UUID.randomUUID(), McpAppConstants.MCP_APP_NAME); + McpUsageRecorder.record("search_metadata", "alice", true); ArgumentCaptor json = ArgumentCaptor.forClass(String.class); @@ -144,4 +177,11 @@ void legacy3ArgOverloadOmitsPhase3Fields() { assertThat(decoded.getErrorCategory()).isNull(); assertThat(decoded.getClientName()).isNull(); } + + private void stubMcpApp(UUID appId, String appName) { + AbstractNativeApplication nativeApp = mock(AbstractNativeApplication.class); + App app = new App().withId(appId).withName(appName); + when(nativeApp.getApp()).thenReturn(app); + when(appContext.getAppIfExists(appName)).thenReturn(nativeApp); + } } diff --git a/openmetadata-sdk/pom.xml b/openmetadata-sdk/pom.xml index 066eb20c8b03..27607ef8a4f5 100644 --- a/openmetadata-sdk/pom.xml +++ b/openmetadata-sdk/pom.xml @@ -129,7 +129,7 @@ org.eclipse.parsson parsson - 1.1.7 + 1.1.8 true diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java index 17d7a9952be6..7a86f422831e 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java @@ -70,6 +70,7 @@ import org.openmetadata.sdk.services.storages.FileService; import org.openmetadata.sdk.services.storages.SpreadsheetService; import org.openmetadata.sdk.services.storages.WorksheetService; +import org.openmetadata.sdk.services.system.SystemSettingsService; import org.openmetadata.sdk.services.tasks.TaskService; import org.openmetadata.sdk.services.teams.PersonaService; import org.openmetadata.sdk.services.teams.RoleService; @@ -130,6 +131,9 @@ public class OpenMetadataClient { private final GlossaryService glossaries; private final GlossaryTermService glossaryTerms; + // System settings + private final SystemSettingsService settings; + // Classification private final ClassificationService classifications; private final TagService tags; @@ -252,6 +256,7 @@ public OpenMetadataClient(OpenMetadataConfig config) { // Initialize glossary services this.glossaries = new GlossaryService(httpClient); this.glossaryTerms = new GlossaryTermService(httpClient); + this.settings = new SystemSettingsService(httpClient); // Initialize classification services this.classifications = new ClassificationService(httpClient); @@ -459,6 +464,10 @@ public GlossaryTermService glossaryTerms() { return glossaryTerms; } + public SystemSettingsService settings() { + return settings; + } + // Classification Service Getters public ClassificationService classifications() { return classifications; diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/fluent/GlossaryTerms.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/fluent/GlossaryTerms.java index c40dcc496db7..2ce504948ee6 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/fluent/GlossaryTerms.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/fluent/GlossaryTerms.java @@ -232,6 +232,10 @@ public org.openmetadata.sdk.fluent.common.EntityRestorer restore() return new org.openmetadata.sdk.fluent.common.EntityRestorer<>( client.glossaryTerms(), identifier); } + + public GlossaryTermRelator relateTo(String toTermIdentifier) { + return new GlossaryTermRelator(client, identifier, isFqn, toTermIdentifier); + } } // ==================== Deleter ==================== @@ -265,6 +269,62 @@ public void confirm() { } } + // ==================== Relator ==================== + + /** + * Fluent builder for adding a typed relation from one glossary term to another. Both endpoints + * accept either a UUID or a fully-qualified name. + * + *

+   * GlossaryTerms.find(hcpId).relateTo(drugFqn).as("prescribes").apply();
+   * 
+ */ + public static class GlossaryTermRelator { + private static final String DEFAULT_RELATION_TYPE = "relatedTo"; + + private final OpenMetadataClient client; + private final String fromIdentifier; + private final boolean fromIsFqn; + private final String toIdentifier; + private String relationType = DEFAULT_RELATION_TYPE; + + GlossaryTermRelator( + OpenMetadataClient client, String fromIdentifier, boolean fromIsFqn, String toIdentifier) { + this.client = client; + this.fromIdentifier = fromIdentifier; + this.fromIsFqn = fromIsFqn; + this.toIdentifier = toIdentifier; + } + + public GlossaryTermRelator as(String relationType) { + this.relationType = relationType; + return this; + } + + public GlossaryTerm apply() { + UUID fromId = resolve(fromIdentifier, fromIsFqn); + UUID toId = resolve(toIdentifier, !isUuid(toIdentifier)); + return client.glossaryTerms().addRelation(fromId, toId, relationType); + } + + private UUID resolve(String identifier, boolean isFqn) { + return isFqn + ? client.glossaryTerms().getByName(identifier).getId() + : UUID.fromString(identifier); + } + + private boolean isUuid(String value) { + boolean result; + try { + UUID.fromString(value); + result = true; + } catch (IllegalArgumentException notAUuid) { + result = false; + } + return result; + } + } + // ==================== Lister ==================== public static class GlossaryTermLister { diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/glossary/GlossaryTermService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/glossary/GlossaryTermService.java index 5a687df1f4c5..ebce79512e1f 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/glossary/GlossaryTermService.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/glossary/GlossaryTermService.java @@ -1,13 +1,23 @@ package org.openmetadata.sdk.services.glossary; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.util.List; +import java.util.Map; +import java.util.UUID; import org.openmetadata.schema.api.data.CreateGlossaryTerm; import org.openmetadata.schema.entity.data.GlossaryTerm; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.TermRelation; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.network.HttpClient; import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; import org.openmetadata.sdk.services.EntityServiceBase; public class GlossaryTermService extends EntityServiceBase { + private static final String GLOSSARY_TERM = "glossaryTerm"; + public GlossaryTermService(HttpClient httpClient) { super(httpClient, "/v1/glossaryTerms"); } @@ -17,8 +27,92 @@ protected Class getEntityClass() { return GlossaryTerm.class; } - // Create glossaryterm using CreateGlossaryTerm request public GlossaryTerm create(CreateGlossaryTerm request) throws OpenMetadataException { return httpClient.execute(HttpMethod.POST, basePath, request, GlossaryTerm.class); } + + /** + * Add a typed relation from one glossary term to another (e.g. {@code broader}, {@code narrower}, + * {@code synonym}, or a custom type registered via {@link + * org.openmetadata.sdk.services.system.SystemSettingsService#defineGlossaryRelationType}). + * + * @param id the source glossary term id + * @param relation the relation to add (target term reference + relation type) + * @return the updated source glossary term + */ + public GlossaryTerm addRelation(UUID id, TermRelation relation) throws OpenMetadataException { + return httpClient.execute( + HttpMethod.POST, basePath + "/" + id + "/relations", relation, GlossaryTerm.class); + } + + /** Convenience overload that builds the {@link TermRelation} from ids and a relation type. */ + public GlossaryTerm addRelation(UUID fromId, UUID toId, String relationType) + throws OpenMetadataException { + TermRelation relation = + new TermRelation() + .withRelationType(relationType) + .withTerm(new EntityReference().withId(toId).withType(GLOSSARY_TERM)); + return addRelation(fromId, relation); + } + + /** + * Remove a relation from one glossary term to another. + * + * @param id the source glossary term id + * @param toTermId the target glossary term id + * @param relationType the relation type to remove, or {@code null} to remove all types + * @return the updated source glossary term + */ + public GlossaryTerm removeRelation(UUID id, UUID toTermId, String relationType) + throws OpenMetadataException { + RequestOptions options = + relationType != null + ? RequestOptions.builder().queryParam("relationType", relationType).build() + : null; + return httpClient.execute( + HttpMethod.DELETE, + basePath + "/" + id + "/relations/" + toTermId, + null, + GlossaryTerm.class, + options); + } + + /** + * Fetch the relation graph rooted at a glossary term. + * + * @param id the root glossary term id + * @param depth traversal depth (1-5) + * @param relationTypes relation types to include, or {@code null}/empty for all + * @return a map with {@code nodes} and {@code edges} entries + */ + public Map relationGraph(UUID id, int depth, List relationTypes) + throws OpenMetadataException { + RequestOptions.Builder options = + RequestOptions.builder().queryParam("depth", String.valueOf(depth)); + if (relationTypes != null && !relationTypes.isEmpty()) { + options.queryParam("relationTypes", String.join(",", relationTypes)); + } + String response = + httpClient.executeForString( + HttpMethod.GET, basePath + "/" + id + "/relationsGraph", null, options.build()); + return deserialize(response, new TypeReference>() {}); + } + + /** Return per-relation-type usage counts across all glossary terms. */ + public Map relationTypeUsage() throws OpenMetadataException { + String response = + httpClient.executeForString(HttpMethod.GET, basePath + "/relationTypes/usage", null); + return deserialize(response, new TypeReference>() {}); + } + + private R deserialize(String json, TypeReference type) throws OpenMetadataException { + R result; + try { + result = objectMapper.readValue(json, type); + } catch (JsonProcessingException e) { + throw new OpenMetadataException( + "Failed to parse glossary term relations response: " + e.getMessage(), e); + } + return result; + } } diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/system/SystemSettingsService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/system/SystemSettingsService.java new file mode 100644 index 000000000000..381aa049233c --- /dev/null +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/system/SystemSettingsService.java @@ -0,0 +1,204 @@ +package org.openmetadata.sdk.services.system; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; +import org.openmetadata.schema.configuration.GlossaryTermRelationType; +import org.openmetadata.schema.settings.Settings; +import org.openmetadata.schema.settings.SettingsType; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpClient; +import org.openmetadata.sdk.network.HttpMethod; + +/** + * Client limited to glossary term relation settings. + * + *

Type registration preserves the server's missing, null, or array representation and + * reconciles a fresh snapshot after a rejected concurrent update. This service never reads or + * writes another system setting type. + */ +public class SystemSettingsService { + private static final int MAX_REGISTRATION_ATTEMPTS = 3; + private static final String SETTINGS_BASE = "/v1/system/settings"; + private static final String RELATION_TYPES_PATH = "/relationTypes"; + private static final String RELATION_TYPES_APPEND_PATH = "/relationTypes/-"; + + private final HttpClient httpClient; + private final ObjectMapper objectMapper; + + public SystemSettingsService(HttpClient httpClient) { + this.httpClient = httpClient; + this.objectMapper = new ObjectMapper(); + } + + /** Return only the glossary term relation configuration. */ + public GlossaryTermRelationSettings getGlossaryRelationSettings() throws OpenMetadataException { + return toRelationConfig(getGlossaryRelationSettingsEnvelope()); + } + + public List glossaryRelationTypes() throws OpenMetadataException { + List types = getGlossaryRelationSettings().getRelationTypes(); + return types != null ? types : List.of(); + } + + /** + * Register a glossary term relation type while preserving the current {@code relationTypes} + * representation. A 400 or 422 response is reconciled once, but retries only when the error + * identifies a failed JSON-Patch {@code test} operation. Explicit 409 or 412 precondition + * failures may retry from a fresh snapshot. A concurrently registered matching name becomes an + * idempotent no-op. + * + * @param relationType the relation type to register + * @return only the updated glossary relation configuration, or the current configuration if the + * name already existed + */ + public GlossaryTermRelationSettings defineGlossaryRelationType( + GlossaryTermRelationType relationType) throws OpenMetadataException { + int attempts = 0; + Settings current = getGlossaryRelationSettingsEnvelope(); + RelationTypesSnapshot snapshot = relationTypesSnapshot(current); + while (true) { + if (relationTypeExists(snapshot.relationTypes(), relationType.getName())) { + return toRelationConfig(current); + } + try { + return appendRelationType(relationType, snapshot); + } catch (OpenMetadataException exception) { + int statusCode = exception.getStatusCode(); + if (!shouldReconcileRegistrationFailure(statusCode)) { + throw exception; + } + Settings latest = getGlossaryRelationSettingsEnvelope(); + RelationTypesSnapshot latestSnapshot = relationTypesSnapshot(latest); + if (relationTypeExists(latestSnapshot.relationTypes(), relationType.getName())) { + return toRelationConfig(latest); + } + if (!isRetryableRegistrationFailure(exception, statusCode) + || hasSamePatchState(snapshot, latestSnapshot)) { + throw exception; + } + attempts++; + if (attempts >= MAX_REGISTRATION_ATTEMPTS) { + throw exception; + } + current = latest; + snapshot = latestSnapshot; + } + } + } + + private GlossaryTermRelationSettings appendRelationType( + GlossaryTermRelationType relationType, RelationTypesSnapshot snapshot) + throws OpenMetadataException { + ArrayNode patch = objectMapper.createArrayNode(); + JsonNode relationTypeValue = objectMapper.valueToTree(relationType); + if (!snapshot.present()) { + addOperation(patch, "test", "", snapshot.config()); + addOperation( + patch, "add", RELATION_TYPES_PATH, objectMapper.createArrayNode().add(relationTypeValue)); + } else if (snapshot.patchValue().isNull()) { + addOperation(patch, "test", RELATION_TYPES_PATH, snapshot.patchValue()); + addOperation( + patch, + "replace", + RELATION_TYPES_PATH, + objectMapper.createArrayNode().add(relationTypeValue)); + } else { + addOperation(patch, "test", RELATION_TYPES_PATH, snapshot.patchValue()); + addOperation(patch, "add", RELATION_TYPES_APPEND_PATH, relationTypeValue); + } + Settings updated = + httpClient.execute( + HttpMethod.PATCH, + SETTINGS_BASE + "/" + glossaryRelationSettingsKey(), + patch, + Settings.class); + return toRelationConfig(updated); + } + + private void addOperation(ArrayNode patch, String op, String path, JsonNode value) { + ObjectNode operation = patch.addObject(); + operation.put("op", op); + operation.put("path", path); + operation.set("value", value); + } + + private RelationTypesSnapshot relationTypesSnapshot(Settings settings) { + JsonNode config = objectMapper.valueToTree(settings.getConfigValue()); + if (!config.isObject()) { + throw new OpenMetadataException("glossary relation settings must be a JSON object"); + } + JsonNode relationTypes = config.get("relationTypes"); + boolean present = config.has("relationTypes"); + if (present && !relationTypes.isNull() && !relationTypes.isArray()) { + throw new OpenMetadataException("glossary relationTypes must be an array, null, or absent"); + } + List types = toRelationConfig(settings).getRelationTypes(); + return new RelationTypesSnapshot( + types != null ? types : List.of(), relationTypes, config, present); + } + + private boolean shouldReconcileRegistrationFailure(int statusCode) { + return statusCode == 400 || statusCode == 409 || statusCode == 412 || statusCode == 422; + } + + private boolean isRetryableRegistrationFailure(OpenMetadataException exception, int statusCode) { + if (statusCode == 409 || statusCode == 412) { + return true; + } + if (statusCode != 400 && statusCode != 422) { + return false; + } + String message = exception.getMessage(); + if (message == null) { + return false; + } + String normalizedMessage = message.toLowerCase(Locale.ROOT); + boolean identifiesTestOperation = + normalizedMessage.contains("operation 'test'") + || normalizedMessage.contains("operation \"test\"") + || normalizedMessage.contains("test operation") + || normalizedMessage.contains("json patch test"); + return identifiesTestOperation + && (normalizedMessage.contains("fail") + || normalizedMessage.contains("mismatch") + || normalizedMessage.contains("did not match")); + } + + private boolean hasSamePatchState(RelationTypesSnapshot first, RelationTypesSnapshot second) { + if (first.present() != second.present()) { + return false; + } + return first.present() + ? Objects.equals(first.patchValue(), second.patchValue()) + : Objects.equals(first.config(), second.config()); + } + + private boolean relationTypeExists(List types, String name) { + return types.stream().anyMatch(type -> Objects.equals(type.getName(), name)); + } + + private Settings getGlossaryRelationSettingsEnvelope() throws OpenMetadataException { + return httpClient.execute( + HttpMethod.GET, SETTINGS_BASE + "/" + glossaryRelationSettingsKey(), null, Settings.class); + } + + private GlossaryTermRelationSettings toRelationConfig(Settings settings) { + return objectMapper.convertValue(settings.getConfigValue(), GlossaryTermRelationSettings.class); + } + + private String glossaryRelationSettingsKey() { + return SettingsType.GLOSSARY_TERM_RELATION_SETTINGS.value(); + } + + private record RelationTypesSnapshot( + List relationTypes, + JsonNode patchValue, + JsonNode config, + boolean present) {} +} diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tasks/TaskService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tasks/TaskService.java index ce6ab8cff4b2..dbe65d733317 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tasks/TaskService.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tasks/TaskService.java @@ -233,6 +233,82 @@ public ListResponse listVisible( return deserializeListResponse(responseStr); } + private ListResponse listScopedTasks( + String path, + TaskEntityStatus status, + String statusGroup, + String domain, + String fields, + Integer limit, + Long startTs, + Long endTs) + throws OpenMetadataException { + RequestOptions.Builder optionsBuilder = RequestOptions.builder(); + if (status != null) { + optionsBuilder.queryParam("status", status.value()); + } + if (statusGroup != null) { + optionsBuilder.queryParam("statusGroup", statusGroup); + } + if (domain != null) { + optionsBuilder.queryParam("domain", domain); + } + if (fields != null) { + optionsBuilder.queryParam("fields", fields); + } + if (limit != null) { + optionsBuilder.queryParam("limit", limit.toString()); + } + if (startTs != null) { + optionsBuilder.queryParam("startTs", startTs.toString()); + } + if (endTs != null) { + optionsBuilder.queryParam("endTs", endTs.toString()); + } + String responseStr = + httpClient.executeForString(HttpMethod.GET, path, null, optionsBuilder.build()); + return deserializeListResponse(responseStr); + } + + public ListResponse listVisible( + TaskEntityStatus status, + String statusGroup, + String domain, + String fields, + Integer limit, + Long startTs, + Long endTs) + throws OpenMetadataException { + return listScopedTasks( + basePath + "/visible", status, statusGroup, domain, fields, limit, startTs, endTs); + } + + public ListResponse listOwned( + TaskEntityStatus status, + String statusGroup, + String domain, + String fields, + Integer limit, + Long startTs, + Long endTs) + throws OpenMetadataException { + return listScopedTasks( + basePath + "/owned", status, statusGroup, domain, fields, limit, startTs, endTs); + } + + public ListResponse listCreated( + TaskEntityStatus status, + String statusGroup, + String domain, + String fields, + Integer limit, + Long startTs, + Long endTs) + throws OpenMetadataException { + return listScopedTasks( + basePath + "/created", status, statusGroup, domain, fields, limit, startTs, endTs); + } + /** * List Data Access Requests with DAR-specific filters and offset-based pagination. * Pre-applies category=DataAccess and type=DataAccessRequest server-side. diff --git a/openmetadata-sdk/src/test/java/org/openmetadata/sdk/services/GlossaryTermRelationsMockTest.java b/openmetadata-sdk/src/test/java/org/openmetadata/sdk/services/GlossaryTermRelationsMockTest.java new file mode 100644 index 000000000000..346da4801984 --- /dev/null +++ b/openmetadata-sdk/src/test/java/org/openmetadata/sdk/services/GlossaryTermRelationsMockTest.java @@ -0,0 +1,419 @@ +package org.openmetadata.sdk.services; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; +import org.openmetadata.schema.configuration.GlossaryTermRelationType; +import org.openmetadata.schema.entity.data.GlossaryTerm; +import org.openmetadata.schema.settings.Settings; +import org.openmetadata.schema.settings.SettingsType; +import org.openmetadata.schema.type.TermRelation; +import org.openmetadata.sdk.exceptions.ApiException; +import org.openmetadata.sdk.exceptions.InvalidRequestException; +import org.openmetadata.sdk.network.HttpClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.sdk.services.glossary.GlossaryTermService; +import org.openmetadata.sdk.services.system.SystemSettingsService; + +/** + * Mock tests for the glossary term relations + system settings SDK surface. The {@link HttpClient} + * boundary is mocked so the tests assert the real URL, HTTP method, payload shape, and idempotency + * logic the SDK constructs. + */ +class GlossaryTermRelationsMockTest { + + private HttpClient httpClient; + private GlossaryTermService glossaryTerms; + private SystemSettingsService settings; + + @BeforeEach + void setUp() { + httpClient = mock(HttpClient.class); + glossaryTerms = new GlossaryTermService(httpClient); + settings = new SystemSettingsService(httpClient); + } + + @Test + void addRelationPostsTypedRelation() { + UUID fromId = UUID.randomUUID(); + UUID toId = UUID.randomUUID(); + GlossaryTerm updated = new GlossaryTerm(); + when(httpClient.execute(eq(HttpMethod.POST), anyString(), any(), eq(GlossaryTerm.class))) + .thenReturn(updated); + + GlossaryTerm result = glossaryTerms.addRelation(fromId, toId, "prescribes"); + + assertSame(updated, result); + ArgumentCaptor path = ArgumentCaptor.forClass(String.class); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(httpClient) + .execute(eq(HttpMethod.POST), path.capture(), body.capture(), eq(GlossaryTerm.class)); + assertEquals("/v1/glossaryTerms/" + fromId + "/relations", path.getValue()); + TermRelation sent = (TermRelation) body.getValue(); + assertEquals("prescribes", sent.getRelationType()); + assertEquals(toId, sent.getTerm().getId()); + assertEquals("glossaryTerm", sent.getTerm().getType()); + } + + @Test + void removeRelationDeletesWithRelationTypeQueryParam() { + UUID fromId = UUID.randomUUID(); + UUID toId = UUID.randomUUID(); + when(httpClient.execute( + eq(HttpMethod.DELETE), anyString(), isNull(), eq(GlossaryTerm.class), any())) + .thenReturn(new GlossaryTerm()); + + glossaryTerms.removeRelation(fromId, toId, "prescribes"); + + ArgumentCaptor path = ArgumentCaptor.forClass(String.class); + ArgumentCaptor options = ArgumentCaptor.forClass(RequestOptions.class); + verify(httpClient) + .execute( + eq(HttpMethod.DELETE), + path.capture(), + isNull(), + eq(GlossaryTerm.class), + options.capture()); + assertEquals("/v1/glossaryTerms/" + fromId + "/relations/" + toId, path.getValue()); + assertEquals("prescribes", options.getValue().getQueryParams().get("relationType")); + } + + @Test + void relationGraphParsesNodesAndEdges() { + UUID id = UUID.randomUUID(); + when(httpClient.executeForString( + eq(HttpMethod.GET), anyString(), isNull(), any(RequestOptions.class))) + .thenReturn("{\"nodes\":[{\"id\":\"a\"}],\"edges\":[]}"); + + Map graph = glossaryTerms.relationGraph(id, 2, List.of("prescribes")); + + assertTrue(graph.containsKey("nodes")); + assertTrue(graph.containsKey("edges")); + } + + @Test + void relationTypeUsageParsesCounts() { + when(httpClient.executeForString( + eq(HttpMethod.GET), eq("/v1/glossaryTerms/relationTypes/usage"), isNull())) + .thenReturn("{\"prescribes\":3,\"synonym\":5}"); + + Map usage = glossaryTerms.relationTypeUsage(); + + assertEquals(3, usage.get("prescribes")); + assertEquals(5, usage.get("synonym")); + } + + @Test + void getGlossaryRelationSettingsReturnsOnlyRelationConfiguration() { + GlossaryTermRelationSettings relationConfiguration = + new GlossaryTermRelationSettings() + .withRelationTypes(List.of(new GlossaryTermRelationType().withName("prescribes"))); + Settings response = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(relationConfiguration); + when(httpClient.execute( + eq(HttpMethod.GET), + eq("/v1/system/settings/glossaryTermRelationSettings"), + isNull(), + eq(Settings.class))) + .thenReturn(response); + + GlossaryTermRelationSettings result = settings.getGlossaryRelationSettings(); + + assertEquals("prescribes", result.getRelationTypes().get(0).getName()); + verify(httpClient) + .execute( + eq(HttpMethod.GET), + eq("/v1/system/settings/glossaryTermRelationSettings"), + isNull(), + eq(Settings.class)); + } + + @Test + void defineGlossaryRelationTypeAppendsWhenAbsent() { + Settings current = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(new GlossaryTermRelationSettings().withRelationTypes(List.of())); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(current); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenReturn(current); + + settings.defineGlossaryRelationType(new GlossaryTermRelationType().withName("prescribes")); + + ArgumentCaptor patch = ArgumentCaptor.forClass(Object.class); + verify(httpClient) + .execute(eq(HttpMethod.PATCH), anyString(), patch.capture(), eq(Settings.class)); + ObjectNode precondition = (ObjectNode) ((ArrayNode) patch.getValue()).get(0); + assertEquals("test", precondition.get("op").asText()); + assertEquals("/relationTypes", precondition.get("path").asText()); + assertTrue(precondition.get("value").isArray()); + assertTrue(precondition.get("value").isEmpty()); + ObjectNode operation = (ObjectNode) ((ArrayNode) patch.getValue()).get(1); + assertEquals("add", operation.get("op").asText()); + assertEquals("/relationTypes/-", operation.get("path").asText()); + assertEquals("prescribes", operation.get("value").get("name").asText()); + } + + @Test + void defineGlossaryRelationTypeSkipsWhenPresent() { + Settings current = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue( + new GlossaryTermRelationSettings() + .withRelationTypes( + List.of(new GlossaryTermRelationType().withName("prescribes")))); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(current); + + GlossaryTermRelationSettings result = + settings.defineGlossaryRelationType(new GlossaryTermRelationType().withName("prescribes")); + + assertEquals("prescribes", result.getRelationTypes().get(0).getName()); + verify(httpClient, never()) + .execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class)); + } + + @Test + void defineGlossaryRelationTypeInitializesNullRelationTypes() { + Map config = new HashMap<>(); + config.put("relationTypes", null); + Settings current = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(config); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(current); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenReturn(current); + + settings.defineGlossaryRelationType(new GlossaryTermRelationType().withName("prescribes")); + + ArgumentCaptor patch = ArgumentCaptor.forClass(Object.class); + verify(httpClient) + .execute(eq(HttpMethod.PATCH), anyString(), patch.capture(), eq(Settings.class)); + ArrayNode operations = (ArrayNode) patch.getValue(); + assertEquals("test", operations.get(0).get("op").asText()); + assertTrue(operations.get(0).get("value").isNull()); + assertEquals("replace", operations.get(1).get("op").asText()); + assertEquals("/relationTypes", operations.get(1).get("path").asText()); + assertEquals("prescribes", operations.get(1).get("value").get(0).get("name").asText()); + } + + @Test + void defineGlossaryRelationTypeInitializesAbsentRelationTypes() { + Settings current = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(Map.of()); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(current); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenReturn(current); + + settings.defineGlossaryRelationType(new GlossaryTermRelationType().withName("prescribes")); + + ArgumentCaptor patch = ArgumentCaptor.forClass(Object.class); + verify(httpClient) + .execute(eq(HttpMethod.PATCH), anyString(), patch.capture(), eq(Settings.class)); + ArrayNode operations = (ArrayNode) patch.getValue(); + assertEquals(2, operations.size()); + assertEquals("test", operations.get(0).get("op").asText()); + assertEquals("", operations.get(0).get("path").asText()); + assertTrue(operations.get(0).get("value").isObject()); + assertTrue(operations.get(0).get("value").isEmpty()); + assertEquals("add", operations.get(1).get("op").asText()); + assertEquals("/relationTypes", operations.get(1).get("path").asText()); + assertEquals("prescribes", operations.get(1).get("value").get(0).get("name").asText()); + } + + @Test + void defineGlossaryRelationTypeRetriesAbsentInitializationAfterBadRequestTestFailure() { + assertAbsentInitializationRetriesAfterTestFailure(400); + } + + @Test + void defineGlossaryRelationTypeRetriesAbsentInitializationAfterUnprocessableTestFailure() { + assertAbsentInitializationRetriesAfterTestFailure(422); + } + + private void assertAbsentInitializationRetriesAfterTestFailure(int statusCode) { + Settings initial = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(Map.of()); + Settings latest = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue( + new GlossaryTermRelationSettings() + .withRelationTypes(List.of(new GlossaryTermRelationType().withName("treats")))); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(initial, latest); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenThrow( + new ApiException("The JSON Patch operation 'test' failed for path ''", statusCode)) + .thenReturn(latest); + + GlossaryTermRelationSettings result = + settings.defineGlossaryRelationType(new GlossaryTermRelationType().withName("prescribes")); + + assertEquals("treats", result.getRelationTypes().get(0).getName()); + ArgumentCaptor patches = ArgumentCaptor.forClass(Object.class); + verify(httpClient, times(2)) + .execute(eq(HttpMethod.PATCH), anyString(), patches.capture(), eq(Settings.class)); + ArrayNode initialPatch = (ArrayNode) patches.getAllValues().get(0); + assertEquals("test", initialPatch.get(0).get("op").asText()); + assertEquals("", initialPatch.get(0).get("path").asText()); + ArrayNode retryPatch = (ArrayNode) patches.getAllValues().get(1); + assertEquals("test", retryPatch.get(0).get("op").asText()); + assertEquals("/relationTypes", retryPatch.get(0).get("path").asText()); + assertEquals("treats", retryPatch.get(0).get("value").get(0).get("name").asText()); + } + + @Test + void defineGlossaryRelationTypeRechecksAfterConcurrentRegistration() { + Settings absent = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(new GlossaryTermRelationSettings().withRelationTypes(List.of())); + Settings present = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue( + new GlossaryTermRelationSettings() + .withRelationTypes( + List.of(new GlossaryTermRelationType().withName("prescribes")))); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(absent, present); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenThrow(new ApiException("unprocessable settings patch", 422)); + + GlossaryTermRelationSettings result = + settings.defineGlossaryRelationType(new GlossaryTermRelationType().withName("prescribes")); + + assertEquals("prescribes", result.getRelationTypes().get(0).getName()); + verify(httpClient, times(2)) + .execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class)); + verify(httpClient).execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class)); + } + + @Test + void defineGlossaryRelationTypeRetriesOnlyAfterSnapshotChanges() { + Settings initial = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(new GlossaryTermRelationSettings().withRelationTypes(List.of())); + Map existingType = new HashMap<>(); + existingType.put("name", "treats"); + existingType.put("description", null); + Settings latest = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(Map.of("relationTypes", List.of(existingType))); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(initial, latest); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenThrow(new ApiException("precondition failed", 412)) + .thenReturn(latest); + + GlossaryTermRelationSettings result = + settings.defineGlossaryRelationType(new GlossaryTermRelationType().withName("prescribes")); + + assertEquals("treats", result.getRelationTypes().get(0).getName()); + ArgumentCaptor patches = ArgumentCaptor.forClass(Object.class); + verify(httpClient, times(2)) + .execute(eq(HttpMethod.PATCH), anyString(), patches.capture(), eq(Settings.class)); + ArrayNode retryPatch = (ArrayNode) patches.getAllValues().get(1); + assertEquals("treats", retryPatch.get(0).get("value").get(0).get("name").asText()); + assertTrue(retryPatch.get(0).get("value").get(0).get("description").isNull()); + } + + @Test + void defineGlossaryRelationTypeDoesNotRetryUnrelatedBadRequest() { + Settings initial = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(new GlossaryTermRelationSettings().withRelationTypes(List.of())); + Settings latest = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue( + new GlossaryTermRelationSettings() + .withRelationTypes(List.of(new GlossaryTermRelationType().withName("treats")))); + InvalidRequestException failure = + new InvalidRequestException("relation type test failed validation"); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(initial, latest); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenThrow(failure); + + InvalidRequestException thrown = + assertThrows( + InvalidRequestException.class, + () -> + settings.defineGlossaryRelationType( + new GlossaryTermRelationType().withName("prescribes"))); + + assertSame(failure, thrown); + verify(httpClient, times(2)) + .execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class)); + verify(httpClient).execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class)); + } + + @Test + void defineGlossaryRelationTypeDoesNotRetryUnrelatedUnprocessablePatch() { + Settings initial = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(new GlossaryTermRelationSettings().withRelationTypes(List.of())); + Settings latest = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue( + new GlossaryTermRelationSettings() + .withRelationTypes(List.of(new GlossaryTermRelationType().withName("treats")))); + ApiException failure = new ApiException("relation type test failed validation", 422); + when(httpClient.execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class))) + .thenReturn(initial, latest); + when(httpClient.execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class))) + .thenThrow(failure); + + ApiException thrown = + assertThrows( + ApiException.class, + () -> + settings.defineGlossaryRelationType( + new GlossaryTermRelationType().withName("prescribes"))); + + assertSame(failure, thrown); + verify(httpClient, times(2)) + .execute(eq(HttpMethod.GET), anyString(), isNull(), eq(Settings.class)); + verify(httpClient).execute(eq(HttpMethod.PATCH), anyString(), any(), eq(Settings.class)); + } +} diff --git a/openmetadata-service/pom.xml b/openmetadata-service/pom.xml index 38ce84097ca0..9a751014e170 100644 --- a/openmetadata-service/pom.xml +++ b/openmetadata-service/pom.xml @@ -26,8 +26,8 @@ 2.1.1 2.5.2 12.1.7 - 1.5.25 - 1.5.25 + 1.5.36 + 1.5.36 2.3.0 24.0.0 3.2.3 @@ -864,10 +864,12 @@ ${quartz.version} + com.mchange c3p0 - 0.12.0 + 0.14.1 com.fasterxml.woodstox @@ -1014,7 +1016,7 @@ org.eclipse.parsson parsson - 1.1.5 + 1.1.8 javax.servlet @@ -1059,7 +1061,7 @@ org.apache.calcite calcite-core - 1.36.0 + 1.42.0 commons-lang diff --git a/openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java b/openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java index 9c1199a29557..fe2765966150 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java +++ b/openmetadata-service/src/main/java/org/openmetadata/csv/CsvUtil.java @@ -339,10 +339,14 @@ public static void addOwners(List csvRecord, List owner } public static void addDomains(List csvRecord, List domains) { + List directDomains = + listOrEmpty(domains).stream() + .filter(domain -> !Boolean.TRUE.equals(domain.getInherited())) + .toList(); csvRecord.add( - nullOrEmpty(domains) + nullOrEmpty(directDomains) ? null - : domains.stream() + : directDomains.stream() .map(EntityReference::getFullyQualifiedName) .collect(Collectors.joining(FIELD_SEPARATOR))); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java b/openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java index d0ed857153d3..5913bfaf8002 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java +++ b/openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java @@ -422,6 +422,53 @@ public List getDomains( return refs; } + /** + * An empty domain column clears direct domains (unchanged behavior) but must not wipe the + * entity's inherited domains: they are never exported to the CSV, and rules such as "Data Product + * Domain Validation" need them to evaluate the entity's effective domain. So on an empty column + * only the inherited references from the already-loaded entity are carried over; they are dropped + * again after rule evaluation (see {@link #dropInheritedDomains}), so they are never persisted as + * a direct domain. + */ + public List getDomains( + CSVPrinter printer, + CSVRecord csvRecord, + int fieldNumber, + List existingDomains) { + List result = null; + if (processRecord) { + List parsedFromCsv = getDomains(printer, csvRecord, fieldNumber); + result = parsedFromCsv; + if (parsedFromCsv == null) { + List inheritedDomains = + listOrEmpty(existingDomains).stream() + .filter(domain -> Boolean.TRUE.equals(domain.getInherited())) + .toList(); + result = inheritedDomains.isEmpty() ? null : inheritedDomains; + } + } + return result; + } + + /** + * Inherited domains are supplied to an updated entity only so platform rules evaluate against its + * effective domain. The import persistence path stores whatever domains the entity carries as + * direct relationships, so the inherited ones must be removed once the rules have run; the entity + * keeps re-inheriting from its parent on read. + */ + private void dropInheritedDomains(EntityInterface entity) { + List domains = entity.getDomains(); + if (!nullOrEmpty(domains)) { + List directDomains = new ArrayList<>(); + for (EntityReference domain : domains) { + if (!Boolean.TRUE.equals(domain.getInherited())) { + directDomains.add(domain); + } + } + entity.setDomains(directDomains.isEmpty() ? null : directDomains); + } + } + /** Owner field is in entityName format */ public EntityReference getOwnerAsUser(CSVPrinter printer, CSVRecord csvRecord, int fieldNumber) { if (!processRecord) { @@ -1079,6 +1126,7 @@ protected void createEntity(CSVPrinter resultsPrinter, CSVRecord csvRecord, T en } else { RuleEngine.getInstance().evaluate(entity); } + dropInheritedDomains(entity); if (Boolean.FALSE.equals(importResult.getDryRun())) { // If not dry run, create the entity if (isUpdate) { @@ -1172,6 +1220,7 @@ protected void createEntity( } else { RuleEngine.getInstance().evaluate(entity); } + dropInheritedDomains(entity); if (Boolean.FALSE.equals(importResult.getDryRun())) { if (isUpdate) { @@ -1583,7 +1632,7 @@ protected void createSchemaEntity(CSVPrinter printer, CSVRecord csvRecord, Strin try { schema = Entity.getEntityByNameWithExcludedFields( - DATABASE_SCHEMA, schemaFqn, "owners,tags,domains,extension", Include.NON_DELETED); + DATABASE_SCHEMA, schemaFqn, "owners,tags,extension", Include.NON_DELETED); } catch (Exception ex) { LOG.warn("Database Schema not found: {}, it will be created with Import.", schemaFqn); schema = @@ -1615,7 +1664,7 @@ protected void createSchemaEntity(CSVPrinter printer, CSVRecord csvRecord, Strin .withCertification(certification) .withRetentionPeriod(csvRecord.get(8)) .withSourceUrl(csvRecord.get(9)) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, schema.getDomains())) .withExtension(getExtension(printer, csvRecord, 11)) .withUpdatedAt(System.currentTimeMillis()) .withUpdatedBy(importedBy); @@ -1677,7 +1726,7 @@ protected void createTableEntity(CSVPrinter printer, CSVRecord csvRecord, String try { table = Entity.getEntityByNameWithExcludedFields( - TABLE, tableFqn, "owners,tags,domains,extension", Include.NON_DELETED); + TABLE, tableFqn, "owners,tags,extension", Include.NON_DELETED); } catch (EntityNotFoundException ex) { // Simulate a table for validation without persisting it table = @@ -1731,7 +1780,7 @@ protected void createTableEntity(CSVPrinter printer, CSVRecord csvRecord, String .withCertification(certification) .withRetentionPeriod(csvRecord.get(8)) .withSourceUrl(csvRecord.get(9)) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, table.getDomains())) .withExtension(getExtension(printer, csvRecord, 11)) .withUpdatedAt(System.currentTimeMillis()) .withUpdatedBy(importedBy); @@ -1798,7 +1847,7 @@ protected void createStoredProcedureEntity( Entity.getEntityByName( STORED_PROCEDURE, entityFQN, - "name,displayName,fullyQualifiedName", + "name,displayName,fullyQualifiedName,domains", Include.NON_DELETED); } catch (Exception ex) { // Simulate a stored procedure for validation without persisting it @@ -1817,7 +1866,7 @@ protected void createStoredProcedureEntity( getEntityWithDependencyResolution( STORED_PROCEDURE, entityFQN, - "name,displayName,fullyQualifiedName", + "name,displayName,fullyQualifiedName,domains", Include.NON_DELETED); } catch (Exception ex) { LOG.warn("Stored procedure not found: {}, it will be created with Import.", entityFQN); @@ -1859,7 +1908,7 @@ protected void createStoredProcedureEntity( .withTags(tagLabels) .withCertification(certification) .withSourceUrl(csvRecord.get(9)) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, sp.getDomains())) .withStoredProcedureCode(storedProcedureCode) .withExtension(getExtension(printer, csvRecord, 11)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java index 5b8abfd2b405..57d6c5d31a2b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplication.java @@ -77,18 +77,15 @@ import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.sqlobject.SqlObjects; import org.jetbrains.annotations.NotNull; -import org.openmetadata.schema.api.configuration.MCPConfiguration; import org.openmetadata.schema.api.configuration.rdf.RdfConfiguration; import org.openmetadata.schema.api.security.AuthenticationConfiguration; import org.openmetadata.schema.api.security.AuthorizerConfiguration; -import org.openmetadata.schema.configuration.AISettings; import org.openmetadata.schema.configuration.LimitsConfiguration; -import org.openmetadata.schema.configuration.McpChatSettings; import org.openmetadata.schema.services.connections.metadata.AuthProvider; -import org.openmetadata.schema.settings.SettingsType; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.search.IndexMappingLoader; +import org.openmetadata.service.apps.ApplicationContext; import org.openmetadata.service.apps.ApplicationHandler; import org.openmetadata.service.apps.McpServerProvider; import org.openmetadata.service.apps.bundles.rdf.distributed.RdfDistributedJobParticipant; @@ -130,7 +127,6 @@ import org.openmetadata.service.llm.LLMClientHolder; import org.openmetadata.service.logging.SwitchableAccessLayoutFactory; import org.openmetadata.service.logging.SwitchableEventLayoutFactory; -import org.openmetadata.service.mcpclient.McpChatServiceHolder; import org.openmetadata.service.migration.MigrationValidationClient; import org.openmetadata.service.migration.api.MigrationWorkflow; import org.openmetadata.service.monitoring.EventMonitorConfiguration; @@ -139,6 +135,7 @@ import org.openmetadata.service.monitoring.UserMetricsServlet; import org.openmetadata.service.rdf.RdfUpdater; import org.openmetadata.service.resources.CollectionRegistry; +import org.openmetadata.service.resources.ai.AuditPackGenerator; import org.openmetadata.service.resources.audit.AuditLogResource; import org.openmetadata.service.resources.csv.CsvAsyncJobResource; import org.openmetadata.service.resources.csv.CsvDocumentationResource; @@ -267,10 +264,9 @@ public void run(OpenMetadataApplicationConfig catalogConfig, Environment environ // Initialize the IndexMapping class IndexMappingLoader.init(catalogConfig.getElasticSearchConfiguration()); - // Initialize the shared LLM completion client from llmConfiguration - LLMClientHolder.initialize(catalogConfig.getLlmConfiguration()); // Publish the platform-wide LLM configuration for features that need completions LlmConfigHolder.initialize(catalogConfig.getLlmConfiguration()); + LLMClientHolder.initialize(catalogConfig.getLlmConfiguration()); // init for dataSourceFactory DatasourceConfig.initialize(catalogConfig.getDataSourceFactory().getDriverClass()); @@ -313,6 +309,10 @@ public void run(OpenMetadataApplicationConfig catalogConfig, Environment environ // Initialize Workflow Handler WorkflowHandler.initialize(catalogConfig); + // Recover AI audit-report jobs interrupted by a prior pod restart: re-queue Queued + // reports and reclaim orphaned Running ones so they don't hang forever. + AuditPackGenerator.recoverInterruptedReports(); + // Init Settings Cache after repositories and Fernet (needed for database access and encryption) SettingsCache.initialize(catalogConfig); @@ -436,7 +436,6 @@ public void run(OpenMetadataApplicationConfig catalogConfig, Environment environ // Register MCP (depends on Auth Handlers for SSO) registerMCPServer(catalogConfig, environment); - initializeMcpChatService(); // Handle Services Jobs registerHealthCheckJobs(catalogConfig); @@ -452,7 +451,7 @@ protected void registerMCPServer( return; } try { - if (isMcpServerEnabled()) { + if (ApplicationContext.getInstance().getAppIfExists("McpApplication") != null) { Class mcpServerClass = Class.forName("org.openmetadata.mcp.McpServer"); McpServerProvider mcpServer = (McpServerProvider) mcpServerClass.getDeclaredConstructor().newInstance(); @@ -467,20 +466,6 @@ protected void registerMCPServer( } } - private boolean isMcpServerEnabled() { - MCPConfiguration mcpConfig = - SettingsCache.getSettingOrDefault( - SettingsType.MCP_CONFIGURATION, new MCPConfiguration(), MCPConfiguration.class); - return mcpConfig != null && Boolean.TRUE.equals(mcpConfig.getEnabled()); - } - - private void initializeMcpChatService() { - AISettings aiSettings = - SettingsCache.getSettingOrDefault(SettingsType.AI_SETTINGS, null, AISettings.class); - McpChatSettings mcpChat = aiSettings == null ? null : aiSettings.getMcpChat(); - McpChatServiceHolder.initialize(LlmConfigHolder.get(), mcpChat); - } - protected @NotNull JobHandlerRegistry getJobHandlerRegistry() { JobHandlerRegistry registry = new JobHandlerRegistry(); registry.register("EnumCleanupHandler", new EnumCleanupHandler(getDao(jdbi))); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplicationConfig.java b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplicationConfig.java index 764458742a58..a7fe924d1473 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplicationConfig.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/OpenMetadataApplicationConfig.java @@ -81,12 +81,12 @@ public class OpenMetadataApplicationConfig extends Configuration { @JsonProperty("elasticsearch") private ElasticSearchConfiguration elasticSearchConfiguration; - @JsonProperty("llmConfiguration") - private LLMConfiguration llmConfiguration; - @JsonProperty("nlqHybridSearch") private JsonNode nlqHybridSearch; + @JsonProperty("llmConfiguration") + private LLMConfiguration llmConfiguration; + @JsonProperty("eventHandlerConfiguration") private EventHandlerConfiguration eventHandlerConfiguration; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/TypeRegistry.java b/openmetadata-service/src/main/java/org/openmetadata/service/TypeRegistry.java index 965b6bbe49e4..096f168b9b2c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/TypeRegistry.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/TypeRegistry.java @@ -17,7 +17,10 @@ import static org.openmetadata.service.Entity.ADMIN_USER_NAME; import static org.openmetadata.service.resources.types.TypeResource.PROPERTIES_FIELD; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; import com.networknt.schema.Schema; +import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; @@ -46,6 +49,35 @@ public class TypeRegistry { /** Custom property map (fully qualified customPropertyName) to (jsonSchema) */ protected static final Map CUSTOM_PROPERTY_SCHEMAS = new ConcurrentHashMap<>(); + /** + * Negative cache of custom-property FQNs that were missing in this process even after a fresh + * read from the shared database. In a multi-replica deployment a custom property created on one + * replica is not pushed to the in-memory registry of its peers; this lets a peer self-heal by + * re-reading the owning type from the database on a cache miss, while the negative entry bounds + * how often a genuinely-unknown field re-triggers that database read. + * + *

Bounded staleness: an entry is only written after an actual database reload still did not + * find the property, so a property that already exists is never wrongly pinned. The one exception + * is a field queried before it is created on a peer (e.g. a typo'd-then-fixed name); it + * stays pinned as unknown until this entry expires. The common create-then-use ordering never + * queries the field before it exists, so it self-heals on first use. + */ + protected static final Cache MISSING_CUSTOM_PROPERTIES = + Caffeine.newBuilder().maximumSize(10_000).expireAfterWrite(Duration.ofSeconds(60)).build(); + + /** + * Coalescing window of entity types whose custom properties were re-read from the database + * recently. A single self-heal reload pulls the whole owning type, so once a type has + * been refreshed, further misses for other fields of that same type within the window reuse that + * read instead of issuing one database round-trip per field. This bounds read amplification (a + * request or import with many distinct unknown fields, or a caller rotating field names, cannot + * fan out into one reload per field) and, via {@link Cache#get(Object, java.util.function.Function)}, + * collapses a thundering herd of concurrent first-time misses for the same type into a single + * reload. The window is short so a newly-created property still propagates within seconds. + */ + protected static final Cache RECENTLY_REFRESHED_TYPES = + Caffeine.newBuilder().maximumSize(1_000).expireAfterWrite(Duration.ofSeconds(2)).build(); + private static final TypeRegistry INSTANCE = new TypeRegistry(); private TypeRegistry() { @@ -108,6 +140,7 @@ private void addCustomProperty( String entityType, String propertyName, CustomProperty customProperty) { String customPropertyFQN = getCustomPropertyFQN(entityType, propertyName); CUSTOM_PROPERTIES.put(customPropertyFQN, customProperty); + MISSING_CUSTOM_PROPERTIES.invalidate(customPropertyFQN); try { Schema jsonSchema = @@ -131,9 +164,73 @@ public void removeCustomProperty(String entityType, String propertyName) { public Schema getSchema(String entityType, String propertyName) { String customPropertyFQN = getCustomPropertyFQN(entityType, propertyName); + ensureCustomPropertyLoaded(entityType, customPropertyFQN); return CUSTOM_PROPERTY_SCHEMAS.get(customPropertyFQN); } + /** + * Self-heals the registry when a custom property is missing locally. Other replicas do not learn + * about a custom property created on a peer, so on a miss we re-read the owning type from the + * shared database (source of truth) and repopulate the registry. A short-lived negative cache + * prevents a genuinely-unknown field from re-reading the database on every request. + */ + private void ensureCustomPropertyLoaded(String entityType, String customPropertyFQN) { + boolean missingLocally = + !CUSTOM_PROPERTIES.containsKey(customPropertyFQN) + && MISSING_CUSTOM_PROPERTIES.getIfPresent(customPropertyFQN) == null; + if (missingLocally) { + boolean reloaded = reloadTypeCoalesced(entityType); + if (reloaded && !CUSTOM_PROPERTIES.containsKey(customPropertyFQN)) { + MISSING_CUSTOM_PROPERTIES.put(customPropertyFQN, Boolean.TRUE); + } + } + } + + /** + * Re-reads the owning type from the database at most once per coalescing window, sharing a single + * reload across concurrent callers for the same type. Returns {@code true} only when this call + * performed a successful reload, so the caller knows the registry was just repopulated and a + * still-missing property is genuinely unknown (safe to negative-cache). A failed reload returns + * {@code false} so a property that exists but could not be read is never wrongly pinned, and the + * coalescing entry is dropped so the next miss retries the database immediately instead of waiting + * out the window. + */ + private boolean reloadTypeCoalesced(String entityType) { + boolean[] loaderRan = {false}; + boolean[] loadSucceeded = {false}; + RECENTLY_REFRESHED_TYPES.get( + entityType, + key -> { + loaderRan[0] = true; + loadSucceeded[0] = refreshTypeFromDb(key); + return Boolean.TRUE; + }); + if (loaderRan[0] && !loadSucceeded[0]) { + RECENTLY_REFRESHED_TYPES.invalidate(entityType); + } + return loadSucceeded[0]; + } + + private boolean refreshTypeFromDb(String entityType) { + boolean refreshed = false; + TypeRepository repository = Entity.getTypeRepository(); + if (repository != null) { + try { + EntityUtil.Fields fields = repository.getFields(PROPERTIES_FIELD); + Type type = repository.getByName(null, entityType, fields); + addType(type); + refreshed = true; + LOG.debug("Refreshed type '{}' from database after custom property cache miss", entityType); + } catch (RuntimeException e) { + LOG.debug( + "Could not refresh type '{}' from database on cache miss: {}", + entityType, + e.getMessage()); + } + } + return refreshed; + } + public void validateCustomProperties(Type type) { // Validate custom properties added to a type for (CustomProperty property : listOrEmpty(type.getCustomProperties())) { @@ -163,6 +260,7 @@ public static String getPropertyName(String propertyFQN) { public static String getCustomPropertyType(String entityType, String propertyName) { String fqn = getCustomPropertyFQN(entityType, propertyName); + instance().ensureCustomPropertyLoaded(entityType, fqn); CustomProperty property = CUSTOM_PROPERTIES.get(fqn); if (property == null) { throw EntityNotFoundException.byMessage( @@ -173,6 +271,7 @@ public static String getCustomPropertyType(String entityType, String propertyNam public static String getCustomPropertyConfig(String entityType, String propertyName) { String fqn = getCustomPropertyFQN(entityType, propertyName); + instance().ensureCustomPropertyLoaded(entityType, fqn); CustomProperty property = CUSTOM_PROPERTIES.get(fqn); if (property != null && property.getCustomPropertyConfig() != null diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java index 116b8c50875b..f2666a5a1b21 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java @@ -26,6 +26,7 @@ import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.search.SearchRequest; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.EntityStatus; import org.openmetadata.schema.type.Relationship; import org.openmetadata.schema.type.aicontext.KnowledgeItem; import org.openmetadata.schema.utils.JsonUtils; @@ -51,6 +52,7 @@ public class AIContextFinder { private static final Map> CONTEXT_FILTER = Map.of("entityType", CONTEXT_ENTITY_TYPES); private static final int SEARCH_K = 100; + private static final int CHUNK_DEDUP_OVERSAMPLE = 3; private static final int MAX_ASSETS_PER_ITEM = 10; private static final int MAX_CONTENT_CHARS = 2000; @@ -78,24 +80,41 @@ public boolean isEmpty() { } public FoundContext find(String query, int size) { - List items = new ArrayList<>(); + Map items = new LinkedHashMap<>(); Map candidates = new LinkedHashMap<>(); VectorSearchResponse response = searchKnowledge(query, size); if (response != null && response.getHits() != null) { for (Map hit : response.getHits()) { + if (items.size() >= size) { + break; + } collectHit(hit, items, candidates); } } - return new FoundContext(items, new ArrayList<>(candidates.values())); + return new FoundContext(new ArrayList<>(items.values()), new ArrayList<>(candidates.values())); } - private void collectHit( - Map hit, List items, Map candidates) { + /** + * Items are keyed by type + FQN. The vector index holds one document per body chunk — a long + * article matches once per relevant chunk and would otherwise appear repeatedly, blowing the + * caller's size budget with duplicates; first (highest-scoring) chunk wins. Type is part of the + * key because knowledge types can share an FQN (a metric and a page both named "Revenue") — an + * FQN-only key would drop the second item along with the assets it routes to. + */ + void collectHit( + Map hit, + Map items, + Map candidates) { KnowledgeItem item = toKnowledgeItem(hit); if (item != null) { - items.add(item); - for (CandidateAsset asset : routeToAssets(hit, item)) { - candidates.putIfAbsent(asset.fullyQualifiedName(), asset); + String itemKey = item.getType().value() + ":" + item.getFullyQualifiedName(); + if (!items.containsKey(itemKey)) { + items.put(itemKey, item); + for (CandidateAsset asset : routeToAssets(hit, item)) { + // FQNs are only unique per entity type (a chart and a dashboard under the same service + // can share one) — a name-only key would silently drop the second asset. + candidates.putIfAbsent(asset.entityType() + ":" + asset.fullyQualifiedName(), asset); + } } } } @@ -106,7 +125,12 @@ private VectorSearchResponse searchKnowledge(String query, int size) { OpenSearchVectorService service = OpenSearchVectorService.getInstance(); if (service != null) { try { - response = service.search(query, CONTEXT_FILTER, size, 0, SEARCH_K, 0.0); + // Over-fetch: collectHit dedupes chunk documents per FQN, so a long item occupying + // several top hits would otherwise shrink the page below the requested size. The KNN + // k (SEARCH_K) caps the real result set regardless. + response = + service.search( + query, CONTEXT_FILTER, size * CHUNK_DEDUP_OVERSAMPLE, 0, SEARCH_K, 0.0); } catch (Exception e) { LOG.warn("AIContext find: vector search failed: {}", e.getMessage()); } @@ -119,7 +143,7 @@ static KnowledgeItem toKnowledgeItem(Map hit) { KnowledgeItem item = null; String fqn = asString(hit.get("fullyQualifiedName")); KnowledgeItem.Type kind = knowledgeType(asString(hit.get("entityType"))); - if (!nullOrEmpty(fqn) && kind != null) { + if (!nullOrEmpty(fqn) && kind != null && isApprovedForContext(hit, kind)) { item = new KnowledgeItem() .withType(kind) @@ -131,6 +155,18 @@ static KnowledgeItem toKnowledgeItem(Map hit) { return item; } + /** + * Draft / in-review glossary terms are untrusted as business-rule context — mirror the Approved + * filter the asset-anchored path applies in {@link AIContextBuilder}. Other knowledge types keep + * their existing behavior (a missing status means no review workflow applies). + */ + static boolean isApprovedForContext(Map hit, KnowledgeItem.Type kind) { + String status = asString(hit.get("entityStatus")); + return kind != KnowledgeItem.Type.GLOSSARY_TERM + || nullOrEmpty(status) + || EntityStatus.APPROVED.value().equals(status); + } + static KnowledgeItem.Type knowledgeType(String entityType) { KnowledgeItem.Type type = null; try { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinderAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinderAccess.java new file mode 100644 index 000000000000..421c87be52d1 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinderAccess.java @@ -0,0 +1,84 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.aicontext; + +import static org.openmetadata.schema.type.MetadataOperation.VIEW_ALL; +import static org.openmetadata.schema.type.MetadataOperation.VIEW_BASIC; + +import jakarta.ws.rs.core.SecurityContext; +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.service.Entity; +import org.openmetadata.service.aicontext.AIContextFinder.CandidateAsset; +import org.openmetadata.service.aicontext.AIContextFinder.FoundContext; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; + +/** Knowledge-layer authorization shared by the find-context REST endpoint and MCP tool. */ +@Slf4j +public final class AIContextFinderAccess { + public static final List KNOWLEDGE_TYPES = + List.of(Entity.GLOSSARY_TERM, Entity.METRIC, Entity.PAGE); + + private AIContextFinderAccess() {} + + /** The caller must hold VIEW_ALL on every knowledge type the finder surfaces. */ + public static void authorizeKnowledgeAccess( + Authorizer authorizer, SecurityContext securityContext) { + for (String knowledgeType : KNOWLEDGE_TYPES) { + authorizer.authorize( + securityContext, + new OperationContext(knowledgeType, VIEW_ALL), + new ResourceContext<>(knowledgeType)); + } + } + + /** + * Drops candidate assets the caller cannot view. Glossary-routed candidates are already + * RBAC-filtered by the subject-scoped search; this guards the relationship-routed ones (metric + * APPLIED_TO, page HAS), which are read straight from the entity-relationship table. + */ + public static FoundContext filterCandidates( + FoundContext found, Authorizer authorizer, SecurityContext securityContext) { + List visible = new ArrayList<>(); + for (CandidateAsset asset : found.candidateAssets()) { + if (canView(asset, authorizer, securityContext)) { + visible.add(asset); + } + } + return new FoundContext(found.items(), visible); + } + + private static boolean canView( + CandidateAsset asset, Authorizer authorizer, SecurityContext securityContext) { + return canView(asset.entityType(), asset.fullyQualifiedName(), authorizer, securityContext); + } + + /** True when the caller holds VIEW_BASIC on the asset; false (never throws) otherwise. */ + public static boolean canView( + String entityType, String fqn, Authorizer authorizer, SecurityContext securityContext) { + boolean visible = false; + try { + authorizer.authorize( + securityContext, + new OperationContext(entityType, VIEW_BASIC), + new ResourceContext<>(entityType, null, fqn)); + visible = true; + } catch (Exception e) { + LOG.debug("Dropping asset {} not viewable by caller: {}", fqn, e.getMessage()); + } + return visible; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextMarkdown.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextMarkdown.java index 237a9873cfc4..2e2e61a53524 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextMarkdown.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextMarkdown.java @@ -15,7 +15,9 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import java.time.Instant; +import java.util.EnumSet; import java.util.List; +import java.util.Set; import org.openmetadata.schema.type.AIContext; import org.openmetadata.schema.type.aicontext.AssetContext; import org.openmetadata.schema.type.aicontext.ColumnProfileSummary; @@ -26,6 +28,7 @@ import org.openmetadata.schema.type.aicontext.KnowledgeItem; import org.openmetadata.schema.type.aicontext.Observability; import org.openmetadata.schema.type.aicontext.TableContext; +import org.openmetadata.schema.type.personaContext.ContextSection; /** * Renders an {@link AIContext} as a self-describing markdown document for consumption by LLM agents, @@ -43,34 +46,70 @@ public final class AIContextMarkdown { private static final int MAX_CONTENT_CHARS = 2000; private static final int MAX_SUMMARY_CHARS = 150; + private static final Set LEGACY_RENDER_SECTIONS = + EnumSet.complementOf(EnumSet.of(ContextSection.TAGS)); private AIContextMarkdown() {} public static String render(AIContext context) { StringBuilder markdown = new StringBuilder(); appendFrontmatter(markdown, context); - appendDescription(markdown, context); - appendAssetContext(markdown, context.getAssetContext()); - appendKnowledgeSection(markdown, "Business Definitions", context.getGlossaryTerms()); - appendKnowledgeSection(markdown, "Metrics", context.getMetrics()); - appendKnowledgeSection(markdown, "Knowledge Articles", context.getArticles()); - appendLineage(markdown, context); - appendObservability(markdown, context.getObservability()); + appendEntitySections(markdown, context, LEGACY_RENDER_SECTIONS, "#"); return markdown.toString().strip() + "\n"; } - private static void appendObservability(StringBuilder markdown, Observability observability) { + static void appendEntitySections( + StringBuilder markdown, + AIContext context, + Set sections, + String headingPrefix) { + Set selected = + sections == null ? EnumSet.noneOf(ContextSection.class) : sections; + if (selected.contains(ContextSection.DESCRIPTION)) { + appendDescription(markdown, context); + } + appendAssetContext(markdown, context.getAssetContext(), selected, headingPrefix); + if (selected.contains(ContextSection.TAGS)) { + appendTags(markdown, context.getTags(), headingPrefix); + } + if (selected.contains(ContextSection.GLOSSARY_TERMS)) { + appendKnowledgeSection( + markdown, "Business Definitions", context.getGlossaryTerms(), headingPrefix, true); + } + if (selected.contains(ContextSection.METRICS)) { + appendKnowledgeSection(markdown, "Metrics", context.getMetrics(), headingPrefix, true); + } + if (selected.contains(ContextSection.ARTICLES)) { + appendKnowledgeSection( + markdown, "Knowledge Articles", context.getArticles(), headingPrefix, true); + } + if (selected.contains(ContextSection.LINEAGE)) { + appendLineage(markdown, context, headingPrefix); + } + appendObservability(markdown, context.getObservability(), selected, headingPrefix); + } + + private static void appendObservability( + StringBuilder markdown, + Observability observability, + Set sections, + String headingPrefix) { if (observability != null) { - appendProfile(markdown, observability); - appendDataQuality(markdown, observability.getDataQuality()); + if (sections.contains(ContextSection.PROFILE)) { + appendProfile(markdown, observability, headingPrefix); + } + if (sections.contains(ContextSection.DATA_QUALITY)) { + appendDataQuality(markdown, observability.getDataQuality(), headingPrefix); + } } } - private static void appendProfile(StringBuilder markdown, Observability observability) { + private static void appendProfile( + StringBuilder markdown, Observability observability, String headingPrefix) { boolean hasProfile = observability.getRowCount() != null || !nullOrEmpty(observability.getColumnProfiles()); if (hasProfile) { - markdown.append("\n# Data Profile\n"); + appendHeading(markdown, headingPrefix, "Data Profile"); if (observability.getRowCount() != null) { markdown .append("\n**Row count:** ") @@ -103,9 +142,11 @@ private static void appendColumnProfiles( } } - private static void appendDataQuality(StringBuilder markdown, DataQuality dataQuality) { + private static void appendDataQuality( + StringBuilder markdown, DataQuality dataQuality, String headingPrefix) { if (dataQuality != null) { - markdown.append("\n# Data Quality\n\n"); + appendHeading(markdown, headingPrefix, "Data Quality"); + markdown.append('\n'); markdown .append("Tests — passed: ") .append(orZero(dataQuality.getPassed())) @@ -149,7 +190,7 @@ public static String renderFound(AIContextFinder.FoundContext found) { .append(typeLabel(item)) .append(")\n"); appendYamlInline(markdown, item.getFullyQualifiedName()); - appendKnowledgeContent(markdown, item); + appendKnowledgeContent(markdown, item, true); } if (!found.candidateAssets().isEmpty()) { markdown.append("\n# Candidate Assets\n\n"); @@ -247,22 +288,46 @@ private static void appendDescription(StringBuilder markdown, AIContext context) } } - private static void appendAssetContext(StringBuilder markdown, AssetContext assetContext) { + private static void appendAssetContext( + StringBuilder markdown, + AssetContext assetContext, + Set sections, + String headingPrefix) { if (assetContext != null && assetContext.getTable() != null) { - appendTableContext(markdown, assetContext.getTable()); + appendTableContext(markdown, assetContext.getTable(), sections, headingPrefix); } } - private static void appendTableContext(StringBuilder markdown, TableContext table) { - appendSchemaTable(markdown, table.getColumns()); + private static void appendTableContext( + StringBuilder markdown, + TableContext table, + Set sections, + String headingPrefix) { + if (sections.contains(ContextSection.SCHEMA)) { + appendSchemaTable(markdown, table.getColumns(), headingPrefix); + } + if (sections.contains(ContextSection.CONSTRAINTS)) { + appendPrimaryKey(markdown, table); + appendForeignKeys(markdown, table.getForeignKeys(), headingPrefix); + } + if (sections.contains(ContextSection.JOINS)) { + appendJoins(markdown, table.getFrequentJoins(), headingPrefix); + } + if (sections.contains(ContextSection.CONSTRAINTS)) { + appendPartitions(markdown, table); + } + } + + private static void appendPrimaryKey(StringBuilder markdown, TableContext table) { if (!nullOrEmpty(table.getPrimaryKey())) { markdown .append("\n**Primary key:** ") .append(String.join(", ", table.getPrimaryKey())) .append('\n'); } - appendForeignKeys(markdown, table.getForeignKeys()); - appendJoins(markdown, table.getFrequentJoins()); + } + + private static void appendPartitions(StringBuilder markdown, TableContext table) { if (!nullOrEmpty(table.getPartitionColumns())) { markdown .append("\n**Partitioned by:** ") @@ -271,11 +336,13 @@ private static void appendTableContext(StringBuilder markdown, TableContext tabl } } - private static void appendSchemaTable(StringBuilder markdown, List columns) { + private static void appendSchemaTable( + StringBuilder markdown, List columns, String headingPrefix) { if (nullOrEmpty(columns)) { return; } - markdown.append("\n# Schema\n\n"); + appendHeading(markdown, headingPrefix, "Schema"); + markdown.append('\n'); markdown.append("| Column | Type | Constraint | Description |\n"); markdown.append("|--------|------|------------|-------------|\n"); for (FieldContext column : columns) { @@ -292,11 +359,13 @@ private static void appendSchemaTable(StringBuilder markdown, List } } - private static void appendForeignKeys(StringBuilder markdown, List foreignKeys) { + private static void appendForeignKeys( + StringBuilder markdown, List foreignKeys, String headingPrefix) { if (nullOrEmpty(foreignKeys)) { return; } - markdown.append("\n# Foreign Keys\n\n"); + appendHeading(markdown, headingPrefix, "Foreign Keys"); + markdown.append('\n'); for (ForeignKey foreignKey : foreignKeys) { markdown .append("- `") @@ -328,11 +397,13 @@ private static String cardinalitySuffix(String relationshipType) { return nullOrEmpty(relationshipType) ? "" : " (" + relationshipType + ")"; } - private static void appendJoins(StringBuilder markdown, List joins) { + private static void appendJoins( + StringBuilder markdown, List joins, String headingPrefix) { if (nullOrEmpty(joins)) { return; } - markdown.append("\n# Frequent Joins\n\n"); + appendHeading(markdown, headingPrefix, "Frequent Joins"); + markdown.append('\n'); for (JoinHint join : joins) { markdown .append("- `") @@ -345,16 +416,20 @@ private static void appendJoins(StringBuilder markdown, List joins) { } } - private static void appendKnowledgeSection( - StringBuilder markdown, String heading, List items) { + static void appendKnowledgeSection( + StringBuilder markdown, + String heading, + List items, + String headingPrefix, + boolean truncateContent) { if (nullOrEmpty(items)) { return; } - markdown.append("\n# ").append(heading).append("\n"); + appendHeading(markdown, headingPrefix, heading); for (KnowledgeItem item : items) { - markdown.append("\n### ").append(labelOf(item)).append('\n'); + markdown.append('\n').append(headingPrefix).append("## ").append(labelOf(item)).append('\n'); appendYamlInline(markdown, item.getFullyQualifiedName()); - appendKnowledgeContent(markdown, item); + appendKnowledgeContent(markdown, item, truncateContent); } } @@ -362,9 +437,11 @@ private static void appendKnowledgeSection( * Renders a knowledge item's body, appending a retrieval hint whenever the content was excerpted * or omitted to fit the context budget, so the agent knows the full text is a fetch away. */ - private static void appendKnowledgeContent(StringBuilder markdown, KnowledgeItem item) { + private static void appendKnowledgeContent( + StringBuilder markdown, KnowledgeItem item, boolean truncateContent) { if (!nullOrEmpty(item.getContent())) { - markdown.append('\n').append(truncate(item.getContent().strip())).append('\n'); + String content = item.getContent().strip(); + markdown.append('\n').append(truncateContent ? truncate(content) : content).append('\n'); } if (Boolean.TRUE.equals(item.getContentTruncated())) { markdown @@ -386,11 +463,13 @@ private static String labelOf(KnowledgeItem item) { return !nullOrEmpty(item.getDisplayName()) ? item.getDisplayName() : item.getName(); } - private static void appendLineage(StringBuilder markdown, AIContext context) { + private static void appendLineage( + StringBuilder markdown, AIContext context, String headingPrefix) { boolean hasLineage = !nullOrEmpty(context.getUpstream()) || !nullOrEmpty(context.getDownstream()); if (hasLineage) { - markdown.append("\n# Lineage\n\n"); + appendHeading(markdown, headingPrefix, "Lineage"); + markdown.append('\n'); if (!nullOrEmpty(context.getUpstream())) { markdown.append("**Upstream:** ").append(codeJoin(context.getUpstream())).append('\n'); } @@ -411,6 +490,17 @@ private static String codeJoin(List values) { return joined.toString(); } + private static void appendTags(StringBuilder markdown, List tags, String headingPrefix) { + if (!nullOrEmpty(tags)) { + appendHeading(markdown, headingPrefix, "Tags"); + markdown.append("\n").append(codeJoin(tags)).append('\n'); + } + } + + private static void appendHeading(StringBuilder markdown, String headingPrefix, String heading) { + markdown.append('\n').append(headingPrefix).append(' ').append(heading).append('\n'); + } + private static String cell(String value) { return nullOrEmpty(value) ? "" : value.replace("|", "\\|").replace("\n", " ").strip(); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AttachedKnowledgeBatch.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AttachedKnowledgeBatch.java new file mode 100644 index 000000000000..8a0953b95d72 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AttachedKnowledgeBatch.java @@ -0,0 +1,186 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.aicontext; + +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.Metric; +import org.openmetadata.schema.entity.data.Page; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.type.aicontext.KnowledgeItem; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.CollectionDAO; + +/** + * Batch lookup of the knowledge attached to a set of assets: glossary terms from asset and column + * tags, metrics via {@code metric --APPLIED_TO--> asset}, and articles via {@code asset --HAS--> + * page}. Deliberately cheap — no profile, no lineage, no budgeting, no vector excerpts — so a + * search layer can annotate every candidate in a result page with its linked knowledge in one + * round-trip. Relationship reads are batched across all assets ({@code findToBatch} / + * {@code findFromBatch}); knowledge entities are bulk-loaded once and shared. + */ +@Slf4j +public final class AttachedKnowledgeBatch { + public static final int MAX_ASSETS = 50; + static final int MAX_ITEMS_PER_ASSET = 10; + static final int MAX_CONTENT_CHARS = 500; + private static final String TABLE_FIELDS = "tags,columns"; + private static final String DEFAULT_FIELDS = "tags"; + + private AttachedKnowledgeBatch() {} + + public record AssetKey(String fullyQualifiedName, String entityType) {} + + public record AssetKnowledge( + String fullyQualifiedName, String entityType, List items) {} + + private record Lookups( + Map> pageIdsByAsset, + Map> metricIdsByAsset, + Map pages, + Map metrics, + Map glossaryTerms) {} + + /** Resolves attached knowledge for each asset. Unknown or unloadable assets are skipped. */ + public static List resolve(List assets) { + Map loaded = loadAssets(assets); + Lookups lookups = lookupKnowledge(loaded); + List result = new ArrayList<>(); + for (Map.Entry entry : loaded.entrySet()) { + result.add( + new AssetKnowledge( + entry.getKey().fullyQualifiedName(), + entry.getKey().entityType(), + itemsFor(entry.getValue(), lookups))); + } + return result; + } + + // Keyed by the full AssetKey (type + FQN): FQNs are only unique per entity type — a chart and + // a dashboard under the same service can share an FQN, and a name-only key would drop one. + private static Map loadAssets(List assets) { + Map loaded = new LinkedHashMap<>(); + for (AssetKey key : assets.stream().limit(MAX_ASSETS).toList()) { + if (!nullOrEmpty(key.fullyQualifiedName()) && !nullOrEmpty(key.entityType())) { + loadAsset(key, loaded); + } + } + return loaded; + } + + private static void loadAsset(AssetKey key, Map into) { + try { + String fields = Entity.TABLE.equals(key.entityType()) ? TABLE_FIELDS : DEFAULT_FIELDS; + into.putIfAbsent( + key, + Entity.getEntityByName( + key.entityType(), key.fullyQualifiedName(), fields, Include.NON_DELETED)); + } catch (EntityNotFoundException | IllegalArgumentException e) { + LOG.debug("Skipping unresolvable asset {}: {}", key.fullyQualifiedName(), e.getMessage()); + } + } + + private static Lookups lookupKnowledge(Map loaded) { + List assetIds = + loaded.values().stream().map(entity -> entity.getId().toString()).toList(); + Map> pageIdsByAsset = Map.of(); + Map> metricIdsByAsset = Map.of(); + if (!assetIds.isEmpty()) { + CollectionDAO.EntityRelationshipDAO relationships = + Entity.getCollectionDAO().relationshipDAO(); + pageIdsByAsset = + PersonaContextBuilder.groupRelatedIds( + relationships.findToBatch(assetIds, Relationship.HAS.ordinal(), Entity.PAGE), true); + metricIdsByAsset = + PersonaContextBuilder.groupRelatedIds( + relationships.findFromBatch( + assetIds, Relationship.APPLIED_TO.ordinal(), Entity.METRIC), + false); + } + return new Lookups( + pageIdsByAsset, + metricIdsByAsset, + PersonaContextBuilder.entitiesById(Entity.PAGE, flattenIds(pageIdsByAsset), Page.class), + PersonaContextBuilder.entitiesById( + Entity.METRIC, flattenIds(metricIdsByAsset), Metric.class), + loadGlossaryTerms(loaded)); + } + + static List flattenIds(Map> idsByAsset) { + return idsByAsset.values().stream().flatMap(List::stream).distinct().toList(); + } + + /** Null values are cached too, so a missing/unapproved term is looked up once per batch. */ + private static Map loadGlossaryTerms( + Map loaded) { + Map terms = new LinkedHashMap<>(); + for (EntityInterface entity : loaded.values()) { + for (String fqn : AIContextBuilder.collectGlossaryFqns(entity)) { + if (!terms.containsKey(fqn)) { + terms.put(fqn, PersonaContextBuilder.loadGlossaryTerm(fqn)); + } + } + } + return terms; + } + + private static List itemsFor(EntityInterface asset, Lookups lookups) { + List items = new ArrayList<>(); + for (String fqn : AIContextBuilder.collectGlossaryFqns(asset)) { + addItem(items, lookups.glossaryTerms().get(fqn)); + } + String assetId = asset.getId().toString(); + for (UUID id : lookups.metricIdsByAsset().getOrDefault(assetId, List.of())) { + addItem(items, knowledgeItemOf(Entity.METRIC, lookups.metrics().get(id))); + } + for (UUID id : lookups.pageIdsByAsset().getOrDefault(assetId, List.of())) { + addItem(items, knowledgeItemOf(Entity.PAGE, lookups.pages().get(id))); + } + return items; + } + + private static void addItem(List items, KnowledgeItem item) { + if (item != null && items.size() < MAX_ITEMS_PER_ASSET) { + items.add(truncated(item)); + } + } + + private static KnowledgeItem knowledgeItemOf(String entityType, EntityInterface entity) { + return entity == null ? null : PersonaContextBuilder.fullKnowledgeItem(entityType, entity); + } + + static KnowledgeItem truncated(KnowledgeItem item) { + KnowledgeItem result = item; + String content = item.getContent(); + if (content != null && content.length() > MAX_CONTENT_CHARS) { + result = + new KnowledgeItem() + .withType(item.getType()) + .withName(item.getName()) + .withDisplayName(item.getDisplayName()) + .withFullyQualifiedName(item.getFullyQualifiedName()) + .withContent(content.substring(0, MAX_CONTENT_CHARS) + "…") + .withContentTruncated(true); + } + return result; + } +} diff --git a/openmetadata-ui/src/main/resources/ui/src/components/common/EntityDescription/description-v1.less b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/BudgetTracker.java similarity index 56% rename from openmetadata-ui/src/main/resources/ui/src/components/common/EntityDescription/description-v1.less rename to openmetadata-service/src/main/java/org/openmetadata/service/aicontext/BudgetTracker.java index 1af139a010ef..657010a5577b 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/common/EntityDescription/description-v1.less +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/BudgetTracker.java @@ -1,5 +1,5 @@ /* - * Copyright 2025 Collate. + * Copyright 2026 Collate * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -10,25 +10,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package org.openmetadata.service.aicontext; -@import (reference) '../../../styles/variables.less'; +final class BudgetTracker { + private int remaining; -.ant-card.new-description-card { - border-radius: 10px; - border: 0.5px solid @grey-100; - background: @grey-50; - height: calc(100% - 20px); - overflow-y: auto; -} - -.description-v1-title-row { - flex-wrap: wrap; + BudgetTracker(int budget) { + remaining = Math.max(0, budget); + } - .ant-space-item { - display: flex; + boolean tryConsume(String value) { + int length = value == null ? 0 : value.length(); + boolean fits = length <= remaining; + if (fits) { + remaining -= length; + } + return fits; } -} -.description-v1-metadata { - margin-top: 12px; + int remaining() { + return remaining; + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextAccess.java new file mode 100644 index 000000000000..48aaedab9abc --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextAccess.java @@ -0,0 +1,76 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.aicontext; + +import jakarta.ws.rs.core.SecurityContext; +import org.openmetadata.schema.entity.teams.Persona; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.UserRepository; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.DefaultAuthorizer; +import org.openmetadata.service.security.policyevaluator.SubjectContext; + +/** Persona-membership authorization shared by the REST endpoint and MCP tool. */ +public final class PersonaContextAccess { + private static final String CONTEXT_DEFINITION_FIELD = "contextDefinition"; + + private PersonaContextAccess() {} + + public static void authorize(SecurityContext securityContext, Persona persona) { + SubjectContext subject = DefaultAuthorizer.getSubjectContext(securityContext); + if (subject.isAdmin() || subject.isBot()) { + return; + } + if (!subject.hasPersona(persona.getId())) { + throw new AuthorizationException( + "User is not assigned to persona " + persona.getFullyQualifiedName()); + } + } + + public static Persona activePersona(SecurityContext securityContext) { + SubjectContext subject = DefaultAuthorizer.getSubjectContext(securityContext); + Persona persona = loadPersona(subject.getActivePersona()); + if (persona != null) { + return persona; + } + UserRepository users = (UserRepository) Entity.getEntityRepository(Entity.USER); + EntityReference personaReference = users.getDefaultPersona(subject.user()); + persona = loadPersona(personaReference); + if (persona == null) { + throw EntityNotFoundException.byMessage("No active persona is configured for this user"); + } + return persona; + } + + private static Persona loadPersona(EntityReference personaReference) { + if (personaReference == null) { + return null; + } + try { + return Entity.getEntity( + Entity.PERSONA, personaReference.getId(), CONTEXT_DEFINITION_FIELD, Include.NON_DELETED); + } catch (EntityNotFoundException e) { + return null; + } + } + + public static void authorizeRefresh(SecurityContext securityContext) { + SubjectContext subject = DefaultAuthorizer.getSubjectContext(securityContext); + if (!subject.isAdmin() && !subject.isBot()) { + throw new AuthorizationException("Only admins and bots can refresh persona context"); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextBuilder.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextBuilder.java new file mode 100644 index 000000000000..af55185b7f2f --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextBuilder.java @@ -0,0 +1,880 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.aicontext; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.ws.rs.ServiceUnavailableException; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.GlossaryTerm; +import org.openmetadata.schema.entity.data.Metric; +import org.openmetadata.schema.entity.data.Page; +import org.openmetadata.schema.entity.teams.Persona; +import org.openmetadata.schema.type.AIContext; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.EntityStatus; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.PersonaContext; +import org.openmetadata.schema.type.PersonaContextDefinition; +import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.type.aicontext.AssetContext; +import org.openmetadata.schema.type.aicontext.KnowledgeItem; +import org.openmetadata.schema.type.aicontext.Observability; +import org.openmetadata.schema.type.aicontext.TableContext; +import org.openmetadata.schema.type.personaContext.ContextRule; +import org.openmetadata.schema.type.personaContext.ContextSection; +import org.openmetadata.schema.type.personaContext.SharedKnowledge; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.schema.utils.ResultList; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.DataProductRepository; +import org.openmetadata.service.jdbi3.TableRepository; +import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.SearchResultListMapper; +import org.openmetadata.service.search.SearchSortFilter; +import org.openmetadata.service.util.FullyQualifiedName; + +/** Materializes the dynamic entity-selection rules attached to a Persona into one AI context. */ +@Slf4j +public class PersonaContextBuilder { + static final int MAX_SHARED_KNOWLEDGE_ITEMS = 500; + private static final int SEARCH_BATCH_SIZE = 100; + private static final int DATA_PRODUCT_ASSET_BATCH_SIZE = 1000; + private static final int DEFAULT_MAX_ASSETS = 200; + private static final Set KNOWLEDGE_ENTITY_TYPES = + Set.of(Entity.GLOSSARY_TERM, Entity.PAGE, Entity.METRIC); + private static final Set ASSET_ENTITY_TYPES = + Set.of( + Entity.TABLE, + Entity.TOPIC, + Entity.CHART, + Entity.DASHBOARD, + Entity.DASHBOARD_DATA_MODEL, + Entity.PIPELINE, + Entity.MLMODEL, + Entity.CONTAINER, + Entity.DATABASE, + Entity.DATABASE_SCHEMA, + Entity.STORED_PROCEDURE, + Entity.SEARCH_INDEX, + Entity.API_COLLECTION, + Entity.API_ENDPOINT, + Entity.DATA_PRODUCT); + private static final Set ASSET_CONTEXT_SECTIONS = + EnumSet.of( + ContextSection.DESCRIPTION, + ContextSection.SCHEMA, + ContextSection.CONSTRAINTS, + ContextSection.JOINS, + ContextSection.TAGS, + ContextSection.GLOSSARY_TERMS, + ContextSection.ARTICLES, + ContextSection.METRICS, + ContextSection.LINEAGE, + ContextSection.PROFILE, + ContextSection.DATA_QUALITY); + private static final Set DEFAULT_ASSET_CONTEXT_SECTIONS = + EnumSet.of( + ContextSection.DESCRIPTION, + ContextSection.SCHEMA, + ContextSection.CONSTRAINTS, + ContextSection.JOINS, + ContextSection.TAGS, + ContextSection.GLOSSARY_TERMS, + ContextSection.ARTICLES, + ContextSection.METRICS); + private static final Set KEYWORD_SORT_ENTITY_TYPES = Set.of("testCase", "user", "team"); + private static final String[] SEARCH_FIELDS = { + "id", + "name", + "displayName", + "fullyQualifiedName", + "description", + "entityType", + "entityStatus", + "href", + "tags", + "tier", + "classificationTags", + "glossaryTags", + "aiContext" + }; + + private final Persona persona; + private final SearchRepository searchRepository; + + public PersonaContextBuilder(Persona persona) { + this(persona, Entity.getSearchRepository()); + } + + PersonaContextBuilder(Persona persona, SearchRepository searchRepository) { + this.persona = persona; + this.searchRepository = searchRepository; + } + + public MaterializedPersonaContext build() { + PersonaContextDefinition definition = definitionOf(persona); + List materializedRules = selectRules(definition); + loadProfiles(materializedRules); + SharedKnowledgeAccumulator knowledge = enrichAssetKnowledge(materializedRules); + SharedKnowledge sharedKnowledge = knowledge.toSharedKnowledge(); + PersonaContext context = + new PersonaContext() + .withPersona(persona.getEntityReference()) + .withGeneratedAt(System.currentTimeMillis()) + .withSharedKnowledge(sharedKnowledge); + return PersonaContextMarkdown.render( + persona, definition, materializedRules, context, knowledge.overflowed()); + } + + static PersonaContextDefinition definitionOf(Persona persona) { + return persona.getContextDefinition() == null + ? new PersonaContextDefinition() + : persona.getContextDefinition(); + } + + static int characterBudget(PersonaContextDefinition definition) { + return definition.getCharacterBudget() == null ? 400_000 : definition.getCharacterBudget(); + } + + static int cacheTtlSeconds(PersonaContextDefinition definition) { + return (definition.getCacheTtlMinutes() == null ? 30 : definition.getCacheTtlMinutes()) * 60; + } + + List selectRules(PersonaContextDefinition definition) { + List results = new ArrayList<>(); + if (!Boolean.TRUE.equals(definition.getEnabled())) { + return results; + } + Set seenEntities = new HashSet<>(); + List orderedRules = new ArrayList<>(listOrEmpty(definition.getRules())); + orderedRules.sort( + Comparator.comparing(rule -> !Boolean.TRUE.equals(rule.getAlwaysInContext()))); + for (ContextRule rule : orderedRules) { + if (!Boolean.TRUE.equals(rule.getEnabled())) { + continue; + } + RuleSearchResult matches = search(rule); + List selected = new ArrayList<>(); + int maxAssets = rule.getMaxAssets() == null ? DEFAULT_MAX_ASSETS : rule.getMaxAssets(); + for (Map document : matches.documents()) { + if (selected.size() >= maxAssets) { + break; + } + String fqn = stringValue(document.get("fullyQualifiedName")); + if (nullOrEmpty(fqn) || !seenEntities.add(rule.getEntityType() + ':' + fqn)) { + continue; + } + SelectedEntity entity = + isKnowledgeEntityType(rule.getEntityType()) + ? buildKnowledgeSelection(rule, document) + : buildAssetSelection(rule, document); + if (entity != null) { + selected.add(entity); + if (Entity.DATA_PRODUCT.equals(rule.getEntityType()) + && Boolean.TRUE.equals(rule.getFullyRendered())) { + int remaining = maxAssets - selected.size(); + for (SelectedEntity member : expandDataProductAssets(entity, remaining)) { + String memberFqn = member.context().getFullyQualifiedName(); + String memberType = member.context().getEntityType(); + if (!nullOrEmpty(memberFqn) + && !nullOrEmpty(memberType) + && seenEntities.add(memberType + ':' + memberFqn)) { + selected.add(member); + } + } + } + } + } + results.add(new RuleMaterialization(rule, matches.matched(), selected)); + } + return results; + } + + RuleSearchResult search(ContextRule rule) { + if (searchRepository == null) { + throw new IllegalStateException("Search is unavailable while materializing persona context"); + } + int maxAssets = rule.getMaxAssets() == null ? DEFAULT_MAX_ASSETS : rule.getMaxAssets(); + List> documents = new ArrayList<>(maxAssets); + Object[] searchAfter = null; + int matched = 0; + String sortField = + KEYWORD_SORT_ENTITY_TYPES.contains(rule.getEntityType()) + ? "fullyQualifiedName.keyword" + : "fullyQualifiedName"; + SearchSortFilter sort = new SearchSortFilter(sortField, "asc", null, null); + String queryFilter = activeEntityFilter(rule.getQueryFilter()); + try { + while (documents.size() < maxAssets) { + int pageSize = Math.min(SEARCH_BATCH_SIZE, maxAssets - documents.size()); + SearchResultListMapper page = + searchRepository.listWithDeepPagination( + rule.getEntityType(), + null, + queryFilter, + SEARCH_FIELDS, + sort, + pageSize, + searchAfter); + if (documents.isEmpty()) { + matched = page.getTotal() > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) page.getTotal(); + } + if (page.getResults() == null || page.getResults().isEmpty()) { + break; + } + documents.addAll(page.getResults()); + searchAfter = page.getLastHitSortValues(); + if (searchAfter == null || page.getResults().size() < pageSize) { + break; + } + } + } catch (IOException | RuntimeException exception) { + ServiceUnavailableException unavailable = + new ServiceUnavailableException( + "Failed to evaluate persona context rule '" + + rule.getName() + + "': " + + exception.getMessage()); + unavailable.initCause(exception); + throw unavailable; + } + return new RuleSearchResult(matched, documents); + } + + static String activeEntityFilter(String queryFilter) { + JsonNode requestedFilter = null; + if (!nullOrEmpty(queryFilter)) { + JsonNode parsedFilter = JsonUtils.readTree(queryFilter); + if (parsedFilter == null || !parsedFilter.isObject()) { + throw new IllegalArgumentException("Persona context queryFilter must be a JSON object"); + } + requestedFilter = parsedFilter.has("query") ? parsedFilter.get("query") : parsedFilter; + } + List filters = new ArrayList<>(); + filters.add(Map.of("term", Map.of("deleted", false))); + if (requestedFilter != null && !requestedFilter.isEmpty()) { + filters.add(requestedFilter); + } + return JsonUtils.pojoToJson(Map.of("query", Map.of("bool", Map.of("filter", filters)))); + } + + public static RulePreview preview(ContextRule rule) { + if (!supportsEntityType(rule.getEntityType())) { + throw new IllegalArgumentException( + "Unsupported persona context entity type: " + rule.getEntityType()); + } + RuleSearchResult result = new PersonaContextBuilder(null).search(rule); + List samples = + result.documents().stream() + .map(PersonaContextBuilder::displayNameOf) + .filter(value -> !nullOrEmpty(value)) + .limit(5) + .toList(); + return new RulePreview(result.matched(), samples); + } + + public static boolean supportsEntityType(String entityType) { + return ASSET_ENTITY_TYPES.contains(entityType) || KNOWLEDGE_ENTITY_TYPES.contains(entityType); + } + + private SelectedEntity buildAssetSelection(ContextRule rule, Map document) { + return buildAssetSelection(rule, document, true); + } + + private SelectedEntity buildAssetSelection( + ContextRule rule, Map document, boolean loadHeavySections) { + String fqn = stringValue(document.get("fullyQualifiedName")); + String id = stringValue(document.get("id")); + AIContext context = + new AIContext() + .withFullyQualifiedName(fqn) + .withEntityType(rule.getEntityType()) + .withDisplayName(stringValue(document.get("displayName"))) + .withDescription(stringValue(document.get("description"))) + .withTags(classificationTags(document)) + .withAssetContext(assetContext(document)) + .withGeneratedAt(System.currentTimeMillis()); + String href = stringValue(document.get("href")); + if (!nullOrEmpty(href)) { + try { + context.withResource(URI.create(href)); + } catch (IllegalArgumentException ignored) { + LOG.debug("Ignoring invalid indexed href for {}: {}", fqn, href); + } + } + if (loadHeavySections && !Entity.DATA_PRODUCT.equals(rule.getEntityType())) { + loadHeavySections(context, selectedSections(rule)); + } + return new SelectedEntity(id, document, context, null, null); + } + + protected List expandDataProductAssets( + SelectedEntity dataProduct, int maxAssets) { + List members = new ArrayList<>(); + if (nullOrEmpty(dataProduct.id()) || maxAssets <= 0) { + return members; + } + UUID dataProductId; + try { + dataProductId = UUID.fromString(dataProduct.id()); + } catch (IllegalArgumentException exception) { + LOG.warn( + "Ignoring invalid data product id for {}: {}", + dataProduct.context().getFullyQualifiedName(), + exception.getMessage()); + return members; + } + DataProductRepository repository = + (DataProductRepository) Entity.getEntityRepository(Entity.DATA_PRODUCT); + int limit = Math.min(maxAssets, DATA_PRODUCT_ASSET_BATCH_SIZE); + ResultList page = repository.getDataProductAssets(dataProductId, limit, 0); + Map> fqnsByType = new LinkedHashMap<>(); + for (EntityReference asset : listOrEmpty(page.getData())) { + if (asset != null + && supportsEntityType(asset.getType()) + && !isKnowledgeEntityType(asset.getType()) + && !nullOrEmpty(asset.getFullyQualifiedName())) { + fqnsByType + .computeIfAbsent(asset.getType(), ignored -> new ArrayList<>()) + .add(asset.getFullyQualifiedName()); + } + } + + for (Map.Entry> entry : fqnsByType.entrySet()) { + if (members.size() >= limit) { + break; + } + List fqns = entry.getValue(); + ContextRule memberRule = + new ContextRule() + .withName("Data product member") + .withEntityType(entry.getKey()) + .withQueryFilter( + JsonUtils.pojoToJson( + Map.of("query", Map.of("terms", Map.of("fullyQualifiedName", fqns))))) + .withMaxAssets(Math.min(fqns.size(), limit - members.size())) + .withFullyRendered(true) + .withSections(ASSET_CONTEXT_SECTIONS); + for (Map document : search(memberRule).documents()) { + members.add(buildAssetSelection(memberRule, document, false)); + } + } + return members; + } + + static Set selectedSections(ContextRule rule) { + return Boolean.TRUE.equals(rule.getFullyRendered()) + ? ASSET_CONTEXT_SECTIONS + : nullOrEmpty(rule.getSections()) ? DEFAULT_ASSET_CONTEXT_SECTIONS : rule.getSections(); + } + + private void loadHeavySections(AIContext context, Set sections) { + Set selected = sections == null ? Set.of() : sections; + boolean needsLineage = selected.contains(ContextSection.LINEAGE); + boolean needsDataQuality = selected.contains(ContextSection.DATA_QUALITY); + if (!needsLineage && !needsDataQuality) { + return; + } + AIContext heavy = + new AIContextBuilder(context.getEntityType(), context.getFullyQualifiedName()).build(); + if (needsLineage) { + context.withUpstream(heavy.getUpstream()).withDownstream(heavy.getDownstream()); + } + if (needsDataQuality && heavy.getObservability() != null) { + context.withObservability( + new Observability().withDataQuality(heavy.getObservability().getDataQuality())); + } + } + + private SelectedEntity buildKnowledgeSelection(ContextRule rule, Map document) { + String entityType = rule.getEntityType(); + String fqn = stringValue(document.get("fullyQualifiedName")); + try { + EntityInterface entity = + Entity.getEntityByName(entityType, fqn, knowledgeFields(entityType), Include.NON_DELETED); + KnowledgeItem item = fullKnowledgeItem(entityType, entity); + if (item == null) { + return null; + } + AIContext context = + new AIContext() + .withFullyQualifiedName(entity.getFullyQualifiedName()) + .withEntityType(entityType) + .withDisplayName(entity.getDisplayName()) + .withDescription(entity.getDescription()) + .withGeneratedAt(System.currentTimeMillis()); + attachKnowledge(context, item, true); + return new SelectedEntity(stringValue(document.get("id")), document, context, item, entity); + } catch (EntityNotFoundException exception) { + LOG.warn("Failed to load persona knowledge entity {}: {}", fqn, exception.getMessage()); + return null; + } + } + + private static String knowledgeFields(String entityType) { + return switch (entityType) { + case Entity.PAGE -> "owners,tags,relatedEntities"; + case Entity.METRIC -> "owners,tags,assets,relatedMetrics"; + case Entity.GLOSSARY_TERM -> "owners,tags,relatedTerms"; + default -> ""; + }; + } + + private SharedKnowledgeAccumulator enrichAssetKnowledge( + List materializedRules) { + List assets = + materializedRules.stream() + .filter(rule -> !isKnowledgeEntityType(rule.rule().getEntityType())) + .flatMap(rule -> rule.entities().stream()) + .filter(entity -> !nullOrEmpty(entity.id())) + .toList(); + SharedKnowledgeAccumulator accumulator = new SharedKnowledgeAccumulator(); + materializedRules.stream() + .filter(rule -> isKnowledgeEntityType(rule.rule().getEntityType())) + .flatMap(rule -> rule.entities().stream()) + .map(SelectedEntity::knowledgeItem) + .forEach(accumulator::exclude); + if (assets.isEmpty()) { + return accumulator; + } + + Map ruleByEntity = indexRulesByEntity(materializedRules); + Map assetById = new LinkedHashMap<>(); + assets.forEach(asset -> assetById.put(asset.id(), asset)); + List assetIds = new ArrayList<>(assetById.keySet()); + CollectionDAO.EntityRelationshipDAO relationships = Entity.getCollectionDAO().relationshipDAO(); + + Map> pageIdsByAsset = + groupRelatedIds( + relationships.findToBatch(assetIds, Relationship.HAS.ordinal(), Entity.PAGE), true); + Map> metricIdsByAsset = + groupRelatedIds( + relationships.findFromBatch(assetIds, Relationship.APPLIED_TO.ordinal(), Entity.METRIC), + false); + Map pages = entitiesById(Entity.PAGE, flatten(pageIdsByAsset.values()), Page.class); + Map metrics = + entitiesById(Entity.METRIC, flatten(metricIdsByAsset.values()), Metric.class); + Set glossaryFqns = new LinkedHashSet<>(); + for (SelectedEntity asset : assets) { + ContextRule rule = ruleByEntity.get(asset); + if (selectedSections(rule).contains(ContextSection.GLOSSARY_TERMS)) { + glossaryFqns.addAll(glossaryFqns(asset.document())); + } + } + Map glossaryTerms = new HashMap<>(); + for (String glossaryFqn : glossaryFqns) { + KnowledgeItem term = loadGlossaryTerm(glossaryFqn); + if (term != null) { + glossaryTerms.put(glossaryFqn, term); + } + } + + for (SelectedEntity asset : assets) { + ContextRule rule = ruleByEntity.get(asset); + Set sections = selectedSections(rule); + if (sections.contains(ContextSection.GLOSSARY_TERMS)) { + for (String termFqn : glossaryFqns(asset.document())) { + KnowledgeItem full = glossaryTerms.get(termFqn); + if (full != null) { + accumulator.add(full); + attachKnowledge(asset.context(), referenceOf(full), false); + } + } + } + if (sections.contains(ContextSection.ARTICLES)) { + for (UUID pageId : pageIdsByAsset.getOrDefault(asset.id(), List.of())) { + Page page = pages.get(pageId); + if (page != null) { + KnowledgeItem full = fullKnowledgeItem(Entity.PAGE, page); + accumulator.add(full); + attachKnowledge(asset.context(), referenceOf(full), false); + } + } + } + if (sections.contains(ContextSection.METRICS)) { + for (UUID metricId : metricIdsByAsset.getOrDefault(asset.id(), List.of())) { + Metric metric = metrics.get(metricId); + if (metric != null) { + KnowledgeItem full = fullKnowledgeItem(Entity.METRIC, metric); + accumulator.add(full); + attachKnowledge(asset.context(), referenceOf(full), false); + } + } + } + } + return accumulator; + } + + private static void loadProfiles(List materializedRules) { + Map assetsByFqnHash = new HashMap<>(); + for (RuleMaterialization materialization : materializedRules) { + if (!selectedSections(materialization.rule()).contains(ContextSection.PROFILE)) { + continue; + } + for (SelectedEntity selected : materialization.entities()) { + if (!Entity.TABLE.equals(selected.context().getEntityType())) { + continue; + } + String fqn = selected.context().getFullyQualifiedName(); + if (!nullOrEmpty(fqn)) { + assetsByFqnHash.put(FullyQualifiedName.buildHash(fqn), selected); + } + } + } + if (assetsByFqnHash.isEmpty()) { + return; + } + + List fqns = + assetsByFqnHash.values().stream() + .map(selected -> selected.context().getFullyQualifiedName()) + .toList(); + List profiles; + try { + profiles = + Entity.getCollectionDAO() + .profilerDataTimeSeriesDao() + .getLatestExtensionsBatch(fqns, TableRepository.TABLE_PROFILE_EXTENSION); + } catch (RuntimeException exception) { + LOG.warn("Failed to load batched persona profile summaries: {}", exception.getMessage()); + return; + } + for (CollectionDAO.ProfilerDataTimeSeriesDAO.LatestExtensionRecord record : profiles) { + SelectedEntity selected = assetsByFqnHash.get(record.entityFQNHash()); + if (selected == null) { + continue; + } + try { + JsonNode profile = JsonUtils.readTree(record.json()); + JsonNode profileData = profile == null ? null : profile.get("profileData"); + if (profileData == null || !profileData.isObject()) { + continue; + } + TableProfile tableProfile = JsonUtils.convertValue(profileData, TableProfile.class); + Observability observability = selected.context().getObservability(); + if (observability == null) { + observability = new Observability(); + selected.context().withObservability(observability); + } + observability + .withRowCount(tableProfile.getRowCount()) + .withProfiledAt(tableProfile.getTimestamp()); + } catch (RuntimeException exception) { + LOG.warn( + "Failed to load persona profile summary for {}: {}", + selected.context().getFullyQualifiedName(), + exception.getMessage()); + } + } + } + + static Map indexRulesByEntity( + List materializedRules) { + Map ruleByEntity = new IdentityHashMap<>(); + for (RuleMaterialization materialization : materializedRules) { + for (SelectedEntity entity : materialization.entities()) { + ruleByEntity.put(entity, materialization.rule()); + } + } + return ruleByEntity; + } + + static Map> groupRelatedIds( + List records, boolean assetIsFrom) { + Map> grouped = new HashMap<>(); + for (CollectionDAO.EntityRelationshipObject record : listOrEmpty(records)) { + String assetId = assetIsFrom ? record.getFromId() : record.getToId(); + String knowledgeId = assetIsFrom ? record.getToId() : record.getFromId(); + try { + grouped + .computeIfAbsent(assetId, ignored -> new ArrayList<>()) + .add(UUID.fromString(knowledgeId)); + } catch (IllegalArgumentException exception) { + LOG.debug("Ignoring invalid knowledge relationship id: {}", knowledgeId); + } + } + return grouped; + } + + static List flatten(Collection> values) { + return values.stream().flatMap(Collection::stream).distinct().toList(); + } + + static Map entitiesById( + String entityType, List ids, Class entityClass) { + Map entitiesById = new HashMap<>(); + if (ids.isEmpty()) { + return entitiesById; + } + List references = + Entity.getEntityReferencesByIds(entityType, ids, Include.NON_DELETED); + List entities = Entity.getEntities(references, "", Include.NON_DELETED); + for (T entity : entities) { + if (entityClass.isInstance(entity)) { + entitiesById.put(entity.getId(), entity); + } + } + return entitiesById; + } + + static KnowledgeItem loadGlossaryTerm(String fqn) { + try { + GlossaryTerm term = + Entity.getEntityByName(Entity.GLOSSARY_TERM, fqn, "", Include.NON_DELETED); + return fullKnowledgeItem(Entity.GLOSSARY_TERM, term); + } catch (EntityNotFoundException exception) { + LOG.warn("Failed to load persona glossary term {}: {}", fqn, exception.getMessage()); + return null; + } + } + + static KnowledgeItem fullKnowledgeItem(String entityType, EntityInterface entity) { + if (entity instanceof GlossaryTerm term && term.getEntityStatus() != EntityStatus.APPROVED) { + return null; + } + KnowledgeItem.Type type = + switch (entityType) { + case Entity.GLOSSARY_TERM -> KnowledgeItem.Type.GLOSSARY_TERM; + case Entity.PAGE -> KnowledgeItem.Type.PAGE; + case Entity.METRIC -> KnowledgeItem.Type.METRIC; + default -> throw new IllegalArgumentException( + "Unsupported knowledge type: " + entityType); + }; + return new KnowledgeItem() + .withType(type) + .withName(entity.getName()) + .withDisplayName(entity.getDisplayName()) + .withFullyQualifiedName(entity.getFullyQualifiedName()) + .withContent(AIContextBuilder.fullContentOf(entity)); + } + + private static KnowledgeItem referenceOf(KnowledgeItem item) { + return new KnowledgeItem() + .withType(item.getType()) + .withName(item.getName()) + .withDisplayName(item.getDisplayName()) + .withFullyQualifiedName(item.getFullyQualifiedName()); + } + + private static void attachKnowledge(AIContext context, KnowledgeItem item, boolean full) { + if (item == null || item.getType() == null) { + return; + } + KnowledgeItem attached = full ? item : referenceOf(item); + switch (item.getType()) { + case GLOSSARY_TERM -> { + List terms = new ArrayList<>(listOrEmpty(context.getGlossaryTerms())); + terms.add(attached); + context.withGlossaryTerms(terms); + } + case METRIC -> { + List metrics = new ArrayList<>(listOrEmpty(context.getMetrics())); + metrics.add(attached); + context.withMetrics(metrics); + } + case PAGE -> { + List articles = new ArrayList<>(listOrEmpty(context.getArticles())); + articles.add(attached); + context.withArticles(articles); + } + case CONTEXT_MEMORY -> { + // Per-user knowledge pills are deliberately excluded from persona-scoped shared context. + } + } + } + + @SuppressWarnings("unchecked") + static AssetContext assetContext(Map document) { + Object indexedContext = document.get("aiContext"); + if (!(indexedContext instanceof Map aiContext)) { + return null; + } + Object table = aiContext.get("table"); + if (!(table instanceof Map)) { + return null; + } + TableContext tableContext = JsonUtils.convertValue(table, TableContext.class); + return new AssetContext().withTable(tableContext); + } + + private static List classificationTags(Map document) { + LinkedHashSet tags = new LinkedHashSet<>(); + addStrings(tags, document.get("classificationTags")); + Object tier = document.get("tier"); + if (tier instanceof Map tierMap) { + String tierFqn = stringValue(tierMap.get("tagFQN")); + if (!nullOrEmpty(tierFqn)) { + tags.add(tierFqn); + } + } + if (tags.isEmpty()) { + for (Map tag : tagMaps(document.get("tags"))) { + if (!"Glossary".equalsIgnoreCase(stringValue(tag.get("source")))) { + String tagFqn = stringValue(tag.get("tagFQN")); + if (!nullOrEmpty(tagFqn)) { + tags.add(tagFqn); + } + } + } + } + return new ArrayList<>(tags); + } + + static List glossaryFqns(Map document) { + LinkedHashSet terms = new LinkedHashSet<>(); + addStrings(terms, document.get("glossaryTags")); + if (terms.isEmpty()) { + for (Map tag : tagMaps(document.get("tags"))) { + if ("Glossary".equalsIgnoreCase(stringValue(tag.get("source")))) { + String tagFqn = stringValue(tag.get("tagFQN")); + if (!nullOrEmpty(tagFqn)) { + terms.add(tagFqn); + } + } + } + } + return new ArrayList<>(terms); + } + + private static void addStrings(Set destination, Object value) { + if (value instanceof Collection values) { + values.stream() + .map(PersonaContextBuilder::stringValue) + .filter(v -> !nullOrEmpty(v)) + .forEach(destination::add); + } + } + + @SuppressWarnings("unchecked") + private static List> tagMaps(Object tags) { + if (!(tags instanceof Collection collection)) { + return List.of(); + } + return collection.stream() + .filter(Map.class::isInstance) + .map(tag -> (Map) tag) + .toList(); + } + + private static String stringValue(Object value) { + return value == null ? null : String.valueOf(value); + } + + private static String displayNameOf(Map document) { + String displayName = stringValue(document.get("displayName")); + if (!nullOrEmpty(displayName)) { + return displayName; + } + String name = stringValue(document.get("name")); + return !nullOrEmpty(name) ? name : stringValue(document.get("fullyQualifiedName")); + } + + public static boolean isKnowledgeEntityType(String entityType) { + return KNOWLEDGE_ENTITY_TYPES.contains(entityType); + } + + public record MaterializedPersonaContext(PersonaContext context, String markdown) {} + + record RuleSearchResult(int matched, List> documents) {} + + record SelectedEntity( + String id, + Map document, + AIContext context, + KnowledgeItem knowledgeItem, + EntityInterface knowledgeEntity) {} + + record RuleMaterialization(ContextRule rule, int matched, List entities) {} + + public record RulePreview(int matchedCount, List sampleNames) {} + + private static final class SharedKnowledgeAccumulator { + private final Set excluded = new HashSet<>(); + private final Map items = new LinkedHashMap<>(); + private boolean overflowed; + + boolean add(KnowledgeItem item) { + if (item == null || item.getType() == null || nullOrEmpty(item.getFullyQualifiedName())) { + return false; + } + String key = item.getType().value() + ':' + item.getFullyQualifiedName(); + if (excluded.contains(key) || items.containsKey(key)) { + return true; + } + if (items.size() >= MAX_SHARED_KNOWLEDGE_ITEMS) { + overflowed = true; + return false; + } + items.put(key, item); + return true; + } + + void exclude(KnowledgeItem item) { + if (item != null && item.getType() != null && !nullOrEmpty(item.getFullyQualifiedName())) { + excluded.add(item.getType().value() + ':' + item.getFullyQualifiedName()); + } + } + + boolean overflowed() { + return overflowed; + } + + SharedKnowledge toSharedKnowledge() { + Comparator byFqn = + Comparator.comparing( + KnowledgeItem::getFullyQualifiedName, Comparator.nullsLast(String::compareTo)); + List terms = new ArrayList<>(); + List metrics = new ArrayList<>(); + List articles = new ArrayList<>(); + for (KnowledgeItem item : items.values()) { + switch (item.getType()) { + case GLOSSARY_TERM -> terms.add(item); + case METRIC -> metrics.add(item); + case PAGE -> articles.add(item); + case CONTEXT_MEMORY -> { + // Per-user knowledge pills are deliberately excluded. + } + } + } + terms.sort(byFqn); + metrics.sort(byFqn); + articles.sort(byFqn); + return new SharedKnowledge() + .withGlossaryTerms(terms) + .withMetrics(metrics) + .withArticles(articles); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextCache.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextCache.java new file mode 100644 index 000000000000..d251bf3a1873 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextCache.java @@ -0,0 +1,402 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.aicontext; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.entity.teams.Persona; +import org.openmetadata.schema.type.PersonaContext; +import org.openmetadata.schema.type.PersonaContextDefinition; +import org.openmetadata.schema.type.personaContext.PersonaContextCacheState; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.cache.CacheBundle; +import org.openmetadata.service.cache.CacheConfig; +import org.openmetadata.service.cache.CacheKeys; +import org.openmetadata.service.cache.CacheProvider; + +/** Two-level cache and distributed single-flight coordinator for persona context documents. */ +@Slf4j +public class PersonaContextCache { + public static final String CACHE_HEADER = "X-Cache"; + private static final int MAX_CACHEABLE_CHARS = 8_000_000; + private static final Duration BUILD_LEASE = Duration.ofSeconds(120); + private static final int POLL_ATTEMPTS = 30; + private static final long POLL_MILLIS = 500; + private static final AtomicInteger REFRESH_THREAD_SEQUENCE = new AtomicInteger(); + private static final ThreadPoolExecutor REFRESH_EXECUTOR = + new ThreadPoolExecutor( + 2, + 2, + 0, + TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(50), + runnable -> { + Thread thread = + new Thread( + runnable, + "persona-context-refresh-" + REFRESH_THREAD_SEQUENCE.incrementAndGet()); + thread.setDaemon(true); + return thread; + }, + new ThreadPoolExecutor.AbortPolicy()); + private static volatile PersonaContextCache instance; + + private final CacheProvider provider; + private final CacheKeys keys; + private final int pollAttempts; + private final long pollMillis; + private final String nodeId = UUID.randomUUID().toString(); + private final Cache local = Caffeine.newBuilder().maximumSize(50).build(); + private final ConcurrentMap generationStates = new ConcurrentHashMap<>(); + + PersonaContextCache(CacheProvider provider, CacheKeys keys) { + this(provider, keys, POLL_ATTEMPTS, POLL_MILLIS); + } + + PersonaContextCache(CacheProvider provider, CacheKeys keys, int pollAttempts, long pollMillis) { + this.provider = provider; + this.keys = keys; + this.pollAttempts = pollAttempts; + this.pollMillis = pollMillis; + } + + public static PersonaContextCache getInstance() { + CacheProvider currentProvider = CacheBundle.getCacheProvider(); + PersonaContextCache current = instance; + if (current == null || current.provider != currentProvider) { + synchronized (PersonaContextCache.class) { + current = instance; + if (current == null || current.provider != currentProvider) { + CacheConfig config = CacheBundle.getCacheConfig(); + String namespace = config == null ? "om:prod" : config.redis.keyspace; + current = new PersonaContextCache(currentProvider, new CacheKeys(namespace)); + instance = current; + } + } + } + return current; + } + + public CachedResult get(Persona persona, boolean refresh) { + PersonaContextDefinition definition = PersonaContextBuilder.definitionOf(persona); + String definitionHash = PersonaContextHash.definitionHash(definition); + String localKey = localKey(persona.getId(), definitionHash); + int ttlSeconds = PersonaContextBuilder.cacheTtlSeconds(definition); + Long previousGeneratedAt = null; + + if (!refresh) { + PersonaContextBuilder.MaterializedPersonaContext localValue = getLocal(localKey); + if (localValue != null) { + return new CachedResult(localValue, CacheStatus.HIT); + } + } + + boolean redisAvailable = provider.available(); + if (refresh) { + PersonaContextBuilder.MaterializedPersonaContext previous = getLocal(localKey); + if (previous == null && redisAvailable) { + previous = getRedis(persona.getId(), definitionHash); + } + if (previous != null && previous.context() != null) { + previousGeneratedAt = previous.context().getGeneratedAt(); + } + } + if (!refresh && redisAvailable) { + PersonaContextBuilder.MaterializedPersonaContext cached = + getRedis(persona.getId(), definitionHash); + if (cached != null) { + putLocal(localKey, cached, ttlSeconds); + return new CachedResult(cached, CacheStatus.HIT); + } + } + + if (!redisAvailable) { + PersonaContextBuilder.MaterializedPersonaContext built = build(persona); + cacheIfEligible(localKey, built, ttlSeconds, false, persona.getId(), definitionHash); + markFresh(persona); + return new CachedResult(built, CacheStatus.BYPASS); + } + + String lockKey = keys.personaContextLock(persona.getId()); + String lockOwner = nodeId + ':' + UUID.randomUUID(); + boolean ownsLock = provider.setIfAbsent(lockKey, lockOwner, BUILD_LEASE); + if (!ownsLock) { + PersonaContextBuilder.MaterializedPersonaContext winner = + waitForWinner(persona.getId(), definitionHash, previousGeneratedAt); + if (winner != null) { + putLocal(localKey, winner, ttlSeconds); + return new CachedResult(winner, refresh ? CacheStatus.BYPASS : CacheStatus.HIT); + } + ownsLock = provider.setIfAbsent(lockKey, lockOwner, BUILD_LEASE); + if (!ownsLock) { + PersonaContextBuilder.MaterializedPersonaContext built = build(persona); + cacheIfEligible(localKey, built, ttlSeconds, false, persona.getId(), definitionHash); + markFresh(persona); + return new CachedResult(built, CacheStatus.BYPASS); + } + } + + try { + PersonaContextBuilder.MaterializedPersonaContext built = build(persona); + cacheIfEligible(localKey, built, ttlSeconds, true, persona.getId(), definitionHash); + markFresh(persona); + return new CachedResult(built, refresh ? CacheStatus.BYPASS : CacheStatus.MISS); + } finally { + if (ownsLock) { + provider.deleteIfValue(lockKey, lockOwner); + } + } + } + + public void invalidate(Persona persona) { + if (persona == null || persona.getId() == null) { + return; + } + String definitionHash = + PersonaContextHash.definitionHash(PersonaContextBuilder.definitionOf(persona)); + invalidate(persona.getId(), definitionHash); + generationStates.remove(persona.getId()); + } + + public void invalidate(Persona original, Persona updated) { + if (original == null || original.getId() == null) { + return; + } + String oldHash = + PersonaContextHash.definitionHash(PersonaContextBuilder.definitionOf(original)); + String newHash = PersonaContextHash.definitionHash(PersonaContextBuilder.definitionOf(updated)); + provider.del( + keys.personaContextMarkdown(original.getId(), oldHash), + keys.personaContextJson(original.getId(), oldHash), + keys.personaContextMarkdown(original.getId(), newHash), + keys.personaContextJson(original.getId(), newHash)); + local.invalidate(localKey(original.getId(), oldHash)); + local.invalidate(localKey(original.getId(), newHash)); + generationStates.remove(original.getId()); + } + + public CachedResult refresh(Persona persona) { + try { + CachedResult result = get(persona, true); + markFresh(persona); + return result; + } catch (RuntimeException exception) { + markFailed(persona, exception); + throw exception; + } + } + + public void refreshAsync(Persona persona) { + if (persona == null || persona.getId() == null) { + return; + } + synchronized (generationStates) { + GenerationState current = generationStates.get(persona.getId()); + if (current != null && current.state() == PersonaContextCacheState.GENERATING) { + return; + } + generationStates.put( + persona.getId(), new GenerationState(PersonaContextCacheState.GENERATING, null)); + } + try { + REFRESH_EXECUTOR.execute( + () -> { + try { + refresh(persona); + } catch (RuntimeException exception) { + LOG.warn( + "Persona context compilation failed for {}: {}", + persona.getFullyQualifiedName(), + exception.getMessage()); + } + }); + } catch (RejectedExecutionException exception) { + markFailed(persona, exception); + LOG.warn("Persona context refresh queue is full for {}", persona.getFullyQualifiedName()); + } + } + + public CacheSnapshot snapshot(Persona persona) { + PersonaContextDefinition definition = PersonaContextBuilder.definitionOf(persona); + String definitionHash = PersonaContextHash.definitionHash(definition); + String localKey = localKey(persona.getId(), definitionHash); + PersonaContextBuilder.MaterializedPersonaContext value = getLocal(localKey); + if (value == null && provider.available()) { + value = getRedis(persona.getId(), definitionHash); + if (value != null) { + putLocal(localKey, value, PersonaContextBuilder.cacheTtlSeconds(definition)); + } + } + GenerationState generation = generationStates.get(persona.getId()); + if (generation != null && generation.state() == PersonaContextCacheState.GENERATING) { + return new CacheSnapshot(generation.state(), value, null); + } + if (generation != null && generation.state() == PersonaContextCacheState.FAILED) { + return new CacheSnapshot(generation.state(), value, generation.error()); + } + return new CacheSnapshot( + value == null ? PersonaContextCacheState.STALE : PersonaContextCacheState.FRESH, + value, + null); + } + + private void invalidate(UUID personaId, String definitionHash) { + provider.del( + keys.personaContextMarkdown(personaId, definitionHash), + keys.personaContextJson(personaId, definitionHash)); + local.invalidate(localKey(personaId, definitionHash)); + } + + protected PersonaContextBuilder.MaterializedPersonaContext build(Persona persona) { + return new PersonaContextBuilder(persona).build(); + } + + private PersonaContextBuilder.MaterializedPersonaContext getLocal(String key) { + LocalEntry entry = local.getIfPresent(key); + PersonaContextBuilder.MaterializedPersonaContext result = null; + if (entry != null) { + if (entry.expiresAtNanos() > System.nanoTime()) { + result = entry.value(); + } else { + local.invalidate(key); + } + } + return result; + } + + private PersonaContextBuilder.MaterializedPersonaContext getRedis( + UUID personaId, String definitionHash) { + List> values = + provider.mget( + List.of( + keys.personaContextMarkdown(personaId, definitionHash), + keys.personaContextJson(personaId, definitionHash))); + if (values.size() != 2 || values.get(0).isEmpty() || values.get(1).isEmpty()) { + return null; + } + try { + PersonaContext context = JsonUtils.readValue(values.get(1).get(), PersonaContext.class); + return new PersonaContextBuilder.MaterializedPersonaContext(context, values.get(0).get()); + } catch (RuntimeException exception) { + LOG.warn("Ignoring invalid cached persona context for {}", personaId, exception); + return null; + } + } + + private PersonaContextBuilder.MaterializedPersonaContext waitForWinner( + UUID personaId, String definitionHash, Long previousGeneratedAt) { + for (int attempt = 0; attempt < pollAttempts; attempt++) { + try { + TimeUnit.MILLISECONDS.sleep(pollMillis); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + break; + } + PersonaContextBuilder.MaterializedPersonaContext cached = getRedis(personaId, definitionHash); + if (cached != null && generatedAfter(cached, previousGeneratedAt)) { + return cached; + } + } + return null; + } + + private static boolean generatedAfter( + PersonaContextBuilder.MaterializedPersonaContext cached, Long previousGeneratedAt) { + Long generatedAt = cached.context().getGeneratedAt(); + return previousGeneratedAt == null + || (generatedAt != null && generatedAt > previousGeneratedAt); + } + + private void cacheIfEligible( + String localKey, + PersonaContextBuilder.MaterializedPersonaContext value, + int ttlSeconds, + boolean writeRedis, + UUID personaId, + String definitionHash) { + String json = JsonUtils.pojoToJson(value.context()); + if (value.markdown().length() > MAX_CACHEABLE_CHARS || json.length() > MAX_CACHEABLE_CHARS) { + LOG.warn("Persona context {} exceeds the cache safety limit", personaId); + return; + } + putLocal(localKey, value, ttlSeconds); + if (writeRedis) { + Duration ttl = Duration.ofSeconds(ttlSeconds); + provider.set(keys.personaContextMarkdown(personaId, definitionHash), value.markdown(), ttl); + provider.set(keys.personaContextJson(personaId, definitionHash), json, ttl); + } + } + + private void putLocal( + String key, PersonaContextBuilder.MaterializedPersonaContext value, int ttlSeconds) { + local.put( + key, + new LocalEntry( + value, System.nanoTime() + TimeUnit.SECONDS.toNanos(Math.max(1, ttlSeconds)))); + } + + private void markFresh(Persona persona) { + if (persona != null && persona.getId() != null) { + generationStates.remove(persona.getId()); + } + } + + private void markFailed(Persona persona, RuntimeException exception) { + if (persona != null && persona.getId() != null) { + generationStates.put( + persona.getId(), + new GenerationState(PersonaContextCacheState.FAILED, nullOrMessage(exception))); + } + } + + private static String nullOrMessage(RuntimeException exception) { + return exception.getMessage() == null + ? "Persona context compilation failed." + : exception.getMessage(); + } + + private static String localKey(UUID personaId, String definitionHash) { + return personaId + ":" + definitionHash; + } + + public enum CacheStatus { + HIT, + MISS, + BYPASS + } + + public record CachedResult( + PersonaContextBuilder.MaterializedPersonaContext value, CacheStatus status) {} + + public record CacheSnapshot( + PersonaContextCacheState state, + PersonaContextBuilder.MaterializedPersonaContext value, + String error) {} + + private record LocalEntry( + PersonaContextBuilder.MaterializedPersonaContext value, long expiresAtNanos) {} + + private record GenerationState(PersonaContextCacheState state, String error) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextHash.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextHash.java new file mode 100644 index 000000000000..4304f6f8d4e2 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextHash.java @@ -0,0 +1,42 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.aicontext; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import org.openmetadata.schema.type.PersonaContextDefinition; +import org.openmetadata.schema.utils.JsonUtils; + +final class PersonaContextHash { + private PersonaContextHash() {} + + static String definitionHash(PersonaContextDefinition definition) { + return shortSha256(JsonUtils.pojoToJson(definition)); + } + + static String contentHash(String content) { + return shortSha256(content); + } + + private static String shortSha256(String value) { + try { + byte[] digest = + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest, 0, 8); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextMarkdown.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextMarkdown.java new file mode 100644 index 000000000000..35cd6d8b69b6 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/PersonaContextMarkdown.java @@ -0,0 +1,679 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.aicontext; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.GlossaryTerm; +import org.openmetadata.schema.entity.data.Metric; +import org.openmetadata.schema.entity.data.Page; +import org.openmetadata.schema.entity.teams.Persona; +import org.openmetadata.schema.type.AIContext; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.PersonaContext; +import org.openmetadata.schema.type.PersonaContextDefinition; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.schema.type.TermRelation; +import org.openmetadata.schema.type.aicontext.FieldContext; +import org.openmetadata.schema.type.aicontext.KnowledgeItem; +import org.openmetadata.schema.type.aicontext.TableContext; +import org.openmetadata.schema.type.personaContext.ContextSection; +import org.openmetadata.schema.type.personaContext.ManifestEntry; +import org.openmetadata.schema.type.personaContext.RuleResult; +import org.openmetadata.schema.type.personaContext.SharedKnowledge; + +/** Renders a materialized persona context with monotonic full/compact/manifest degradation. */ +final class PersonaContextMarkdown { + private static final int COMPACT_MAX_CHARS = 1200; + private static final int DOCUMENT_OVERHEAD_RESERVE = 1024; + + private PersonaContextMarkdown() {} + + static PersonaContextBuilder.MaterializedPersonaContext render( + Persona persona, + PersonaContextDefinition definition, + List rules, + PersonaContext context, + boolean knowledgeOverflowed) { + int maxChars = PersonaContextBuilder.characterBudget(definition); + int headingChars = rules.stream().mapToInt(PersonaContextMarkdown::ruleHeadingEstimate).sum(); + Map renderedKnowledge = + new IdentityHashMap<>(); + int mandatoryKnowledgeChars = 0; + for (PersonaContextBuilder.RuleMaterialization rule : rules) { + if (PersonaContextBuilder.isKnowledgeEntityType(rule.rule().getEntityType())) { + RuleRenderResult rendered = renderKnowledgeRule(rule); + renderedKnowledge.put(rule, rendered); + mandatoryKnowledgeChars += rendered.body().length(); + } + } + String sharedKnowledge = renderSharedKnowledge(context.getSharedKnowledge()); + mandatoryKnowledgeChars += sharedKnowledge.length(); + int contentBudget = Math.max(0, maxChars - headingChars - DOCUMENT_OVERHEAD_RESERVE); + BudgetTracker budget = new BudgetTracker(Math.max(0, contentBudget - mandatoryKnowledgeChars)); + List ruleResults = new ArrayList<>(); + List manifest = new ArrayList<>(); + StringBuilder body = new StringBuilder(); + RenderTier tier = RenderTier.FULL; + + for (PersonaContextBuilder.RuleMaterialization rule : rules) { + RuleRenderResult rendered = + PersonaContextBuilder.isKnowledgeEntityType(rule.rule().getEntityType()) + ? renderedKnowledge.get(rule) + : renderAssetRule(rule, budget, tier, manifest); + if (!PersonaContextBuilder.isKnowledgeEntityType(rule.rule().getEntityType())) { + tier = rendered.nextTier(); + } + ruleResults.add(rendered.result()); + body.append(ruleHeading(rule, rendered.result())).append(rendered.body()); + } + body.append(sharedKnowledge); + appendManifest(body, manifest); + + boolean truncated = + knowledgeOverflowed || mandatoryKnowledgeChars > contentBudget || !manifest.isEmpty(); + context.withRules(ruleResults).withManifest(manifest).withTruncated(truncated); + + String definitionHash = PersonaContextHash.definitionHash(definition); + context.withFingerprint(definitionHash); + int tokensEstimate = Math.max(1, (renderTitle(persona).length() + body.length()) / 4); + String deterministicContent = renderTitle(persona) + body; + context.withFingerprint( + definitionHash + ':' + PersonaContextHash.contentHash(deterministicContent)); + String markdown = + (frontmatter(context, maxChars, tokensEstimate) + renderTitle(persona) + body).strip() + + "\n"; + return new PersonaContextBuilder.MaterializedPersonaContext(context, markdown); + } + + private static RuleRenderResult renderKnowledgeRule( + PersonaContextBuilder.RuleMaterialization rule) { + StringBuilder body = new StringBuilder(); + List entities = new ArrayList<>(); + for (PersonaContextBuilder.SelectedEntity selected : rule.entities()) { + body.append(renderKnowledgeEntity(selected, Set.of(), true)); + entities.add(selected.context()); + } + RuleResult result = + new RuleResult() + .withRuleName(rule.rule().getName()) + .withEntityType(rule.rule().getEntityType()) + .withMatched(rule.matched()) + .withRenderedFull(entities.size()) + .withRenderedCompact(0) + .withManifestOnly(0) + .withEntities(entities); + return new RuleRenderResult(result, body.toString(), RenderTier.FULL); + } + + private static String renderKnowledgeEntity( + PersonaContextBuilder.SelectedEntity selected, + Set sections, + boolean fullyRendered) { + KnowledgeItem item = selected.knowledgeItem(); + if (item == null) { + return ""; + } + StringBuilder markdown = new StringBuilder(); + markdown + .append("\n## ") + .append(knowledgeTypeLabel(item)) + .append(": ") + .append(labelOf(item)) + .append('\n'); + if (!nullOrEmpty(item.getFullyQualifiedName())) { + markdown.append('`').append(item.getFullyQualifiedName()).append("`\n"); + } + EntityInterface entity = selected.knowledgeEntity(); + if (entity == null) { + if (!nullOrEmpty(item.getContent())) { + markdown.append('\n').append(item.getContent().strip()).append('\n'); + } + return markdown.toString(); + } + appendKnowledgeSections(markdown, entity, sections, fullyRendered); + return markdown.toString(); + } + + private static void appendKnowledgeSections( + StringBuilder markdown, + EntityInterface entity, + Set sections, + boolean fullyRendered) { + if (entity instanceof Page page) { + appendArticleSections(markdown, page, sections, fullyRendered); + } else if (entity instanceof Metric metric) { + appendMetricSections(markdown, metric, sections, fullyRendered); + } else if (entity instanceof GlossaryTerm term) { + appendGlossarySections(markdown, term, sections, fullyRendered); + } + } + + private static void appendArticleSections( + StringBuilder markdown, Page page, Set sections, boolean all) { + String content = page.getDescription(); + if ((all || sections.contains(ContextSection.TITLE_SUMMARY)) && !nullOrEmpty(content)) { + appendSection(markdown, "Summary", firstLine(content)); + } + if ((all || sections.contains(ContextSection.FULL_BODY)) && !nullOrEmpty(content)) { + appendSection(markdown, "Full Body", content); + } + if (all || sections.contains(ContextSection.TAGS)) { + appendTags(markdown, page.getTags()); + } + if (all || sections.contains(ContextSection.GLOSSARY_TERMS)) { + appendGlossaryTags(markdown, page.getTags()); + } + if (all || sections.contains(ContextSection.RELATED_ASSETS)) { + appendReferences(markdown, "Related Assets", page.getRelatedEntities()); + } + } + + private static void appendMetricSections( + StringBuilder markdown, Metric metric, Set sections, boolean all) { + if ((all || sections.contains(ContextSection.DEFINITION)) + && !nullOrEmpty(metric.getDescription())) { + appendSection(markdown, "Definition", metric.getDescription()); + } + if ((all || sections.contains(ContextSection.FORMULA_EXPRESSION)) + && metric.getMetricExpression() != null + && !nullOrEmpty(metric.getMetricExpression().getCode())) { + String language = + metric.getMetricExpression().getLanguage() == null + ? "text" + : metric.getMetricExpression().getLanguage().value().toLowerCase(); + appendSection( + markdown, + "Formula / Expression", + "```" + language + '\n' + metric.getMetricExpression().getCode() + "\n```"); + } + if (all || sections.contains(ContextSection.UNIT_GRAIN)) { + List values = new ArrayList<>(); + if (!nullOrEmpty(metric.getCustomUnitOfMeasurement())) { + values.add("Unit: " + metric.getCustomUnitOfMeasurement()); + } else if (metric.getUnitOfMeasurement() != null) { + values.add("Unit: " + metric.getUnitOfMeasurement().value()); + } + if (metric.getGranularity() != null) { + values.add("Grain: " + metric.getGranularity().value()); + } + if (!values.isEmpty()) { + appendSection(markdown, "Unit & Grain", String.join("\n\n", values)); + } + } + if (all || sections.contains(ContextSection.OWNER)) { + appendReferences(markdown, "Owners", metric.getOwners()); + } + if (all || sections.contains(ContextSection.TAGS)) { + appendTags(markdown, metric.getTags()); + } + if (all || sections.contains(ContextSection.RELATED_ASSETS)) { + appendReferences(markdown, "Related Assets", metric.getAssets()); + } + } + + private static void appendGlossarySections( + StringBuilder markdown, GlossaryTerm term, Set sections, boolean all) { + if ((all || sections.contains(ContextSection.DEFINITION)) + && !nullOrEmpty(term.getDescription())) { + appendSection(markdown, "Definition", term.getDescription()); + } + if ((all || sections.contains(ContextSection.SYNONYMS)) + && !listOrEmpty(term.getSynonyms()).isEmpty()) { + appendSection(markdown, "Synonyms", String.join(", ", term.getSynonyms())); + } + if (all || sections.contains(ContextSection.RELATED_TERMS)) { + appendRelatedTerms(markdown, term.getRelatedTerms()); + } + if (all || sections.contains(ContextSection.TAGS)) { + appendTags(markdown, term.getTags()); + } + if (all || sections.contains(ContextSection.RELATED_ASSETS)) { + appendSection( + markdown, + "Related Assets", + "Resolve assets tagged with `" + term.getFullyQualifiedName() + "` in Explore."); + } + } + + private static void appendSection(StringBuilder markdown, String heading, String content) { + if (!nullOrEmpty(content)) { + markdown.append("\n### ").append(heading).append("\n\n").append(content.strip()).append('\n'); + } + } + + private static void appendTags(StringBuilder markdown, List tags) { + List labels = + listOrEmpty(tags).stream() + .filter( + tag -> + tag.getSource() == null + || !"Glossary".equalsIgnoreCase(tag.getSource().value())) + .map(TagLabel::getTagFQN) + .filter(value -> !nullOrEmpty(value)) + .toList(); + if (!labels.isEmpty()) { + appendSection(markdown, "Tags", String.join(", ", labels)); + } + } + + private static void appendGlossaryTags(StringBuilder markdown, List tags) { + List labels = + listOrEmpty(tags).stream() + .filter( + tag -> + tag.getSource() != null && "Glossary".equalsIgnoreCase(tag.getSource().value())) + .map(TagLabel::getTagFQN) + .filter(value -> !nullOrEmpty(value)) + .toList(); + if (!labels.isEmpty()) { + appendSection(markdown, "Related Glossary Terms", String.join(", ", labels)); + } + } + + private static void appendReferences( + StringBuilder markdown, String heading, List references) { + List labels = + listOrEmpty(references).stream() + .map(PersonaContextMarkdown::referenceLabel) + .filter(value -> !nullOrEmpty(value)) + .map(value -> "- `" + value + '`') + .toList(); + if (!labels.isEmpty()) { + appendSection(markdown, heading, String.join("\n", labels)); + } + } + + private static void appendRelatedTerms(StringBuilder markdown, List relations) { + List labels = + listOrEmpty(relations).stream() + .filter(relation -> relation.getTerm() != null) + .map( + relation -> + "- `" + + referenceLabel(relation.getTerm()) + + "` (" + + relation.getRelationType() + + ')') + .toList(); + if (!labels.isEmpty()) { + appendSection(markdown, "Related Terms", String.join("\n", labels)); + } + } + + private static String referenceLabel(EntityReference reference) { + if (reference == null) { + return null; + } + return !nullOrEmpty(reference.getFullyQualifiedName()) + ? reference.getFullyQualifiedName() + : !nullOrEmpty(reference.getDisplayName()) + ? reference.getDisplayName() + : reference.getName(); + } + + private static RuleRenderResult renderAssetRule( + PersonaContextBuilder.RuleMaterialization rule, + BudgetTracker budget, + RenderTier currentTier, + List manifest) { + StringBuilder body = new StringBuilder(); + List renderedEntities = new ArrayList<>(); + int full = 0; + int compact = 0; + int omitted = 0; + RenderTier tier = currentTier; + Set sections = PersonaContextBuilder.selectedSections(rule.rule()); + + for (PersonaContextBuilder.SelectedEntity selected : rule.entities()) { + AIContext entity = selected.context(); + if (tier == RenderTier.FULL) { + String fragment = renderFullEntity(entity, sections); + if (budget.tryConsume(fragment)) { + body.append(fragment); + renderedEntities.add(entity); + full++; + continue; + } + tier = RenderTier.COMPACT; + } + if (tier == RenderTier.COMPACT) { + String fragment = renderCompactEntity(entity); + if (budget.tryConsume(fragment)) { + body.append(fragment); + renderedEntities.add(entity); + manifest.add(manifestEntry(entity, ManifestEntry.Reason.COMPACT)); + compact++; + continue; + } + tier = RenderTier.MANIFEST; + } + manifest.add(manifestEntry(entity, ManifestEntry.Reason.OMITTED)); + omitted++; + } + + RuleResult result = + new RuleResult() + .withRuleName(rule.rule().getName()) + .withEntityType(rule.rule().getEntityType()) + .withMatched(rule.matched()) + .withRenderedFull(full) + .withRenderedCompact(compact) + .withManifestOnly(omitted) + .withEntities(renderedEntities); + return new RuleRenderResult(result, body.toString(), tier); + } + + private static String renderFullEntity(AIContext context, Set sections) { + StringBuilder markdown = new StringBuilder(); + markdown + .append("\n## ") + .append(entityTypeLabel(context.getEntityType())) + .append(": ") + .append(titleOf(context)) + .append('\n'); + if (!nullOrEmpty(context.getFullyQualifiedName())) { + markdown.append('`').append(context.getFullyQualifiedName()).append("`\n"); + } + AIContextMarkdown.appendEntitySections(markdown, context, sections, "###"); + if (sections.contains(ContextSection.PROFILE)) { + boolean hasProfileSummary = + context.getObservability() != null && context.getObservability().getRowCount() != null; + if (!hasProfileSummary) { + markdown.append("\n### Data Profile\n"); + } + if (context.getObservability() != null + && context.getObservability().getProfiledAt() != null) { + markdown + .append("\n**Profiled at:** ") + .append(Instant.ofEpochMilli(context.getObservability().getProfiledAt())) + .append('\n'); + } + markdown + .append("\n_Column-level profile details are caller-sensitive; fetch ") + .append(contextEndpoint(context)) + .append(" for the latest permitted profile._\n"); + } + return markdown.toString(); + } + + private static String renderCompactEntity(AIContext context) { + String marker = + "\n_Compact rendering — fetch " + + contextEndpoint(context) + + " for the complete asset context._\n"; + StringBuilder compact = new StringBuilder(); + compact + .append("\n## ") + .append(entityTypeLabel(context.getEntityType())) + .append(": ") + .append(titleOf(context)) + .append('\n'); + if (!nullOrEmpty(context.getFullyQualifiedName())) { + compact.append('`').append(context.getFullyQualifiedName()).append("`\n"); + } + String description = firstLine(context.getDescription()); + if (!nullOrEmpty(description)) { + compact.append('\n').append(description).append('\n'); + } + appendCompactColumns(compact, context); + int contentLimit = Math.max(0, COMPACT_MAX_CHARS - marker.length()); + String content = + compact.length() > contentLimit ? compact.substring(0, contentLimit) : compact.toString(); + return content.stripTrailing() + marker; + } + + private static void appendCompactColumns(StringBuilder markdown, AIContext context) { + if (context.getAssetContext() == null || context.getAssetContext().getTable() == null) { + return; + } + TableContext table = context.getAssetContext().getTable(); + if (listOrEmpty(table.getColumns()).isEmpty()) { + return; + } + markdown.append("\n**Columns:** "); + int count = 0; + for (FieldContext column : table.getColumns()) { + if (count > 0) { + markdown.append(", "); + } + markdown.append('`').append(column.getName()); + if (!nullOrEmpty(column.getDataType())) { + markdown.append(':').append(column.getDataType()); + } + markdown.append('`'); + count++; + if (count == 40) { + markdown.append(", …"); + break; + } + } + markdown.append('\n'); + } + + private static String renderSharedKnowledge(SharedKnowledge shared) { + if (shared == null + || (listOrEmpty(shared.getGlossaryTerms()).isEmpty() + && listOrEmpty(shared.getMetrics()).isEmpty() + && listOrEmpty(shared.getArticles()).isEmpty())) { + return ""; + } + StringBuilder markdown = new StringBuilder("\n# Shared Knowledge\n"); + appendSharedKnowledge(markdown, shared.getGlossaryTerms()); + appendSharedKnowledge(markdown, shared.getMetrics()); + appendSharedKnowledge(markdown, shared.getArticles()); + return markdown.toString(); + } + + private static void appendSharedKnowledge(StringBuilder markdown, List items) { + for (KnowledgeItem item : listOrEmpty(items)) { + markdown.append(renderKnowledgeItem(item)); + } + } + + private static String renderKnowledgeItem(KnowledgeItem item) { + StringBuilder markdown = + new StringBuilder("\n## ") + .append(knowledgeTypeLabel(item)) + .append(": ") + .append(labelOf(item)) + .append('\n'); + if (!nullOrEmpty(item.getFullyQualifiedName())) { + markdown.append('`').append(item.getFullyQualifiedName()).append("`\n"); + } + if (!nullOrEmpty(item.getContent())) { + markdown.append('\n').append(item.getContent().strip()).append('\n'); + } + return markdown.toString(); + } + + private static void appendManifest(StringBuilder markdown, List manifest) { + if (manifest.isEmpty()) { + return; + } + markdown.append("\n# Overflow Manifest\n"); + for (ManifestEntry entry : manifest) { + markdown + .append("\n- `") + .append(entry.getFullyQualifiedName()) + .append("` (") + .append(entry.getEntityType()) + .append(") — ") + .append(entry.getReason().value()) + .append("; fetch ") + .append(contextEndpoint(entry.getEntityType(), entry.getFullyQualifiedName())); + } + markdown.append('\n'); + } + + private static String frontmatter( + PersonaContext context, int characterBudget, int tokensEstimate) { + int matched = + listOrEmpty(context.getRules()).stream().mapToInt(rule -> value(rule.getMatched())).sum(); + int rendered = + listOrEmpty(context.getRules()).stream() + .mapToInt(rule -> value(rule.getRenderedFull()) + value(rule.getRenderedCompact())) + .sum(); + return "---\n" + + "kind: personaContext\n" + + "persona: " + + yamlQuote( + context.getPersona() == null ? null : context.getPersona().getFullyQualifiedName()) + + "\n" + + "generated_at: " + + yamlQuote(Instant.ofEpochMilli(context.getGeneratedAt()).toString()) + + "\n" + + "budget: " + + characterBudget + + "\n" + + "tokens_est: " + + tokensEstimate + + "\n" + + "fingerprint: " + + yamlQuote(context.getFingerprint()) + + "\n" + + "rules: " + + listOrEmpty(context.getRules()).size() + + "\n" + + "matched: " + + matched + + "\n" + + "rendered: " + + rendered + + "\n" + + "truncated: " + + Boolean.TRUE.equals(context.getTruncated()) + + "\n---\n"; + } + + private static String renderTitle(Persona persona) { + String title = + !nullOrEmpty(persona.getDisplayName()) ? persona.getDisplayName() : persona.getName(); + StringBuilder markdown = new StringBuilder("\n# Persona context: ").append(title).append('\n'); + if (!nullOrEmpty(persona.getDescription())) { + markdown.append('\n').append(persona.getDescription().strip()).append('\n'); + } + return markdown.toString(); + } + + private static String ruleHeading( + PersonaContextBuilder.RuleMaterialization rule, RuleResult rendered) { + int renderedCount = value(rendered.getRenderedFull()) + value(rendered.getRenderedCompact()); + return "\n# Rule: " + + rule.rule().getName() + + " (" + + rule.rule().getEntityType() + + ") — " + + rule.matched() + + " matched, " + + renderedCount + + " rendered\n"; + } + + private static int ruleHeadingEstimate(PersonaContextBuilder.RuleMaterialization rule) { + return rule.rule().getName().length() + rule.rule().getEntityType().length() + 96; + } + + private static ManifestEntry manifestEntry(AIContext context, ManifestEntry.Reason reason) { + return new ManifestEntry() + .withEntityType(context.getEntityType()) + .withFullyQualifiedName(context.getFullyQualifiedName()) + .withReason(reason); + } + + private static String contextEndpoint(AIContext context) { + return contextEndpoint(context.getEntityType(), context.getFullyQualifiedName()); + } + + private static String contextEndpoint(String entityType, String fqn) { + return "`GET /v1/" + collectionPath(entityType) + "/name/" + fqn + "/context`"; + } + + static String collectionPath(String entityType) { + return switch (entityType) { + case "glossaryTerm" -> "glossaryTerms"; + case "mlmodel" -> "mlmodels"; + case "searchIndex" -> "searchIndexes"; + case "databaseSchema" -> "databaseSchemas"; + case "storedProcedure" -> "storedProcedures"; + case "apiEndpoint" -> "apiEndpoints"; + case "page" -> "contextCenter/pages"; + case "dashboardDataModel" -> "dashboard/datamodels"; + default -> entityType.endsWith("s") ? entityType : entityType + 's'; + }; + } + + private static String entityTypeLabel(String entityType) { + if (nullOrEmpty(entityType)) { + return "Entity"; + } + String spaced = entityType.replaceAll("([a-z])([A-Z])", "$1 $2"); + return Character.toUpperCase(spaced.charAt(0)) + spaced.substring(1); + } + + private static String knowledgeTypeLabel(KnowledgeItem item) { + return item.getType() == null + ? "Knowledge" + : switch (item.getType()) { + case GLOSSARY_TERM -> "Glossary Term"; + case METRIC -> "Metric"; + case PAGE -> "Article"; + case CONTEXT_MEMORY -> "Knowledge Pill"; + }; + } + + private static String titleOf(AIContext context) { + return !nullOrEmpty(context.getDisplayName()) + ? context.getDisplayName() + : context.getFullyQualifiedName(); + } + + private static String labelOf(KnowledgeItem item) { + return !nullOrEmpty(item.getDisplayName()) ? item.getDisplayName() : item.getName(); + } + + private static String firstLine(String value) { + if (nullOrEmpty(value)) { + return null; + } + String line = value.strip().split("\n", 2)[0].strip(); + return line.length() > 240 ? line.substring(0, 240) + "…" : line; + } + + private static String yamlQuote(String value) { + String safe = value == null ? "" : value; + return '"' + + safe.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", " ").replace("\r", " ") + + '"'; + } + + private static int value(Integer number) { + return number == null ? 0 : number; + } + + private enum RenderTier { + FULL, + COMPACT, + MANIFEST + } + + private record RuleRenderResult(RuleResult result, String body, RenderTier nextTier) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationContext.java index 8d5d17d78972..71d10eba643a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationContext.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationContext.java @@ -1,9 +1,9 @@ package org.openmetadata.service.apps; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.entity.app.App; import org.openmetadata.schema.type.Include; @@ -17,7 +17,10 @@ public class ApplicationContext { private final Map apps; private ApplicationContext() { - this.apps = new HashMap<>(); + // ConcurrentHashMap: registerApp (put) runs on every Quartz job execution while request/event + // threads iterate getAllApps()/getApp() concurrently — a plain HashMap threw + // ConcurrentModificationException and could tear reads during a resize. + this.apps = new ConcurrentHashMap<>(); } public static ApplicationContext getInstance() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java index f28c973cbb72..33c8a5a0ca81 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java @@ -64,6 +64,9 @@ public abstract class AbstractEventConsumer public static final String FAILED_EVENT_EXTENSION = "eventSubscription.failedEvent"; protected final DIContainer dependencies; private long offset = -1; + // Highest change_event.offset actually read in the last poll. Used to advance the cursor by true + // offset instead of row count, since change_event.offset is a non-contiguous AUTO_INCREMENT. + private long lastReadOffset = -1; private long startingOffset = -1; private AlertMetrics alertMetrics; @@ -379,19 +382,38 @@ private void batchRecordSuccessfulEvents(UUID subscriptionId, long timestamp) { @Override public ResultList pollEvents(long offset, long batchSize) { - List eventJson = Entity.getCollectionDAO().changeEventDAO().list(batchSize, offset); + var records = + Entity.getCollectionDAO().changeEventDAO().listWithOffset((int) batchSize, offset); List changeEvents = new ArrayList<>(); List errorEvents = new ArrayList<>(); - for (String json : eventJson) { + long maxOffset = offset; + for (var eventRecord : records) { + maxOffset = Math.max(maxOffset, eventRecord.offset()); try { - ChangeEvent event = JsonUtils.readValue(json, ChangeEvent.class); + ChangeEvent event = JsonUtils.readValue(eventRecord.json(), ChangeEvent.class); + if (event == null) { + // JsonUtils.readValue returns null (it does not throw) on a null/blank json column, which + // would add a null ChangeEvent to the delivered batch and NPE downstream. Route it to + // errorEvents like any other unparseable row instead of silently delivering null. + throw new IllegalStateException( + "Null or blank change_event.json at offset " + eventRecord.offset()); + } changeEvents.add(event); } catch (Exception ex) { - errorEvents.add(new EntityError().withMessage(ex.getMessage()).withEntity(json)); - LOG.error("Error in Parsing Change Event : {} , Message: {} ", json, ex.getMessage(), ex); + errorEvents.add( + new EntityError().withMessage(ex.getMessage()).withEntity(eventRecord.json())); + LOG.error( + "Error in Parsing Change Event : {} , Message: {} ", + eventRecord.json(), + ex.getMessage(), + ex); } } - return new ResultList<>(changeEvents, errorEvents, null, null, eventJson.size()); + // Track the true maximum offset read so the cursor advances past exactly these rows. Advancing + // by row count re-read the tail whenever the AUTO_INCREMENT offset column had gaps (rolled-back + // txns / retention deletes), redelivering those change events. + this.lastReadOffset = maxOffset; + return new ResultList<>(changeEvents, errorEvents, null, null, records.size()); } @Override @@ -421,7 +443,8 @@ public void execute(JobExecutionContext jobExecutionContext) { } finally { if (!eventsWithReceivers.isEmpty()) { - offset += batchSize; + // Advance to the true max offset read (set by pollEvents), not by row count. + offset = lastReadOffset; commit(jobExecutionContext); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/generic/GenericPublisher.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/generic/GenericPublisher.java index 94efddc9e29c..610ac03571b4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/generic/GenericPublisher.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/generic/GenericPublisher.java @@ -107,8 +107,6 @@ public void sendMessage(ChangeEvent event, Set recipients) } } } - } catch (EventPublisherException ex) { - throw ex; } catch (Exception ex) { if (ex.getCause() instanceof UnknownHostException) { String message = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataContracts/DataContractValidationApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataContracts/DataContractValidationApp.java index eb5df3c94468..334117ae575e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataContracts/DataContractValidationApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataContracts/DataContractValidationApp.java @@ -3,9 +3,8 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import static org.openmetadata.service.apps.scheduler.OmAppJobListener.APP_RUN_STATS; -import java.util.HashMap; +import java.util.ArrayList; import java.util.List; -import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.exception.ExceptionUtils; import org.openmetadata.schema.EntityInterface; @@ -14,6 +13,8 @@ import org.openmetadata.schema.entity.data.DataContract; import org.openmetadata.schema.entity.datacontract.DataContractResult; import org.openmetadata.schema.entity.domains.DataProduct; +import org.openmetadata.schema.system.EntityError; +import org.openmetadata.schema.system.IndexingError; import org.openmetadata.schema.system.Stats; import org.openmetadata.schema.system.StepStats; import org.openmetadata.schema.type.EntityReference; @@ -36,7 +37,8 @@ public class DataContractValidationApp extends AbstractNativeApplication { private final Stats stats = new Stats(); private JobExecutionContext jobExecutionContext; - private final Map failureDetails = new HashMap<>(); + private final IndexingError failureDetails = + new IndexingError().withFailedEntities(new ArrayList<>()); public DataContractValidationApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { super(collectionDAO, searchRepository); @@ -76,8 +78,10 @@ public void startApp(JobExecutionContext jobExecutionContext) { updateStatsRecord(AppRunRecord.Status.COMPLETED); } catch (Exception e) { LOG.error("Error running DataContractValidationApp", e); - failureDetails.put("message", e.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(e)); + failureDetails + .withErrorSource(IndexingError.ErrorSource.JOB) + .withMessage(e.getMessage()) + .withStackTrace(ExceptionUtils.getStackTrace(e)); updateStatsRecord(AppRunRecord.Status.FAILED); } } @@ -120,7 +124,7 @@ private int[] validateExistingContracts(DataContractRepository repository) { "Failed to validate data contract %s: %s", dataContract.getFullyQualifiedName(), e.getMessage()); LOG.error(msg, e); - failureDetails.put(dataContract.getFullyQualifiedName(), msg); + recordEntityFailure(dataContract.getFullyQualifiedName(), msg); totalErrors++; } } @@ -230,7 +234,7 @@ private int[] processDataProductContracts(DataContractRepository contractReposit "Failed to process asset %s from Data Product %s: %s", assetRef.getName(), dataProduct.getName(), e.getMessage()); LOG.error(msg, e); - failureDetails.put(assetRef.getFullyQualifiedName(), msg); + recordEntityFailure(assetRef.getFullyQualifiedName(), msg); totalErrors++; } } @@ -244,13 +248,13 @@ private int[] processDataProductContracts(DataContractRepository contractReposit String.format( "Failed to process Data Product %s: %s", dataProduct.getName(), e.getMessage()); LOG.error(msg, e); - failureDetails.put(dataProduct.getFullyQualifiedName(), msg); + recordEntityFailure(dataProduct.getFullyQualifiedName(), msg); totalErrors++; } } } catch (Exception e) { LOG.error("Error processing Data Products: {}", e.getMessage(), e); - failureDetails.put("dataProductProcessing", e.getMessage()); + recordEntityFailure("dataProductProcessing", e.getMessage()); } return new int[] {totalProcessed, totalErrors}; @@ -265,13 +269,22 @@ private void setStats(Integer totalRecords, Integer successRecords, Integer fail stats.setJobStats(jobStats); } + private void recordEntityFailure(String entity, String message) { + failureDetails + .getFailedEntities() + .add(new EntityError().withEntity(entity).withMessage(message)); + } + + private boolean hasFailures() { + return failureDetails.getMessage() != null || !nullOrEmpty(failureDetails.getFailedEntities()); + } + private void updateStatsRecord(AppRunRecord.Status status) { AppRunRecord appRecord = getJobRecord(jobExecutionContext); appRecord.setStatus(status); - if (!nullOrEmpty(failureDetails)) { - appRecord.setFailureContext( - new FailureContext().withAdditionalProperty("failure", failureDetails)); + if (hasFailures()) { + appRecord.setFailureContext(new FailureContext().withFailure(failureDetails)); appRecord.setStatus(AppRunRecord.Status.FAILED); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataRetention/DataRetention.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataRetention/DataRetention.java index 54c578a524ce..e1be7502c873 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataRetention/DataRetention.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/dataRetention/DataRetention.java @@ -4,7 +4,6 @@ import java.time.Duration; import java.time.Instant; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -18,6 +17,7 @@ import org.openmetadata.schema.entity.app.FailureContext; import org.openmetadata.schema.entity.applications.configuration.internal.DataRetentionConfiguration; import org.openmetadata.schema.system.EntityStats; +import org.openmetadata.schema.system.IndexingError; import org.openmetadata.schema.system.Stats; import org.openmetadata.schema.system.StepStats; import org.openmetadata.schema.utils.JsonUtils; @@ -29,6 +29,7 @@ import org.openmetadata.service.search.SearchRepository; import org.openmetadata.service.socket.WebSocketManager; import org.openmetadata.service.util.EntityRelationshipCleanupUtil; +import org.openmetadata.service.util.OrphanIngestionPipelineCleanup; import org.openmetadata.service.util.OrphanTestCaseCleanup; import org.openmetadata.service.util.OrphanTestCaseRelationshipCleanup; import org.openmetadata.service.util.TagUsageCleanup; @@ -44,7 +45,7 @@ public class DataRetention extends AbstractNativeApplication { private JobExecutionContext jobExecutionContext; private AppRunRecord.Status internalStatus = AppRunRecord.Status.COMPLETED; - private Map failureDetails = null; + private IndexingError failureDetails = null; private final FeedRepository feedRepository; private final CollectionDAO.FeedDAO feedDAO; @@ -93,9 +94,7 @@ public void startApp(JobExecutionContext jobExecutionContext) { LOG.error("DataRetention job failed.", ex); internalStatus = AppRunRecord.Status.FAILED; - failureDetails = new HashMap<>(); - failureDetails.put("message", ex.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(ex)); + failureDetails = toIndexingError(ex); updateRecordToDbAndNotify(ex); } @@ -126,6 +125,7 @@ private void initializeStatsDefaults() { entityStats.withAdditionalProperty("orphaned_test_cases", new StepStats()); entityStats.withAdditionalProperty("test_cases_missing_test_definition", new StepStats()); entityStats.withAdditionalProperty("test_cases_missing_executable_suite", new StepStats()); + entityStats.withAdditionalProperty("orphaned_ingestion_pipelines", new StepStats()); entityStats.withAdditionalProperty("orphan_test_case_resolution_status", new StepStats()); entityStats.withAdditionalProperty("orphan_agent_execution", new StepStats()); entityStats.withAdditionalProperty("orphan_mcp_execution", new StepStats()); @@ -164,6 +164,13 @@ public void executeCleanup(DataRetentionConfiguration config) { LOG.info("Starting cleanup for test cases with missing relationships."); cleanTestCasesWithMissingRelationships(); + // Clean up ingestion pipelines whose container (service/test suite) CONTAINS row is gone. Such + // a pipeline can never run and breaks search indexing ("does not have expected relationship + // contains to/from entity type null"). Runs after the relationship/hierarchy cleanup above so a + // container relationship that was just repaired is not mistaken for missing. + LOG.info("Starting cleanup for orphaned ingestion pipelines."); + cleanOrphanedIngestionPipelines(); + // Run after orphan test case cleanup so resolution-status rows for deleted test cases // also get swept up. LOG.info("Starting cleanup for orphaned time-series rows."); @@ -272,11 +279,7 @@ private void cleanOrphanedRelationshipsAndHierarchies() { LOG.error("Failed to clean orphaned relationships and hierarchies", ex); internalStatus = AppRunRecord.Status.ACTIVE_ERROR; - if (failureDetails == null) { - failureDetails = new HashMap<>(); - failureDetails.put("message", ex.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(ex)); - } + recordFirstFailure(ex); } } @@ -295,11 +298,7 @@ private void cleanOrphanedTagUsages() { LOG.error("Failed to clean orphaned tag usages", ex); internalStatus = AppRunRecord.Status.ACTIVE_ERROR; - if (failureDetails == null) { - failureDetails = new HashMap<>(); - failureDetails.put("message", ex.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(ex)); - } + recordFirstFailure(ex); } } @@ -317,11 +316,7 @@ private void cleanOrphanTestCases() { } catch (Exception ex) { LOG.error("Failed to clean orphan test cases", ex); internalStatus = AppRunRecord.Status.ACTIVE_ERROR; - if (failureDetails == null) { - failureDetails = new HashMap<>(); - failureDetails.put("message", ex.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(ex)); - } + recordFirstFailure(ex); } } @@ -349,10 +344,29 @@ private void cleanTestCasesWithMissingRelationships() { } catch (Exception ex) { LOG.error("Failed to clean test cases with missing relationships", ex); internalStatus = AppRunRecord.Status.ACTIVE_ERROR; + recordFirstFailure(ex); + } + } + + private void cleanOrphanedIngestionPipelines() { + try { + OrphanIngestionPipelineCleanup cleanup = + new OrphanIngestionPipelineCleanup(collectionDAO, false); + OrphanIngestionPipelineCleanup.Result result = cleanup.performCleanup(BATCH_SIZE); + updateStats( + "orphaned_ingestion_pipelines", result.getOrphansDeleted(), result.getOrphanFailures()); + LOG.info( + "Orphan ingestion pipeline cleanup completed - Scanned: {}, Deleted: {}, Failed: {}", + result.getTotalScanned(), + result.getOrphansDeleted(), + result.getOrphanFailures()); + } catch (Exception ex) { + LOG.error("Failed to clean orphan ingestion pipelines", ex); + internalStatus = AppRunRecord.Status.ACTIVE_ERROR; if (failureDetails == null) { - failureDetails = new HashMap<>(); - failureDetails.put("message", ex.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(ex)); + failureDetails = new IndexingError(); + failureDetails.setMessage(ex.getMessage()); + failureDetails.setStackTrace(ExceptionUtils.getStackTrace(ex)); } } } @@ -442,11 +456,7 @@ private void executeOrphanCleanup(String entity, Supplier deleteFunctio totalFailed += BATCH_SIZE; internalStatus = AppRunRecord.Status.ACTIVE_ERROR; - if (failureDetails == null) { - failureDetails = new HashMap<>(); - failureDetails.put("message", ex.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(ex)); - } + recordFirstFailure(ex); stoppedByCondition = true; break; } @@ -477,11 +487,7 @@ private void executeWithStatsTracking(String entity, Supplier deleteFun totalFailed += BATCH_SIZE; internalStatus = AppRunRecord.Status.ACTIVE_ERROR; - if (failureDetails == null) { - failureDetails = new HashMap<>(); - failureDetails.put("message", ex.getMessage()); - failureDetails.put("jobStackTrace", ExceptionUtils.getStackTrace(ex)); - } + recordFirstFailure(ex); break; } } @@ -514,13 +520,25 @@ private synchronized void updateStats(String entity, int successCount, int failu jobStats.setFailedRecords(jobStats.getFailedRecords() + failureCount); } + private void recordFirstFailure(Exception ex) { + if (failureDetails == null) { + failureDetails = toIndexingError(ex); + } + } + + private static IndexingError toIndexingError(Exception ex) { + return new IndexingError() + .withErrorSource(IndexingError.ErrorSource.JOB) + .withMessage(ex.getMessage()) + .withStackTrace(ExceptionUtils.getStackTrace(ex)); + } + private void updateRecordToDbAndNotify(Exception error) { AppRunRecord appRecord = getJobRecord(jobExecutionContext); appRecord.setStatus(internalStatus); if (failureDetails != null) { - appRecord.setFailureContext( - new FailureContext().withAdditionalProperty("failure", failureDetails)); + appRecord.setFailureContext(new FailureContext().withFailure(failureDetails)); } if (WebSocketManager.getInstance() != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsApp.java index 9c3da8b4ae11..3ce23d06a2eb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsApp.java @@ -24,7 +24,6 @@ import org.openmetadata.schema.entity.applications.configuration.internal.CostAnalysisConfig; import org.openmetadata.schema.entity.applications.configuration.internal.DataAssetsConfig; import org.openmetadata.schema.entity.applications.configuration.internal.DataInsightsAppConfig; -import org.openmetadata.schema.entity.applications.configuration.internal.DataQualityConfig; import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; import org.openmetadata.schema.system.EntityStats; import org.openmetadata.schema.system.EventPublisherJob; @@ -33,7 +32,6 @@ import org.openmetadata.schema.system.StepStats; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.search.IndexMapping; -import org.openmetadata.service.Entity; import org.openmetadata.service.apps.AbstractNativeApplication; import org.openmetadata.service.apps.bundles.insights.search.DataInsightsSearchInterface; import org.openmetadata.service.apps.bundles.insights.search.elasticsearch.ElasticSearchDataInsightsClient; @@ -42,7 +40,6 @@ import org.openmetadata.service.apps.bundles.insights.workflows.WorkflowStats; import org.openmetadata.service.apps.bundles.insights.workflows.costAnalysis.CostAnalysisWorkflow; import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataAssetsWorkflow; -import org.openmetadata.service.apps.bundles.insights.workflows.dataQuality.DataQualityWorkflow; import org.openmetadata.service.apps.bundles.insights.workflows.webAnalytics.WebAnalyticsWorkflow; import org.openmetadata.service.exception.SearchIndexException; import org.openmetadata.service.jdbi3.CollectionDAO; @@ -60,7 +57,6 @@ public record Backfill(String startDate, String endDate) {} private CostAnalysisConfig costAnalysisConfig; private DataAssetsConfig dataAssetsConfig; - private DataQualityConfig dataQualityConfig; private AppAnalyticsConfig webAnalyticsConfig; private Optional recreateDataAssetsIndex; @@ -89,9 +85,6 @@ public record Backfill(String startDate, String endDate) {} "tag", "metric"); - public final Set dataQualityEntities = - Set.of(Entity.TEST_CASE_RESULT, Entity.TEST_CASE_RESOLUTION_STATUS); - public DataInsightsApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { super(collectionDAO, searchRepository); } @@ -124,47 +117,6 @@ public static String getDataStreamName(String prefix, String dataAssetType) { return dataStreamName; } - private void createIndexInternal(String entityType) throws IOException { - IndexMapping resultIndexType = searchRepository.getIndexMapping(entityType); - if (!searchRepository.indexExists(resultIndexType)) { - LOG.info("[Data Insights] Creating Index for Entity Type: '{}'", entityType); - searchRepository.createIndex(resultIndexType); - } - DataInsightsSearchInterface searchInterface = getSearchInterface(); - if (!searchInterface.dataAssetDataStreamExists( - getDataStreamName(searchRepository.getClusterAlias(), entityType))) { - LOG.info("[Data Insights] Creating Index for Entity Type: '{}'", entityType); - searchRepository - .getSearchClient() - .addIndexAlias( - resultIndexType, getDataStreamName(searchRepository.getClusterAlias(), entityType)); - } - } - - private void deleteIndexInternal(String entityType) { - IndexMapping resultIndexType = searchRepository.getIndexMapping(entityType); - if (searchRepository.indexExists(resultIndexType)) { - LOG.info("[Data Insights] Deleting Index for Entity Type: '{}'", entityType); - searchRepository.deleteIndex(resultIndexType); - } - } - - public void createDataQualityDataIndex() { - try { - createIndexInternal(Entity.TEST_CASE_RESULT); - createIndexInternal(Entity.TEST_CASE_RESOLUTION_STATUS); - } catch (IOException ex) { - LOG.error( - "Couldn't install DataInsightsApp: Can't initialize ElasticSearch Index for DataQuality.", - ex); - } - } - - public void deleteDataQualityDataIndex() { - deleteIndexInternal(Entity.TEST_CASE_RESULT); - deleteIndexInternal(Entity.TEST_CASE_RESOLUTION_STATUS); - } - public void createOrUpdateDataAssetsDataStream() { DataInsightsSearchInterface searchInterface = getSearchInterface(); @@ -218,7 +170,6 @@ public void init(App app) { // Get the configuration for the different modules costAnalysisConfig = config.getModuleConfiguration().getCostAnalysis(); dataAssetsConfig = parseDataAssetsConfig(config.getModuleConfiguration().getDataAssets()); - dataQualityConfig = config.getModuleConfiguration().getDataQuality(); webAnalyticsConfig = config.getModuleConfiguration().getAppAnalytics(); // Configure batchSize @@ -240,7 +191,6 @@ public void init(App app) { } createOrUpdateDataAssetsDataStream(); - createDataQualityDataIndex(); jobData = new EventPublisherJob().withStats(new Stats()); } @@ -273,8 +223,6 @@ public void startApp(JobExecutionContext jobExecutionContext) { if (recreateDataAssetsIndex.isPresent() && recreateDataAssetsIndex.get().equals(true)) { deleteDataAssetsDataStream(); createOrUpdateDataAssetsDataStream(); - deleteDataQualityDataIndex(); - createDataQualityDataIndex(); } WorkflowStats webAnalyticsStats = processWebAnalytics(); @@ -286,9 +234,6 @@ public void startApp(JobExecutionContext jobExecutionContext) { WorkflowStats dataAssetsStats = processDataAssets(); updateJobStatsWithWorkflowStats(dataAssetsStats); - WorkflowStats dataQualityStats = processDataQuality(); - updateJobStatsWithWorkflowStats(dataQualityStats); - if (webAnalyticsStats.hasFailed() || costAnalysisStats.hasFailed() || dataAssetsStats.hasFailed()) { @@ -382,29 +327,6 @@ private WorkflowStats processDataAssets() { return workflowStats; } - private WorkflowStats processDataQuality() { - for (String entityType : dataQualityEntities) { - DataQualityWorkflow workflow = - new DataQualityWorkflow( - dataQualityConfig, - timestamp, - batchSize, - backfill, - entityType, - collectionDAO, - searchRepository); - - try { - workflow.process(); - } catch (SearchIndexException ex) { - jobData.setStatus(EventPublisherJob.Status.FAILED); - jobData.setFailure(ex.getIndexingError()); - } - } - - return DataQualityWorkflow.getWorkflowStats(); - } - private void updateJobStatsWithWorkflowStats(WorkflowStats workflowStats) { for (Map.Entry entry : workflowStats.getWorkflowStepStats().entrySet()) { String stepName = entry.getKey(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/processors/DataInsightsEntityEnricherProcessor.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/processors/DataInsightsEntityEnricherProcessor.java index c17b5cb52f62..77dbb8314de3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/processors/DataInsightsEntityEnricherProcessor.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/processors/DataInsightsEntityEnricherProcessor.java @@ -28,6 +28,7 @@ import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps.DescriptionStatsStep; import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps.EntityStatusStep; import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps.IdentityProjectionStep; +import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps.OwnerNameStep; import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps.OwnerTeamStep; import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps.TagAndTierSourcesStep; import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps.TierStep; @@ -75,6 +76,7 @@ public class DataInsightsEntityEnricherProcessor new DescriptionSourcesStep(), new TagAndTierSourcesStep(), new OwnerTeamStep(ownerResolver), + new OwnerNameStep(), new TierStep(), new DescriptionStatsStep(), new CustomPropertiesStep())); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/processors/enricher/steps/OwnerNameStep.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/processors/enricher/steps/OwnerNameStep.java new file mode 100644 index 000000000000..97e5891abf79 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataAssets/processors/enricher/steps/OwnerNameStep.java @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.steps; + +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.util.List; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.EnrichmentStep; +import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.processors.enricher.EnrichmentTarget; + +/** + * Projects a flat {@code ownerName} keyword list onto the snapshot, mirroring the computed field + * the entity search index sets in {@code SearchIndex.populateCommonFields}. The DI document + * otherwise carries owners only as the {@code nested} {@code owners} array, which flat + * {@code query_string} DI filters (e.g. {@code ownerName: *}) cannot reach. Entities with no + * owners contribute no {@code ownerName} key rather than an empty list, so a + * {@code query_string} existence filter cleanly excludes unowned assets. + */ +public final class OwnerNameStep implements EnrichmentStep { + + public static final String NAME = "ownerName"; + + @Override + public String name() { + return NAME; + } + + @Override + public void apply(EnrichmentTarget target) { + List owners = target.entity().getOwners(); + if (nullOrEmpty(owners)) { + return; + } + List ownerNames = + owners.stream().map(EntityReference::getName).filter(name -> !nullOrEmpty(name)).toList(); + if (!ownerNames.isEmpty()) { + target.entityMap().put(NAME, ownerNames); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataQuality/DataQualityWorkflow.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataQuality/DataQualityWorkflow.java deleted file mode 100644 index 6006e859a5df..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/workflows/dataQuality/DataQualityWorkflow.java +++ /dev/null @@ -1,220 +0,0 @@ -package org.openmetadata.service.apps.bundles.insights.workflows.dataQuality; - -import static org.openmetadata.service.apps.bundles.insights.utils.TimestampUtils.END_TIMESTAMP_KEY; -import static org.openmetadata.service.apps.bundles.insights.utils.TimestampUtils.START_TIMESTAMP_KEY; -import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.ENTITY_TYPE_KEY; -import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.getInitialStatsForEntities; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import lombok.Getter; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.EntityTimeSeriesInterface; -import org.openmetadata.schema.entity.applications.configuration.internal.DataQualityConfig; -import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; -import org.openmetadata.schema.system.IndexingError; -import org.openmetadata.schema.system.StepStats; -import org.openmetadata.schema.utils.ResultList; -import org.openmetadata.search.IndexMapping; -import org.openmetadata.service.apps.bundles.insights.DataInsightsApp; -import org.openmetadata.service.apps.bundles.insights.utils.TimestampUtils; -import org.openmetadata.service.apps.bundles.insights.workflows.WorkflowStats; -import org.openmetadata.service.exception.SearchIndexException; -import org.openmetadata.service.jdbi3.CollectionDAO; -import org.openmetadata.service.search.SearchRepository; -import org.openmetadata.service.search.elasticsearch.ElasticSearchEntityTimeSeriesProcessor; -import org.openmetadata.service.search.elasticsearch.ElasticSearchIndexSink; -import org.openmetadata.service.search.opensearch.OpenSearchEntityTimeSeriesProcessor; -import org.openmetadata.service.search.opensearch.OpenSearchIndexSink; -import org.openmetadata.service.workflows.interfaces.Processor; -import org.openmetadata.service.workflows.interfaces.Sink; -import org.openmetadata.service.workflows.interfaces.Source; -import org.openmetadata.service.workflows.interfaces.TaggedOperation; -import org.openmetadata.service.workflows.searchIndex.PaginatedEntityTimeSeriesSource; - -@Slf4j -public class DataQualityWorkflow { - public static final String DATA_STREAM_KEY = "DataStreamKey"; - private final int retentionDays = 30; - private final Long startTimestamp; - private final Long endTimestamp; - private final int batchSize; - private final DataQualityConfig dataQualityConfig; - - private final SearchRepository searchRepository; - private final CollectionDAO collectionDAO; - private final List sources = new ArrayList<>(); - - String entityType; - - Processor entityProcessor; - Sink searchIndexSink; - - @Getter - private static final WorkflowStats workflowStats = new WorkflowStats("DataQualityWorkflow"); - - public DataQualityWorkflow( - DataQualityConfig dataQualityConfig, - Long timestamp, - int batchSize, - Optional backfill, - String entityType, - CollectionDAO collectionDAO, - SearchRepository searchRepository) { - if (backfill.isPresent()) { - Long oldestPossibleTimestamp = - TimestampUtils.getStartOfDayTimestamp( - TimestampUtils.subtractDays(timestamp, retentionDays)); - - this.endTimestamp = - TimestampUtils.getEndOfDayTimestamp( - Collections.max( - List.of(TimestampUtils.getTimestampFromDateString(backfill.get().endDate())))); - this.startTimestamp = - TimestampUtils.getStartOfDayTimestamp( - Collections.max( - List.of( - TimestampUtils.getTimestampFromDateString(backfill.get().startDate()), - oldestPossibleTimestamp))); - - if (oldestPossibleTimestamp.equals(TimestampUtils.getStartOfDayTimestamp(endTimestamp))) { - LOG.warn( - "Backfill won't happen because the set date is before the limit of {}", - oldestPossibleTimestamp); - } - } else { - this.endTimestamp = TimestampUtils.getEndOfDayTimestamp(timestamp); - this.startTimestamp = - TimestampUtils.getStartOfDayTimestamp(TimestampUtils.subtractDays(timestamp, 1)); - } - - this.batchSize = batchSize; - this.searchRepository = searchRepository; - this.collectionDAO = collectionDAO; - this.entityType = entityType; - this.dataQualityConfig = dataQualityConfig; - } - - public String getIndexNameByType(String entityType) { - IndexMapping indexMapping = searchRepository.getIndexMapping(entityType); - return indexMapping.getIndexName(searchRepository.getClusterAlias()); - } - - private void initialize() { - int totalRecords = - getInitialStatsForEntities(Set.of(entityType)).getJobStats().getTotalRecords(); - - List fields = List.of("*"); - PaginatedEntityTimeSeriesSource source = - new PaginatedEntityTimeSeriesSource( - entityType, batchSize, fields, startTimestamp, endTimestamp); - sources.add(source); - - if (searchRepository.getSearchType().equals(ElasticSearchConfiguration.SearchType.OPENSEARCH)) { - this.entityProcessor = new OpenSearchEntityTimeSeriesProcessor(totalRecords); - this.searchIndexSink = - new OpenSearchIndexSink( - searchRepository, - totalRecords, - searchRepository.getSearchConfiguration().getPayLoadSize()); - } else { - this.entityProcessor = new ElasticSearchEntityTimeSeriesProcessor(totalRecords); - this.searchIndexSink = - new ElasticSearchIndexSink( - searchRepository, - totalRecords, - searchRepository.getSearchConfiguration().getPayLoadSize()); - } - } - - private void deleteDataBeforeInserting(String indexName) throws SearchIndexException { - try { - searchRepository - .getSearchClient() - .deleteByRangeQuery(indexName, "@timestamp", null, startTimestamp, null, endTimestamp); - } catch (Exception rx) { - throw new SearchIndexException(new IndexingError().withMessage(rx.getMessage())); - } - } - - public void process() throws SearchIndexException { - if (!dataQualityConfig.getEnabled()) { - return; - } - LOG.info("[Data Insights] Processing Data Quality Insights."); - initialize(); - Map contextData = new HashMap<>(); - - contextData.put(START_TIMESTAMP_KEY, startTimestamp); - contextData.put(END_TIMESTAMP_KEY, endTimestamp); - - for (PaginatedEntityTimeSeriesSource source : sources) { - - deleteDataBeforeInserting(getIndexNameByType(source.getEntityType())); - contextData.put(ENTITY_TYPE_KEY, entityType); - - String keysetCursor = null; - while (true) { - try { - ResultList resultList = - source.readNextKeyset(keysetCursor); - keysetCursor = resultList.getPaging().getAfter(); - processEntity(resultList, contextData, source); - if (keysetCursor == null) { - break; - } - } catch (SearchIndexException ex) { - source.updateStats( - ex.getIndexingError().getSuccessCount(), ex.getIndexingError().getFailedCount()); - String errorMessage = - String.format("Failed processing Data from %s: %s", source.getEntityType(), ex); - workflowStats.addFailure(errorMessage); - break; - } finally { - updateWorkflowStats("[DataQualityWorkflow] " + source.getEntityType(), source.getStats()); - } - } - } - } - - @SuppressWarnings("unchecked") - private void processEntity( - ResultList resultList, - Map contextData, - Source paginatedSource) - throws SearchIndexException { - if (!resultList.getData().isEmpty()) { - LOG.debug( - "[DataQualityWorkflow] Processing a Batch of Size: {}, EntityType: {}", - resultList.getData().size(), - contextData.get(ENTITY_TYPE_KEY)); - List> taggedOps = new ArrayList<>(); - for (EntityTimeSeriesInterface entity : resultList.getData()) { - Object op = entityProcessor.process(entity, contextData); - taggedOps.add(new TaggedOperation<>(op, entity.getEntityReference())); - } - searchIndexSink.write(taggedOps); - paginatedSource.updateStats(resultList.getData().size(), 0); - } - } - - private void updateWorkflowStats(String stepName, StepStats newStepStats) { - workflowStats.updateWorkflowStepStats(stepName, newStepStats); - - int currentSuccess = - workflowStats.getWorkflowStepStats().values().stream() - .mapToInt(StepStats::getSuccessRecords) - .sum(); - int currentFailed = - workflowStats.getWorkflowStepStats().values().stream() - .mapToInt(StepStats::getFailedRecords) - .sum(); - - workflowStats.updateWorkflowStats(currentSuccess, currentFailed); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/mcp/McpAppConstants.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/mcp/McpAppConstants.java index 308db5ea974f..8952dc9b2720 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/mcp/McpAppConstants.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/mcp/McpAppConstants.java @@ -13,28 +13,14 @@ package org.openmetadata.service.apps.bundles.mcp; -import java.nio.charset.StandardCharsets; -import java.util.UUID; - /** - * Single source of truth for the MCP server identity written into - * {@code apps_extension_time_series.appName}/{@code appId} and queried by the read-side resource, - * plus the impersonation bot name derived as {@code MCP_APP_NAME + "Bot"}. Prevents value drift - * across the usage recorder, the MCP server, and the REST resource. + * Single source of truth for the {@link McpApplication} name written into + * {@code apps_extension_time_series.appName} and queried by the read-side resource. Prevents + * value drift across the recorder, the MCP server, and the REST resource. */ public final class McpAppConstants { public static final String MCP_APP_NAME = "McpApplication"; - /** - * Id stamped on MCP usage rows. No MCP-usage query reads it (the recorder writes and the resource - * reads by {@code appName}), but the {@code apps_extension_time_series.appId} generated column is - * {@code NOT NULL}, so a value is required. Derived deterministically from {@link #MCP_APP_NAME} - * so it is stable across runs without a per-record lookup, now that no {@code McpApplication} - * entity exists to own a real id. - */ - public static final UUID MCP_APP_ID = - UUID.nameUUIDFromBytes(MCP_APP_NAME.getBytes(StandardCharsets.UTF_8)); - private McpAppConstants() {} } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/mcp/McpApplication.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/mcp/McpApplication.java new file mode 100644 index 000000000000..c159bd4b9e07 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/mcp/McpApplication.java @@ -0,0 +1,13 @@ +package org.openmetadata.service.apps.bundles.mcp; + +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.service.apps.AbstractNativeApplication; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.SearchRepository; + +@Slf4j +public class McpApplication extends AbstractNativeApplication { + public McpApplication(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java index 6caf0eae0619..3f76e49e1817 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java @@ -1203,6 +1203,11 @@ private void flushIfNeeded() { if (!buffer.isEmpty() && !closed) { flushInternal(); } + } catch (Exception e) { + // An exception escaping here would cancel the scheduled task permanently + // (ScheduledExecutorService contract), silently disabling periodic flushing so trailing + // buffers only ship on an explicit flush/close. Log and continue to the next interval. + LOG.error("Scheduled flush failed; will retry on the next interval", e); } finally { lock.unlock(); } @@ -1273,8 +1278,23 @@ private void executeBulkWithRetry( long bulkStartNanos = System.nanoTime(); Set participatingTrackers = collectTrackers(operations); - CompletableFuture future = - asyncClient.bulk(b -> b.operations(operations).refresh(Refresh.False)); + CompletableFuture future; + try { + future = asyncClient.bulk(b -> b.operations(operations).refresh(Refresh.False)); + } catch (Exception e) { + // A synchronous throw here (e.g., dead transport) means the completion handler below + // never runs. Without this catch the semaphore permit and activeBulkRequests slot leak, + // eventually starving the pipeline and hanging close(). Mirror OpenSearchBulkSink so both + // backends clean up identically. + circuitBreaker.recordFailure(); + boolean retryScheduled = + handleBulkFailure(operations, executionId, numberOfActions, attemptNumber, e); + if (!retryScheduled) { + activeBulkRequests.decrementAndGet(); + concurrentRequestSemaphore.release(); + } + return; + } future.whenComplete( (response, error) -> { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EntityReindexContextMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EntityReindexContextMapper.java index a501b73e27c9..48c8bb6c2c4f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EntityReindexContextMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/EntityReindexContextMapper.java @@ -32,6 +32,7 @@ public static EntityReindexContext fromStagedContext( .canonicalIndex(stagedIndexContext.getCanonicalIndex(entityType).orElse(null)) .activeIndex(originalIndex) .stagedIndex(stagedIndexContext.getStagedIndex(entityType).orElse(null)) + .stagedChunkIndex(stagedIndexContext.getStagedChunkIndex().orElse(null)) .canonicalAliases(stagedIndexContext.getCanonicalAlias(entityType).orElse(null)) .existingAliases(stagedIndexContext.getExistingAliases(entityType)) .parentAliases(new HashSet<>(listOrEmpty(stagedIndexContext.getParentAliases(entityType)))) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java index aa8567426a8c..a55c0284e9e1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java @@ -448,7 +448,13 @@ private void addEntity( String json = JsonUtils.pojoToJson(searchIndexDoc); if (embeddingsEnabled) { - json = enrichWithEmbedding(entity, json, existingEmbeddingsById, tracker); + // Run-scoped chunk routing: the staged chunk generation (when this run created one) is + // carried in the ReindexContext, so writes target exactly this run's generation — partial + // recreates and normal runs carry none and write to the live index. + String stagedChunkTarget = + reindexContext != null ? reindexContext.getStagedChunkIndex().orElse(null) : null; + json = + enrichWithEmbedding(entity, json, existingEmbeddingsById, tracker, stagedChunkTarget); } String finalJson = json; @@ -921,7 +927,8 @@ private String enrichWithEmbedding( EntityInterface entity, String json, Map existingEmbeddingsById, - StageStatsTracker tracker) { + StageStatsTracker tracker, + String stagedChunkTarget) { try { OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); if (vectorService == null) { @@ -936,10 +943,8 @@ private String enrichWithEmbedding( return json; } - int expectedDimension = - vectorService.getEmbeddingClient() != null - ? vectorService.getEmbeddingClient().getDimension() - : -1; + var embeddingClient = vectorService.getEmbeddingClient(); + int expectedDimension = embeddingClient != null ? embeddingClient.getDimension() : -1; JsonNode cached = existingEmbeddingsById.get(entity.getId().toString()); if (canReuseCachedEmbedding(cached, expectedDimension)) { // Splices chunkIndex/chunkCount/parentId along with embedding — safe because the @@ -951,19 +956,20 @@ private String enrichWithEmbedding( // shipped). The call is fingerprint-guarded, so it is a cheap no-op once chunks exist; // chunk docs reflect committed entity state, so writing them mid-reindex is safe even if // the staged index is never promoted. - vectorService.updateEntityEmbeddingChunks(entity); - } else { + vectorService.backfillEntityChunks(entity, stagedChunkTarget); + } else if (embeddingClient != null && embeddingClient.isAvailable()) { // Build the chunk docs once (one embedding call per chunk): chunk 0's embedding fields - // are spliced into the staged entity doc for hybrid search, and the full set is written - // to the dedicated chunk index for the semantic vector path (issue #4789). - List> chunkDocs = - VectorDocBuilder.fromEntity(entity, vectorService.getEmbeddingClient()); + // are spliced into the staged entity doc for hybrid search, and the full set is written to + // the dedicated chunk index for the semantic vector path (issue #4789). Skipped when the + // provider circuit is open so a transient outage indexes without embeddings (self-heals on + // the next reindex) instead of failing every entity. + List> chunkDocs = VectorDocBuilder.fromEntity(entity, embeddingClient); if (!chunkDocs.isEmpty()) { doc.setAll( (ObjectNode) OBJECT_MAPPER.valueToTree( OpenSearchVectorService.legacyEmbeddingFields(chunkDocs.get(0)))); - vectorService.writeEntityChunks(entity.getId().toString(), chunkDocs); + vectorService.writeEntityChunks(entity.getId().toString(), chunkDocs, stagedChunkTarget); } } @@ -1268,6 +1274,11 @@ private void flushIfNeeded() { if (!buffer.isEmpty() && !closed) { flushInternal(); } + } catch (Exception e) { + // An exception escaping here would cancel the scheduled task permanently + // (ScheduledExecutorService contract), silently disabling periodic flushing so trailing + // buffers only ship on an explicit flush/close. Log and continue to the next interval. + LOG.error("Scheduled flush failed; will retry on the next interval", e); } finally { lock.unlock(); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/AppScheduler.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/AppScheduler.java index d6a4dfcef11e..bae6a22d6036 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/AppScheduler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/AppScheduler.java @@ -85,6 +85,7 @@ public class AppScheduler { private static AppScheduler instance; private static volatile boolean initialized = false; @Getter private final Scheduler scheduler; + private final ScheduledExecutorService errorTriggerResetScheduler; private static final @Getter CronMapper cronMapper = CronMapper.fromUnixToQuartz(); private static final @Getter CronParser cronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(UNIX)); @@ -108,10 +109,14 @@ private AppScheduler( .getListenerManager() .addJobListener(new OmAppJobListener(), jobGroupEquals(APPS_JOB_GROUP)); - ScheduledExecutorService threadScheduler = + // Daemon thread + retained reference so shutDown() can stop it. Previously this pool was a + // local with a non-daemon thread that was never shut down, so it survived shutDown() and + // blocked JVM exit (and leaked another pool on each re-initialize in embedded/test contexts). + this.errorTriggerResetScheduler = Executors.newScheduledThreadPool( - 1, Thread.ofPlatform().name("om-app-error-trigger-reset").factory()); - threadScheduler.scheduleAtFixedRate(this::resetErrorTriggers, 0, 24, TimeUnit.HOURS); + 1, Thread.ofPlatform().daemon().name("om-app-error-trigger-reset").factory()); + this.errorTriggerResetScheduler.scheduleAtFixedRate( + this::resetErrorTriggers, 0, 24, TimeUnit.HOURS); } public void start() throws SchedulerException { @@ -243,6 +248,7 @@ private Trigger trigger(App app) { public static void shutDown() throws SchedulerException { if (instance != null) { instance.scheduler.shutdown(); + instance.errorTriggerResetScheduler.shutdownNow(); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/OmAppJobListener.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/OmAppJobListener.java index b5d5380762f8..b58e9b0c40bc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/OmAppJobListener.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/scheduler/OmAppJobListener.java @@ -4,8 +4,6 @@ import static org.openmetadata.service.apps.scheduler.AppScheduler.APP_CONFIG_KEY; import static org.openmetadata.service.apps.scheduler.AppScheduler.APP_NAME; -import java.util.HashMap; -import java.util.Map; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -15,6 +13,7 @@ import org.openmetadata.schema.entity.app.FailureContext; import org.openmetadata.schema.entity.app.SuccessContext; import org.openmetadata.schema.entity.applications.configuration.ApplicationConfig; +import org.openmetadata.schema.system.IndexingError; import org.openmetadata.schema.system.Stats; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; @@ -225,10 +224,11 @@ public void jobWasExecuted( context = runRecord.getFailureContext(); } if (jobException != null) { - Map failure = new HashMap<>(); - failure.put("message", jobException.getMessage()); - failure.put("jobStackTrace", ExceptionUtils.getStackTrace(jobException)); - context.withAdditionalProperty("failure", failure); + context.withFailure( + new IndexingError() + .withErrorSource(IndexingError.ErrorSource.JOB) + .withMessage(jobException.getMessage()) + .withStackTrace(ExceptionUtils.getStackTrace(jobException))); } runRecord.setFailureContext(context); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/attachments/AssetServiceFactory.java b/openmetadata-service/src/main/java/org/openmetadata/service/attachments/AssetServiceFactory.java index fb413e756a7c..7186b164f7c7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/attachments/AssetServiceFactory.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/attachments/AssetServiceFactory.java @@ -14,12 +14,6 @@ public static synchronized void init(OpenMetadataApplicationConfig config) { registerShutdownHook(); ObjectStorageConfiguration objectStorageConfiguration = config.getObjectStorage(); if (objectStorageConfiguration == null || !objectStorageConfiguration.isEnabled()) { - LOG.warn( - "Object storage is disabled (objectStorage.enabled=false or missing). File uploads " - + "(e.g. Context Center Drive) will be accepted but their content will be " - + "discarded, and file processing will fail with 'Unable to read file content " - + "from object storage'. Configure objectStorage with provider s3, azure, or " - + "inmemory to enable file storage."); // Storage disabled — always swap to a fresh NoOp provider. If a previous init // wired up S3/Azure/InMemory, leaving that instance live after a reload to the // disabled state would keep serving real uploads/downloads against the old diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java index 568f533de003..b11c2a03d8f7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java @@ -3,6 +3,11 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import static org.openmetadata.service.formatter.field.DefaultFieldFormatter.getFieldValue; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -272,7 +277,8 @@ public interface ExportProgressCallback { * * @param progressCallback Optional callback for progress notifications (can be null) */ - public List exportInBatches( + public int streamExportAsJson( + OutputStream outputStream, String userName, String actorType, String serviceName, @@ -282,10 +288,13 @@ public List exportInBatches( Long endTs, String searchTerm, int totalLimit, - ExportProgressCallback progressCallback) { + ExportProgressCallback progressCallback) + throws IOException { long startTime = System.currentTimeMillis(); - List allResults = new ArrayList<>(); + Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); + writer.write("["); + int exported = 0; String afterCursor = null; int remaining = totalLimit; @@ -319,7 +328,7 @@ public List exportInBatches( LOG.warn( "Export timed out after {} ms, returning {} records fetched so far", EXPORT_TIMEOUT_MS, - allResults.size()); + exported); break; } @@ -344,7 +353,13 @@ public List exportInBatches( break; } - allResults.addAll(batch.getData()); + for (AuditLogEntry entry : batch.getData()) { + if (exported > 0) { + writer.write(","); + } + writer.write(JsonUtils.pojoToJson(entry)); + exported++; + } remaining -= batch.getData().size(); batchNumber++; @@ -352,8 +367,8 @@ public List exportInBatches( if (progressCallback != null) { String message = String.format( - "Fetched %d of %d records (batch %d)", allResults.size(), actualTotal, batchNumber); - progressCallback.onProgress(allResults.size(), actualTotal, message); + "Fetched %d of %d records (batch %d)", exported, actualTotal, batchNumber); + progressCallback.onProgress(exported, actualTotal, message); } // Get cursor for next batch @@ -363,33 +378,9 @@ public List exportInBatches( } } - return allResults; - } - - /** - * Export audit logs in batches without progress callback (backwards compatibility). - */ - public List exportInBatches( - String userName, - String actorType, - String serviceName, - String entityType, - String eventType, - Long startTs, - Long endTs, - String searchTerm, - int totalLimit) { - return exportInBatches( - userName, - actorType, - serviceName, - entityType, - eventType, - startTs, - endTs, - searchTerm, - totalLimit, - null); + writer.write("]"); + writer.flush(); + return exported; } public ResultList list( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java index 7c2c1df603d0..d573f2429c76 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java @@ -225,10 +225,9 @@ public static void registerInvalidatable(Invalidatable layer) { * pub-sub handler above when a remote pod publishes a write, and from the admin * {@code POST /system/cache/invalidate} endpoint. * - *

Note: not every entity mutation hook calls this — {@code postUpdate} / {@code postDelete} - * / {@code restoreEntity} currently rely on the write-through cache + L1 eviction rather - * than the {@link Invalidatable} registry. If you wire a new Invalidatable that needs to - * react to those events, you'll need to add the call there as well. + *

Entity creates call this directly, while update, delete, and restore paths reach it through + * the repository's mutation cache invalidation. New mutation paths must do the same so registered + * layers such as the negative cache cannot outlive a successful write. * *

No-op if no layers are registered (cache disabled or none registered yet). */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheKeys.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheKeys.java index 703c771bbfde..0ea2e99cf43a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheKeys.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheKeys.java @@ -55,6 +55,18 @@ public String refByName(String type, String fqn) { return ns + ":rn:" + type + ":" + fqnHash; } + public String personaContextMarkdown(UUID personaId, String definitionHash) { + return ns + ":pctx:" + personaId + ":md:" + definitionHash; + } + + public String personaContextJson(UUID personaId, String definitionHash) { + return ns + ":pctx:" + personaId + ":json:" + definitionHash; + } + + public String personaContextLock(UUID personaId) { + return ns + ":pctx:lock:" + personaId; + } + /** * Redis hash key holding cached listing totals for an entity type. Each ListFilter variant * lives as a field (hash of its WHERE clause + bound params) under this single key, so a diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java index 937f80fe746d..3813f98b2b8f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java @@ -13,6 +13,16 @@ public interface CacheProvider extends AutoCloseable { void del(String... keys); + /** Deletes {@code key} only when its current value is {@code expectedValue}. */ + default boolean deleteIfValue(String key, String expectedValue) { + Optional current = get(key); + if (current.isPresent() && current.get().equals(expectedValue)) { + del(key); + return true; + } + return false; + } + Optional hget(String key, String field); void hset(String key, Map fields, Duration ttl); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java index f0cf2c5e58c7..ae7a020e23dc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java @@ -4,6 +4,7 @@ import io.lettuce.core.RedisClient; import io.lettuce.core.RedisFuture; import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; import io.lettuce.core.SetArgs; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; @@ -353,6 +354,33 @@ public void del(String... keys) { } } + @Override + public boolean deleteIfValue(String key, String expectedValue) { + if (!available) return false; + + CacheMetrics m = metrics(); + Timer.Sample sample = startWriteTimer(m); + try { + Long deleted = + syncCommands.eval( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) else return 0 end", + ScriptOutputType.INTEGER, + new String[] {key}, + expectedValue); + if (m != null && deleted != null && deleted > 0) m.recordEviction(); + recordSuccess(); + return deleted != null && deleted > 0; + } catch (Exception e) { + if (m != null) m.recordError(); + recordFailure(e); + LOG.error("Error deleting key with owner check: {}", key, e); + return false; + } finally { + stopWriteTimer(m, sample); + } + } + @Override public Optional hget(String key, String field) { if (!available) return Optional.empty(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/AnthropicLlmClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/AnthropicLlmClient.java deleted file mode 100644 index 3336544a2748..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/AnthropicLlmClient.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.clients.llm; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.configuration.LLMAnthropicConfig; -import org.openmetadata.schema.configuration.LLMConfiguration; -import org.openmetadata.schema.utils.JsonUtils; - -@Slf4j -public class AnthropicLlmClient implements LlmClient { - private static final String DEFAULT_ENDPOINT = "https://api.anthropic.com"; - private static final String ANTHROPIC_VERSION = "2023-06-01"; - private static final int MAX_TOKENS = 4096; - private static final Duration TIMEOUT = Duration.ofSeconds(120); - - private final String apiEndpoint; - private final String apiKey; - private final String model; - private final ObjectMapper mapper; - private final HttpClient httpClient; - - public AnthropicLlmClient(LLMConfiguration config) { - LLMAnthropicConfig anthropic = config.getAnthropic(); - this.apiKey = anthropic == null ? null : anthropic.getApiKey(); - if (apiKey == null || apiKey.isBlank()) { - throw new IllegalArgumentException("An API key is required for the Anthropic LLM provider."); - } - this.model = anthropic.getModelId(); - this.apiEndpoint = - anthropic.getBaseUrl() != null && !anthropic.getBaseUrl().isBlank() - ? anthropic.getBaseUrl() - : DEFAULT_ENDPOINT; - this.mapper = JsonUtils.getObjectMapper(); - this.httpClient = HttpClient.newBuilder().connectTimeout(TIMEOUT).build(); - } - - @Override - public LlmResponse sendMessages(List messages, List> tools) { - try { - ObjectNode requestBody = buildRequestBody(messages, tools); - String json = mapper.writeValueAsString(requestBody); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(apiEndpoint + "/v1/messages")) - .header("Content-Type", "application/json") - .header("x-api-key", apiKey) - .header("anthropic-version", ANTHROPIC_VERSION) - .timeout(TIMEOUT) - .POST(HttpRequest.BodyPublishers.ofString(json)) - .build(); - - HttpResponse response = - httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - throw new LlmException( - "Anthropic API returned status " + response.statusCode() + ": " + response.body()); - } - - return parseResponse(response.body()); - } catch (IOException e) { - throw new LlmException("Failed to call Anthropic API", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new LlmException("Anthropic API call interrupted", e); - } - } - - private ObjectNode buildRequestBody(List messages, List> tools) { - ObjectNode body = mapper.createObjectNode(); - body.put("model", model); - body.put("max_tokens", MAX_TOKENS); - - String systemPrompt = extractSystemPrompt(messages); - if (systemPrompt != null) { - body.put("system", systemPrompt); - } - - ArrayNode messagesArray = body.putArray("messages"); - for (LlmMessage msg : messages) { - if (msg.role() == LlmMessage.Role.system) { - continue; - } - messagesArray.add(buildMessageNode(msg)); - } - - if (tools != null && !tools.isEmpty()) { - ArrayNode toolsArray = body.putArray("tools"); - for (Map tool : tools) { - toolsArray.add(buildToolNode(tool)); - } - } - - return body; - } - - private String extractSystemPrompt(List messages) { - for (LlmMessage msg : messages) { - if (msg.role() == LlmMessage.Role.system && msg.content() != null) { - return msg.content(); - } - } - return null; - } - - private ObjectNode buildMessageNode(LlmMessage msg) { - ObjectNode node = mapper.createObjectNode(); - - if (msg.role() == LlmMessage.Role.tool) { - node.put("role", "user"); - ArrayNode contentArray = node.putArray("content"); - ObjectNode toolResultBlock = mapper.createObjectNode(); - toolResultBlock.put("type", "tool_result"); - toolResultBlock.put("tool_use_id", msg.toolCallId()); - toolResultBlock.put("content", msg.content() != null ? msg.content() : ""); - contentArray.add(toolResultBlock); - return node; - } - - node.put("role", msg.role() == LlmMessage.Role.assistant ? "assistant" : "user"); - - if (msg.toolCalls() != null && !msg.toolCalls().isEmpty()) { - ArrayNode contentArray = node.putArray("content"); - for (LlmToolCall tc : msg.toolCalls()) { - ObjectNode toolUseBlock = mapper.createObjectNode(); - toolUseBlock.put("type", "tool_use"); - toolUseBlock.put("id", tc.id()); - toolUseBlock.put("name", tc.name()); - try { - toolUseBlock.set("input", mapper.readTree(tc.arguments())); - } catch (IOException e) { - toolUseBlock.put("input", tc.arguments()); - } - contentArray.add(toolUseBlock); - } - return node; - } - - if (msg.content() != null) { - node.put("content", msg.content()); - } - - return node; - } - - @SuppressWarnings("unchecked") - private ObjectNode buildToolNode(Map tool) { - ObjectNode toolNode = mapper.createObjectNode(); - - Map function = (Map) tool.get("function"); - if (function != null) { - toolNode.put("name", (String) function.get("name")); - if (function.containsKey("description")) { - toolNode.put("description", (String) function.get("description")); - } - if (function.containsKey("parameters")) { - toolNode.set("input_schema", mapper.valueToTree(function.get("parameters"))); - } - } - - return toolNode; - } - - @Override - public LlmResponse sendMessagesStreaming( - List messages, List> tools, Consumer onTextChunk) { - try { - ObjectNode requestBody = buildRequestBody(messages, tools); - requestBody.put("stream", true); - - String json = mapper.writeValueAsString(requestBody); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(apiEndpoint + "/v1/messages")) - .header("Content-Type", "application/json") - .header("x-api-key", apiKey) - .header("anthropic-version", ANTHROPIC_VERSION) - .timeout(TIMEOUT) - .POST(HttpRequest.BodyPublishers.ofString(json)) - .build(); - - HttpResponse response = - httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); - - if (response.statusCode() != 200) { - throw new LlmException( - "Anthropic API returned status " - + response.statusCode() - + ": " - + readErrorBody(response)); - } - - return parseStreamingResponse(response.body(), onTextChunk); - } catch (IOException e) { - throw new LlmException("Failed to call Anthropic streaming API", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new LlmException("Anthropic streaming API call interrupted", e); - } - } - - private static String readErrorBody(HttpResponse response) throws IOException { - try (InputStream errorStream = response.body()) { - return new String(errorStream.readAllBytes(), StandardCharsets.UTF_8); - } - } - - private LlmResponse parseStreamingResponse(InputStream body, Consumer onTextChunk) - throws IOException { - StringBuilder textContent = new StringBuilder(); - List toolCalls = new ArrayList<>(); - int inputTokens = 0; - int outputTokens = 0; - String stopReason = null; - - String currentToolId = null; - String currentToolName = null; - StringBuilder currentToolArgs = new StringBuilder(); - - try (BufferedReader reader = - new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8))) { - String line; - String currentEvent = null; - - while ((line = reader.readLine()) != null) { - if (line.startsWith("event: ")) { - currentEvent = line.substring(7).trim(); - continue; - } - if (!line.startsWith("data: ")) { - continue; - } - String data = line.substring(6).trim(); - if (data.isEmpty()) { - continue; - } - - JsonNode chunk = mapper.readTree(data); - - if (currentEvent == null) { - continue; - } - - switch (currentEvent) { - case "message_start" -> { - JsonNode usage = chunk.path("message").path("usage"); - inputTokens = usage.path("input_tokens").asInt(0); - } - case "content_block_start" -> { - JsonNode contentBlock = chunk.path("content_block"); - if ("tool_use".equals(contentBlock.path("type").asText())) { - currentToolId = contentBlock.path("id").asText(); - currentToolName = contentBlock.path("name").asText(); - currentToolArgs = new StringBuilder(); - } - } - case "content_block_delta" -> { - JsonNode delta = chunk.path("delta"); - String deltaType = delta.path("type").asText(); - if ("text_delta".equals(deltaType)) { - String text = delta.path("text").asText(); - textContent.append(text); - onTextChunk.accept(text); - } else if ("input_json_delta".equals(deltaType)) { - currentToolArgs.append(delta.path("partial_json").asText()); - } - } - case "content_block_stop" -> { - if (currentToolId != null) { - toolCalls.add( - new LlmToolCall(currentToolId, currentToolName, currentToolArgs.toString())); - currentToolId = null; - currentToolName = null; - currentToolArgs = new StringBuilder(); - } - } - case "message_delta" -> { - JsonNode delta = chunk.path("delta"); - if (delta.has("stop_reason") && !delta.get("stop_reason").isNull()) { - stopReason = delta.get("stop_reason").asText(); - } - outputTokens = chunk.path("usage").path("output_tokens").asInt(0); - } - default -> {} - } - } - } - - String content = textContent.length() > 0 ? textContent.toString() : null; - return new LlmResponse(content, toolCalls, inputTokens, outputTokens, stopReason); - } - - private LlmResponse parseResponse(String responseBody) throws IOException { - JsonNode root = mapper.readTree(responseBody); - - String stopReason = root.has("stop_reason") ? root.get("stop_reason").asText() : null; - - JsonNode usage = root.path("usage"); - int inputTokens = usage.path("input_tokens").asInt(0); - int outputTokens = usage.path("output_tokens").asInt(0); - - StringBuilder textContent = new StringBuilder(); - List toolCalls = new ArrayList<>(); - - JsonNode contentArray = root.path("content"); - if (contentArray.isArray()) { - for (JsonNode block : contentArray) { - String type = block.path("type").asText(); - if ("text".equals(type)) { - textContent.append(block.path("text").asText()); - } else if ("tool_use".equals(type)) { - String id = block.get("id").asText(); - String name = block.get("name").asText(); - String arguments = mapper.writeValueAsString(block.get("input")); - toolCalls.add(new LlmToolCall(id, name, arguments)); - } - } - } - - String content = textContent.length() > 0 ? textContent.toString() : null; - return new LlmResponse(content, toolCalls, inputTokens, outputTokens, stopReason); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/BedrockLlmClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/BedrockLlmClient.java deleted file mode 100644 index 5fdd91c2bdea..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/BedrockLlmClient.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.clients.llm; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.configuration.LLMBedrockConfig; -import org.openmetadata.schema.configuration.LLMConfiguration; -import org.openmetadata.schema.security.credentials.AWSBaseConfig; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.util.AwsCredentialsUtil; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; -import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClientBuilder; -import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelRequest; -import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse; - -@Slf4j -public class BedrockLlmClient implements LlmClient { - private static final int MAX_TOKENS = 4096; - private static final String ANTHROPIC_VERSION = "bedrock-2023-05-31"; - - private final String model; - private final ObjectMapper mapper; - private final BedrockRuntimeClient bedrockClient; - - public BedrockLlmClient(LLMConfiguration config) { - LLMBedrockConfig bedrock = config.getBedrock(); - if (bedrock == null) { - throw new IllegalArgumentException( - "Bedrock configuration is required for the Bedrock LLM provider."); - } - this.model = bedrock.getModelId(); - this.mapper = JsonUtils.getObjectMapper(); - - AWSBaseConfig awsConfig = bedrock.getAwsConfig(); - if (awsConfig == null || awsConfig.getRegion() == null) { - throw new IllegalArgumentException( - "AWS configuration with a region is required for the Bedrock LLM provider."); - } - BedrockRuntimeClientBuilder builder = - BedrockRuntimeClient.builder() - .credentialsProvider(AwsCredentialsUtil.buildCredentialsProvider(awsConfig)) - .region(Region.of(awsConfig.getRegion())); - - if (awsConfig.getEndpointUrl() != null) { - builder.endpointOverride(awsConfig.getEndpointUrl()); - } - - this.bedrockClient = builder.build(); - } - - @Override - public LlmResponse sendMessages(List messages, List> tools) { - ObjectNode requestBody = buildRequestBody(messages, tools); - String json; - try { - json = mapper.writeValueAsString(requestBody); - } catch (IOException e) { - throw new LlmException("Failed to serialize Bedrock request", e); - } - - InvokeModelRequest request = - InvokeModelRequest.builder() - .modelId(model) - .contentType("application/json") - .accept("application/json") - .body(SdkBytes.fromUtf8String(json)) - .build(); - - InvokeModelResponse response = bedrockClient.invokeModel(request); - return parseResponse(response.body().asUtf8String()); - } - - @Override - public LlmResponse sendMessagesStreaming( - List messages, List> tools, Consumer onTextChunk) { - LOG.warn( - "Bedrock provider does not support true streaming; falling back to non-streaming response"); - LlmResponse response = sendMessages(messages, tools); - if (response.content() != null) { - onTextChunk.accept(response.content()); - } - return response; - } - - @Override - public void close() { - if (bedrockClient != null) { - bedrockClient.close(); - } - } - - private ObjectNode buildRequestBody(List messages, List> tools) { - ObjectNode body = mapper.createObjectNode(); - body.put("anthropic_version", ANTHROPIC_VERSION); - body.put("max_tokens", MAX_TOKENS); - - String systemPrompt = extractSystemPrompt(messages); - if (systemPrompt != null) { - body.put("system", systemPrompt); - } - - ArrayNode messagesArray = body.putArray("messages"); - for (LlmMessage msg : messages) { - if (msg.role() == LlmMessage.Role.system) { - continue; - } - messagesArray.add(buildMessageNode(msg)); - } - - if (tools != null && !tools.isEmpty()) { - ArrayNode toolsArray = body.putArray("tools"); - for (Map tool : tools) { - toolsArray.add(buildToolNode(tool)); - } - } - - return body; - } - - private String extractSystemPrompt(List messages) { - for (LlmMessage msg : messages) { - if (msg.role() == LlmMessage.Role.system && msg.content() != null) { - return msg.content(); - } - } - return null; - } - - private ObjectNode buildMessageNode(LlmMessage msg) { - ObjectNode node = mapper.createObjectNode(); - - if (msg.role() == LlmMessage.Role.tool) { - node.put("role", "user"); - ArrayNode contentArray = node.putArray("content"); - ObjectNode toolResultBlock = mapper.createObjectNode(); - toolResultBlock.put("type", "tool_result"); - toolResultBlock.put("tool_use_id", msg.toolCallId()); - toolResultBlock.put("content", msg.content() != null ? msg.content() : ""); - contentArray.add(toolResultBlock); - return node; - } - - node.put("role", msg.role() == LlmMessage.Role.assistant ? "assistant" : "user"); - - if (msg.toolCalls() != null && !msg.toolCalls().isEmpty()) { - ArrayNode contentArray = node.putArray("content"); - for (LlmToolCall tc : msg.toolCalls()) { - ObjectNode toolUseBlock = mapper.createObjectNode(); - toolUseBlock.put("type", "tool_use"); - toolUseBlock.put("id", tc.id()); - toolUseBlock.put("name", tc.name()); - try { - toolUseBlock.set("input", mapper.readTree(tc.arguments())); - } catch (IOException e) { - toolUseBlock.put("input", tc.arguments()); - } - contentArray.add(toolUseBlock); - } - return node; - } - - if (msg.content() != null) { - node.put("content", msg.content()); - } - - return node; - } - - @SuppressWarnings("unchecked") - private ObjectNode buildToolNode(Map tool) { - ObjectNode toolNode = mapper.createObjectNode(); - - Map function = (Map) tool.get("function"); - if (function != null) { - toolNode.put("name", (String) function.get("name")); - if (function.containsKey("description")) { - toolNode.put("description", (String) function.get("description")); - } - if (function.containsKey("parameters")) { - toolNode.set("input_schema", mapper.valueToTree(function.get("parameters"))); - } - } - - return toolNode; - } - - private LlmResponse parseResponse(String responseBody) { - try { - JsonNode root = mapper.readTree(responseBody); - - String stopReason = root.has("stop_reason") ? root.get("stop_reason").asText() : null; - - JsonNode usage = root.path("usage"); - int inputTokens = usage.path("input_tokens").asInt(0); - int outputTokens = usage.path("output_tokens").asInt(0); - - StringBuilder textContent = new StringBuilder(); - List toolCalls = new ArrayList<>(); - - JsonNode contentArray = root.path("content"); - if (contentArray.isArray()) { - for (JsonNode block : contentArray) { - String type = block.path("type").asText(); - if ("text".equals(type)) { - textContent.append(block.path("text").asText()); - } else if ("tool_use".equals(type)) { - String id = block.get("id").asText(); - String name = block.get("name").asText(); - String arguments = mapper.writeValueAsString(block.get("input")); - toolCalls.add(new LlmToolCall(id, name, arguments)); - } - } - } - - String content = textContent.length() > 0 ? textContent.toString() : null; - return new LlmResponse(content, toolCalls, inputTokens, outputTokens, stopReason); - } catch (IOException e) { - throw new LlmException("Failed to parse Bedrock response", e); - } - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmClient.java deleted file mode 100644 index c1981669fa83..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmClient.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.clients.llm; - -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -public interface LlmClient extends AutoCloseable { - LlmResponse sendMessages(List messages, List> tools); - - @Override - default void close() {} - - default LlmResponse sendMessagesStreaming( - List messages, List> tools, Consumer onTextChunk) { - LlmResponse response = sendMessages(messages, tools); - if (response.content() != null && !response.content().isEmpty()) { - onTextChunk.accept(response.content()); - } - return response; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmClientFactory.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmClientFactory.java deleted file mode 100644 index 9013e8295b70..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmClientFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.clients.llm; - -import org.openmetadata.schema.configuration.LLMConfiguration; - -public final class LlmClientFactory { - - private LlmClientFactory() {} - - public static LlmClient create(LLMConfiguration config) { - if (config == null || config.getProvider() == null) { - throw new IllegalArgumentException( - "llmConfiguration.provider must be set to build an LLM client."); - } - return switch (config.getProvider()) { - case OPENAI -> new OpenAiLlmClient(config); - case ANTHROPIC -> new AnthropicLlmClient(config); - case BEDROCK -> new BedrockLlmClient(config); - case AZURE_OPENAI, GOOGLE, NOOP -> throw new IllegalArgumentException( - "LLM provider '" - + config.getProvider() - + "' is not supported by MCP chat. Use one of: openai, anthropic, bedrock."); - }; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmConfigHolder.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmConfigHolder.java index bad6a76851b2..4499d8b7a09a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmConfigHolder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmConfigHolder.java @@ -16,9 +16,8 @@ /** * Holds the platform-wide {@link LLMConfiguration} loaded from {@code openmetadata.yaml} at startup, - * so any feature needing LLM access (e.g. the MCP Chat application) can read it without threading - * the config through every layer. Features build their own client from this config via {@link - * LlmClientFactory}. + * so any feature needing LLM access (e.g. semantic-search embeddings) can read it without threading + * the config through every layer. */ public final class LlmConfigHolder { private static volatile LLMConfiguration configuration; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmMessage.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmMessage.java deleted file mode 100644 index a205db9cdc49..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmMessage.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.clients.llm; - -import java.util.List; - -public record LlmMessage( - Role role, String content, String toolCallId, List toolCalls) { - public enum Role { - system, - user, - assistant, - tool - } - - public static LlmMessage system(String content) { - return new LlmMessage(Role.system, content, null, null); - } - - public static LlmMessage user(String content) { - return new LlmMessage(Role.user, content, null, null); - } - - public static LlmMessage assistant(String content) { - return new LlmMessage(Role.assistant, content, null, null); - } - - public static LlmMessage assistantWithToolCalls(String content, List toolCalls) { - return new LlmMessage(Role.assistant, content, null, toolCalls); - } - - public static LlmMessage toolResult(String toolCallId, String content) { - return new LlmMessage(Role.tool, content, toolCallId, null); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmToolCall.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmToolCall.java deleted file mode 100644 index da2a36ea1b5f..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/LlmToolCall.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.clients.llm; - -public record LlmToolCall(String id, String name, String arguments) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/OpenAiLlmClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/OpenAiLlmClient.java deleted file mode 100644 index fd37fe880b54..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/clients/llm/OpenAiLlmClient.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.clients.llm; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.configuration.LLMConfiguration; -import org.openmetadata.schema.configuration.LLMOpenAIConfig; -import org.openmetadata.schema.utils.JsonUtils; - -@Slf4j -public class OpenAiLlmClient implements LlmClient { - private static final String DEFAULT_ENDPOINT = "https://api.openai.com"; - private static final Duration TIMEOUT = Duration.ofSeconds(120); - - private final String apiEndpoint; - private final String apiKey; - private final String model; - private final ObjectMapper mapper; - private final HttpClient httpClient; - - public OpenAiLlmClient(LLMConfiguration config) { - LLMOpenAIConfig openai = config.getOpenai(); - this.apiKey = openai == null ? null : openai.getApiKey(); - if (apiKey == null || apiKey.isBlank()) { - throw new IllegalArgumentException("An API key is required for the OpenAI LLM provider."); - } - this.model = openai.getModelId(); - this.apiEndpoint = - openai.getEndpoint() != null && !openai.getEndpoint().isBlank() - ? openai.getEndpoint() - : DEFAULT_ENDPOINT; - this.mapper = JsonUtils.getObjectMapper(); - this.httpClient = HttpClient.newBuilder().connectTimeout(TIMEOUT).build(); - } - - @Override - public LlmResponse sendMessages(List messages, List> tools) { - try { - ObjectNode requestBody = buildRequestBody(messages, tools); - String json = mapper.writeValueAsString(requestBody); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(apiEndpoint + "/v1/chat/completions")) - .header("Content-Type", "application/json") - .header("Authorization", "Bearer " + apiKey) - .timeout(TIMEOUT) - .POST(HttpRequest.BodyPublishers.ofString(json)) - .build(); - - HttpResponse response = - httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - throw new LlmException( - "OpenAI API returned status " + response.statusCode() + ": " + response.body()); - } - - return parseResponse(response.body()); - } catch (IOException e) { - throw new LlmException("Failed to call OpenAI API", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new LlmException("OpenAI API call interrupted", e); - } - } - - private ObjectNode buildRequestBody(List messages, List> tools) { - ObjectNode body = mapper.createObjectNode(); - body.put("model", model); - - ArrayNode messagesArray = body.putArray("messages"); - for (LlmMessage msg : messages) { - messagesArray.add(buildMessageNode(msg)); - } - - if (tools != null && !tools.isEmpty()) { - ArrayNode toolsArray = body.putArray("tools"); - for (Map tool : tools) { - toolsArray.add(mapper.valueToTree(tool)); - } - } - - return body; - } - - private ObjectNode buildMessageNode(LlmMessage msg) { - ObjectNode node = mapper.createObjectNode(); - node.put("role", msg.role().name()); - - if (msg.content() != null) { - node.put("content", msg.content()); - } - - if (msg.toolCallId() != null) { - node.put("tool_call_id", msg.toolCallId()); - } - - if (msg.toolCalls() != null && !msg.toolCalls().isEmpty()) { - ArrayNode toolCallsArray = node.putArray("tool_calls"); - for (LlmToolCall tc : msg.toolCalls()) { - ObjectNode tcNode = mapper.createObjectNode(); - tcNode.put("id", tc.id()); - tcNode.put("type", "function"); - ObjectNode fnNode = tcNode.putObject("function"); - fnNode.put("name", tc.name()); - fnNode.put("arguments", tc.arguments()); - toolCallsArray.add(tcNode); - } - } - - return node; - } - - @Override - public LlmResponse sendMessagesStreaming( - List messages, List> tools, Consumer onTextChunk) { - try { - ObjectNode requestBody = buildRequestBody(messages, tools); - requestBody.put("stream", true); - ObjectNode streamOptions = requestBody.putObject("stream_options"); - streamOptions.put("include_usage", true); - - String json = mapper.writeValueAsString(requestBody); - - HttpRequest request = - HttpRequest.newBuilder() - .uri(URI.create(apiEndpoint + "/v1/chat/completions")) - .header("Content-Type", "application/json") - .header("Authorization", "Bearer " + apiKey) - .timeout(TIMEOUT) - .POST(HttpRequest.BodyPublishers.ofString(json)) - .build(); - - HttpResponse response = - httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); - - if (response.statusCode() != 200) { - throw new LlmException( - "OpenAI API returned status " + response.statusCode() + ": " + readErrorBody(response)); - } - - return parseStreamingResponse(response.body(), onTextChunk); - } catch (IOException e) { - throw new LlmException("Failed to call OpenAI streaming API", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new LlmException("OpenAI streaming API call interrupted", e); - } - } - - private static String readErrorBody(HttpResponse response) throws IOException { - try (InputStream errorStream = response.body()) { - return new String(errorStream.readAllBytes(), StandardCharsets.UTF_8); - } - } - - private LlmResponse parseStreamingResponse(InputStream body, Consumer onTextChunk) - throws IOException { - StringBuilder contentBuilder = new StringBuilder(); - Map toolCallIds = new HashMap<>(); - Map toolCallNames = new HashMap<>(); - Map toolCallArgs = new HashMap<>(); - int inputTokens = 0; - int outputTokens = 0; - String stopReason = null; - - try (BufferedReader reader = - new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8))) { - String line; - while ((line = reader.readLine()) != null) { - if (!line.startsWith("data: ")) { - continue; - } - String data = line.substring(6).trim(); - if ("[DONE]".equals(data)) { - break; - } - - JsonNode chunk = mapper.readTree(data); - - if (chunk.has("usage") && !chunk.get("usage").isNull()) { - JsonNode usage = chunk.get("usage"); - inputTokens = usage.path("prompt_tokens").asInt(0); - outputTokens = usage.path("completion_tokens").asInt(0); - } - - JsonNode choices = chunk.path("choices"); - if (!choices.isArray() || choices.isEmpty()) { - continue; - } - - JsonNode choice = choices.get(0); - if (choice.has("finish_reason") && !choice.get("finish_reason").isNull()) { - stopReason = choice.get("finish_reason").asText(); - } - - JsonNode delta = choice.path("delta"); - - if (delta.has("content") && !delta.get("content").isNull()) { - String text = delta.get("content").asText(); - contentBuilder.append(text); - onTextChunk.accept(text); - } - - if (delta.has("tool_calls")) { - for (JsonNode tc : delta.get("tool_calls")) { - int index = tc.get("index").asInt(); - if (tc.has("id")) { - toolCallIds.put(index, tc.get("id").asText()); - } - JsonNode function = tc.path("function"); - if (function.has("name")) { - toolCallNames.put(index, function.get("name").asText()); - } - if (function.has("arguments")) { - toolCallArgs - .computeIfAbsent(index, k -> new StringBuilder()) - .append(function.get("arguments").asText()); - } - } - } - } - } - - List toolCalls = new ArrayList<>(); - for (Map.Entry entry : toolCallIds.entrySet()) { - int idx = entry.getKey(); - toolCalls.add( - new LlmToolCall( - entry.getValue(), - toolCallNames.getOrDefault(idx, ""), - toolCallArgs.containsKey(idx) ? toolCallArgs.get(idx).toString() : "{}")); - } - - String content = contentBuilder.length() > 0 ? contentBuilder.toString() : null; - return new LlmResponse(content, toolCalls, inputTokens, outputTokens, stopReason); - } - - private LlmResponse parseResponse(String responseBody) throws IOException { - JsonNode root = mapper.readTree(responseBody); - JsonNode choice = root.path("choices").path(0); - JsonNode message = choice.path("message"); - - String content = - message.has("content") && !message.get("content").isNull() - ? message.get("content").asText() - : null; - - List toolCalls = new ArrayList<>(); - if (message.has("tool_calls")) { - for (JsonNode tc : message.get("tool_calls")) { - JsonNode function = tc.get("function"); - toolCalls.add( - new LlmToolCall( - tc.get("id").asText(), - function.get("name").asText(), - function.get("arguments").asText())); - } - } - - String stopReason = choice.has("finish_reason") ? choice.get("finish_reason").asText() : null; - - JsonNode usage = root.path("usage"); - int inputTokens = usage.path("prompt_tokens").asInt(0); - int outputTokens = usage.path("completion_tokens").asInt(0); - - return new LlmResponse(content, toolCalls, inputTokens, outputTokens, stopReason); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java new file mode 100644 index 000000000000..e96c2f813def --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java @@ -0,0 +1,268 @@ +package org.openmetadata.service.drive; + +import static org.openmetadata.service.Entity.ADMIN_USER_NAME; + +import java.io.InputStream; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.attachments.Asset; +import org.openmetadata.schema.entity.data.ContextFile; +import org.openmetadata.schema.entity.data.ContextFileContent; +import org.openmetadata.schema.entity.data.ProcessingStatus; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.attachments.AssetService; +import org.openmetadata.service.attachments.AssetServiceFactory; +import org.openmetadata.service.jdbi3.ContextFileRepository; + +@Slf4j +public class ContextFileExtractionService { + private final ContextFileRepository repository; + private final Supplier assetServiceSupplier; + private final Executor executor; + private final ContextFileTextExtractor textExtractor; + + public ContextFileExtractionService(ContextFileRepository repository) { + this( + repository, + AssetServiceFactory::getService, + DEFAULT_EXECUTOR, + new ContextFileTextExtractor()); + } + + /** + * Single shared thread pool for text extraction. Kept separate from + * {@code AsyncService.getExecutorService()} because {@link #process(UUID, UUID)} + * blocks on {@code AssetService.read(...).join()} for S3/Azure reads, which are + * themselves scheduled on AsyncService — sharing the pool would starve those read + * tasks (and potentially deadlock) once every thread is busy running extractions. + * + *

Held {@code static final} so every production {@link ContextFileExtractionService} + * instance reuses one pool — tests that instantiate the service repeatedly no longer + * leak a new pool each construction. Threads are daemons, so the pool never blocks + * JVM shutdown; explicit lifecycle management isn't required. + */ + private static final Executor DEFAULT_EXECUTOR = createDefaultExtractionExecutor(); + + private static Executor createDefaultExtractionExecutor() { + int threads = Math.max(2, Runtime.getRuntime().availableProcessors() / 2); + ThreadFactory threadFactory = + new ThreadFactory() { + private final AtomicInteger counter = new AtomicInteger(); + + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, "context-file-extraction-" + counter.incrementAndGet()); + t.setDaemon(true); + return t; + } + }; + // Bounded queue + AbortPolicy so an overloaded server rejects new extractions + // rather than accumulating an unbounded backlog on the heap. The RejectedExecutionException + // handling in submit(...) below turns the rejection into a Failed processing status + // on the content, so callers see a clear "retry later" signal instead of silent buildup. + int queueCapacity = Math.max(64, threads * 8); + return new ThreadPoolExecutor( + threads, + threads, + 0L, + TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(queueCapacity), + threadFactory, + new ThreadPoolExecutor.AbortPolicy()); + } + + ContextFileExtractionService( + ContextFileRepository repository, + Supplier assetServiceSupplier, + Executor executor, + ContextFileTextExtractor textExtractor) { + this.repository = repository; + this.assetServiceSupplier = assetServiceSupplier; + this.executor = executor; + this.textExtractor = textExtractor; + } + + public void submit(UUID fileId, UUID contentId) { + try { + executor.execute(() -> process(fileId, contentId)); + } catch (RejectedExecutionException e) { + LOG.warn( + "Skipping text extraction for file {} because the async executor rejected it", fileId, e); + applyFailure(fileId, contentId, "Text extraction queue is full. Please retry later."); + } + } + + void process(UUID fileId, UUID contentId) { + ContextFile file = getFile(fileId); + if (file == null || !contentId.toString().equals(file.getHeadContentId())) { + return; + } + + updateFile( + fileId, + current -> { + if (!contentId.toString().equals(current.getHeadContentId())) { + return null; + } + ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); + updated.setProcessingStatus(ProcessingStatus.Analyzing); + return updated; + }); + updateContent( + contentId, + current -> { + // Re-read the file inside the content updater so we don't mark an + // older content "Analyzing" when headContentId changed concurrently. + // Without this guard, a no-op updateFile above would still be followed + // by a status update on the now-stale content, leaving it stuck once + // the later head-check early-returns. + ContextFile currentHead = getFile(fileId); + if (currentHead == null || !contentId.toString().equals(currentHead.getHeadContentId())) { + return null; + } + ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); + updated.setProcessingStatus(ProcessingStatus.Analyzing); + updated.setProcessingError(null); + return updated; + }); + + try { + ContextFile currentFile = getFile(fileId); + ContextFileContent currentContent = getContent(contentId); + if (currentFile == null + || currentContent == null + || !contentId.toString().equals(currentFile.getHeadContentId())) { + return; + } + + AssetService assetService = assetServiceSupplier.get(); + if (assetService == null) { + applyFailure(fileId, contentId, "Object storage is not configured for text extraction"); + return; + } + + Asset asset = repository.getAssetRepository().getById(currentContent.getAssetId()); + try (InputStream inputStream = assetService.read(asset).join()) { + if (inputStream == null) { + applyFailure(fileId, contentId, "Unable to read file content from object storage"); + return; + } + ContextFileTextExtractor.ExtractionResult result = + textExtractor.extract(inputStream, currentFile); + applyResult(fileId, contentId, result); + } + } catch (Throwable t) { + if (t instanceof VirtualMachineError vmError) { + throw vmError; + } + LOG.error("Failed to extract text for file {} content {}", fileId, contentId, t); + applyFailure(fileId, contentId, describeFailure(t)); + } + } + + private String describeFailure(Throwable t) { + return t.getMessage() == null || t.getMessage().isBlank() ? t.toString() : t.getMessage(); + } + + private void applyResult( + UUID fileId, UUID contentId, ContextFileTextExtractor.ExtractionResult result) { + updateContent( + contentId, + current -> { + ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); + updated.setProcessingStatus(result.processingStatus()); + updated.setProcessingError(result.processingError()); + updated.setExtractedText(result.extractedText()); + return updated; + }); + + updateFile( + fileId, + current -> { + if (!contentId.toString().equals(current.getHeadContentId())) { + return null; + } + ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); + updated.setProcessingStatus(result.processingStatus()); + updated.setExtractedText(result.indexedText()); + updated.setPageCount(result.pageCount()); + return updated; + }); + } + + private void applyFailure(UUID fileId, UUID contentId, String reason) { + updateContent( + contentId, + current -> { + ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); + updated.setProcessingStatus(ProcessingStatus.Failed); + updated.setProcessingError(reason); + updated.setExtractedText(null); + return updated; + }); + + updateFile( + fileId, + current -> { + if (!contentId.toString().equals(current.getHeadContentId())) { + return null; + } + ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); + updated.setProcessingStatus(ProcessingStatus.Failed); + updated.setExtractedText(null); + updated.setPageCount(null); + return updated; + }); + } + + private ContextFile getFile(UUID fileId) { + try { + return repository.get(null, fileId, repository.getFields(""), Include.NON_DELETED, false); + } catch (Exception e) { + return null; + } + } + + private ContextFileContent getContent(UUID contentId) { + try { + return repository.getContentRepository().getById(contentId); + } catch (Exception e) { + return null; + } + } + + private void updateFile( + UUID fileId, java.util.function.Function updater) { + ContextFile current = getFile(fileId); + if (current == null) { + return; + } + ContextFile updated = updater.apply(current); + if (updated == null) { + return; + } + repository.update(null, current, updated, ADMIN_USER_NAME); + } + + private void updateContent( + UUID contentId, java.util.function.Function updater) { + ContextFileContent current = getContent(contentId); + if (current == null) { + return; + } + ContextFileContent updated = updater.apply(current); + if (updated == null) { + return; + } + repository.getContentRepository().update(null, current, updated, ADMIN_USER_NAME); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileProcessingService.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileProcessingService.java deleted file mode 100644 index 9e9c2d05119a..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileProcessingService.java +++ /dev/null @@ -1,441 +0,0 @@ -package org.openmetadata.service.drive; - -import static org.openmetadata.service.Entity.ADMIN_USER_NAME; - -import java.io.InputStream; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.attachments.Asset; -import org.openmetadata.schema.entity.data.ContextFile; -import org.openmetadata.schema.entity.data.ContextFileContent; -import org.openmetadata.schema.entity.data.ProcessingStatus; -import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.attachments.AssetService; -import org.openmetadata.service.attachments.AssetServiceFactory; -import org.openmetadata.service.jdbi3.ContextFileRepository; -import org.openmetadata.service.jdbi3.ContextMemoryRepository; -import org.openmetadata.service.jdbi3.ListFilter; -import org.openmetadata.service.llm.LLMClientHolder; -import org.openmetadata.service.util.AISettingsUtil; - -/** - * Orchestrates asynchronous processing of an uploaded {@link ContextFile}: text extraction - * (Analyzing) followed by LLM knowledge-pill extraction (ExtractingContext), ending at Processed. - * The two stages run on separate pools — text extraction is CPU-bound, the LLM step is - * network-bound and seconds-long, so mixing them would starve the text pool. - */ -@Slf4j -public class ContextFileProcessingService { - private final ContextFileRepository repository; - private final Supplier assetServiceSupplier; - private final Executor executor; - private final ContextFileTextExtractor textExtractor; - private final Executor llmExecutor; - private final Supplier memoryExtractorSupplier; - private final Supplier llmEnabledSupplier; - private final Supplier fileEngineSupplier; - private volatile FileContextProcessingEngine fileEngine; - - public ContextFileProcessingService(ContextFileRepository repository) { - this( - repository, - AssetServiceFactory::getService, - DEFAULT_EXECUTOR, - new ContextFileTextExtractor(), - LLM_EXECUTOR, - ContextFileProcessingService::buildDefaultExtractor, - () -> - LLMClientHolder.isEnabled() - && AISettingsUtil.isFileExtractionEnabled(AISettingsUtil.get()), - null); - } - - ContextFileProcessingService( - ContextFileRepository repository, - Supplier assetServiceSupplier, - Executor executor, - ContextFileTextExtractor textExtractor, - Executor llmExecutor, - Supplier memoryExtractorSupplier, - Supplier llmEnabledSupplier, - Supplier fileEngineSupplier) { - this.repository = repository; - this.assetServiceSupplier = assetServiceSupplier; - this.executor = executor; - this.textExtractor = textExtractor; - this.llmExecutor = llmExecutor; - this.memoryExtractorSupplier = memoryExtractorSupplier; - this.llmEnabledSupplier = llmEnabledSupplier; - this.fileEngineSupplier = fileEngineSupplier; - } - - /** - * CPU-bound text-extraction pool (see the class comment for why it is kept off AsyncService). - * Bounded queue + AbortPolicy so an overloaded server rejects new work instead of accumulating an - * unbounded backlog; the rejection is turned into a Failed status by {@link #submit}. - */ - private static final Executor DEFAULT_EXECUTOR = - createBoundedExecutor("context-file-extraction-"); - - /** Separate network-bound pool for LLM completion so slow calls never starve text extraction. */ - private static final Executor LLM_EXECUTOR = createBoundedExecutor("context-memory-extraction-"); - - private static final Set TRANSIENT_STATUSES = - Set.of( - ProcessingStatus.Uploaded, - ProcessingStatus.Analyzing, - ProcessingStatus.ExtractingContext); - - private static Executor createBoundedExecutor(String threadPrefix) { - int threads = Math.max(2, Runtime.getRuntime().availableProcessors() / 2); - ThreadFactory threadFactory = - new ThreadFactory() { - private final AtomicInteger counter = new AtomicInteger(); - - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r, threadPrefix + counter.incrementAndGet()); - t.setDaemon(true); - return t; - } - }; - int queueCapacity = Math.max(64, threads * 8); - return new ThreadPoolExecutor( - threads, - threads, - 0L, - TimeUnit.MILLISECONDS, - new ArrayBlockingQueue<>(queueCapacity), - threadFactory, - new ThreadPoolExecutor.AbortPolicy()); - } - - private static ContextMemoryExtractor buildDefaultExtractor() { - return new ContextMemoryExtractor(LLMClientHolder.get()); - } - - public void submit(UUID fileId, UUID contentId) { - try { - executor.execute(() -> process(fileId, contentId)); - } catch (RejectedExecutionException e) { - LOG.warn("Skipping processing for file {} because the async executor rejected it", fileId, e); - applyFailure(fileId, contentId, "Processing queue is full. Please retry later."); - } - } - - /** - * Requeues files a previous server shutdown left in a transient processing state. Without this, - * a file interrupted mid-pipeline stays Uploaded/Analyzing/ExtractingContext forever, since - * processing only ever starts at upload time. - */ - public int recoverInterruptedProcessing() { - int resubmitted = 0; - try { - List files = - repository.listAll(repository.getFields(""), new ListFilter(Include.NON_DELETED)); - for (ContextFile file : files) { - if (isInterrupted(file)) { - submit(file.getId(), UUID.fromString(file.getHeadContentId())); - resubmitted++; - } - } - } catch (Exception e) { - LOG.error("Failed to recover interrupted context file processing", e); - } - if (resubmitted > 0) { - LOG.info("Resubmitted {} context files interrupted by a previous shutdown", resubmitted); - } - return resubmitted; - } - - private boolean isInterrupted(ContextFile file) { - return file.getHeadContentId() != null - && TRANSIENT_STATUSES.contains(file.getProcessingStatus()); - } - - void process(UUID fileId, UUID contentId) { - ContextFile file = getFile(fileId); - if (file != null && contentId.toString().equals(file.getHeadContentId())) { - markAnalyzing(fileId, contentId); - ProcessingStatus textStatus = extractText(fileId, contentId); - if (shouldExtractContext(textStatus)) { - submitMemoryExtraction(fileId, contentId); - } - } - } - - private void submitMemoryExtraction(UUID fileId, UUID contentId) { - try { - llmExecutor.execute(() -> runMemoryExtraction(fileId, contentId)); - } catch (RejectedExecutionException e) { - LOG.warn( - "Skipping knowledge pill extraction for file {} because the LLM executor rejected it", - fileId, - e); - applyFailure( - fileId, contentId, "Knowledge pill extraction queue is full. Please retry later.", false); - } - } - - private void markAnalyzing(UUID fileId, UUID contentId) { - updateFile( - fileId, - current -> { - if (!contentId.toString().equals(current.getHeadContentId())) { - return null; - } - ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); - updated.setProcessingStatus(ProcessingStatus.Analyzing); - updated.setProcessingError(null); - return updated; - }); - updateContent( - contentId, - current -> { - ContextFile currentHead = getFile(fileId); - if (currentHead == null || !contentId.toString().equals(currentHead.getHeadContentId())) { - return null; - } - ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); - updated.setProcessingStatus(ProcessingStatus.Analyzing); - updated.setProcessingError(null); - return updated; - }); - } - - private ProcessingStatus extractText(UUID fileId, UUID contentId) { - try { - ContextFile currentFile = getFile(fileId); - ContextFileContent currentContent = getContent(contentId); - if (currentFile == null - || currentContent == null - || !contentId.toString().equals(currentFile.getHeadContentId())) { - return null; - } - - AssetService assetService = assetServiceSupplier.get(); - if (assetService == null) { - applyFailure(fileId, contentId, "Object storage is not configured for text extraction"); - return ProcessingStatus.Failed; - } - - Asset asset = repository.getAssetRepository().getById(currentContent.getAssetId()); - try (InputStream inputStream = assetService.read(asset).join()) { - if (inputStream == null) { - applyFailure(fileId, contentId, "Unable to read file content from object storage"); - return ProcessingStatus.Failed; - } - ContextFileTextExtractor.ExtractionResult result = - textExtractor.extract(inputStream, currentFile); - applyTextResult(fileId, contentId, result); - return result.processingStatus(); - } - } catch (Throwable t) { - if (t instanceof VirtualMachineError vmError) { - throw vmError; - } - LOG.error("Failed to extract text for file {} content {}", fileId, contentId, t); - applyFailure(fileId, contentId, describeFailure(t)); - return ProcessingStatus.Failed; - } - } - - private void runMemoryExtraction(UUID fileId, UUID contentId) { - ContextFile file = getFile(fileId); - if (file == null || !contentId.toString().equals(file.getHeadContentId())) { - return; - } - try { - // The shared engine skips the LLM when the content hash is unchanged, derives pills - // otherwise, and reconciles them against the file's existing pills (preserving identity and - // retrieval telemetry) rather than the previous wholesale delete-and-recreate. - fileEngine().runExtraction(fileId); - markProcessed(fileId, contentId); - } catch (Exception e) { - LOG.error("Knowledge pill extraction failed for file {}", fileId, e); - applyFailure(fileId, contentId, describeFailure(e), false); - } - } - - private FileContextProcessingEngine fileEngine() { - FileContextProcessingEngine engine = fileEngine; - if (engine == null) { - engine = buildFileEngine(); - } - return engine; - } - - private synchronized FileContextProcessingEngine buildFileEngine() { - if (fileEngine == null) { - fileEngine = fileEngineSupplier != null ? fileEngineSupplier.get() : defaultFileEngine(); - } - return fileEngine; - } - - private FileContextProcessingEngine defaultFileEngine() { - ContextMemoryRepository memoryRepository = - (ContextMemoryRepository) Entity.getEntityRepository(Entity.CONTEXT_MEMORY); - return new FileContextProcessingEngine( - repository, memoryExtractorSupplier.get(), new ContextMemoryReconciler(memoryRepository)); - } - - private void markProcessed(UUID fileId, UUID contentId) { - updateFile( - fileId, - current -> { - if (!contentId.toString().equals(current.getHeadContentId())) { - return null; - } - ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); - updated.setProcessingStatus(ProcessingStatus.Processed); - updated.setProcessingError(null); - return updated; - }); - } - - private String describeFailure(Throwable t) { - return t.getMessage() == null || t.getMessage().isBlank() ? t.toString() : t.getMessage(); - } - - private void applyTextResult( - UUID fileId, UUID contentId, ContextFileTextExtractor.ExtractionResult result) { - updateContent( - contentId, - current -> { - ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); - updated.setProcessingStatus(result.processingStatus()); - updated.setProcessingError(result.processingError()); - updated.setExtractedText(result.extractedText()); - return updated; - }); - - ProcessingStatus fileStatus = fileStatusAfterText(result.processingStatus()); - updateFile( - fileId, - current -> { - if (!contentId.toString().equals(current.getHeadContentId())) { - return null; - } - ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); - updated.setProcessingStatus(fileStatus); - updated.setProcessingError(result.processingError()); - updated.setExtractedText(result.indexedText()); - updated.setPageCount(result.pageCount()); - return updated; - }); - } - - private ProcessingStatus fileStatusAfterText(ProcessingStatus textStatus) { - ProcessingStatus result = textStatus; - if (shouldExtractContext(textStatus)) { - result = ProcessingStatus.ExtractingContext; - } - return result; - } - - /** - * Whether text extraction should be followed by LLM knowledge-pill extraction. The {@code - * llmEnabledSupplier} carries the full gate (LLM availability AND the AISettings file-extraction - * toggle in production); keeping it a single injected supplier makes the status machine unit - * testable without a live settings cache. - */ - private boolean shouldExtractContext(ProcessingStatus textStatus) { - return textStatus == ProcessingStatus.Processed - && Boolean.TRUE.equals(llmEnabledSupplier.get()); - } - - private void applyFailure(UUID fileId, UUID contentId, String reason) { - applyFailure(fileId, contentId, reason, true); - } - - /** - * Marks the content and file Failed with {@code reason}. {@code clearExtractedText} is false for - * failures that happen after a successful text extraction (the knowledge-pill stage), so the - * already-extracted text survives for indexing and retries. - */ - private void applyFailure( - UUID fileId, UUID contentId, String reason, boolean clearExtractedText) { - LOG.error("Processing failed for file {} content {}: {}", fileId, contentId, reason); - updateContent( - contentId, - current -> { - ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); - updated.setProcessingStatus(ProcessingStatus.Failed); - updated.setProcessingError(reason); - if (clearExtractedText) { - updated.setExtractedText(null); - } - return updated; - }); - - updateFile( - fileId, - current -> { - if (!contentId.toString().equals(current.getHeadContentId())) { - return null; - } - ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); - updated.setProcessingStatus(ProcessingStatus.Failed); - updated.setProcessingError(reason); - if (clearExtractedText) { - updated.setExtractedText(null); - updated.setPageCount(null); - } - return updated; - }); - } - - private ContextFile getFile(UUID fileId) { - try { - return repository.get(null, fileId, repository.getFields(""), Include.NON_DELETED, false); - } catch (Exception e) { - return null; - } - } - - private ContextFileContent getContent(UUID contentId) { - try { - return repository.getContentRepository().getById(contentId); - } catch (Exception e) { - return null; - } - } - - private void updateFile( - UUID fileId, java.util.function.Function updater) { - ContextFile current = getFile(fileId); - if (current == null) { - return; - } - ContextFile updated = updater.apply(current); - if (updated == null) { - return; - } - repository.update(null, current, updated, ADMIN_USER_NAME); - } - - private void updateContent( - UUID contentId, java.util.function.Function updater) { - ContextFileContent current = getContent(contentId); - if (current == null) { - return; - } - ContextFileContent updated = updater.apply(current); - if (updated == null) { - return; - } - repository.getContentRepository().update(null, current, updated, ADMIN_USER_NAME); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextMemoryExtractor.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextMemoryExtractor.java deleted file mode 100644 index d79577a258fd..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextMemoryExtractor.java +++ /dev/null @@ -1,210 +0,0 @@ -package org.openmetadata.service.drive; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.entity.context.ContextMemorySourceType; -import org.openmetadata.schema.entity.context.ContextMemoryStatus; -import org.openmetadata.schema.entity.context.ContextMemoryType; -import org.openmetadata.schema.entity.context.MemoryShareConfig; -import org.openmetadata.schema.entity.context.MemoryVisibility; -import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.service.Entity; -import org.openmetadata.service.llm.KnowledgePill; -import org.openmetadata.service.llm.LLMCompletionClient; -import org.openmetadata.service.llm.LLMCompletionException; -import org.openmetadata.service.util.AISettingsUtil; -import org.openmetadata.service.util.FullyQualifiedName; - -/** - * Turns a Context Center source's extracted text into reusable {@link ContextMemory} knowledge - * pills via an {@link LLMCompletionClient}. The source can be any entity (a ContextFile, a Page, - * ...); derived memories are linked back to it via {@code sourceEntity} and tagged with the - * supplied {@link ContextMemorySourceType}. This is a side-effect-free derivation; persisting the - * pills (and the embedding/indexing that rides the create path) is the {@link - * ContextMemoryReconciler}'s job. - */ -@Slf4j -public class ContextMemoryExtractor { - static final int MAX_PROMPT_CHARS = 60_000; - static final int MAX_CHUNKS = 8; - static final int MAX_NAME_BASE_LENGTH = 200; - static final String SYSTEM_PROMPT = - "You extract reusable company knowledge from a document as a JSON array. Each element is an " - + "object with keys: title, question, answer, summary, memoryType (one of Faq, Note, " - + "Runbook, UseCase, Preference). Capture durable facts, definitions, policies, and " - + "how-to guidance. Return ONLY the JSON array, no prose."; - - private final LLMCompletionClient llmClient; - - public ContextMemoryExtractor(LLMCompletionClient llmClient) { - this.llmClient = llmClient; - } - - /** Result of an LLM derive pass, carrying chunk-level stats for the source's extractionStats. */ - public record DeriveResult(List memories, int chunksTotal, int chunksProcessed) {} - - /** - * Derives memories from {@code text} without persisting anything. Long documents are processed in - * paragraph-aligned chunks, one LLM call per chunk, with pills deduplicated across chunks. Chunk - * failures are tolerated as long as at least one chunk succeeds — the stats in the result expose - * partial coverage; if every chunk fails the run fails. Kept side-effect free so callers can - * reconcile the source's previous pills only after the LLM pass succeeded. Each derived memory is - * linked to {@code sourceRef} and tagged {@code sourceType}. - */ - public DeriveResult derive( - String text, EntityReference sourceRef, ContextMemorySourceType sourceType) { - ChunkPlan plan = chunkText(text, sourceRef); - List collected = new ArrayList<>(); - int processed = 0; - RuntimeException firstFailure = null; - for (String chunk : plan.chunks()) { - try { - collected.addAll(callLlm(chunk)); - processed++; - } catch (RuntimeException e) { - LOG.warn( - "Knowledge pill extraction failed for a chunk of {} {}", - sourceRef.getType(), - sourceRef.getId(), - e); - firstFailure = firstFailure == null ? e : firstFailure; - } - } - if (processed == 0 && firstFailure != null) { - throw new LLMCompletionException( - "All " + plan.chunks().size() + " chunks failed knowledge pill extraction", firstFailure); - } - List memories = new ArrayList<>(); - for (KnowledgePill pill : dedupe(collected)) { - memories.add(toMemory(pill, sourceRef, sourceType)); - } - return new DeriveResult(memories, plan.totalChunks(), processed); - } - - /** The chunks submitted to the LLM plus the count the document would need without the cap. */ - private record ChunkPlan(List chunks, int totalChunks) {} - - private ChunkPlan chunkText(String text, EntityReference sourceRef) { - List chunks = new ArrayList<>(); - int skippedChunks = 0; - if (text != null && !text.isBlank()) { - int position = 0; - while (position < text.length() && chunks.size() < MAX_CHUNKS) { - int end = chunkEnd(text, position); - chunks.add(text.substring(position, end)); - position = end; - } - if (position < text.length()) { - int remaining = text.length() - position; - skippedChunks = (remaining + MAX_PROMPT_CHARS - 1) / MAX_PROMPT_CHARS; - LOG.warn( - "{} {} text exceeds {} chunks of {} chars; skipping the remaining {} chars", - sourceRef.getType(), - sourceRef.getId(), - MAX_CHUNKS, - MAX_PROMPT_CHARS, - remaining); - } - } - return new ChunkPlan(chunks, chunks.size() + skippedChunks); - } - - /** Ends the chunk at the last paragraph (or line, or word) boundary inside the size budget. */ - private int chunkEnd(String text, int start) { - int result = Math.min(start + MAX_PROMPT_CHARS, text.length()); - if (result < text.length()) { - int boundary = lastBoundaryBefore(text, start, result); - if (boundary > start) { - result = boundary; - } - } - return result; - } - - private int lastBoundaryBefore(String text, int start, int limit) { - int minAcceptable = start + MAX_PROMPT_CHARS / 2; - int boundary = text.lastIndexOf("\n\n", limit); - if (boundary <= minAcceptable) { - boundary = text.lastIndexOf('\n', limit); - } - if (boundary <= minAcceptable) { - boundary = text.lastIndexOf(' ', limit); - } - return boundary > minAcceptable ? boundary + 1 : -1; - } - - private List callLlm(String text) { - List result = new ArrayList<>(); - if (text != null && !text.isBlank()) { - String prompt = AISettingsUtil.memoryExtractionPrompt(AISettingsUtil.get(), SYSTEM_PROMPT); - result = llmClient.completeStructured(prompt, text, KnowledgePill.class); - } - return result; - } - - private List dedupe(List pills) { - Map byQuestion = new LinkedHashMap<>(); - for (KnowledgePill pill : pills) { - if (isValid(pill)) { - byQuestion.putIfAbsent(pill.question().trim().toLowerCase(Locale.ROOT), pill); - } - } - return new ArrayList<>(byQuestion.values()); - } - - private boolean isValid(KnowledgePill pill) { - return pill != null - && pill.question() != null - && !pill.question().isBlank() - && pill.answer() != null - && !pill.answer().isBlank(); - } - - private ContextMemory toMemory( - KnowledgePill pill, EntityReference sourceRef, ContextMemorySourceType sourceType) { - String name = memoryName(sourceRef); - return new ContextMemory() - .withId(UUID.randomUUID()) - .withName(name) - .withFullyQualifiedName(FullyQualifiedName.build(name)) - .withTitle(pill.title()) - .withQuestion(pill.question()) - .withAnswer(pill.answer()) - .withSummary(pill.summary()) - .withMemoryType(parseType(pill.memoryType())) - .withStatus(ContextMemoryStatus.ACTIVE) - .withSourceType(sourceType) - .withSourceEntity(sourceRef) - .withShareConfig(new MemoryShareConfig().withVisibility(MemoryVisibility.SHARED)) - .withUpdatedBy(Entity.ADMIN_USER_NAME) - .withUpdatedAt(System.currentTimeMillis()); - } - - /** Keeps the generated memory name within the 256-char entityName limit (UUID suffix included). */ - private String memoryName(EntityReference sourceRef) { - String base = sourceRef.getName(); - if (base.length() > MAX_NAME_BASE_LENGTH) { - base = base.substring(0, MAX_NAME_BASE_LENGTH); - } - return base + "-" + UUID.randomUUID(); - } - - private ContextMemoryType parseType(String raw) { - ContextMemoryType result = ContextMemoryType.NOTE; - if (raw != null) { - for (ContextMemoryType type : ContextMemoryType.values()) { - if (type.value().equalsIgnoreCase(raw.trim())) { - result = type; - break; - } - } - } - return result; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextMemoryReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextMemoryReconciler.java deleted file mode 100644 index e03282551720..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextMemoryReconciler.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.openmetadata.service.drive; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.entity.context.ContextMemorySourceType; -import org.openmetadata.schema.entity.context.ContextMemoryStatus; -import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.ContextMemoryRepository; - -/** - * Reconciles a freshly-derived set of knowledge pills against the pills already linked to a Context - * Center source, instead of deleting and recreating them wholesale on every run. Matching by - * normalized question preserves pill identity — and the usageCount/lastUsedAt retrieval telemetry - * that rides it — across re-extractions. An automated pill that is no longer derived from the - * source is hard-deleted (these pills are regenerable from the source, so a tombstone would only - * leave an invisible row polluting search and counts). A pill a human has edited (sourceType - * flipped to Manual) is left untouched. - */ -@Slf4j -public class ContextMemoryReconciler { - private final ContextMemoryRepository memoryRepository; - - public ContextMemoryReconciler(ContextMemoryRepository memoryRepository) { - this.memoryRepository = memoryRepository; - } - - /** Counts of what the run did, by reconciliation outcome. */ - public record ReconcileResult(int created, int updated, int kept, int deleted) {} - - public ReconcileResult reconcile( - EntityReference sourceRef, String sourceType, List derived) { - Map derivedByQuestion = indexByQuestion(derived); - List existing = - memoryRepository.listExtractedMemories(sourceRef.getId(), sourceType); - Counts counts = new Counts(); - for (ContextMemory pill : existing) { - reconcileExisting(pill, derivedByQuestion, counts); - } - for (ContextMemory pill : derivedByQuestion.values()) { - memoryRepository.create(null, pill); - counts.created++; - } - LOG.info( - "Reconciled pills for {} {}: {} created, {} updated, {} kept, {} deleted", - sourceRef.getType(), - sourceRef.getId(), - counts.created, - counts.updated, - counts.kept, - counts.deleted); - return new ReconcileResult(counts.created, counts.updated, counts.kept, counts.deleted); - } - - private void reconcileExisting( - ContextMemory pill, Map derivedByQuestion, Counts counts) { - // Always claim the matching question, even for a human-owned (Manual) pill: it stops a - // re-derived duplicate from being created alongside it. Only automated pills are then updated - // or deleted; a pill a human edited (sourceType flipped to Manual) is left exactly as-is. - ContextMemory match = derivedByQuestion.remove(questionKey(pill)); - if (isAutomated(pill)) { - if (match == null) { - deleteRetired(pill); - counts.deleted++; - } else if (applyDerived(pill, match)) { - counts.updated++; - } else { - counts.kept++; - } - } - } - - /** - * Hard-deletes an automated pill the source no longer yields. These pills are regenerable from the - * source, so removing the row (and its search/vector index entry) is cleaner than an invisible - * ARCHIVED tombstone that would still pollute retrieval and counts. - */ - private void deleteRetired(ContextMemory pill) { - memoryRepository.delete(Entity.ADMIN_USER_NAME, pill.getId(), false, true); - } - - private Map indexByQuestion(List derived) { - Map byQuestion = new LinkedHashMap<>(); - for (ContextMemory pill : derived) { - byQuestion.putIfAbsent(questionKey(pill), pill); - } - return byQuestion; - } - - /** - * Updates an existing pill in place from its newly-derived match, preserving id/name/telemetry. - * Returns true only when something actually changed, so an unchanged pill keeps its embedding - * instead of being needlessly re-indexed. - */ - private boolean applyDerived(ContextMemory existing, ContextMemory derived) { - boolean changed = - !sameContent(existing, derived) || existing.getStatus() != ContextMemoryStatus.ACTIVE; - if (changed) { - ContextMemory updated = JsonUtils.deepCopy(existing, ContextMemory.class); - updated.setTitle(derived.getTitle()); - updated.setAnswer(derived.getAnswer()); - updated.setSummary(derived.getSummary()); - updated.setMemoryType(derived.getMemoryType()); - updated.setStatus(ContextMemoryStatus.ACTIVE); - updated.setUpdatedBy(Entity.ADMIN_USER_NAME); - updated.setUpdatedAt(System.currentTimeMillis()); - memoryRepository.update(null, existing, updated, Entity.ADMIN_USER_NAME); - } - return changed; - } - - private boolean sameContent(ContextMemory a, ContextMemory b) { - return Objects.equals(a.getTitle(), b.getTitle()) - && Objects.equals(a.getAnswer(), b.getAnswer()) - && Objects.equals(a.getSummary(), b.getSummary()) - && Objects.equals(a.getMemoryType(), b.getMemoryType()); - } - - private boolean isAutomated(ContextMemory pill) { - return pill.getSourceType() == ContextMemorySourceType.FILE_EXTRACTION - || pill.getSourceType() == ContextMemorySourceType.PAGE_EXTRACTION; - } - - private String questionKey(ContextMemory pill) { - String question = pill.getQuestion(); - return question == null ? "" : question.trim().toLowerCase(Locale.ROOT); - } - - /** Mutable tally threaded through reconciliation to keep each step a small single-purpose method. */ - private static final class Counts { - private int created; - private int updated; - private int kept; - private int deleted; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextProcessingEngine.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextProcessingEngine.java deleted file mode 100644 index faf432905cc6..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextProcessingEngine.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.openmetadata.service.drive; - -import java.util.UUID; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.entity.context.ContextMemorySourceType; -import org.openmetadata.schema.entity.data.ExtractionStats; -import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.service.drive.ContextMemoryExtractor.DeriveResult; -import org.openmetadata.service.drive.ContextMemoryReconciler.ReconcileResult; - -/** - * Shared core of Context Center knowledge-pill extraction. Given a source entity (a ContextFile, a - * Page, ...) it loads the source text, skips work when the content is unchanged (hash gate), - * derives pills via the LLM, reconciles them against the source's existing pills, and stamps the - * source's extractionStats. Subclasses supply the per-source bits: how to load the text and its - * hash, where the extractionStats live, the entity type, and the sourceType to tag pills with. - */ -@Slf4j -public abstract class ContextProcessingEngine { - protected final ContextMemoryExtractor extractor; - protected final ContextMemoryReconciler reconciler; - - protected ContextProcessingEngine( - ContextMemoryExtractor extractor, ContextMemoryReconciler reconciler) { - this.extractor = extractor; - this.reconciler = reconciler; - } - - /** A source's current text, a stable hash of it, and the reference pills are linked back to. */ - public record Source(String text, String hash, EntityReference sourceRef) {} - - /** Outcome of a runExtraction call: a skip (unchanged content) or a processed run with stats. */ - public record ExtractionOutcome( - boolean skipped, ExtractionStats stats, ReconcileResult reconciled) { - static ExtractionOutcome skip() { - return new ExtractionOutcome(true, null, null); - } - - static ExtractionOutcome processed(ExtractionStats stats, ReconcileResult reconciled) { - return new ExtractionOutcome(false, stats, reconciled); - } - } - - /** - * Runs the full pipeline for one source. Skips when the content hash matches the last successful - * run (so the LLM is never called for unchanged content) and when a never-extracted source is - * empty. A source that was previously extracted and has since been emptied is NOT skipped: it is - * reconciled against an empty derived set so its now-stale pills are archived rather than left - * ACTIVE forever. - */ - public final ExtractionOutcome runExtraction(UUID entityId) { - ExtractionOutcome outcome = ExtractionOutcome.skip(); - Source source = loadSource(entityId); - if (source != null) { - ExtractionStats previous = loadStats(entityId); - if (shouldProcess(source, previous)) { - outcome = extractAndReconcile(entityId, source); - } - } - return outcome; - } - - private boolean shouldProcess(Source source, ExtractionStats previous) { - boolean hasContent = source.text() != null && !source.text().isBlank(); - boolean everExtracted = previous != null; - boolean changed = previous == null || !source.hash().equals(previous.getSourceHash()); - return (hasContent || everExtracted) && changed; - } - - private ExtractionOutcome extractAndReconcile(UUID entityId, Source source) { - DeriveResult derived = extractor.derive(source.text(), source.sourceRef(), sourceType()); - ReconcileResult reconciled = - reconciler.reconcile(source.sourceRef(), entityType(), derived.memories()); - ExtractionStats stats = - new ExtractionStats() - .withChunksTotal(derived.chunksTotal()) - .withChunksProcessed(derived.chunksProcessed()) - .withPillsCreated(reconciled.created()) - .withLastExtractedAt(System.currentTimeMillis()) - .withSourceHash(source.hash()); - stampStats(entityId, stats); - return ExtractionOutcome.processed(stats, reconciled); - } - - protected abstract Source loadSource(UUID entityId); - - protected abstract ExtractionStats loadStats(UUID entityId); - - protected abstract void stampStats(UUID entityId, ExtractionStats stats); - - protected abstract String entityType(); - - protected abstract ContextMemorySourceType sourceType(); -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/FileContextProcessingEngine.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/FileContextProcessingEngine.java deleted file mode 100644 index 884a696d8636..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/FileContextProcessingEngine.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.openmetadata.service.drive; - -import java.util.UUID; -import org.openmetadata.schema.entity.context.ContextMemorySourceType; -import org.openmetadata.schema.entity.data.ContextFile; -import org.openmetadata.schema.entity.data.ContextFileContent; -import org.openmetadata.schema.entity.data.ExtractionStats; -import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.ContextFileRepository; - -/** - * {@link ContextProcessingEngine} for ContextFile sources. The source text is the current content - * snapshot's canonical extracted text; the hash is that snapshot's stored checksum, so re-uploading - * identical bytes is short-circuited by the hash gate. - */ -public class FileContextProcessingEngine extends ContextProcessingEngine { - private final ContextFileRepository fileRepository; - - public FileContextProcessingEngine( - ContextFileRepository fileRepository, - ContextMemoryExtractor extractor, - ContextMemoryReconciler reconciler) { - super(extractor, reconciler); - this.fileRepository = fileRepository; - } - - @Override - protected Source loadSource(UUID fileId) { - Source source = null; - ContextFile file = getFile(fileId); - if (file != null && file.getHeadContentId() != null) { - ContextFileContent content = fileRepository.getContentById(file.getHeadContentId()); - if (content != null) { - // Empty extracted text still yields a source so a file whose content became empty - // reconciles to an empty pill set (archiving stale pills) rather than being skipped. - String text = content.getExtractedText() == null ? "" : content.getExtractedText(); - String hash = - content.getChecksum() != null ? content.getChecksum() : content.getId().toString(); - source = new Source(text, hash, file.getEntityReference()); - } - } - return source; - } - - @Override - protected ExtractionStats loadStats(UUID fileId) { - ContextFile file = getFile(fileId); - return file == null ? null : file.getExtractionStats(); - } - - @Override - protected void stampStats(UUID fileId, ExtractionStats stats) { - ContextFile current = getFile(fileId); - if (current != null) { - ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); - updated.setExtractionStats(stats); - fileRepository.update(null, current, updated, Entity.ADMIN_USER_NAME); - } - } - - @Override - protected String entityType() { - return Entity.CONTEXT_FILE; - } - - @Override - protected ContextMemorySourceType sourceType() { - return ContextMemorySourceType.FILE_EXTRACTION; - } - - private ContextFile getFile(UUID fileId) { - ContextFile result = null; - try { - result = - fileRepository.get( - null, fileId, fileRepository.getFields(""), Include.NON_DELETED, false); - } catch (Exception e) { - result = null; - } - return result; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/PageContextProcessingEngine.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/PageContextProcessingEngine.java deleted file mode 100644 index 27c4fa8ac9c4..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/PageContextProcessingEngine.java +++ /dev/null @@ -1,222 +0,0 @@ -package org.openmetadata.service.drive; - -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.codec.digest.DigestUtils; -import org.openmetadata.schema.entity.context.ContextMemorySourceType; -import org.openmetadata.schema.entity.data.ExtractionStats; -import org.openmetadata.schema.entity.data.Page; -import org.openmetadata.schema.entity.data.PageProcessingStatus; -import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.exception.EntityNotFoundException; -import org.openmetadata.service.jdbi3.KnowledgePageRepository; - -/** - * {@link ContextProcessingEngine} for Page (Knowledge Center article) sources. A page's markdown - * body is its text, so there is no text-extraction stage. Because pages autosave every few seconds, - * extraction is debounced through an in-memory, per-page trailing throttle: each body change - * (re)schedules a run {@code quietPeriodMillis} after the last edit, so an entire editing session - * yields a single extraction. The hash gate makes a run a no-op when the body is unchanged, so a - * throttle entry lost on restart is recovered by the next edit — no sweep, no extra process. - */ -@Slf4j -public class PageContextProcessingEngine extends ContextProcessingEngine { - static final long DEFAULT_QUIET_PERIOD_MILLIS = TimeUnit.MINUTES.toMillis(5); - static final int DEFAULT_MAX_PENDING_PAGES = 10_000; - - private final KnowledgePageRepository pageRepository; - private final long quietPeriodMillis; - private final int maxPendingPages; - private final ScheduledExecutorService scheduler; - private final Map> pending = new ConcurrentHashMap<>(); - - public PageContextProcessingEngine( - KnowledgePageRepository pageRepository, - ContextMemoryExtractor extractor, - ContextMemoryReconciler reconciler) { - this( - pageRepository, - extractor, - reconciler, - DEFAULT_QUIET_PERIOD_MILLIS, - DEFAULT_MAX_PENDING_PAGES); - } - - public PageContextProcessingEngine( - KnowledgePageRepository pageRepository, - ContextMemoryExtractor extractor, - ContextMemoryReconciler reconciler, - long quietPeriodMillis, - int maxPendingPages) { - this( - pageRepository, - extractor, - reconciler, - quietPeriodMillis, - maxPendingPages, - defaultScheduler()); - } - - PageContextProcessingEngine( - KnowledgePageRepository pageRepository, - ContextMemoryExtractor extractor, - ContextMemoryReconciler reconciler, - long quietPeriodMillis, - int maxPendingPages, - ScheduledExecutorService scheduler) { - super(extractor, reconciler); - this.pageRepository = pageRepository; - this.quietPeriodMillis = quietPeriodMillis; - this.maxPendingPages = maxPendingPages; - this.scheduler = scheduler; - } - - private static ScheduledExecutorService defaultScheduler() { - return Executors.newSingleThreadScheduledExecutor( - runnable -> { - Thread thread = new Thread(runnable, "page-context-extraction"); - thread.setDaemon(true); - return thread; - }); - } - - /** - * (Re)schedules extraction for a page after the quiet period, cancelling any pending run so a - * burst of autosaves collapses into one. Bounded: when too many pages are already pending, one is - * dropped with a warning (its next edit re-arms it, and the hash gate keeps the eventual run - * correct). - */ - public void schedule(UUID pageId) { - evictIfFull(); - AtomicReference> holder = new AtomicReference<>(); - holder.set( - scheduler.schedule( - () -> runScheduled(pageId, holder.get()), quietPeriodMillis, TimeUnit.MILLISECONDS)); - ScheduledFuture previous = pending.put(pageId, holder.get()); - if (previous != null) { - previous.cancel(false); - } - } - - /** Cancels a pending run, e.g. when the page is deleted. */ - public void cancel(UUID pageId) { - ScheduledFuture previous = pending.remove(pageId); - if (previous != null) { - previous.cancel(false); - } - } - - private void evictIfFull() { - // Best-effort bound: size() and the caller's put() are not atomic, so concurrent schedulers can - // briefly push pending past maxPendingPages by the number of in-flight callers. The dropped - // entry is whatever the hash order yields first rather than the least-recent; at the (large) - // default cap that is acceptable — a dropped page re-arms on its next edit and the hash gate - // keeps the eventual run correct. - if (pending.size() >= maxPendingPages) { - UUID dropped = pending.keySet().stream().findFirst().orElse(null); - if (dropped != null) { - cancel(dropped); - LOG.warn( - "Page extraction throttle is full ({} pending); dropped page {}. It re-arms on its next edit.", - maxPendingPages, - dropped); - } - } - } - - private void runScheduled(UUID pageId, ScheduledFuture firedFuture) { - // Only clear the entry if it is still the future that just fired. A concurrent schedule() may - // have already installed a newer future for this page, which must stay tracked so a later - // cancel() (e.g. on delete) can reach it. - pending.remove(pageId, firedFuture); - try { - ExtractionOutcome outcome = runExtraction(pageId); - if (outcome.skipped()) { - stampStatus(pageId, PageProcessingStatus.Processed, null); - } - } catch (Exception e) { - LOG.error("Knowledge pill extraction failed for page {}", pageId, e); - stampStatus(pageId, PageProcessingStatus.Failed, e.getMessage()); - } - } - - /** - * Persists a terminal processing status from the scheduler thread (post-commit, so it never races - * the body edit that armed the run) for the paths the pipeline does not stamp itself: a skip - * (content unchanged since the last run) and a failure. The success path stamps {@link - * PageProcessingStatus#Processed} through {@link #stampStats} alongside the run's stats. A no-op - * when the page already carries the target status, so an unchanged-content skip does not churn the - * row. - */ - private void stampStatus(UUID pageId, PageProcessingStatus status, String error) { - Page current = getPage(pageId); - if (current != null && current.getProcessingStatus() != status) { - Page updated = JsonUtils.deepCopy(current, Page.class); - updated.setProcessingStatus(status); - updated.setProcessingError(error); - pageRepository.update(null, current, updated, Entity.ADMIN_USER_NAME); - } - } - - @Override - protected Source loadSource(UUID pageId) { - Source source = null; - Page page = getPage(pageId); - if (page != null) { - // Return a source even for an empty body so a cleared article reconciles to an empty pill - // set (archiving its stale pills); null is reserved for a page that no longer exists. - String body = page.getDescription() == null ? "" : page.getDescription(); - source = new Source(body, DigestUtils.sha256Hex(body), page.getEntityReference()); - } - return source; - } - - @Override - protected ExtractionStats loadStats(UUID pageId) { - Page page = getPage(pageId); - return page == null ? null : page.getExtractionStats(); - } - - @Override - protected void stampStats(UUID pageId, ExtractionStats stats) { - Page current = getPage(pageId); - if (current != null) { - Page updated = JsonUtils.deepCopy(current, Page.class); - updated.setExtractionStats(stats); - updated.setProcessingStatus(PageProcessingStatus.Processed); - updated.setProcessingError(null); - pageRepository.update(null, current, updated, Entity.ADMIN_USER_NAME); - } - } - - @Override - protected String entityType() { - return Entity.PAGE; - } - - @Override - protected ContextMemorySourceType sourceType() { - return ContextMemorySourceType.PAGE_EXTRACTION; - } - - private Page getPage(UUID pageId) { - Page result = null; - try { - result = - pageRepository.get( - null, pageId, pageRepository.getFields(""), Include.NON_DELETED, false); - } catch (EntityNotFoundException e) { - result = null; - } - return result; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/PageContextProcessingEngineHolder.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/PageContextProcessingEngineHolder.java deleted file mode 100644 index f4d4b185ff91..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/PageContextProcessingEngineHolder.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.openmetadata.service.drive; - -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.ContextMemoryRepository; -import org.openmetadata.service.jdbi3.KnowledgePageRepository; -import org.openmetadata.service.llm.LLMClientHolder; - -/** - * Process-wide holder of the single {@link PageContextProcessingEngine}. The engine owns an - * in-memory throttle (a scheduler + per-page timers), so it must be a singleton — the repository - * post-update hook reaches it through here. Lazily built on first use so it picks up the registered - * repositories and the initialized LLM client; {@link #setForTesting} is the test seam. - */ -public final class PageContextProcessingEngineHolder { - private static volatile PageContextProcessingEngine instance; - - private PageContextProcessingEngineHolder() {} - - public static PageContextProcessingEngine get() { - PageContextProcessingEngine engine = instance; - if (engine == null) { - engine = build(); - } - return engine; - } - - private static synchronized PageContextProcessingEngine build() { - if (instance == null) { - ContextMemoryRepository memoryRepository = - (ContextMemoryRepository) Entity.getEntityRepository(Entity.CONTEXT_MEMORY); - KnowledgePageRepository pageRepository = - (KnowledgePageRepository) Entity.getEntityRepository(Entity.PAGE); - ContextMemoryExtractor extractor = new ContextMemoryExtractor(LLMClientHolder.get()); - ContextMemoryReconciler reconciler = new ContextMemoryReconciler(memoryRepository); - long quietPeriodMillis = - Long.getLong( - "page.context.quiet.period.millis", - PageContextProcessingEngine.DEFAULT_QUIET_PERIOD_MILLIS); - int maxPendingPages = - Integer.getInteger( - "page.context.max.pending.pages", - PageContextProcessingEngine.DEFAULT_MAX_PENDING_PAGES); - instance = - new PageContextProcessingEngine( - pageRepository, extractor, reconciler, quietPeriodMillis, maxPendingPages); - } - return instance; - } - - public static void setForTesting(PageContextProcessingEngine engine) { - instance = engine; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryAction.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryAction.java deleted file mode 100644 index 2cf469b73993..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryAction.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -/** Action constants for ontology term and metric verdicts produced by the LLM. */ -public final class MemoryAction { - public static final String REUSE = "REUSE"; - public static final String CREATE = "CREATE"; - public static final String SKIP = "SKIP"; - - private MemoryAction() {} -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryCandidate.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryCandidate.java deleted file mode 100644 index 03a70accda67..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryCandidate.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -/** A candidate glossary term, metric, or glossary surfaced by keyword grounding. */ -public record MemoryCandidate(String type, String fqn, String name, String description) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryContext.java deleted file mode 100644 index 32bd4204d5d2..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryContext.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import java.util.List; - -/** - * Grounding context supplied to the memory agent. - * - *

{@code terms}, {@code metrics}, and {@code glossaries} are cross-document candidates surfaced - * by keyword search (glossaries are the full existing set, so the agent reuses one rather than - * minting near-duplicates). {@code siblingTerms} are the terms already derived from OTHER memories - * of the SAME source document — read straight from the repository so they are visible even before - * the search index catches up; they give the agent concrete FQNs to relate to. {@code - * siblingGlossaryFqn} is the glossary those siblings already live in, used to pin a document's whole - * concept set into one glossary. - */ -public record MemoryContext( - List terms, - List metrics, - List glossaries, - List siblingTerms, - String siblingGlossaryFqn) { - - /** Backward-compatible constructor for call sites that predate sibling grounding. */ - public MemoryContext( - List terms, - List metrics, - List glossaries) { - this(terms, metrics, glossaries, List.of(), null); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryDerivation.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryDerivation.java deleted file mode 100644 index 82406d41b594..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryDerivation.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Anti-corruption DTO for the full ontology derivation response produced by the LLM. Mirrors - * {@link org.openmetadata.service.llm.KnowledgePill}: intentionally narrow, tolerant of unknown - * fields, and kept separate from the entity model. The caller promotes validated fields into - * trusted domain objects. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public record MemoryDerivation( - @JsonProperty("termVerdict") MemoryVerdict termVerdict, - @JsonProperty("metricVerdict") MemoryVerdict metricVerdict) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryExtractor.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryExtractor.java deleted file mode 100644 index a69ca2920f28..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryExtractor.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; - -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.service.llm.LLMCompletionClient; -import org.openmetadata.service.util.AISettingsUtil; - -/** - * Pure derivation step: asks the LLM to decide whether a ContextMemory maps to a Glossary Term - * and/or Metric (REUSE existing / CREATE new / SKIP). Returns SKIP/SKIP when the LLM produces - * an empty response. - */ -@Slf4j -public class MemoryExtractor { - static final String FALLBACK_PROMPT = - "You are a memory agent. Decide whether the memory maps to a Glossary Term and/or Metric " - + "(REUSE existing / CREATE new / SKIP). Return ONLY a JSON array with one object " - + "{termVerdict, metricVerdict}."; - - private final LLMCompletionClient llmClient; - - public MemoryExtractor(LLMCompletionClient llmClient) { - this.llmClient = llmClient; - } - - public MemoryDerivation derive(ContextMemory memory, MemoryContext context) { - final String prompt = AISettingsUtil.memoryAgentPrompt(AISettingsUtil.get(), FALLBACK_PROMPT); - final String userPrompt = MemoryPromptBuilder.build(memory, context); - final List verdicts = - llmClient.completeStructured(prompt, userPrompt, MemoryDerivation.class); - MemoryDerivation result = empty(); - if (!nullOrEmpty(verdicts)) { - result = verdicts.getFirst(); - } - return result; - } - - private MemoryDerivation empty() { - final MemoryVerdict skip = - new MemoryVerdict(MemoryAction.SKIP, null, null, null, null, null, null, null, null, null); - return new MemoryDerivation(skip, skip); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryGrounding.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryGrounding.java deleted file mode 100644 index 544370d601d1..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryGrounding.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import static org.openmetadata.service.search.SearchClient.GLOSSARY_TERM_SEARCH_INDEX; -import static org.openmetadata.service.search.SearchConstants.DEFAULT_SORT_FIELD; -import static org.openmetadata.service.search.SearchConstants.DEFAULT_SORT_ORDER; -import static org.openmetadata.service.search.SearchConstants.FULLY_QUALIFIED_NAME; -import static org.openmetadata.service.search.SearchConstants.HITS; -import static org.openmetadata.service.search.SearchConstants.SEARCH_SOURCE; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import jakarta.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.entity.data.Glossary; -import org.openmetadata.schema.entity.data.GlossaryTerm; -import org.openmetadata.schema.search.SearchRequest; -import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.type.Relationship; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.ContextMemoryRepository; -import org.openmetadata.service.jdbi3.GlossaryRepository; -import org.openmetadata.service.jdbi3.GlossaryTermRepository; -import org.openmetadata.service.jdbi3.ListFilter; - -/** - * Keyword-searches the glossary-term, metric, and glossary indexes to surface the top-k candidates - * that most closely match a ContextMemory. Results are passed to the memory agent so it can - * decide REUSE / CREATE / SKIP without hallucinating new names for existing entities. - * - *

All axes fail-safe: a search error returns an empty list for THAT axis and logs a warning; - * grounding never propagates exceptions out of {@link #fetchCandidates}. - */ -@Slf4j -public class MemoryGrounding { - static final int MAX_CANDIDATES = 20; - static final int MAX_GLOSSARIES = 200; - - private static final String METRIC_SEARCH_INDEX = "metric_search_index"; - private static final String TYPE_TERM = "glossaryTerm"; - private static final String TYPE_METRIC = "metric"; - private static final String TYPE_GLOSSARY = "glossary"; - private static final String FIELD_GLOSSARY = "glossary"; - - public MemoryContext fetchCandidates(ContextMemory memory) { - final String text = groundingText(memory); - final List terms = searchTopK(GLOSSARY_TERM_SEARCH_INDEX, TYPE_TERM, text); - final List metrics = searchTopK(METRIC_SEARCH_INDEX, TYPE_METRIC, text); - final List glossaries = listAllGlossaries(); - final SiblingContext siblings = fetchSiblings(memory); - return new MemoryContext(terms, metrics, glossaries, siblings.terms(), siblings.glossaryFqn()); - } - - /** - * Lists every existing glossary straight from the repository (not the search index, which lags - * behind sibling glossaries minted moments earlier) so the agent reuses one instead of minting a - * near-duplicate. Bounded by {@link #MAX_GLOSSARIES}; fail-safe to empty on error. - */ - private List listAllGlossaries() { - List result = List.of(); - try { - final GlossaryRepository repo = - (GlossaryRepository) Entity.getEntityRepository(Entity.GLOSSARY); - final List all = - repo.listAll(repo.getFields(""), new ListFilter(Include.NON_DELETED)); - result = toGlossaryCandidates(all); - } catch (RuntimeException ex) { - LOG.warn("MemoryGrounding: listing glossaries failed: {}", ex.getMessage()); - } - return result; - } - - private List toGlossaryCandidates(List all) { - final List capped = - all.size() > MAX_GLOSSARIES ? all.subList(0, MAX_GLOSSARIES) : all; - final List out = new ArrayList<>(); - for (final Glossary g : capped) { - out.add( - new MemoryCandidate( - TYPE_GLOSSARY, g.getFullyQualifiedName(), g.getName(), g.getDescription())); - } - return out; - } - - /** - * Reads the terms already derived from the memory's same-document siblings, and the glossary they - * predominantly live in. These come from the repository (current despite search-index lag, since - * derivation runs serially) so the agent can REUSE them and connect new terms to them. Fail-safe - * to empty. - */ - private SiblingContext fetchSiblings(ContextMemory memory) { - SiblingContext result = new SiblingContext(List.of(), null); - final EntityReference source = memory.getSourceEntity(); - if (source != null) { - try { - result = collectSiblings(memory, source); - } catch (RuntimeException ex) { - LOG.warn( - "MemoryGrounding: sibling lookup failed for memory {}: {}", - memory.getId(), - ex.getMessage()); - } - } - return result; - } - - private SiblingContext collectSiblings(ContextMemory memory, EntityReference source) { - final ContextMemoryRepository memoryRepo = - (ContextMemoryRepository) Entity.getEntityRepository(Entity.CONTEXT_MEMORY); - final GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - final List siblings = - memoryRepo.listExtractedMemories(source.getId(), source.getType()); - final List terms = new ArrayList<>(); - final Map glossaryFreq = new HashMap<>(); - for (final ContextMemory sib : siblings) { - if (!sib.getId().equals(memory.getId()) && terms.size() < MAX_CANDIDATES) { - addSiblingTerms(sib, termRepo, terms, glossaryFreq); - } - } - return new SiblingContext(terms, mostFrequent(glossaryFreq)); - } - - private void addSiblingTerms( - ContextMemory sib, - GlossaryTermRepository termRepo, - List terms, - Map glossaryFreq) { - final List derived = - termRepo.findFrom( - sib.getId(), Entity.CONTEXT_MEMORY, Relationship.DERIVED_FROM, Entity.GLOSSARY_TERM); - for (final EntityReference ref : derived) { - final GlossaryTerm term = termRepo.get(null, ref.getId(), termRepo.getFields(FIELD_GLOSSARY)); - terms.add( - new MemoryCandidate( - TYPE_TERM, term.getFullyQualifiedName(), term.getName(), term.getDescription())); - countGlossary(term, glossaryFreq); - } - } - - private void countGlossary(GlossaryTerm term, Map freq) { - if (term.getGlossary() != null && term.getGlossary().getFullyQualifiedName() != null) { - freq.merge(term.getGlossary().getFullyQualifiedName(), 1, Integer::sum); - } - } - - private String mostFrequent(Map freq) { - String result = null; - int best = 0; - for (final Map.Entry entry : freq.entrySet()) { - if (entry.getValue() > best) { - best = entry.getValue(); - result = entry.getKey(); - } - } - return result; - } - - /** The terms derived from a memory's siblings and the glossary they predominantly live in. */ - private record SiblingContext(List terms, String glossaryFqn) {} - - private List searchTopK(String index, String type, String text) { - List result = List.of(); - try { - final SearchRequest request = buildRequest(index, text); - final Response response = Entity.getSearchRepository().search(request, null); - result = parseHits((String) response.getEntity(), type); - } catch (java.io.IOException | RuntimeException ex) { - LOG.warn("MemoryGrounding: keyword search failed for index '{}': {}", index, ex.getMessage()); - } - return result; - } - - private SearchRequest buildRequest(String index, String text) { - return new SearchRequest() - .withQuery(text) - .withIndex(Entity.getSearchRepository().getIndexOrAliasName(index)) - .withSize(MAX_CANDIDATES) - .withFrom(0) - .withFetchSource(true) - .withTrackTotalHits(false) - .withSortFieldParam(DEFAULT_SORT_FIELD) - .withDeleted(false) - .withSortOrder(DEFAULT_SORT_ORDER) - .withIncludeSourceFields(new ArrayList<>()); - } - - private List parseHits(String json, String type) { - final List candidates = new ArrayList<>(); - final Object hitsRaw = JsonUtils.extractValue(json, HITS, HITS); - if (hitsRaw instanceof ArrayNode hits) { - for (final JsonNode hit : hits) { - final String fqn = JsonUtils.extractValue(hit, SEARCH_SOURCE, FULLY_QUALIFIED_NAME); - final String name = JsonUtils.extractValue(hit, SEARCH_SOURCE, Entity.FIELD_NAME); - final String description = - JsonUtils.extractValue(hit, SEARCH_SOURCE, Entity.FIELD_DESCRIPTION); - if (fqn != null && name != null) { - candidates.add(new MemoryCandidate(type, fqn, name, description)); - } - } - } - return candidates; - } - - private String groundingText(ContextMemory m) { - return String.join( - " ", - StringUtils.defaultString(m.getTitle()), - StringUtils.defaultString(m.getQuestion()), - StringUtils.defaultString(m.getAnswer())); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryProcessingEngine.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryProcessingEngine.java deleted file mode 100644 index 3fcb4da38099..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryProcessingEngine.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.StringUtils; -import org.openmetadata.schema.configuration.AISettings; -import org.openmetadata.schema.configuration.MemoryAgentSettings; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.entity.context.MemoryProcessingStatus; -import org.openmetadata.schema.entity.context.MemoryStats; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.ContextMemoryRepository; -import org.openmetadata.service.jdbi3.GlossaryRepository; -import org.openmetadata.service.jdbi3.GlossaryTermRepository; -import org.openmetadata.service.jdbi3.MetricRepository; -import org.openmetadata.service.llm.LLMClientHolder; -import org.openmetadata.service.util.AISettingsUtil; - -/** - * Orchestrates Memory Agent derivation from {@link ContextMemory}. When memory content changes, - * a trailing-throttle (debounce) collapses rapid edits into one run. Each run is guarded by a - * content hash so an identical memory is never re-derived, protecting against cost blowout and the - * postUpdate→schedule→run re-entry loop. - * - *

The stamp persists memoryStats with {@code updateVersion=false}, so it does NOT bump the - * entity version (no history churn). It DOES still fire postUpdate ({@code entityChanged=true}). - * The recursion loop is therefore broken solely by the hash-gate: after a stamp, {@code sourceHash - * == hashOf(memory)}, so a re-triggered ontology run skips derivation. The hash-gate is - * load-bearing — do NOT remove it. - */ -@Slf4j -public class MemoryProcessingEngine { - static final String SYSPROP_QUIET_MILLIS = "ontology.context.quiet.period.millis"; - static final String SYSPROP_MAX_PENDING = "ontology.context.max.pending.memories"; - - /** Fetched so grounding can find the memory's same-document siblings for reuse + relations. */ - private static final String FIELD_SOURCE_ENTITY = "sourceEntity"; - - // Short, not the 5-minute article-extraction debounce: a memory is a one-shot save (created by - // extraction, or a single manual create/edit), not autosaved keystroke-by-keystroke like an - // article body. So derivation runs promptly after the memory settles. The few seconds still keep - // the run off the request thread (post-commit), coalesce the create -> status-stamp re-arm, and - // let the hash gate make the re-triggered run a no-op. Override via SYSPROP_QUIET_MILLIS. - static final long DEFAULT_QUIET_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(2); - static final int DEFAULT_MAX_PENDING_MEMORIES = 10_000; - - private final ContextMemoryRepository memoryRepo; - private final MemoryGrounding grounding; - private final MemoryExtractor extractor; - private final MemoryReconciler reconciler; - private final long quietPeriodMillis; - private final int maxPendingMemories; - private final ScheduledExecutorService scheduler; - private final boolean skipInfraGates; - private final Map> pending = new ConcurrentHashMap<>(); - - /** Production singleton — lazily built on first call to {@link #instance()}. */ - private static volatile MemoryProcessingEngine singleton; - - private MemoryProcessingEngine( - final ContextMemoryRepository memoryRepo, - final MemoryGrounding grounding, - final MemoryExtractor extractor, - final MemoryReconciler reconciler, - final long quietPeriodMillis, - final int maxPendingMemories, - final ScheduledExecutorService scheduler, - final boolean skipInfraGates) { - this.memoryRepo = memoryRepo; - this.grounding = grounding; - this.extractor = extractor; - this.reconciler = reconciler; - this.quietPeriodMillis = quietPeriodMillis; - this.maxPendingMemories = maxPendingMemories; - this.scheduler = scheduler; - this.skipInfraGates = skipInfraGates; - } - - /** Returns the production singleton, building it on first call. */ - public static MemoryProcessingEngine instance() { - if (singleton == null) { - synchronized (MemoryProcessingEngine.class) { - if (singleton == null) { - singleton = buildProduction(); - } - } - } - return singleton; - } - - /** - * Test seam: injects deterministic collaborators, bypasses LLM and AISettings infrastructure - * gates (which require a running settings cache), and uses a daemon scheduler so {@link - * #run(UUID)} can be exercised synchronously without timing dependencies. - */ - static MemoryProcessingEngine forTest( - final ContextMemoryRepository memoryRepo, - final MemoryGrounding grounding, - final MemoryExtractor extractor, - final MemoryReconciler reconciler) { - return new MemoryProcessingEngine( - memoryRepo, - grounding, - extractor, - reconciler, - 0L, - DEFAULT_MAX_PENDING_MEMORIES, - immediateExecutor(), - true); - } - - private static MemoryProcessingEngine buildProduction() { - final ContextMemoryRepository memoryRepo = - (ContextMemoryRepository) Entity.getEntityRepository(Entity.CONTEXT_MEMORY); - final GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - final MetricRepository metricRepo = - (MetricRepository) Entity.getEntityRepository(Entity.METRIC); - final GlossaryRepository glossaryRepo = - (GlossaryRepository) Entity.getEntityRepository(Entity.GLOSSARY); - final long quietMillis = Long.getLong(SYSPROP_QUIET_MILLIS, DEFAULT_QUIET_PERIOD_MILLIS); - final int maxPending = Integer.getInteger(SYSPROP_MAX_PENDING, DEFAULT_MAX_PENDING_MEMORIES); - return new MemoryProcessingEngine( - memoryRepo, - new MemoryGrounding(), - new MemoryExtractor(LLMClientHolder.get()), - new MemoryReconciler(termRepo, metricRepo, glossaryRepo), - quietMillis, - maxPending, - defaultScheduler(), - false); - } - - /** - * (Re)schedules an ontology derivation run after the quiet period, collapsing rapid memory edits - * into one. Bounded: when the pending map is full, one entry is evicted with a warning; its next - * edit re-arms it and the hash gate keeps the eventual run correct. - */ - public void schedule(final UUID memoryId) { - evictIfFull(); - final AtomicReference> holder = new AtomicReference<>(); - holder.set( - scheduler.schedule( - () -> runScheduled(memoryId, holder.get()), quietPeriodMillis, TimeUnit.MILLISECONDS)); - final ScheduledFuture previous = pending.put(memoryId, holder.get()); - if (previous != null) { - previous.cancel(false); - } - } - - /** Cancels any pending run for a memory, e.g. when it is deleted. */ - public void cancel(final UUID memoryId) { - final ScheduledFuture previous = pending.remove(memoryId); - if (previous != null) { - previous.cancel(false); - } - } - - /** - * Runs the full derivation pipeline for one memory. Package-visible so tests can invoke - * synchronously via {@link #forTest}. Gates on LLM availability, agent enablement, and content - * hash before calling grounding → extractor → reconciler → stamp. - */ - void run(final UUID memoryId) { - final boolean eligible = skipInfraGates || (LLMClientHolder.isEnabled() && isAgentEnabled()); - if (eligible) { - runIfHashChanged(memoryId); - } - } - - /** Returns {@code sha256Hex(title + " " + question + " " + answer + " " + memoryType)}. */ - public static String hashOf(final ContextMemory m) { - final String text = - StringUtils.defaultString(m.getTitle()) - + " " - + StringUtils.defaultString(m.getQuestion()) - + " " - + StringUtils.defaultString(m.getAnswer()) - + " " - + (m.getMemoryType() == null ? "" : m.getMemoryType().value()); - return DigestUtils.sha256Hex(text); - } - - private boolean isAgentEnabled() { - final AISettings settings = AISettingsUtil.get(); - return AISettingsUtil.isMemoryAgentEnabled(settings); - } - - private void runIfHashChanged(final UUID memoryId) { - final ContextMemory memory = - memoryRepo.get(null, memoryId, memoryRepo.getFields(FIELD_SOURCE_ENTITY)); - final String hash = hashOf(memory); - final boolean unchanged = isHashUnchanged(memory, hash); - if (!unchanged) { - derive(memory, hash); - } - } - - private boolean isHashUnchanged(final ContextMemory memory, final String hash) { - return memory.getMemoryStats() != null && hash.equals(memory.getMemoryStats().getSourceHash()); - } - - private void derive(final ContextMemory memory, final String hash) { - final AISettings settings = AISettingsUtil.get(); - stampStatus(memory, MemoryProcessingStatus.Processing, null); - MemoryStats stats; - try { - final MemoryContext ctx = grounding.fetchCandidates(memory); - final MemoryDerivation verdict = extractor.derive(memory, ctx); - final MemoryReconciler.ReconcileResult result = - reconciler.reconcile( - memory, - verdict, - ctx, - AISettingsUtil.deletionPolicy(settings), - deriveTermsEnabled(settings), - deriveMetricsEnabled(settings)); - stats = buildStats(hash, result, MemoryProcessingStatus.Processed, null); - } catch (RuntimeException ex) { - // Stamp Failed AND the content hash: a deterministic failure would otherwise retry forever - // (the hash gate skips a re-derive once sourceHash == hashOf), and the error is surfaced on - // the memory so the UI can show why derivation did not produce ontologies. - LOG.error("Ontology derivation failed for memory {}", memory.getId(), ex); - stats = buildStats(hash, null, MemoryProcessingStatus.Failed, ex.getMessage()); - } - memoryRepo.stampMemoryStats(memory, stats); - } - - /** Flips only the lifecycle status (preserving prior counts/hash), e.g. to mark a run Processing. */ - private void stampStatus( - final ContextMemory memory, final MemoryProcessingStatus status, final String error) { - final MemoryStats stats = - memory.getMemoryStats() == null - ? new MemoryStats() - : JsonUtils.deepCopy(memory.getMemoryStats(), MemoryStats.class); - stats.withStatus(status).withError(error); - memoryRepo.stampMemoryStats(memory, stats); - } - - private boolean deriveTermsEnabled(final AISettings settings) { - final MemoryAgentSettings agent = settings == null ? null : settings.getMemoryAgent(); - return agent == null || !Boolean.FALSE.equals(agent.getDeriveGlossaryTerms()); - } - - private boolean deriveMetricsEnabled(final AISettings settings) { - final MemoryAgentSettings agent = settings == null ? null : settings.getMemoryAgent(); - return agent == null || !Boolean.FALSE.equals(agent.getDeriveMetrics()); - } - - private MemoryStats buildStats( - final String hash, - final MemoryReconciler.ReconcileResult r, - final MemoryProcessingStatus status, - final String error) { - final int terms = r == null ? 0 : r.createdTerms(); - final int metrics = r == null ? 0 : r.createdMetrics(); - final int reused = r == null ? 0 : r.reused(); - return new MemoryStats() - .withStatus(status) - .withError(error) - .withSourceHash(hash) - .withDerivedTermCount(terms) - .withDerivedMetricCount(metrics) - .withReusedCount(reused) - .withLastRunAt(System.currentTimeMillis()); - } - - private void runScheduled(final UUID memoryId, final ScheduledFuture firedFuture) { - pending.remove(memoryId, firedFuture); - try { - run(memoryId); - } catch (RuntimeException e) { - // Intentional broad catch: an uncaught exception here would kill the scheduler thread. - LOG.error("Ontology derivation failed for memory {}", memoryId, e); - } - } - - private void evictIfFull() { - if (pending.size() >= maxPendingMemories) { - final UUID dropped = pending.keySet().stream().findFirst().orElse(null); - if (dropped != null) { - cancel(dropped); - LOG.warn( - "Ontology derivation throttle is full ({} pending); dropped memory {}. It re-arms on its next edit.", - maxPendingMemories, - dropped); - } - } - } - - private static ScheduledExecutorService defaultScheduler() { - return newScheduler("ontology-derivation"); - } - - private static ScheduledExecutorService immediateExecutor() { - return newScheduler("ontology-derivation-test"); - } - - private static ScheduledExecutorService newScheduler(final String threadName) { - return Executors.newSingleThreadScheduledExecutor( - runnable -> { - final Thread thread = new Thread(runnable, threadName); - thread.setDaemon(true); - return thread; - }); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryPromptBuilder.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryPromptBuilder.java deleted file mode 100644 index 6db5ac7a6639..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryPromptBuilder.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; - -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang3.StringUtils; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.type.MetricType; -import org.openmetadata.schema.type.MetricUnitOfMeasurement; -import org.openmetadata.service.jdbi3.GlossaryTermRepository; - -/** Renders a compact user-prompt from a ContextMemory and its grounding candidates. */ -final class MemoryPromptBuilder { - private MemoryPromptBuilder() {} - - static String build(ContextMemory memory, MemoryContext context) { - return renderMemory(memory) - + "EXISTING GLOSSARY TERMS\n" - + renderCandidates(context.terms()) - + "\n" - + "EXISTING METRICS\n" - + renderCandidates(context.metrics()) - + "\n" - + "AVAILABLE GLOSSARIES (reuse one; do not mint near-duplicates)\n" - + renderCandidates(context.glossaries()) - + "\n" - + "SAME-DOCUMENT TERMS (reuse these, or relate to them via termVerdict.relatedTerms)\n" - + renderCandidates(context.siblingTerms()) - + "\n" - + renderRelationTypes() - + "\n" - + renderMetricEnums(); - } - - private static String renderRelationTypes() { - return "ALLOWED RELATION TYPES (relatedTerms[].relationType; direction is \"this term target\")\n" - + String.join(", ", GlossaryTermRepository.DEFAULT_RELATION_TYPES) - + "\n"; - } - - private static String renderMetricEnums() { - return "ALLOWED METRIC ENUMS (use exactly one value or null)\n" - + "metricType: " - + enumValues(MetricType.values()) - + "\n" - + "unitOfMeasurement: " - + enumValues(MetricUnitOfMeasurement.values()) - + "\n"; - } - - private static > String enumValues(E[] values) { - final List out = new ArrayList<>(); - for (final E value : values) { - out.add(value.toString()); - } - return String.join(", ", out); - } - - private static String renderMemory(ContextMemory memory) { - return "MEMORY\n" - + "title: " - + StringUtils.defaultString(memory.getTitle()) - + "\n" - + "question: " - + StringUtils.defaultString(memory.getQuestion()) - + "\n" - + "answer: " - + StringUtils.defaultString(memory.getAnswer()) - + "\n\n"; - } - - private static String renderCandidates(List candidates) { - String result = "(none)\n"; - if (!nullOrEmpty(candidates)) { - StringBuilder sb = new StringBuilder(); - for (MemoryCandidate c : candidates) { - sb.append(c.fqn()) - .append(" — ") - .append(c.name()) - .append(" — ") - .append(StringUtils.defaultString(c.description())) - .append("\n"); - } - result = sb.toString(); - } - return result; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryReconciler.java deleted file mode 100644 index 4369cd36f798..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryReconciler.java +++ /dev/null @@ -1,687 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; -import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; - -import java.util.List; -import java.util.Objects; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.function.Function; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.EntityInterface; -import org.openmetadata.schema.api.data.MetricExpression; -import org.openmetadata.schema.configuration.AIDeletionPolicy; -import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.entity.data.Glossary; -import org.openmetadata.schema.entity.data.GlossaryTerm; -import org.openmetadata.schema.entity.data.Metric; -import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.schema.type.EntityStatus; -import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.type.MetricExpressionLanguage; -import org.openmetadata.schema.type.MetricType; -import org.openmetadata.schema.type.MetricUnitOfMeasurement; -import org.openmetadata.schema.type.ProviderType; -import org.openmetadata.schema.type.Relationship; -import org.openmetadata.schema.type.TermRelation; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.EntityRepository; -import org.openmetadata.service.jdbi3.GlossaryRepository; -import org.openmetadata.service.jdbi3.GlossaryTermRepository; -import org.openmetadata.service.jdbi3.MetricRepository; -import org.openmetadata.service.util.FullyQualifiedName; -import org.openmetadata.service.util.MemoryOwnership; - -/** - * Owns every ontology write: it turns an {@link MemoryDerivation} into real Glossary Terms and - * Metrics, manages the {@code DERIVED_FROM} (agent-owned) and {@code RELATED_TO} (reused) edges back - * to the source {@link ContextMemory}, and enforces the ownership lifecycle from the design's §9. - * - *

Ownership is keyed on {@link ProviderType#AUTOMATION}: the agent only ever manages entities it - * created with that provider. A CREATE verdict mints the entity (minting its glossary too when none - * fits) and owns it; a REUSE verdict only links an existing entity for provenance and never claims - * it; on re-derive, owned entities the new verdict no longer implies are retired, while any entity a - * human has adopted (provider flipped off {@code automation}) is left untouched. Both re-derive - * retirement and memory-deletion retirement (via {@link #onMemoryDeleted}) route through the same - * {@code deletionPolicy}-driven {@link AIDeletionPolicy} modes; re-derive passes {@code - * hardDelete=true} for the {@code CASCADE} case since the entity is regenerable from the memory. An - * all-SKIP derivation (the signal {@code MemoryExtractor} emits on an empty or failed LLM result) - * is treated as carrying no actionable intent and is a complete no-op, so a transient LLM hiccup can - * never mass-retire a memory's derived set. - */ -@Slf4j -public class MemoryReconciler { - private static final String CORE_FIELDS = ""; - - /** Default SKOS-style relation used when the agent links a term to its sibling concepts. */ - private static final String RELATION_TYPE_RELATED_TO = "relatedTo"; - - private static final MemoryContext EMPTY_CONTEXT = - new MemoryContext(List.of(), List.of(), List.of()); - - private final GlossaryTermRepository termRepo; - private final MetricRepository metricRepo; - private final GlossaryRepository glossaryRepo; - - public MemoryReconciler( - final GlossaryTermRepository termRepo, - final MetricRepository metricRepo, - final GlossaryRepository glossaryRepo) { - this.termRepo = termRepo; - this.metricRepo = metricRepo; - this.glossaryRepo = glossaryRepo; - } - - /** Tally of what a reconcile run did, by ownership outcome. */ - public record ReconcileResult(int createdTerms, int createdMetrics, int reused, int retired) { - /** Total entities created; kept for call sites that do not need axis-level granularity. */ - public int created() { - return createdTerms + createdMetrics; - } - } - - /** - * Convenience overload with both axes enabled; used by unit tests and any caller that does not - * need per-axis gating. - */ - public ReconcileResult reconcile( - final ContextMemory memory, final MemoryDerivation verdict, final AIDeletionPolicy policy) { - return reconcile(memory, verdict, EMPTY_CONTEXT, policy, true, true); - } - - public ReconcileResult reconcile( - final ContextMemory memory, - final MemoryDerivation verdict, - final MemoryContext context, - final AIDeletionPolicy policy, - final boolean deriveTerms, - final boolean deriveMetrics) { - final MemoryContext ctx = context == null ? EMPTY_CONTEXT : context; - final ReconcileResult result; - if (isAllSkip(verdict)) { - LOG.info("All-SKIP derivation for memory {}; skipping reconcile entirely", memory.getId()); - result = new ReconcileResult(0, 0, 0, 0); - } else { - result = reconcileNonSkip(memory, verdict, ctx, policy, deriveTerms, deriveMetrics); - } - return result; - } - - private ReconcileResult reconcileNonSkip( - final ContextMemory memory, - final MemoryDerivation verdict, - final MemoryContext ctx, - final AIDeletionPolicy policy, - final boolean deriveTerms, - final boolean deriveMetrics) { - final Counts counts = new Counts(); - if (deriveTerms) { - final String implied = applyTermAxis(memory, verdict.termVerdict(), ctx, counts); - retireStaleOwned(memory, Entity.GLOSSARY_TERM, termRepo, implied, policy, counts); - } - if (deriveMetrics) { - final String implied = applyMetricAxis(memory, verdict.metricVerdict(), counts); - retireStaleOwned(memory, Entity.METRIC, metricRepo, implied, policy, counts); - } - LOG.info( - "Reconciled ontology for memory {}: {} terms created, {} metrics created, {} reused, {} retired", - memory.getId(), - counts.createdTerms, - counts.createdMetrics, - counts.reused, - counts.retired); - return new ReconcileResult( - counts.createdTerms, counts.createdMetrics, counts.reused, counts.retired); - } - - private boolean isAllSkip(final MemoryDerivation verdict) { - return isSkip(verdict.termVerdict()) && isSkip(verdict.metricVerdict()); - } - - private boolean isSkip(final MemoryVerdict verdict) { - final String action = verdict == null ? MemoryAction.SKIP : verdict.action(); - return action == null || MemoryAction.SKIP.equals(action); - } - - private String applyTermAxis( - final ContextMemory memory, - final MemoryVerdict verdict, - final MemoryContext ctx, - final Counts counts) { - final String action = verdict == null ? MemoryAction.SKIP : verdict.action(); - String implied = null; - if (MemoryAction.CREATE.equals(action)) { - implied = createTerm(memory, verdict, ctx, counts); - } else if (MemoryAction.REUSE.equals(action)) { - reuseTerm(memory, verdict, counts); - } - return implied; - } - - private String applyMetricAxis( - final ContextMemory memory, final MemoryVerdict verdict, final Counts counts) { - final String action = verdict == null ? MemoryAction.SKIP : verdict.action(); - String implied = null; - if (MemoryAction.CREATE.equals(action)) { - implied = createMetric(memory, verdict, counts); - } else if (MemoryAction.REUSE.equals(action)) { - reuse(memory, verdict, Entity.METRIC, metricRepo, counts); - } - return implied; - } - - private String createTerm( - final ContextMemory memory, - final MemoryVerdict verdict, - final MemoryContext ctx, - final Counts counts) { - if (!isValidName(verdict.name())) { - LOG.warn("Skipping CREATE term: invalid LLM name '{}'", verdict.name()); - return null; - } - final EntityReference existingOwned = - findOwnedByName(memory, Entity.GLOSSARY_TERM, termRepo, verdict.name()); - final String result; - if (existingOwned != null) { - wireRelatedTerms(existingOwned.getId(), verdict.relatedTerms()); - result = verdict.name(); - } else { - result = createTermWithFqnPrecheck(memory, verdict, ctx, counts); - } - return result; - } - - private String createTermWithFqnPrecheck( - final ContextMemory memory, - final MemoryVerdict verdict, - final MemoryContext ctx, - final Counts counts) { - final String glossaryFqn = resolveGlossaryFqn(verdict, ctx); - final String termFqn = - nullOrEmpty(glossaryFqn) ? null : FullyQualifiedName.build(glossaryFqn, verdict.name()); - final EntityInterface existing = findByFqn(termRepo, termFqn); - final String result; - if (existing != null) { - LOG.info("Term FQN '{}' already exists; reusing instead of creating", termFqn); - reuseExisting(memory, existing, Entity.GLOSSARY_TERM, termRepo, counts); - wireRelatedTerms(existing.getId(), verdict.relatedTerms()); - result = verdict.name(); - } else { - result = mintTerm(memory, verdict, ctx, counts); - } - return result; - } - - /** - * Picks the glossary FQN to file a CREATE term under: the agent's explicit choice, else the - * glossary the source document's sibling terms already live in (so one document maps to one - * glossary instead of sprawling), else the agent's proposed new glossary name. - */ - private String resolveGlossaryFqn(final MemoryVerdict verdict, final MemoryContext ctx) { - final String fqn; - if (!nullOrEmpty(verdict.targetFqn())) { - fqn = verdict.targetFqn(); - } else if (ctx != null && !nullOrEmpty(ctx.siblingGlossaryFqn())) { - fqn = ctx.siblingGlossaryFqn(); - } else if (!nullOrEmpty(verdict.newGlossaryName())) { - fqn = verdict.newGlossaryName(); - } else { - fqn = null; - } - return fqn; - } - - private String mintTerm( - final ContextMemory memory, - final MemoryVerdict verdict, - final MemoryContext ctx, - final Counts counts) { - final EntityReference glossary = resolveOrMintGlossary(verdict, ctx); - String result = null; - if (glossary != null) { - final GlossaryTerm term = - new GlossaryTerm() - .withId(UUID.randomUUID()) - .withName(verdict.name()) - .withDisplayName(verdict.displayName()) - .withDescription(verdict.description()) - .withGlossary(glossary) - .withProvider(ProviderType.AUTOMATION) - .withUpdatedBy(MemoryOwnership.MEMORY_BOT_NAME) - .withUpdatedAt(System.currentTimeMillis()); - final GlossaryTerm created = termRepo.createInternal(term); - addDerivedFromEdge(created.getId(), memory.getId(), Entity.GLOSSARY_TERM, termRepo); - wireRelatedTerms(created.getId(), verdict.relatedTerms()); - counts.createdTerms++; - result = verdict.name(); - } - return result; - } - - /** - * Connects a term to the other terms the agent named, with the typed relationship it chose - * (SKOS-style: broader/narrower, partOf/hasPart, calculatedFrom/usedToCalculate, synonym, ...), so - * a document's concepts form a real ontology instead of disconnected "related to" units. Each FQN - * is resolved against existing terms (so a hallucinated name is dropped, not minted) and self-links - * are skipped. {@link GlossaryTermRepository#addTermRelation} is idempotent, so re-derivation does - * not duplicate edges, and it canonicalizes direction for inverse pairs (e.g. broader/narrower). - */ - private void wireRelatedTerms(final UUID termId, final List relations) { - for (final MemoryRelation relation : listOrEmpty(relations)) { - final EntityInterface related = findByFqn(termRepo, relation.targetFqn()); - if (related != null && !related.getId().equals(termId)) { - termRepo.addTermRelation( - termId, - new TermRelation() - .withTerm(related.getEntityReference()) - .withRelationType(normalizeRelationType(relation.relationType()))); - } - } - } - - /** - * Maps the LLM's raw relation type to the glossary's allowed vocabulary (case-insensitive), - * defaulting to {@code relatedTo}. Keeps {@link GlossaryTermRepository#addTermRelation} — which - * throws {@code BadRequestException} on an unknown type — from aborting the whole derivation over a - * bad LLM string. - */ - private String normalizeRelationType(final String raw) { - String result = RELATION_TYPE_RELATED_TO; - if (!nullOrEmpty(raw)) { - for (final String allowed : GlossaryTermRepository.DEFAULT_RELATION_TYPES) { - if (allowed.equalsIgnoreCase(raw.trim())) { - result = allowed; - } - } - } - return result; - } - - private void reuseTerm( - final ContextMemory memory, final MemoryVerdict verdict, final Counts counts) { - final EntityInterface target = findByFqn(termRepo, verdict.targetFqn()); - if (target == null) { - LOG.warn("REUSE verdict for term could not resolve fqn '{}'; skipping", verdict.targetFqn()); - } else { - reuseExisting(memory, target, Entity.GLOSSARY_TERM, termRepo, counts); - wireRelatedTerms(target.getId(), verdict.relatedTerms()); - } - } - - private String createMetric( - final ContextMemory memory, final MemoryVerdict verdict, final Counts counts) { - if (!isValidName(verdict.name())) { - LOG.warn("Skipping CREATE metric: invalid LLM name '{}'", verdict.name()); - return null; - } - final EntityReference existingOwned = - findOwnedByName(memory, Entity.METRIC, metricRepo, verdict.name()); - final String result; - if (existingOwned != null) { - result = verdict.name(); - } else { - result = createMetricWithFqnPrecheck(memory, verdict, counts); - } - return result; - } - - private String createMetricWithFqnPrecheck( - final ContextMemory memory, final MemoryVerdict verdict, final Counts counts) { - final EntityInterface existing = findByFqn(metricRepo, verdict.name()); - final String result; - if (existing != null) { - LOG.info("Metric FQN '{}' already exists; reusing instead of creating", verdict.name()); - reuseExisting(memory, existing, Entity.METRIC, metricRepo, counts); - result = verdict.name(); - } else { - result = mintMetric(memory, verdict, counts); - } - return result; - } - - private String mintMetric( - final ContextMemory memory, final MemoryVerdict verdict, final Counts counts) { - final Metric metric = - new Metric() - .withId(UUID.randomUUID()) - .withName(verdict.name()) - .withDisplayName(verdict.displayName()) - .withDescription(verdict.description()) - .withMetricType(toMetricType(verdict.metricType())) - .withUnitOfMeasurement(toUnit(verdict.unitOfMeasurement())) - .withMetricExpression(toExpression(verdict.metricExpressionCode())) - .withProvider(ProviderType.AUTOMATION) - .withUpdatedBy(MemoryOwnership.MEMORY_BOT_NAME) - .withUpdatedAt(System.currentTimeMillis()); - final Metric created = metricRepo.createInternal(metric); - addDerivedFromEdge(created.getId(), memory.getId(), Entity.METRIC, metricRepo); - counts.createdMetrics++; - return verdict.name(); - } - - private void reuse( - final ContextMemory memory, - final MemoryVerdict verdict, - final String entityType, - final EntityRepository repo, - final Counts counts) { - final EntityInterface target = findByFqn(repo, verdict.targetFqn()); - if (target == null) { - LOG.warn( - "REUSE verdict for {} could not resolve fqn '{}'; skipping", - entityType, - verdict.targetFqn()); - } else { - reuseExisting(memory, target, entityType, repo, counts); - } - } - - private void reuseExisting( - final ContextMemory memory, - final EntityInterface target, - final String entityType, - final EntityRepository repo, - final Counts counts) { - repo.addRelationship( - memory.getId(), - target.getId(), - Entity.CONTEXT_MEMORY, - entityType, - Relationship.RELATED_TO, - false); - counts.reused++; - } - - private EntityReference resolveOrMintGlossary( - final MemoryVerdict verdict, final MemoryContext ctx) { - EntityReference glossary = resolveGlossary(verdict.targetFqn()); - if (glossary == null && ctx != null) { - glossary = resolveGlossary(ctx.siblingGlossaryFqn()); - } - if (glossary == null) { - glossary = resolveOrMintByName(verdict); - } - return glossary; - } - - private EntityReference resolveOrMintByName(final MemoryVerdict verdict) { - if (!isValidName(verdict.newGlossaryName())) { - LOG.warn("Skipping glossary mint: invalid LLM name '{}'", verdict.newGlossaryName()); - return null; - } - final EntityReference existing = resolveGlossary(verdict.newGlossaryName()); - final EntityReference result; - if (existing != null) { - result = existing; - } else { - result = mintGlossary(verdict); - } - return result; - } - - private EntityReference mintGlossary(final MemoryVerdict verdict) { - final Glossary minted = - new Glossary() - .withId(UUID.randomUUID()) - .withName(verdict.newGlossaryName()) - .withDisplayName(verdict.newGlossaryName()) - .withDescription(verdict.newGlossaryDescription()) - .withProvider(ProviderType.AUTOMATION) - .withUpdatedBy(MemoryOwnership.MEMORY_BOT_NAME) - .withUpdatedAt(System.currentTimeMillis()); - return glossaryRepo.createInternal(minted).getEntityReference(); - } - - private EntityReference resolveGlossary(final String fqn) { - EntityReference ref = null; - if (!nullOrEmpty(fqn)) { - final Glossary glossary = glossaryRepo.findByNameOrNull(fqn, Include.NON_DELETED); - ref = glossary == null ? null : glossary.getEntityReference(); - } - return ref; - } - - private EntityInterface findByFqn(final EntityRepository repo, final String fqn) { - EntityInterface entity = null; - if (!nullOrEmpty(fqn)) { - entity = repo.findByNameOrNull(fqn, Include.NON_DELETED); - } - return entity; - } - - private EntityReference findOwnedByName( - final ContextMemory memory, - final String entityType, - final EntityRepository repo, - final String name) { - EntityReference match = null; - for (final EntityReference owned : ownedDerived(memory, entityType, repo)) { - if (Objects.equals(owned.getName(), name)) { - match = owned; - } - } - return match; - } - - private void retireStaleOwned( - final ContextMemory memory, - final String entityType, - final EntityRepository repo, - final String impliedName, - final AIDeletionPolicy policy, - final Counts counts) { - for (final EntityReference owned : ownedDerived(memory, entityType, repo)) { - if (!Objects.equals(owned.getName(), impliedName) && isAutomationOwned(repo, owned)) { - retireByPolicy(memory, entityType, repo, owned, true, policy); - counts.retired++; - } - } - } - - public void onMemoryDeleted( - final ContextMemory memory, final boolean hardDelete, final AIDeletionPolicy policy) { - retireAllOwned(memory, Entity.GLOSSARY_TERM, termRepo, hardDelete, policy); - retireAllOwned(memory, Entity.METRIC, metricRepo, hardDelete, policy); - dropReusedLinks(memory, Entity.GLOSSARY_TERM, termRepo); - dropReusedLinks(memory, Entity.METRIC, metricRepo); - } - - /** - * Restores CASCADE-soft-deleted owned entities when their source memory is restored. Only - * automation-owned entities that still have a {@code DERIVED_FROM} edge back to this memory are - * restored — ORPHAN/DEPRECATE-released entities lost that edge during deletion, so they are - * correctly NOT re-linked. {@link EntityRepository#restoreEntity} is a no-op on already-active - * entities, so calling it unconditionally on all {@code Include.ALL} results is safe. - */ - public void onMemoryRestored(final ContextMemory memory) { - restoreOwnedByType(memory, Entity.GLOSSARY_TERM, termRepo); - restoreOwnedByType(memory, Entity.METRIC, metricRepo); - } - - private void restoreOwnedByType( - final ContextMemory memory, final String entityType, final EntityRepository repo) { - for (final EntityReference ref : - repo.findFrom( - memory.getId(), - Entity.CONTEXT_MEMORY, - Relationship.DERIVED_FROM, - entityType, - Include.ALL)) { - if (isAutomationOwnedIncludeAll(repo, ref)) { - repo.restoreEntity(MemoryOwnership.MEMORY_BOT_NAME, ref.getId()); - } - } - } - - private boolean isAutomationOwnedIncludeAll( - final EntityRepository repo, final EntityReference ref) { - final EntityInterface entity = repo.find(ref.getId(), Include.ALL); - return entity.getProvider() == ProviderType.AUTOMATION; - } - - private void retireAllOwned( - final ContextMemory memory, - final String entityType, - final EntityRepository repo, - final boolean hardDelete, - final AIDeletionPolicy policy) { - for (final EntityReference owned : ownedDerived(memory, entityType, repo)) { - if (isAutomationOwned(repo, owned)) { - retireByPolicy(memory, entityType, repo, owned, hardDelete, policy); - } - } - } - - private void retireByPolicy( - final ContextMemory memory, - final String entityType, - final EntityRepository repo, - final EntityReference owned, - final boolean hardDelete, - final AIDeletionPolicy policy) { - switch (policy) { - case CASCADE -> repo.delete( - MemoryOwnership.MEMORY_BOT_NAME, owned.getId(), false, hardDelete); - case ORPHAN -> { - editOwned(repo, owned.getId(), entity -> setProvider(entity, ProviderType.USER)); - dropDerivedFromEdge(memory, entityType, repo, owned.getId()); - } - case DEPRECATE -> { - editOwned(repo, owned.getId(), entity -> entity.setEntityStatus(EntityStatus.DEPRECATED)); - dropDerivedFromEdge(memory, entityType, repo, owned.getId()); - } - } - } - - private void dropReusedLinks( - final ContextMemory memory, final String entityType, final EntityRepository repo) { - final List reused = - repo.findTo(memory.getId(), Entity.CONTEXT_MEMORY, Relationship.RELATED_TO, entityType); - for (final EntityReference link : reused) { - repo.deleteRelationship( - memory.getId(), Entity.CONTEXT_MEMORY, link.getId(), entityType, Relationship.RELATED_TO); - } - } - - private void editOwned( - final EntityRepository repo, final UUID id, final Consumer mutation) { - editOwnedTyped(repo, id, mutation); - } - - private void editOwnedTyped( - final EntityRepository repo, final UUID id, final Consumer mutation) { - final T original = repo.get(null, id, repo.getFields(CORE_FIELDS)); - final T updated = JsonUtils.deepCopy(original, repo.getEntityClass()); - mutation.accept(updated); - updated.setUpdatedBy(MemoryOwnership.MEMORY_BOT_NAME); - updated.setUpdatedAt(System.currentTimeMillis()); - repo.update(null, original, updated, MemoryOwnership.MEMORY_BOT_NAME); - } - - private void dropDerivedFromEdge( - final ContextMemory memory, - final String entityType, - final EntityRepository repo, - final UUID derivedId) { - repo.deleteRelationship( - derivedId, entityType, memory.getId(), Entity.CONTEXT_MEMORY, Relationship.DERIVED_FROM); - } - - private void addDerivedFromEdge( - final UUID derivedId, - final UUID memoryId, - final String entityType, - final EntityRepository repo) { - repo.addRelationship( - derivedId, memoryId, entityType, Entity.CONTEXT_MEMORY, Relationship.DERIVED_FROM, false); - } - - private List ownedDerived( - final ContextMemory memory, final String entityType, final EntityRepository repo) { - return repo.findFrom( - memory.getId(), Entity.CONTEXT_MEMORY, Relationship.DERIVED_FROM, entityType); - } - - private boolean isAutomationOwned(final EntityRepository repo, final EntityReference ref) { - final EntityInterface entity = repo.get(null, ref.getId(), repo.getFields(CORE_FIELDS)); - return entity.getProvider() == ProviderType.AUTOMATION; - } - - private void setProvider(final EntityInterface entity, final ProviderType provider) { - if (entity instanceof GlossaryTerm term) { - term.setProvider(provider); - } else if (entity instanceof Metric metric) { - metric.setProvider(provider); - } - } - - private boolean isValidName(final String name) { - return !nullOrEmpty(name) && name.chars().noneMatch(c -> c == '.' || c == '"' || c == '/'); - } - - private MetricExpression toExpression(final String code) { - MetricExpression expression = null; - if (!nullOrEmpty(code)) { - expression = new MetricExpression().withLanguage(MetricExpressionLanguage.SQL).withCode(code); - } - return expression; - } - - private MetricType toMetricType(final String value) { - return resolveEnum(value, MetricType.values(), MetricType::value, "metricType"); - } - - private MetricUnitOfMeasurement toUnit(final String value) { - return resolveEnum( - value, - MetricUnitOfMeasurement.values(), - MetricUnitOfMeasurement::value, - "unitOfMeasurement"); - } - - /** - * Promotes a raw LLM enum string to a schema enum, matching case-insensitively against the enum's - * JSON values. Returns {@code null} (with a warning) when nothing matches instead of letting the - * generated {@code fromValue} throw {@link IllegalArgumentException} and abort the entire - * derivation — both fields are optional on the Metric schema, so an unset value is valid. - */ - private static > E resolveEnum( - final String raw, final E[] values, final Function valueOf, final String label) { - E result = null; - if (!nullOrEmpty(raw)) { - final String normalized = raw.trim(); - for (final E candidate : values) { - if (valueOf.apply(candidate).equalsIgnoreCase(normalized)) { - result = candidate; - } - } - if (result == null) { - LOG.warn("Ontology: ignoring unrecognized {} '{}' from LLM; leaving it unset", label, raw); - } - } - return result; - } - - /** Mutable tally threaded through reconciliation to keep each step a small single-purpose method. */ - private static final class Counts { - private int createdTerms; - private int createdMetrics; - private int reused; - private int retired; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryRelation.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryRelation.java deleted file mode 100644 index b53a4762f8e8..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryRelation.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Anti-corruption DTO for one typed relationship the agent proposes between the term being derived - * and an existing term. {@code relationType} is read from the LLM as a raw string and validated by - * {@link MemoryReconciler} against the glossary's allowed vocabulary (SKOS-style: {@code relatedTo}, - * {@code synonym}, {@code broader}/{@code narrower}, {@code partOf}/{@code hasPart}, {@code - * calculatedFrom}/{@code usedToCalculate}, ...); an unrecognized value degrades to {@code relatedTo} - * rather than throwing. The direction is "this term {@code relationType} targetFqn". - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public record MemoryRelation( - @JsonProperty("targetFqn") String targetFqn, - @JsonProperty("relationType") String relationType) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryVerdict.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryVerdict.java deleted file mode 100644 index 2e2b4b0d738c..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/memory/MemoryVerdict.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2024 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.drive.memory; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.List; - -/** - * Anti-corruption DTO for a single ontology verdict as returned by the LLM. All fields are raw - * Strings for leniency; callers validate and promote to domain types. See {@link MemoryAction} - * for the expected {@code action} values. - * - *

{@code relatedTerms} lets the agent connect a term to other terms (typically the sibling - * concepts surfaced from the same source document) with a typed relationship, so derivation produces - * a real ontology rather than disconnected units. It applies only to the term axis; it is ignored - * for metrics. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public record MemoryVerdict( - @JsonProperty("action") String action, - @JsonProperty("targetFqn") String targetFqn, - @JsonProperty("newGlossaryName") String newGlossaryName, - @JsonProperty("newGlossaryDescription") String newGlossaryDescription, - @JsonProperty("name") String name, - @JsonProperty("displayName") String displayName, - @JsonProperty("description") String description, - @JsonProperty("metricType") String metricType, - @JsonProperty("unitOfMeasurement") String unitOfMeasurement, - @JsonProperty("metricExpressionCode") String metricExpressionCode, - @JsonProperty("relatedTerms") List relatedTerms) { - - /** Backward-compatible constructor for call sites that predate {@code relatedTerms}. */ - public MemoryVerdict( - String action, - String targetFqn, - String newGlossaryName, - String newGlossaryDescription, - String name, - String displayName, - String description, - String metricType, - String unitOfMeasurement, - String metricExpressionCode) { - this( - action, - targetFqn, - newGlossaryName, - newGlossaryDescription, - name, - displayName, - description, - metricType, - unitOfMeasurement, - metricExpressionCode, - null); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/Workflow.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/Workflow.java index 19a594e30b18..d563d135f786 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/Workflow.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/Workflow.java @@ -27,6 +27,10 @@ public class Workflow { public static final String GLOBAL_NAMESPACE = "global"; public static final String SUCCESSFUL_RESULT = "success"; public static final String FAILURE_RESULT = "failure"; + // Cause string passed to deleteProcessInstance when a newer approval run replaces an older one. + // Whitelisted in WorkflowFailureListener so PROCESS_CANCELLED stays silent for supersede. + public static final String SUPERSEDED_BY_NEWER_RUN = + "Superseded by a newer approval workflow run for the same entity"; private final TriggerWorkflow triggerWorkflow; private final MainWorkflow mainWorkflow; private final WorkflowDefinition workflowDefinition; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowFailureListener.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowFailureListener.java index 073f05f2be5d..817127379ffb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowFailureListener.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowFailureListener.java @@ -8,6 +8,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent; @@ -20,6 +21,7 @@ import org.flowable.engine.delegate.event.FlowableCancelledEvent; import org.flowable.engine.runtime.ProcessInstance; import org.openmetadata.schema.governance.workflows.WorkflowDefinition; +import org.openmetadata.schema.governance.workflows.WorkflowInstance; import org.openmetadata.service.Entity; import org.openmetadata.service.governance.workflows.elements.TriggerFactory; import org.openmetadata.service.jdbi3.WorkflowDefinitionRepository; @@ -27,34 +29,40 @@ import org.openmetadata.service.jdbi3.WorkflowInstanceStateRepository; import org.openmetadata.service.util.EntityUtil; +/** + * Records workflow failures in the WorkflowInstance / WorkflowInstanceState time-series tables. + * Workflow failures are business events (task threw, cancelled by supersede), not code bugs, so + * this listener logs at WARN/DEBUG and never at ERROR. Real code bugs still surface as exceptions + * from callers into their own error paths. + */ @Slf4j public class WorkflowFailureListener implements FlowableEventListener { public static final String WORKFLOW_FAILURE_LISTENER_STAGE = "workflowFailureListener"; + private static final String STATUS_VARIABLE_KEY = "status"; + + private static final Set INTENTIONAL_CANCELLATION_CAUSES = + Set.of( + "Cleanup before redeployment", + "Cleanup old workflow version", + "Terminated due to conflicting workflow instance", + Workflow.SUPERSEDED_BY_NEWER_RUN); + + private static final String DRAFT_TASK_CANCEL_CAUSE_PREFIX = "Workflow-managed draft task "; @Override public void onEvent(FlowableEvent event) { switch (event.getType()) { case JOB_EXECUTION_FAILURE: - LOG.error("[WorkflowFailure] JOB_EXECUTION_FAILURE: {}", event); + LOG.warn("[WorkflowFailure] JOB_EXECUTION_FAILURE: {}", event); storeFailureInDatabase(event, "JOB_EXECUTION_FAILURE"); break; case PROCESS_COMPLETED_WITH_ERROR_END_EVENT: - LOG.error("[WorkflowFailure] PROCESS_COMPLETED_WITH_ERROR: {}", event); + LOG.warn("[WorkflowFailure] PROCESS_COMPLETED_WITH_ERROR: {}", event); storeFailureInDatabase(event, "PROCESS_ERROR"); break; case PROCESS_CANCELLED: - if (event instanceof FlowableCancelledEvent cancelledEvent - && ("Cleanup before redeployment".equals(cancelledEvent.getCause()) - || "Terminated due to conflicting workflow instance" - .equals(cancelledEvent.getCause()))) { - LOG.debug( - "[WorkflowFailure] Ignoring expected PROCESS_CANCELLED: {}", - cancelledEvent.getCause()); - break; - } - LOG.error("[WorkflowFailure] PROCESS_CANCELLED: {}", event); - storeFailureInDatabase(event, "PROCESS_CANCELLED"); + handleProcessCancelled(event); break; default: if (event instanceof FlowableExceptionEvent exceptionEvent) { @@ -64,23 +72,40 @@ public void onEvent(FlowableEvent event) { } } + private void handleProcessCancelled(FlowableEvent event) { + // FlowableCancelledEvent carries the reason string passed to deleteProcessInstance. A + // whitelisted cause means the cancel was intentional (supersede / redeployment cleanup). + String cause = + event instanceof FlowableCancelledEvent cancelled && cancelled.getCause() != null + ? cancelled.getCause().toString() + : null; + if (cause != null + && (INTENTIONAL_CANCELLATION_CAUSES.contains(cause) + || cause.startsWith(DRAFT_TASK_CANCEL_CAUSE_PREFIX))) { + LOG.debug("[WorkflowFailure] Ignoring expected PROCESS_CANCELLED: {}", cause); + } else { + LOG.warn("[WorkflowFailure] PROCESS_CANCELLED: {}", event); + storeFailureInDatabase(event, "PROCESS_CANCELLED"); + } + } + private void handleFlowableException(FlowableExceptionEvent exceptionEvent) { Throwable cause = exceptionEvent.getCause(); String errorMessage = cause != null ? cause.getMessage() : "Unknown Flowable exception"; String processInstanceId = null; + // FlowableExceptionEvent may or may not carry entity context; pattern-match to reach it. if (exceptionEvent instanceof FlowableEngineEntityEvent entityEvent) { processInstanceId = entityEvent.getProcessInstanceId(); } - LOG.error( + LOG.warn( "[WorkflowFailure] FLOWABLE_EXCEPTION: processInstanceId={}, error={}", processInstanceId, - errorMessage, - cause); + errorMessage); if (errorMessage.contains("No outgoing sequence flow")) { - LOG.error("[WorkflowFailure] DESIGN_ERROR: Missing conditional sequence flows detected"); + LOG.warn("[WorkflowFailure] DESIGN_ERROR: Missing conditional sequence flows detected"); storeFailureInDatabase((FlowableEvent) exceptionEvent, "DESIGN_ERROR"); terminateStuckProcess(processInstanceId, errorMessage); } else { @@ -92,7 +117,7 @@ private void storeFailureInDatabase(FlowableEvent event, String failureType) { try { String processInstanceId = getProcessInstanceId(event); if (processInstanceId == null) { - LOG.warn( + LOG.debug( "[WorkflowFailure] Cannot store failure - missing processInstanceId for failureType: {}", failureType); return; @@ -108,14 +133,14 @@ private void storeFailureInDatabase(FlowableEvent event, String failureType) { .singleResult(); if (processInstance == null) { - LOG.error( + LOG.debug( "[WorkflowFailure] ProcessInstance not found: processInstanceId={}", processInstanceId); return; } String businessKey = processInstance.getBusinessKey(); if (businessKey == null || businessKey.isEmpty()) { - LOG.error( + LOG.debug( "[WorkflowFailure] Missing businessKey for processInstance: {}", processInstanceId); return; } @@ -138,34 +163,36 @@ private void storeFailureInDatabase(FlowableEvent event, String failureType) { workflowInstanceId, processInstanceId, workflowName, failureType, errorMessage); } - LOG.warn( - "[WorkflowFailure] FAILURE_STORED: workflowInstanceId={}, processInstanceId={}, failureType={}", + LOG.debug( + "[WorkflowFailure] FAILURE_STORED: workflowInstanceId={}, failureType={}", workflowInstanceId, - processInstanceId, failureType); } catch (Exception e) { - LOG.error( - "[WorkflowFailure] Failed to store workflow failure in database: error={}", - e.getMessage(), - e); + LOG.warn( + "[WorkflowFailure] Failed to store workflow failure in database: {}", e.getMessage()); } } private String getProcessInstanceId(FlowableEvent event) { + String processInstanceId = null; + // Flowable delivers event bodies via the FlowableEngineEntityEvent interface. if (event instanceof FlowableEngineEntityEvent entityEvent) { - return entityEvent.getProcessInstanceId(); + processInstanceId = entityEvent.getProcessInstanceId(); } - return null; + return processInstanceId; } private String getErrorMessage(FlowableEvent event) { + String message = "Workflow failure: " + event.getType().name(); + // Exception events carry the underlying Throwable; extract its message when present. if (event instanceof FlowableExceptionEvent exceptionEvent) { - return exceptionEvent.getCause() != null - ? exceptionEvent.getCause().getMessage() - : "Unknown Flowable exception"; + message = + exceptionEvent.getCause() != null + ? exceptionEvent.getCause().getMessage() + : "Unknown Flowable exception"; } - return "Workflow failure: " + event.getType().name(); + return message; } private void markWorkflowInstanceAsFailed( @@ -176,7 +203,7 @@ private void markWorkflowInstanceAsFailed( Entity.getEntityTimeSeriesRepository(Entity.WORKFLOW_INSTANCE); Map failureVariables = new HashMap<>(); - failureVariables.put("status", "EXCEPTION"); + failureVariables.put(STATUS_VARIABLE_KEY, WorkflowInstance.WorkflowStatus.EXCEPTION.value()); failureVariables.put("failureType", failureType); failureVariables.put("error", errorMessage); failureVariables.put("processInstanceId", processInstanceId); @@ -185,16 +212,14 @@ private void markWorkflowInstanceAsFailed( workflowInstanceRepository.updateWorkflowInstance( workflowInstanceId, System.currentTimeMillis(), failureVariables); - LOG.info( - "[WorkflowFailure] INSTANCE_MARKED_FAILED: workflowInstanceId={}, status=EXCEPTION", - workflowInstanceId); + LOG.debug( + "[WorkflowFailure] INSTANCE_MARKED_FAILED: workflowInstanceId={}", workflowInstanceId); } catch (Exception e) { - LOG.error( - "[WorkflowFailure] Failed to mark workflow instance as failed: workflowInstanceId={}, error={}", + LOG.warn( + "[WorkflowFailure] Failed to mark workflow instance as failed (workflowInstanceId={}): {}", workflowInstanceId, - e.getMessage(), - e); + e.getMessage()); } } @@ -220,28 +245,28 @@ private void addFailureStage( System.currentTimeMillis()); Map stageData = new HashMap<>(); - stageData.put("status", "FAILED"); + stageData.put(STATUS_VARIABLE_KEY, "FAILED"); stageData.put("failureType", failureType); stageData.put("processInstanceId", processInstanceId); stageData.put("exception", errorMessage); stateRepository.updateStage(stageId, System.currentTimeMillis(), stageData); - LOG.info( + LOG.debug( "[WorkflowFailure] FAILURE_STAGE_ADDED: workflowInstanceId={}, stageId={}", workflowInstanceId, stageId); } catch (Exception e) { - LOG.error( - "[WorkflowFailure] Failed to add failure stage: workflowInstanceId={}, error={}", + LOG.warn( + "[WorkflowFailure] Failed to add failure stage (workflowInstanceId={}): {}", workflowInstanceId, - e.getMessage(), - e); + e.getMessage()); } } private boolean isStageStatusEnabled(String workflowDefinitionKey) { + boolean enabled = false; try { WorkflowDefinitionRepository workflowDefRepository = (WorkflowDefinitionRepository) Entity.getEntityRepository(Entity.WORKFLOW_DEFINITION); @@ -251,32 +276,26 @@ private boolean isStageStatusEnabled(String workflowDefinitionKey) { null, workflowDefinitionKey, EntityUtil.Fields.EMPTY_FIELDS); if (workflowDef != null && workflowDef.getConfig() != null) { - boolean storeStageStatus = workflowDef.getConfig().getStoreStageStatus(); - LOG.debug( - "[WorkflowFailure] Retrieved config for '{}': storeStageStatus={}", - workflowDefinitionKey, - storeStageStatus); - return storeStageStatus; + enabled = workflowDef.getConfig().getStoreStageStatus(); } else { - LOG.warn( - "[WorkflowFailure] WorkflowDefinition '{}' not found or has no config, defaulting to false", + LOG.debug( + "[WorkflowFailure] WorkflowDefinition '{}' not found or has no config", workflowDefinitionKey); - return false; } } catch (Exception e) { - LOG.error( - "[WorkflowFailure] Failed to retrieve WorkflowDefinition '{}', defaulting to false: {}", + LOG.debug( + "[WorkflowFailure] Failed to retrieve WorkflowDefinition '{}': {}", workflowDefinitionKey, e.getMessage()); - return false; } + return enabled; } private void terminateStuckProcess(String processInstanceId, String errorMessage) { try { if (processInstanceId == null) { - LOG.warn("[WorkflowFailure] Cannot terminate process - missing processInstanceId"); + LOG.debug("[WorkflowFailure] Cannot terminate process - missing processInstanceId"); return; } @@ -297,20 +316,18 @@ private void terminateStuckProcess(String processInstanceId, String errorMessage runtimeService.deleteProcessInstance( processInstanceId, "Terminated due to workflow design error: " + errorMessage); - LOG.info("[WorkflowFailure] PROCESS_TERMINATED: processInstanceId={}", processInstanceId); + LOG.debug("[WorkflowFailure] PROCESS_TERMINATED: processInstanceId={}", processInstanceId); } } catch (Exception e) { - LOG.error( - "[WorkflowFailure] TERMINATION_FAILED: processInstanceId={}, error={}", + LOG.warn( + "[WorkflowFailure] TERMINATION_FAILED: processInstanceId={}: {}", processInstanceId, - e.getMessage(), - e); + e.getMessage()); } } @Override public boolean isFailOnException() { - // Return true if the listener should fail the operation on an exception return false; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowHandler.java index 606a8cb5cafb..2c86c2ee7f11 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowHandler.java @@ -18,10 +18,12 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.Semaphore; import javax.sql.DataSource; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.flowable.bpmn.converter.BpmnXMLConverter; +import org.flowable.common.engine.api.FlowableException; import org.flowable.common.engine.api.FlowableObjectNotFoundException; import org.flowable.common.engine.api.FlowableWrongDbException; import org.flowable.common.engine.impl.el.DefaultExpressionManager; @@ -75,11 +77,33 @@ public class WorkflowHandler { private static final String CONNECTION_VALIDATION_QUERY = "SELECT 1"; + /** + * Message name used by the Collate Policy Agent node's await event. The batch coordinator delivers + * this message (via {@link #signalPolicyAgentResult}) to wake a parked DAR the moment its clubbed + * run's per-policy outcomes are written — push, not poll. Shared so the BPMN builder and the + * signal agree on the name. + */ + public static final String POLICY_AGENT_RESULT_MESSAGE = "policyAgentResult"; + // Validate any pooled connection idle longer than this before reuse. Kept below Flowable's // 60s reset-expired-jobs interval so the periodic async-executor threads always re-validate, // while connections in active sub-second use skip the check and pay no overhead. private static final int CONNECTION_PING_NOT_USED_FOR_MILLIS = 30000; + // Admission control for synchronous task resolutions. Flowable runs its own bounded connection + // pool; an unbounded approval burst calling taskService.complete() concurrently stampedes that + // pool — excess threads block in MyBatis popConnection past the client timeout and strand tasks + // in + // review. A fair semaphore sized BELOW the Flowable pool lets excess approvals queue efficiently + // (in-JVM, FIFO) and drain in order, so the pool is never exhausted and other workflows keep + // their + // connections. This bounds the failure mode from catastrophic pool-stampede to graceful queueing; + // it does not add capacity (a finite pool always has a ceiling) — it makes the existing capacity + // usable without the popConnection pathology. + private static final int MAX_CONCURRENT_TASK_RESOLUTIONS = 8; + private final Semaphore taskResolutionPermits = + new Semaphore(MAX_CONCURRENT_TASK_RESOLUTIONS, true); + private WorkflowHandler(OpenMetadataApplicationConfig config, boolean isMigrationContext) { this.isMigrationContext = isMigrationContext; StandaloneProcessEngineConfiguration processEngineConfiguration = @@ -824,6 +848,17 @@ private boolean resolveTaskInternal( UUID customTaskId, Map variables, boolean legacyThreadTask) { TaskService taskService = processEngine.getTaskService(); LOG.debug("[WorkflowTask] RESOLVE: customTaskId='{}' variables={}", customTaskId, variables); + // Admission control: bound how many resolutions touch Flowable at once so an approval burst + // queues here (fair FIFO) instead of stampeding the Flowable connection pool. A permit is held + // only for this resolution's Flowable work. + try { + taskResolutionPermits.acquire(); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + LOG.error( + "[WorkflowTask] Interrupted while awaiting resolution permit for '{}'", customTaskId); + return false; + } try { Optional oTask = Optional.ofNullable(getTaskFromCustomTaskId(customTaskId)); if (oTask.isPresent()) { @@ -891,6 +926,8 @@ private boolean resolveTaskInternal( LOG.error( "[WorkflowTask] ERROR: Failed to resolve task '{}': {}", customTaskId, e.getMessage(), e); return false; + } finally { + taskResolutionPermits.release(); } } @@ -1360,6 +1397,40 @@ public void terminateTaskProcessInstance(UUID customTaskId, String reason) { } } + /** + * Deliver the Policy Agent "result ready" message to a parked DAR process instance, waking its + * PolicyAgent node so it resolves immediately instead of waiting for the safety timer. No-op if the + * instance is not currently waiting on that message (already resolved, not yet parked, or the timer + * already fired) — the node re-reads the authoritative DB rows on wake, so a missed signal still + * self-corrects at the deadline. + * + *

Queries by {@code list()} (not {@code singleResult()}): the message name is shared across all + * PolicyAgent nodes, so a single instance could in principle hold more than one parked node — wake + * every matching subscription. Each delivery is isolated so one consumed/raced subscription does + * not block the others. + */ + public void signalPolicyAgentResult(String processInstanceId) { + RuntimeService runtimeService = processEngine.getRuntimeService(); + List executions = + runtimeService + .createExecutionQuery() + .processInstanceId(processInstanceId) + .messageEventSubscriptionName(POLICY_AGENT_RESULT_MESSAGE) + .list(); + for (Execution execution : executions) { + try { + runtimeService.messageEventReceived(POLICY_AGENT_RESULT_MESSAGE, execution.getId()); + } catch (FlowableException ex) { + // Subscription consumed/removed between query and delivery (timer won the race, or a + // concurrent signal): safe to ignore — the node resolves from the DB rows regardless. + LOG.debug( + "PolicyAgent result signal no-op for execution {}: {}", + execution.getId(), + ex.getMessage()); + } + } + } + private void terminateTask(RuntimeService runtimeService, Task task, UUID customTaskId) { try { String taskDefinitionKey = task.getTaskDefinitionKey(); @@ -1676,9 +1747,10 @@ public void terminateWorkflow(String workflowName) { */ public void terminateWorkflowInstance( UUID workflowInstanceId, String mainWorkflowName, String reason) { - // Mark the audit record FAILED first, then delete the Flowable process. The two are guarded - // independently so a failure in either step is logged on its own and never prevents the other. - markWorkflowInstanceFailedQuietly(workflowInstanceId, reason); + // Two steps guarded independently — a failure in one is logged on its own, never blocks the + // other. Reason string is whitelisted in WorkflowFailureListener so PROCESS_CANCELLED stays + // silent. + markWorkflowInstanceSupersededQuietly(workflowInstanceId, reason); deleteMainProcessInstanceQuietly(workflowInstanceId, mainWorkflowName, reason); } @@ -1704,7 +1776,7 @@ private void deleteMainProcessInstanceQuietly( } } - private void markWorkflowInstanceFailedQuietly(UUID workflowInstanceId, String reason) { + private void markWorkflowInstanceSupersededQuietly(UUID workflowInstanceId, String reason) { try { WorkflowInstanceStateRepository workflowInstanceStateRepository = (WorkflowInstanceStateRepository) @@ -1712,11 +1784,11 @@ private void markWorkflowInstanceFailedQuietly(UUID workflowInstanceId, String r WorkflowInstanceRepository workflowInstanceRepository = (WorkflowInstanceRepository) Entity.getEntityTimeSeriesRepository(Entity.WORKFLOW_INSTANCE); - workflowInstanceStateRepository.markInstanceStatesAsFailed(workflowInstanceId, reason); - workflowInstanceRepository.markInstanceAsFailed(workflowInstanceId, reason); + workflowInstanceStateRepository.markInstanceStatesAsSuperseded(workflowInstanceId, reason); + workflowInstanceRepository.markInstanceAsSuperseded(workflowInstanceId, reason); } catch (Exception e) { LOG.warn( - "Failed to mark superseded workflow instance {} as FAILED: {}", + "Failed to mark superseded workflow instance {} as SUPERSEDED: {}", workflowInstanceId, e.getMessage()); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowInstanceListener.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowInstanceListener.java index 158215867995..f023c3c709b5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowInstanceListener.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/WorkflowInstanceListener.java @@ -6,11 +6,15 @@ import lombok.extern.slf4j.Slf4j; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.JavaDelegate; +import org.openmetadata.schema.governance.workflows.WorkflowInstance; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.WorkflowInstanceRepository; @Slf4j public class WorkflowInstanceListener implements JavaDelegate { + + private static final String STATUS_VARIABLE_KEY = "status"; + @Override public void execute(DelegateExecution execution) { String workflowName = getProcessDefinitionKeyFromId(execution.getProcessDefinitionId()); @@ -45,44 +49,41 @@ public void execute(DelegateExecution execution) { eventName); } } catch (Exception exc) { - LOG.error( - "[WORKFLOW_INSTANCE_ERROR] Workflow: {}, ProcessInstance: {}, Event: {} - Failed to process workflow instance. Error: {}", + LOG.warn( + "[WORKFLOW_INSTANCE_ERROR] Workflow: {}, ProcessInstance: {}, Event: {}: {}", workflowName, processInstanceId, eventName, - exc.getMessage(), - exc); + exc.getMessage()); - // CRITICAL: Even on failure, we must record the state in the database if ("end".equals(eventName) && workflowInstanceRepository != null) { try { String businessKey = execution.getProcessInstanceBusinessKey(); if (businessKey != null && !businessKey.isEmpty()) { UUID workflowInstanceId = UUID.fromString(businessKey); java.util.Map errorVariables = new java.util.HashMap<>(); - errorVariables.put("status", "FAILURE"); + errorVariables.put( + STATUS_VARIABLE_KEY, WorkflowInstance.WorkflowStatus.FAILURE.value()); errorVariables.put("error", exc.getMessage()); errorVariables.put("errorClass", exc.getClass().getSimpleName()); workflowInstanceRepository.updateWorkflowInstance( workflowInstanceId, System.currentTimeMillis(), errorVariables); - LOG.warn( - "[WORKFLOW_INSTANCE_FAILED] Workflow: {}, ProcessInstance: {}, InstanceId: {} - Workflow marked as FAILED in database", + LOG.debug( + "[WORKFLOW_INSTANCE_FAILED] Workflow: {}, InstanceId: {}", workflowName, - processInstanceId, workflowInstanceId); } else { - LOG.error( - "[WORKFLOW_INSTANCE_NO_KEY] Workflow: {}, ProcessInstance: {} - Cannot update workflow status, business key is missing", + LOG.warn( + "[WORKFLOW_INSTANCE_NO_KEY] Workflow: {}, ProcessInstance: {}", workflowName, processInstanceId); } } catch (Exception updateExc) { - LOG.error( - "[WORKFLOW_INSTANCE_DB_ERROR] Workflow: {}, ProcessInstance: {} - Failed to record workflow failure in database. Error: {}", + LOG.warn( + "[WORKFLOW_INSTANCE_DB_ERROR] Workflow: {}, ProcessInstance: {}: {}", workflowName, processInstanceId, - updateExc.getMessage(), - updateExc); + updateExc.getMessage()); } } } @@ -135,32 +136,27 @@ private void updateWorkflowInstance( // Capture all variables including any failure indicators java.util.Map variables = new java.util.HashMap<>(execution.getVariables()); - // Determine final status based on what happened during execution - String status = "FINISHED"; // Default - if (Boolean.TRUE.equals(variables.get(Workflow.FAILURE_VARIABLE))) { - status = "FAILURE"; - } else if (variables.containsKey(Workflow.EXCEPTION_VARIABLE) - && variables.get(Workflow.EXCEPTION_VARIABLE) != null) { - status = "EXCEPTION"; - } - variables.put("status", status); - + WorkflowInstance.WorkflowStatus status = computeFinalStatus(variables); + variables.put(STATUS_VARIABLE_KEY, status.value()); workflowInstanceRepository.updateWorkflowInstance( workflowInstanceId, System.currentTimeMillis(), variables); + LOG.debug( + "[WORKFLOW_INSTANCE_COMPLETED] Workflow: {}, InstanceId: {}, Status: {}", + workflowDefinitionName, + workflowInstanceId, + status); + } - if ("FAILURE".equals(status) || "EXCEPTION".equals(status)) { - LOG.warn( - "[WORKFLOW_INSTANCE_COMPLETED_WITH_ERRORS] Workflow: {}, InstanceId: {}, Status: {} - Workflow completed with errors", - workflowDefinitionName, - workflowInstanceId, - status); - } else { - LOG.debug( - "[WORKFLOW_INSTANCE_COMPLETED] Workflow: {}, InstanceId: {}, Status: {} - Workflow completed successfully", - workflowDefinitionName, - workflowInstanceId, - status); + private WorkflowInstance.WorkflowStatus computeFinalStatus( + java.util.Map variables) { + WorkflowInstance.WorkflowStatus status = WorkflowInstance.WorkflowStatus.FINISHED; + if (Boolean.TRUE.equals(variables.get(Workflow.FAILURE_VARIABLE))) { + status = WorkflowInstance.WorkflowStatus.FAILURE; + } else if (variables.containsKey(Workflow.EXCEPTION_VARIABLE) + && variables.get(Workflow.EXCEPTION_VARIABLE) != null) { + status = WorkflowInstance.WorkflowStatus.EXCEPTION; } + return status; } private String getMainWorkflowDefinitionNameFromTrigger(String triggerWorkflowDefinitionName) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/NodeFactory.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/NodeFactory.java index 04804bf31d25..d4d4d97b0c19 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/NodeFactory.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/NodeFactory.java @@ -87,6 +87,16 @@ public static NodeInterface createNode( () -> new IllegalStateException( "policyAgentTask is a Collate-only feature — handler not registered")); + case CREATE_AND_RUN_AI_AUTOMATION_TASK -> NodeFactoryRegistry.getInstance() + .create( + NodeSubType.CREATE_AND_RUN_AI_AUTOMATION_TASK, + nodeDefinition, + config, + workflowDefinitionName) + .orElseThrow( + () -> + new IllegalStateException( + "createAndRunAIAutomationTask is a Collate-only feature — handler not registered")); default -> throw new IllegalArgumentException( "Unsupported node subtype: " + nodeDefinition.getSubType()); }; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/automatedTask/runApp/RunAppImpl.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/automatedTask/runApp/RunAppImpl.java index 76d5a1e78e06..d2b3d8222894 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/automatedTask/runApp/RunAppImpl.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/automatedTask/runApp/RunAppImpl.java @@ -20,7 +20,6 @@ import org.openmetadata.schema.entity.applications.configuration.internal.CostAnalysisConfig; import org.openmetadata.schema.entity.applications.configuration.internal.DataAssetsConfig; import org.openmetadata.schema.entity.applications.configuration.internal.DataInsightsAppConfig; -import org.openmetadata.schema.entity.applications.configuration.internal.DataQualityConfig; import org.openmetadata.schema.entity.applications.configuration.internal.ModuleConfiguration; import org.openmetadata.schema.entity.applications.configuration.internal.ServiceFilter; import org.openmetadata.schema.entity.services.ingestionPipelines.IngestionPipeline; @@ -134,7 +133,6 @@ private Map getConfig(App app, ServiceEntityInterface service) { .getModuleConfiguration() .withAppAnalytics(new AppAnalyticsConfig().withEnabled(false)) .withCostAnalysis(new CostAnalysisConfig().withEnabled(false)) - .withDataQuality(new DataQualityConfig().withEnabled(false)) .withDataAssets( new DataAssetsConfig() .withRetention( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java index 2ca98ea42746..eb5293fe67d0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java @@ -17,14 +17,13 @@ import static org.openmetadata.service.governance.workflows.Workflow.GLOBAL_NAMESPACE; import static org.openmetadata.service.governance.workflows.Workflow.RECOGNIZER_FEEDBACK; import static org.openmetadata.service.governance.workflows.Workflow.RELATED_ENTITY_VARIABLE; +import static org.openmetadata.service.governance.workflows.Workflow.SUPERSEDED_BY_NEWER_RUN; import static org.openmetadata.service.governance.workflows.Workflow.WORKFLOW_RUNTIME_EXCEPTION; import static org.openmetadata.service.governance.workflows.WorkflowHandler.getProcessDefinitionKeyFromId; import io.github.resilience4j.core.IntervalFunction; import io.github.resilience4j.retry.Retry; import io.github.resilience4j.retry.RetryConfig; -import java.time.Duration; -import java.time.Period; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeParseException; @@ -50,6 +49,7 @@ import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.governance.workflows.WorkflowDefinition; import org.openmetadata.schema.type.ChangeEvent; +import org.openmetadata.schema.type.DataAccessRequestPayload; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EventType; import org.openmetadata.schema.type.Include; @@ -75,6 +75,7 @@ import org.openmetadata.service.resources.feeds.MessageParser; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver; import org.openmetadata.service.util.AsyncService; +import org.openmetadata.service.util.DurationUtil; import org.openmetadata.service.util.WebsocketNotificationHandler; /** @@ -91,8 +92,6 @@ public class CreateTask implements TaskListener { static final String PENDING_WORKFLOW_START_STAGE_ID = "pending-workflow-start"; private static final String DEFAULT_SYSTEM_USER = "admin"; - private static final String SUPERSEDED_BY_NEWER_RUN = - "Superseded by a newer approval workflow run for the same entity"; private static final int WORKFLOW_MANAGED_DRAFT_LOOKUP_MAX_ATTEMPTS = 6; private static final long INITIAL_WORKFLOW_MANAGED_DRAFT_LOOKUP_DELAY_MILLIS = 25L; private static final long MAX_WORKFLOW_MANAGED_DRAFT_LOOKUP_DELAY_MILLIS = 250L; @@ -386,6 +385,7 @@ private Task createOrUpdateTask( WorkflowVariableResolver.stringVariable(delegateTask, "taskDisplayName"); String taskDescription = WorkflowVariableResolver.stringVariable(delegateTask, "taskDescription"); + String manualGrantReason = resolveManualGrantReason(delegateTask); TaskPriority requestedPriority = resolveTaskPriority(delegateTask); Object requestedPayload = WorkflowVariableResolver.workflowObjectVariable(delegateTask, "taskPayload"); @@ -529,6 +529,7 @@ private Task createOrUpdateTask( updatedTask.setDueDate(effectiveDueDate); } updatedTask.setPayload(withGrantExpirationDate(stageStatus, updatedTask.getPayload())); + updatedTask.setPayload(mergeManualGrantReason(updatedTask.getPayload(), manualGrantReason)); updatedTask.setPayload( applyProposedChangesIfApproval(taskType, entity, updatedTask.getPayload())); if (requestedExternalReference != null) { @@ -598,6 +599,7 @@ private Task createOrUpdateTask( task.setDueDate(effectiveDueDate); } task.setPayload(withGrantExpirationDate(stageStatus, task.getPayload())); + task.setPayload(mergeManualGrantReason(task.getPayload(), manualGrantReason)); task.setPayload(applyProposedChangesIfApproval(taskType, entity, task.getPayload())); if (requestedExternalReference != null) { task.setExternalReference( @@ -970,22 +972,19 @@ static Object applyProposedChangesIfApproval( } static Long parseMillisFromIso8601Duration(String duration, Long fallback) { + Long millis = fallback; try { - return System.currentTimeMillis() + Duration.parse(duration).toMillis(); - } catch (DateTimeParseException ignored) { - // Duration.parse does not support month/year designators; try Period - } - try { - return ZonedDateTime.now(ZoneOffset.UTC) - .plus(Period.parse(duration)) - .toInstant() - .toEpochMilli(); - } catch (DateTimeParseException e) { + millis = + ZonedDateTime.now(ZoneOffset.UTC) + .plus(DurationUtil.parseIso8601(duration)) + .toInstant() + .toEpochMilli(); + } catch (DateTimeParseException invalid) { LOG.warn( "[CreateTask] Could not parse ISO-8601 duration '{}'; falling back to caller default", duration); - return fallback; } + return millis; } private TaskPriority resolveTaskPriority(DelegateTask delegateTask) { @@ -1000,6 +999,47 @@ private String buildTaskDescription(EntityInterface entity, TaskEntityType taskT return String.format("Approval required for %s", entity.getName()); } + /** + * Optional, workflow-supplied reason (only the Policy Agent DAR path sets it). Wrapped so a + * problem reading or typing it can never break task creation for the generic approval workflows + * (Glossary, etc.) that never set it — for those it returns null and {@link #mergeManualGrantReason} + * is a no-op. + */ + private static String resolveManualGrantReason(DelegateTask delegateTask) { + try { + Object reason = + new WorkflowVariableHandler(delegateTask) + .getNamespacedVariable(GLOBAL_NAMESPACE, "manualGrantReason"); + // Flowable process variables are untyped Object; the DAR path sets this as a String. Any + // other + // shape (or an unset variable → null) means "no reason", so mergeManualGrantReason no-ops. + return reason instanceof String s ? s : null; + } catch (Exception e) { + // Missing variable already returns null above; only a real lookup error reaches here. + LOG.debug("[CreateTask] Could not resolve manualGrantReason: {}", e.getMessage()); + return null; + } + } + + /** + * Attach a workflow-supplied reason (only the Policy Agent DAR path sets it) to the task payload + * as {@code manualGrantReason} — its own structured field, so the UI renders it separately from + * the description. Returns the payload unchanged for tasks/workflows that don't set one. + */ + static Object mergeManualGrantReason(Object payload, String reason) { + Object result = payload; + if (reason != null && !reason.isBlank()) { + // manualGrantReason is only ever set on the DAR path, so the payload is a + // DataAccessRequestPayload — bind the typed POJO and set the field instead of hand-merging a + // raw Map. JsonUtils ignores unknown properties, so the round-trip preserves every field. A + // null payload (convertValue returns null) yields a fresh payload carrying only the reason. + DataAccessRequestPayload dar = + JsonUtils.convertValue(payload, DataAccessRequestPayload.class); + result = (dar != null ? dar : new DataAccessRequestPayload()).withManualGrantReason(reason); + } + return result; + } + private EntityReference resolveCreatedByReference( EntityReference requestedCreatedBy, EntityInterface entity, Object payload) { if (requestedCreatedBy != null && requestedCreatedBy.getId() != null) { @@ -1127,6 +1167,7 @@ private void terminateDeletedWorkflowManagedDraftTask( "[CreateTask] Draft task '{}' was deleted before materialization; deleting workflow instance '{}'", requestedTaskId, processInstanceId); + // Reason string matches WorkflowFailureListener's "Workflow-managed draft task " prefix. runtimeService.deleteProcessInstance(processInstanceId, terminationReason); } catch (FlowableObjectNotFoundException e) { LOG.debug( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIAssetStatusSync.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIAssetStatusSync.java index 77aa48e7d22d..47b97ee5fe7f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIAssetStatusSync.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIAssetStatusSync.java @@ -12,6 +12,8 @@ */ package org.openmetadata.service.jdbi3; +import java.util.function.Consumer; +import java.util.function.Supplier; import org.openmetadata.schema.entity.ai.AIApplication; import org.openmetadata.schema.entity.ai.GovernanceMetadata; import org.openmetadata.schema.entity.ai.LLMModel; @@ -26,12 +28,19 @@ * Governance dashboard reads. * *

Forward: when the workflow (or the intake resource) moves {@code entityStatus} - * to an approval-flow state, the registration status is updated to match. + * to an approval-flow state, the registration status is updated to match. On an + * {@code Approved} transition the approver ({@code approvedBy}/{@code approvedAt}) is + * stamped from {@code updatedBy} when not already set, so workflow-driven approvals + * record who approved just like the REST {@code approve()} path. * Reverse: when {@code entityStatus} is unset (existing or freshly seeded assets), * it is derived from the registration status so the asset converges to a consistent * state on its next save without a separate backfill migration. Shadow AI * ({@code Unregistered}) and {@code Registered} assets are left untouched in both * directions. + * + *

{@code Draft}, {@code Deprecated}, and {@code Archived} are lifecycle states that + * sit outside the registration approval flow — they have no registration-status + * equivalent and are intentionally left untouched in both directions. */ final class AIAssetStatusSync { private static final String STATUS_PENDING_APPROVAL = "PendingApproval"; @@ -44,9 +53,15 @@ private AIAssetStatusSync() {} static void sync(AIApplication app) { EntityStatus status = app.getEntityStatus(); if (isApprovalStatus(status)) { - governanceMetadata(app) - .setRegistrationStatus( - GovernanceMetadata.RegistrationStatus.fromValue(registrationFor(status))); + GovernanceMetadata governance = governanceMetadata(app); + governance.setRegistrationStatus( + GovernanceMetadata.RegistrationStatus.fromValue(registrationFor(status))); + stampApprover( + status, + app.getUpdatedBy(), + governance::getApprovedBy, + governance::setApprovedBy, + governance::setApprovedAt); } else if (isUnset(status)) { EntityStatus derived = entityStatusFor(registrationOf(app)); if (derived != null) { @@ -58,9 +73,15 @@ static void sync(AIApplication app) { static void sync(McpServer server) { EntityStatus status = server.getEntityStatus(); if (isApprovalStatus(status)) { - governanceMetadata(server) - .setRegistrationStatus( - McpGovernanceMetadata.RegistrationStatus.fromValue(registrationFor(status))); + McpGovernanceMetadata governance = governanceMetadata(server); + governance.setRegistrationStatus( + McpGovernanceMetadata.RegistrationStatus.fromValue(registrationFor(status))); + stampApprover( + status, + server.getUpdatedBy(), + governance::getApprovedBy, + governance::setApprovedBy, + governance::setApprovedAt); } else if (isUnset(status)) { EntityStatus derived = entityStatusFor(registrationOf(server)); if (derived != null) { @@ -91,6 +112,23 @@ private static boolean isUnset(EntityStatus status) { return status == null || status == EntityStatus.UNPROCESSED; } + /** + * Stamps the approver on an {@code Approved} transition when not already set. The two AI + * governance-metadata POJOs share no supertype, so callers pass method references to their + * respective approver getter/setters rather than the metadata object itself. + */ + private static void stampApprover( + EntityStatus status, + String updatedBy, + Supplier currentApprovedBy, + Consumer setApprovedBy, + Consumer setApprovedAt) { + if (status == EntityStatus.APPROVED && currentApprovedBy.get() == null && updatedBy != null) { + setApprovedBy.accept(updatedBy); + setApprovedAt.accept(System.currentTimeMillis()); + } + } + private static String registrationFor(EntityStatus status) { String result; switch (status) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIGovernanceFrameworkRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIGovernanceFrameworkRepository.java index 4a0e80b213b2..91a8255df887 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIGovernanceFrameworkRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AIGovernanceFrameworkRepository.java @@ -12,11 +12,24 @@ */ package org.openmetadata.service.jdbi3; +import jakarta.ws.rs.core.UriInfo; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.api.ai.CopiedAIFrameworkControl; +import org.openmetadata.schema.api.ai.ForkAIGovernanceFrameworkRequest; +import org.openmetadata.schema.api.ai.ForkAIGovernanceFrameworkResponse; +import org.openmetadata.schema.api.ai.FrameworkCoverageResponse; +import org.openmetadata.schema.entity.ai.AIFrameworkControl; import org.openmetadata.schema.entity.ai.AIGovernanceFramework; +import org.openmetadata.schema.entity.ai.FrameworkSource; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.change.ChangeSource; +import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.resources.ai.AIGovernanceFrameworkResource; +import org.openmetadata.service.resources.ai.FrameworkCoverageComputer; import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.EntityUtil.RelationIncludes; @@ -24,6 +37,7 @@ @Repository public class AIGovernanceFrameworkRepository extends EntityRepository { private static final String FIELDS = "stewards,autoApply"; + private static final int CONTROL_PAGE_SIZE = 1000; public AIGovernanceFrameworkRepository() { super( @@ -62,6 +76,101 @@ public void storeRelationships(AIGovernanceFramework framework) { // Relationships stored as part of the JSON } + public FrameworkCoverageResponse getCoverage(UriInfo uriInfo, AIGovernanceFramework framework) { + AIFrameworkControlRepository controlRepo = controlRepository(); + ListFilter filter = new ListFilter(Include.NON_DELETED); + List allControls = listControls(uriInfo, controlRepo, "", filter); + String frameworkName = framework.getName(); + List controls = new ArrayList<>(); + for (AIFrameworkControl control : allControls) { + if (control.getFramework() != null + && frameworkName.equals(control.getFramework().getName())) { + controls.add(control); + } + } + + return FrameworkCoverageComputer.compute(framework, controls); + } + + public ForkAIGovernanceFrameworkResponse fork( + UriInfo uriInfo, + AIGovernanceFramework source, + ForkAIGovernanceFrameworkRequest request, + String user) { + AIGovernanceFramework created = + create(uriInfo, forkedFramework(source, request, user), user, null); + AIFrameworkControlRepository controlRepo = controlRepository(); + ListFilter controlFilter = new ListFilter(Include.NON_DELETED); + if (source.getFullyQualifiedName() != null) { + controlFilter.addQueryParam("framework", source.getFullyQualifiedName()); + } + + List copiedControls = new ArrayList<>(); + long now = System.currentTimeMillis(); + for (AIFrameworkControl control : listControls(uriInfo, controlRepo, FIELDS, controlFilter)) { + control.setId(UUID.randomUUID()); + control.setFullyQualifiedName(null); + control.setVersion(null); + control.setFramework(created.getEntityReference()); + control.setUpdatedAt(now); + control.setUpdatedBy(user); + controlRepo.create(uriInfo, control, user, null); + copiedControls.add( + new CopiedAIFrameworkControl().withCode(control.getCode()).withName(control.getName())); + } + + return new ForkAIGovernanceFrameworkResponse() + .withFramework(created) + .withCopiedControlsCount(copiedControls.size()) + .withCopiedControls(copiedControls); + } + + private AIGovernanceFramework forkedFramework( + AIGovernanceFramework source, ForkAIGovernanceFrameworkRequest request, String user) { + String newName = + request != null && request.getName() != null && !request.getName().isBlank() + ? request.getName() + : source.getName() + "_fork"; + AIGovernanceFramework copy = new AIGovernanceFramework(); + copy.setId(UUID.randomUUID()); + copy.setName(newName); + copy.setDisplayName( + request != null && request.getDisplayName() != null + ? request.getDisplayName() + : "Fork of " + + (source.getDisplayName() == null ? source.getName() : source.getDisplayName())); + copy.setDescription(source.getDescription()); + copy.setReference(source.getReference()); + copy.setRegion(source.getRegion()); + copy.setSource(FrameworkSource.ForkedFrom); + copy.setForkedFrom(source.getEntityReference()); + copy.setEnabled(false); + copy.setAssessmentCadence(source.getAssessmentCadence()); + copy.setAutoApply(source.getAutoApply()); + copy.setUpdatedAt(System.currentTimeMillis()); + copy.setUpdatedBy(user); + return copy; + } + + private List listControls( + UriInfo uriInfo, AIFrameworkControlRepository controlRepo, String fields, ListFilter filter) { + List result = new ArrayList<>(); + String after = null; + do { + ResultList page = + controlRepo.listAfter( + uriInfo, controlRepo.getFields(fields), filter, CONTROL_PAGE_SIZE, after); + result.addAll(page.getData()); + after = page.getPaging() == null ? null : page.getPaging().getAfter(); + } while (after != null); + + return result; + } + + private static AIFrameworkControlRepository controlRepository() { + return (AIFrameworkControlRepository) Entity.getEntityRepository(Entity.AI_FRAMEWORK_CONTROL); + } + @Override public EntityRepository.EntityUpdater getUpdater( AIGovernanceFramework original, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AuditReportRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AuditReportRepository.java index c709ee39c98e..ecb7ab376cfc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AuditReportRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AuditReportRepository.java @@ -87,6 +87,9 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { () -> recordChange( "failureReason", original.getFailureReason(), updated.getFailureReason())); + compareAndUpdate( + "runningOn", + () -> recordChange("runningOn", original.getRunningOn(), updated.getRunningOn())); compareAndUpdate( "artifacts", () -> recordChange("artifacts", original.getArtifacts(), updated.getArtifacts(), true)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeEventRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeEventRepository.java index ab0bf73282e5..36ff0d8a655a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeEventRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeEventRepository.java @@ -20,11 +20,14 @@ import static org.openmetadata.schema.type.EventType.ENTITY_UPDATED; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import org.jdbi.v3.sqlobject.transaction.Transaction; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO.ChangeEventDAO.ChangeEventRecord; @Repository public class ChangeEventRepository { @@ -35,24 +38,52 @@ public ChangeEventRepository() { Entity.setChangeEventRepository(this); } - public List list( + public ResultList list( long timestamp, + long endTs, List entityCreatedList, List entityUpdatedList, List entityRestoredList, - List entityDeletedList) { - List jsons = new ArrayList<>(); - jsons.addAll(dao.list(ENTITY_CREATED, entityCreatedList, timestamp)); - jsons.addAll(dao.list(ENTITY_UPDATED, entityUpdatedList, timestamp)); - jsons.addAll(dao.list(ENTITY_RESTORED, entityRestoredList, timestamp)); - jsons.addAll(dao.list(ENTITY_DELETED, entityDeletedList, timestamp)); - jsons.addAll(dao.list(ENTITY_SOFT_DELETED, entityDeletedList, timestamp)); + List entityDeletedList, + long afterOffset, + int limit) { + int fetchLimit = limit + 1; + List records = new ArrayList<>(); + records.addAll( + dao.listAfter( + ENTITY_CREATED, entityCreatedList, timestamp, endTs, afterOffset, fetchLimit)); + records.addAll( + dao.listAfter( + ENTITY_UPDATED, entityUpdatedList, timestamp, endTs, afterOffset, fetchLimit)); + records.addAll( + dao.listAfter( + ENTITY_RESTORED, entityRestoredList, timestamp, endTs, afterOffset, fetchLimit)); + records.addAll( + dao.listAfter( + ENTITY_DELETED, entityDeletedList, timestamp, endTs, afterOffset, fetchLimit)); + records.addAll( + dao.listAfter( + ENTITY_SOFT_DELETED, entityDeletedList, timestamp, endTs, afterOffset, fetchLimit)); - List changeEvents = new ArrayList<>(); - for (String json : jsons) { - changeEvents.add(JsonUtils.readValue(json, ChangeEvent.class)); + Page page = mergePage(records, limit); + List events = new ArrayList<>(); + for (ChangeEventRecord record : page.records()) { + events.add(JsonUtils.readValue(record.json(), ChangeEvent.class)); } - return changeEvents; + return new ResultList<>(events, null, page.afterCursor(), events.size()); + } + + record Page(List records, String afterCursor) {} + + // Sort merged pages by offset, keep the first `limit`, cursor = last kept offset (raw; ResultList + // base64-encodes it into paging.after). + static Page mergePage(List records, int limit) { + records.sort(Comparator.comparingLong(ChangeEventRecord::offset)); + boolean hasMore = records.size() > limit; + List page = hasMore ? new ArrayList<>(records.subList(0, limit)) : records; + String afterCursor = + hasMore && !page.isEmpty() ? String.valueOf(page.getLast().offset()) : null; + return new Page(page, afterCursor); } @Transaction diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeSummarizer.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeSummarizer.java index 40f32f731d2c..5d0dabaef73e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeSummarizer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ChangeSummarizer.java @@ -72,53 +72,55 @@ private boolean hasField(Class clazz, String fieldName) { } /** - * Given a list of fields that were deleted, process the fields and return the set of keys to delete + * Given a list of fields that were deleted, return the change-summary keys to remove. A key is + * removed when either the tracked field itself was deleted (for example clearing a single + * column's description) or when a parent list holding tracked fields was deleted (for example + * removing a whole column). The keys mirror the ones produced by {@link #summarizeChanges}, which + * uses the raw {@link FieldChange#getName()} as the map key. */ public Set processDeleted(List fieldsDeleted) { + Set keysToDelete = new HashSet<>(directlyDeletedKeys(fieldsDeleted)); + keysToDelete.addAll(nestedListDeletedKeys(fieldsDeleted)); + return keysToDelete; + } + + private Set directlyDeletedKeys(List fieldsDeleted) { + return fieldsDeleted.stream() + .map(FieldChange::getName) + .filter(this::isFieldTracked) + .collect(Collectors.toSet()); + } + + private Set nestedListDeletedKeys(List fieldsDeleted) { Set keysToDelete = new HashSet<>(); for (String field : fields) { - // process top level fields - List topLevel = - fieldsDeleted.stream() - .filter(fieldChange -> fieldChange.getName().equals(field)) - .map( - fieldChange -> - FullyQualifiedName.build( - fieldChange.getName(), (String) fieldChange.getOldValue())) - .toList(); - if (!topLevel.isEmpty()) { - keysToDelete.addAll(topLevel); - continue; - } - - // process nested fields - Set nestedFields = + Set deletedParentLists = fieldsDeleted.stream() .filter(fieldChange -> field.startsWith(fieldChange.getName() + ".")) + .filter(fieldChange -> isListField(clazz, fieldChange.getName())) .collect(Collectors.toSet()); - - for (FieldChange fieldChange : nestedFields) { - if (!isListField(clazz, fieldChange.getName())) { - continue; - } - - try { - String nestedField = field.substring(fieldChange.getName().length() + 1); - JsonUtils.readObjects((String) fieldChange.getOldValue(), Map.class).stream() - .map(map -> (Map) map) - .map(map -> (String) map.get("name")) - .forEach( - name -> - keysToDelete.add( - FullyQualifiedName.build(fieldChange.getName(), name, nestedField))); - } catch (JsonParsingException e) { - LOG.warn("Error processing deleted fields", e); - } + for (FieldChange fieldChange : deletedParentLists) { + keysToDelete.addAll(expandListItemKeys(field, fieldChange)); } } return keysToDelete; } + private Set expandListItemKeys(String trackedField, FieldChange deletedList) { + Set keys = new HashSet<>(); + try { + String nestedField = trackedField.substring(deletedList.getName().length() + 1); + JsonUtils.readObjects((String) deletedList.getOldValue(), Map.class).stream() + .map(map -> (Map) map) + .map(map -> (String) map.get("name")) + .forEach( + name -> keys.add(FullyQualifiedName.build(deletedList.getName(), name, nestedField))); + } catch (JsonParsingException e) { + LOG.warn("Error processing deleted fields", e); + } + return keys; + } + private boolean matchesTrackedField(String trackedField, String fieldName) { if (trackedField.equals(fieldName)) { return true; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index 67c5a80f1250..f552bbd9eac7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -84,7 +84,6 @@ import org.openmetadata.schema.auth.RefreshToken; import org.openmetadata.schema.auth.TokenType; import org.openmetadata.schema.auth.collate.SupportToken; -import org.openmetadata.schema.configuration.AISettings; import org.openmetadata.schema.configuration.AssetCertificationSettings; import org.openmetadata.schema.configuration.EntityRulesSettings; import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; @@ -203,12 +202,6 @@ import org.slf4j.LoggerFactory; public interface CollectionDAO { - @CreateSqlObject - McpConversationDAO mcpConversationDAO(); - - @CreateSqlObject - McpMessageDAO mcpMessageDAO(); - @CreateSqlObject DatabaseDAO databaseDAO(); @@ -840,16 +833,20 @@ private static java.util.Map rootListingParams(ListFilter filter // .%.%` and reject those rows. ListFilter.getFqnPrefixCondition binds // both `:serviceHash` (already used by the prefix LIKE in ) and // `:serviceHashChild` (the `.%.%` companion) so the SQL just plugs them in. + // Deferred join: resolve the page index-only on (name, id) in the derived table, then fetch + // c.json by primary key for only the paged rows, so the json blob never enters the filesort. @SqlQuery( value = - "SELECT json FROM (" - + "SELECT name, id, ce.json FROM ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + " AND " + "ce.fqnHash NOT LIKE :serviceHashChild AND " + "(name < :beforeName OR (name = :beforeName AND id < :beforeId)) " + "ORDER BY name DESC, id DESC " + "LIMIT :limit" - + ") last_rows_subquery ORDER BY name, id") + + ") last_rows_subquery ON c.id = last_rows_subquery.id " + + "ORDER BY c.name, c.id") List listRootBefore( @Define("table") String table, @BindMap Map params, @@ -860,12 +857,16 @@ List listRootBefore( @SqlQuery( value = - "SELECT ce.json FROM
ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + " AND " + "ce.fqnHash NOT LIKE :serviceHashChild AND " + "(name > :afterName OR (name = :afterName AND id > :afterId)) " + "ORDER BY name, id " - + "LIMIT :limit") + + "LIMIT :limit" + + ") next_rows_subquery ON c.id = next_rows_subquery.id " + + "ORDER BY c.name, c.id") List listRootAfter( @Define("table") String table, @BindMap Map params, @@ -1194,8 +1195,9 @@ default int listCount(ListFilter filter) { @SqlQuery( value = - "SELECT json FROM (" - + "SELECT name,id, ce.json FROM
ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + "LEFT JOIN (" + " SELECT toId FROM entity_relationship " + " WHERE fromEntity = 'directory' AND toEntity = 'directory' AND relation = 0 " @@ -1205,7 +1207,7 @@ default int listCount(ListFilter filter) { + "(name < :beforeName OR (name = :beforeName AND id < :beforeId)) " + "ORDER BY name DESC,id DESC " + "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id") + + ") last_rows_subquery ON c.id = last_rows_subquery.id ORDER BY c.name,c.id") List listBefore( @Define("table") String table, @BindMap Map params, @@ -1216,7 +1218,9 @@ List listBefore( @SqlQuery( value = - "SELECT ce.json FROM
ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + "LEFT JOIN (" + " SELECT toId FROM entity_relationship " + " WHERE fromEntity = 'directory' AND toEntity = 'directory' AND relation = 0 " @@ -1225,7 +1229,8 @@ List listBefore( + " AND " + "(name > :afterName OR (name = :afterName AND id > :afterId)) " + "ORDER BY name,id " - + "LIMIT :limit") + + "LIMIT :limit" + + ") next_rows_subquery ON c.id = next_rows_subquery.id ORDER BY c.name,c.id") List listAfter( @Define("table") String table, @BindMap Map params, @@ -1315,8 +1320,9 @@ default int listCount(ListFilter filter) { @SqlQuery( value = - "SELECT json FROM (" - + "SELECT name,id, ce.json FROM
ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + "LEFT JOIN (" + " SELECT toId FROM entity_relationship " + " WHERE fromEntity IN ('directory', 'spreadsheet') AND toEntity = 'file' AND relation = 0 " @@ -1326,7 +1332,7 @@ default int listCount(ListFilter filter) { + "(name < :beforeName OR (name = :beforeName AND id < :beforeId)) " + "ORDER BY name DESC,id DESC " + "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id") + + ") last_rows_subquery ON c.id = last_rows_subquery.id ORDER BY c.name,c.id") List listBefore( @Define("table") String table, @BindMap Map params, @@ -1337,7 +1343,9 @@ List listBefore( @SqlQuery( value = - "SELECT ce.json FROM
ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + "LEFT JOIN (" + " SELECT toId FROM entity_relationship " + " WHERE fromEntity IN ('directory', 'spreadsheet') AND toEntity = 'file' AND relation = 0 " @@ -1346,7 +1354,8 @@ List listBefore( + " AND " + "(name > :afterName OR (name = :afterName AND id > :afterId)) " + "ORDER BY name,id " - + "LIMIT :limit") + + "LIMIT :limit" + + ") next_rows_subquery ON c.id = next_rows_subquery.id ORDER BY c.name,c.id") List listAfter( @Define("table") String table, @BindMap Map params, @@ -1436,8 +1445,9 @@ default int listCount(ListFilter filter) { @SqlQuery( value = - "SELECT json FROM (" - + "SELECT name,id, ce.json FROM
ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + "LEFT JOIN (" + " SELECT toId FROM entity_relationship " + " WHERE fromEntity = 'directory' AND toEntity = 'spreadsheet' AND relation = 0 " @@ -1447,7 +1457,7 @@ default int listCount(ListFilter filter) { + "(name < :beforeName OR (name = :beforeName AND id < :beforeId)) " + "ORDER BY name DESC,id DESC " + "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id") + + ") last_rows_subquery ON c.id = last_rows_subquery.id ORDER BY c.name,c.id") List listBefore( @Define("table") String table, @BindMap Map params, @@ -1458,7 +1468,9 @@ List listBefore( @SqlQuery( value = - "SELECT ce.json FROM
ce " + "SELECT c.json FROM
c " + + "INNER JOIN (" + + "SELECT ce.id FROM
ce " + "LEFT JOIN (" + " SELECT toId FROM entity_relationship " + " WHERE fromEntity = 'directory' AND toEntity = 'spreadsheet' AND relation = 0 " @@ -1467,7 +1479,8 @@ List listBefore( + " AND " + "(name > :afterName OR (name = :afterName AND id > :afterId)) " + "ORDER BY name,id " - + "LIMIT :limit") + + "LIMIT :limit" + + ") next_rows_subquery ON c.id = next_rows_subquery.id ORDER BY c.name,c.id") List listAfter( @Define("table") String table, @BindMap Map params, @@ -4638,19 +4651,40 @@ List listIdAndFqnByCreatorAndCategory( @RegisterRowMapper(TaskCountSummaryMapper.class) @SqlQuery( - // 'Approved' double-counts in `completedCount` AND `approvedCount` because the - // same status means different things across task types: terminal for - // Glossary/DescriptionUpdate (legacy dashboards expect it under "completed") and - // non-terminal for Data Access Requests (the dedicated DAR list uses - // `approvedCount` / `grantedCount` and the `active` status group instead). - // See ListFilter.getTaskStatusCondition for the matching status-group semantics. + // Row-aware bucketing so openCount + completedCount = total across mixed task types. + // Bucket predicates and status/type literals are shared with ListFilter via + // TaskBucketSql — see that class for the invariant + drift-guard test. "SELECT " + "COUNT(id) AS total, " - + "COALESCE(SUM(CASE WHEN status IN ('Open', 'InProgress', 'Pending') THEN 1 ELSE 0 END), 0) AS openCount, " - + "COALESCE(SUM(CASE WHEN status IN ('Approved', 'Rejected', 'Completed', 'Cancelled', 'Failed', 'Revoked') THEN 1 ELSE 0 END), 0) AS completedCount, " - + "COALESCE(SUM(CASE WHEN status = 'InProgress' THEN 1 ELSE 0 END), 0) AS inProgressCount, " - + "COALESCE(SUM(CASE WHEN status = 'Approved' THEN 1 ELSE 0 END), 0) AS approvedCount, " - + "COALESCE(SUM(CASE WHEN status = 'Granted' THEN 1 ELSE 0 END), 0) AS grantedCount " + + "COALESCE(SUM(CASE" + + " WHEN status IN (" + + TaskBucketSql.SHARED_OPEN_STATUSES + + ") THEN 1" + + " WHEN type = '" + + TaskBucketSql.TASK_TYPE_DAR + + "' AND status = '" + + TaskBucketSql.STATUS_APPROVED + + "' THEN 1" + + " ELSE 0 END), 0) AS openCount, " + + "COALESCE(SUM(CASE" + + " WHEN status IN (" + + TaskBucketSql.SHARED_TERMINAL_STATUSES + + ") THEN 1" + + " WHEN type <> '" + + TaskBucketSql.TASK_TYPE_DAR + + "' AND status = '" + + TaskBucketSql.STATUS_APPROVED + + "' THEN 1" + + " ELSE 0 END), 0) AS completedCount, " + + "COALESCE(SUM(CASE WHEN status = '" + + TaskBucketSql.STATUS_IN_PROGRESS + + "' THEN 1 ELSE 0 END), 0) AS inProgressCount, " + + "COALESCE(SUM(CASE WHEN status = '" + + TaskBucketSql.STATUS_APPROVED + + "' THEN 1 ELSE 0 END), 0) AS approvedCount, " + + "COALESCE(SUM(CASE WHEN status = '" + + TaskBucketSql.STATUS_GRANTED + + "' THEN 1 ELSE 0 END), 0) AS grantedCount " + "FROM task_entity ") TaskCountSummary getTaskCountSummary( @Define("condition") String condition, @BindMap Map params); @@ -8716,31 +8750,76 @@ default void insertBatch(List jsons) { @SqlUpdate("DELETE FROM change_event WHERE entityType = :entityType") void deleteAll(@Bind("entityType") String entityType); - default List list(EventType eventType, List entityTypes, long timestamp) { + default List listAfter( + EventType eventType, + List entityTypes, + long timestamp, + long endTs, + long afterOffset, + int limit) { + List result; if (nullOrEmpty(entityTypes)) { - return Collections.emptyList(); - } - if (entityTypes.get(0).equals("*")) { - return listWithoutEntityFilter(eventType.value(), timestamp); + result = Collections.emptyList(); + } else if (entityTypes.getFirst().equals("*")) { + result = + listAfterWithoutEntityFilter(eventType.value(), timestamp, endTs, afterOffset, limit); + } else { + result = + listAfterWithEntityFilter( + eventType.value(), entityTypes, timestamp, endTs, afterOffset, limit); } - return listWithEntityFilter(eventType.value(), entityTypes, timestamp); + return result; } - @SqlQuery( - "SELECT json FROM change_event WHERE " - + "eventType = :eventType AND (entityType IN ()) AND eventTime >= :timestamp " - + "ORDER BY eventTime ASC") - List listWithEntityFilter( + // Deferred join: sort/limit on `offset` only, fetch json by PK — keeps the json blob out of + // MySQL's filesort (else ER_OUT_OF_SORTMEMORY on wide rows). Caller re-sorts; no outer ORDER + // BY. + @ConnectionAwareSqlQuery( + value = + "SELECT c.`offset` AS offset, c.json AS json FROM change_event c INNER JOIN (" + + "SELECT `offset` FROM change_event WHERE eventType = :eventType " + + "AND entityType IN () AND eventTime >= :timestamp AND eventTime <= :endTs " + + "AND `offset` > :afterOffset ORDER BY `offset` ASC LIMIT :limit) k " + + "ON c.`offset` = k.`offset`", + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = + "SELECT c.\"offset\" AS offset, c.json AS json FROM change_event c INNER JOIN (" + + "SELECT \"offset\" FROM change_event WHERE eventType = :eventType " + + "AND entityType IN () AND eventTime >= :timestamp AND eventTime <= :endTs " + + "AND \"offset\" > :afterOffset ORDER BY \"offset\" ASC LIMIT :limit) k " + + "ON c.\"offset\" = k.\"offset\"", + connectionType = POSTGRES) + @RegisterRowMapper(ChangeEventRecordMapper.class) + List listAfterWithEntityFilter( @Bind("eventType") String eventType, @BindList("entityTypes") List entityTypes, - @Bind("timestamp") long timestamp); + @Bind("timestamp") long timestamp, + @Bind("endTs") long endTs, + @Bind("afterOffset") long afterOffset, + @Bind("limit") int limit); - @SqlQuery( - "SELECT json FROM change_event WHERE " - + "eventType = :eventType AND eventTime >= :timestamp " - + "ORDER BY eventTime ASC") - List listWithoutEntityFilter( - @Bind("eventType") String eventType, @Bind("timestamp") long timestamp); + @ConnectionAwareSqlQuery( + value = + "SELECT c.`offset` AS offset, c.json AS json FROM change_event c INNER JOIN (" + + "SELECT `offset` FROM change_event WHERE eventType = :eventType " + + "AND eventTime >= :timestamp AND eventTime <= :endTs AND `offset` > :afterOffset " + + "ORDER BY `offset` ASC LIMIT :limit) k ON c.`offset` = k.`offset`", + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = + "SELECT c.\"offset\" AS offset, c.json AS json FROM change_event c INNER JOIN (" + + "SELECT \"offset\" FROM change_event WHERE eventType = :eventType " + + "AND eventTime >= :timestamp AND eventTime <= :endTs AND \"offset\" > :afterOffset " + + "ORDER BY \"offset\" ASC LIMIT :limit) k ON c.\"offset\" = k.\"offset\"", + connectionType = POSTGRES) + @RegisterRowMapper(ChangeEventRecordMapper.class) + List listAfterWithoutEntityFilter( + @Bind("eventType") String eventType, + @Bind("timestamp") long timestamp, + @Bind("endTs") long endTs, + @Bind("afterOffset") long afterOffset, + @Bind("limit") int limit); @SqlQuery( "SELECT json FROM change_event ce WHERE ce.offset > :offset ORDER BY ce.offset ASC LIMIT :limit") @@ -9159,9 +9238,7 @@ default List listBefore( boolean includeEmptyTestSuite = Boolean.parseBoolean(filter.getQueryParam("includeEmptyTestSuites")); if (!includeEmptyTestSuite) { - groupBy = - String.format( - "group by %s.json, %s.name, %s.id", getTableName(), getTableName(), getTableName()); + groupBy = String.format("GROUP BY %s.name, %s.id", getTableName(), getTableName()); String condition = String.format( "INNER JOIN entity_relationship er ON %s.id=er.fromId AND er.relation=%s AND er.toEntity='%s'", @@ -9185,9 +9262,7 @@ default List listAfter(ListFilter filter, int limit, String afterName, S boolean includeEmptyTestSuite = Boolean.parseBoolean(filter.getQueryParam("includeEmptyTestSuites")); if (!includeEmptyTestSuite) { - groupBy = - String.format( - "group by %s.json, %s.name, %s.id", getTableName(), getTableName(), getTableName()); + groupBy = String.format("GROUP BY %s.name, %s.id", getTableName(), getTableName()); String condition = String.format( "INNER JOIN entity_relationship er ON %s.id=er.fromId AND er.relation=%s AND er.toEntity='%s'", @@ -10732,6 +10807,14 @@ interface SystemDAO { @RegisterRowMapper(SettingsRowMapper.class) Settings getConfigWithKey(@Bind("configType") String configType) throws StatementException; + @SqlQuery("SELECT json FROM openmetadata_settings WHERE configType = :configType") + String getConfigJsonWithKey(@Bind("configType") String configType) throws StatementException; + + @SqlQuery( + "SELECT json FROM openmetadata_settings " + + "WHERE configType = 'glossaryTermRelationSettings'") + String getGlossaryTermRelationSettingsJson() throws StatementException; + @ConnectionAwareSqlUpdate( value = "INSERT into openmetadata_settings (configType, json)" @@ -10744,6 +10827,39 @@ interface SystemDAO { connectionType = POSTGRES) void insertSettings(@Bind("configType") String configType, @Bind("json") String json); + @ConnectionAwareSqlUpdate( + value = + "UPDATE openmetadata_settings SET json = :updatedJson " + + "WHERE configType = :configType " + + "AND SHA2(CAST(json AS CHAR), 256) = " + + "SHA2(CAST(CAST(:expectedJson AS JSON) AS CHAR), 256)", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "UPDATE openmetadata_settings SET json = (:updatedJson :: jsonb) " + + "WHERE configType = :configType AND json = (:expectedJson :: jsonb)", + connectionType = POSTGRES) + int updateSettingsIfCurrent( + @Bind("configType") String configType, + @Bind("expectedJson") String expectedJson, + @Bind("updatedJson") String updatedJson); + + @ConnectionAwareSqlUpdate( + value = + "UPDATE openmetadata_settings SET json = :updatedJson " + + "WHERE configType = 'glossaryTermRelationSettings' " + + "AND SHA2(CAST(json AS CHAR), 256) = " + + "SHA2(CAST(CAST(:expectedJson AS JSON) AS CHAR), 256)", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "UPDATE openmetadata_settings SET json = (:updatedJson :: jsonb) " + + "WHERE configType = 'glossaryTermRelationSettings' " + + "AND json = (:expectedJson :: jsonb)", + connectionType = POSTGRES) + int updateGlossaryTermRelationSettingsIfCurrent( + @Bind("expectedJson") String expectedJson, @Bind("updatedJson") String updatedJson); + @SqlUpdate(value = "DELETE from openmetadata_settings WHERE configType = :configType") void delete(@Bind("configType") String configType); @@ -10807,7 +10923,6 @@ public static Settings getSettings(SettingsType configType, String json) { case MCP_CONFIGURATION -> JsonUtils.readValue(json, MCPConfiguration.class); case GLOSSARY_TERM_RELATION_SETTINGS -> JsonUtils.readValue( json, GlossaryTermRelationSettings.class); - case AI_SETTINGS -> JsonUtils.readValue(json, AISettings.class); case SEARCH_INDEX_MAPPINGS -> JsonUtils.readValue(json, SearchIndexMappings.class); default -> throw new IllegalArgumentException("Invalid Settings Type " + configType); }; @@ -12139,6 +12254,84 @@ default Class getEntityClass() { default String getNameHashColumn() { return "fqnHash"; } + + /** + * Atomically claims a Queued report for this node, flipping it to Running only if it is still + * Queued. Returns 1 for the single winning caller and 0 for losers, so concurrent recovery + * re-drives across pods generate the pack exactly once. + */ + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = JSON_SET(json, '$.status', 'Running', '$.runningOn', :runningOn, '$.startedAt', :startedAt) " + + "WHERE id = :id AND status = 'Queued'", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = json || jsonb_build_object('status', 'Running', 'runningOn', CAST(:runningOn AS text), 'startedAt', CAST(:startedAt AS bigint)) " + + "WHERE id = :id AND status = 'Queued'", + connectionType = POSTGRES) + int claimQueued( + @Bind("id") String id, + @Bind("runningOn") String runningOn, + @Bind("startedAt") long startedAt); + + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = JSON_SET(json, '$.status', 'Completed', '$.completedAt', :completedAt, '$.artifacts', CAST(:artifacts AS JSON), '$.manifest', CAST(:manifest AS JSON), '$.updatedAt', :completedAt, '$.updatedBy', :updatedBy) " + + "WHERE id = :id AND status = 'Running' AND json ->> '$.runningOn' = :runningOn", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = json || jsonb_build_object('status', 'Completed', 'completedAt', CAST(:completedAt AS bigint), 'artifacts', CAST(:artifacts AS jsonb), 'manifest', CAST(:manifest AS jsonb), 'updatedAt', CAST(:completedAt AS bigint), 'updatedBy', CAST(:updatedBy AS text)) " + + "WHERE id = :id AND status = 'Running' AND json->>'runningOn' = :runningOn", + connectionType = POSTGRES) + int completeRunning( + @Bind("id") String id, + @Bind("runningOn") String runningOn, + @Bind("completedAt") long completedAt, + @Bind("artifacts") String artifacts, + @Bind("manifest") String manifest, + @Bind("updatedBy") String updatedBy); + + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = JSON_SET(json, '$.status', 'Failed', '$.completedAt', :completedAt, '$.failureReason', :failureReason, '$.updatedAt', :completedAt, '$.updatedBy', :updatedBy) " + + "WHERE id = :id AND status = 'Running' AND json ->> '$.runningOn' = :runningOn", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = json || jsonb_build_object('status', 'Failed', 'completedAt', CAST(:completedAt AS bigint), 'failureReason', CAST(:failureReason AS text), 'updatedAt', CAST(:completedAt AS bigint), 'updatedBy', CAST(:updatedBy AS text)) " + + "WHERE id = :id AND status = 'Running' AND json->>'runningOn' = :runningOn", + connectionType = POSTGRES) + int failRunning( + @Bind("id") String id, + @Bind("runningOn") String runningOn, + @Bind("completedAt") long completedAt, + @Bind("failureReason") String failureReason, + @Bind("updatedBy") String updatedBy); + + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = JSON_REMOVE(JSON_SET(json, '$.status', 'Queued', '$.updatedAt', :updatedAt, '$.updatedBy', :updatedBy), '$.runningOn', '$.startedAt') " + + "WHERE id = :id AND status = 'Running' AND (JSON_EXTRACT(json, '$.startedAt') IS NULL OR CAST(json ->> '$.startedAt' AS UNSIGNED) < :staleBefore)", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "UPDATE audit_report_entity SET json = (json || jsonb_build_object('status', 'Queued', 'updatedAt', CAST(:updatedAt AS bigint), 'updatedBy', CAST(:updatedBy AS text))) - 'runningOn' - 'startedAt' " + + "WHERE id = :id AND status = 'Running' AND ((json->>'startedAt') IS NULL OR CAST(json->>'startedAt' AS bigint) < :staleBefore)", + connectionType = POSTGRES) + int requeueStaleRunning( + @Bind("id") String id, + @Bind("staleBefore") long staleBefore, + @Bind("updatedAt") long updatedAt, + @Bind("updatedBy") String updatedBy); + + /** Indexed lookup of an in-flight (Queued/Running) report by its request signature. */ + @SqlQuery( + "SELECT json FROM audit_report_entity " + + "WHERE requestSignature = :signature AND status IN ('Queued', 'Running') " + + "AND (deleted = FALSE OR deleted IS NULL) LIMIT 1") + String findActiveByRequestSignature(@Bind("signature") String signature); } interface McpServerDAO extends EntityDAO { @@ -13291,6 +13484,32 @@ List findByStatus( List findByStatuses( @BindList("statuses") List statuses, @Bind("limit") int limit); + @ConnectionAwareSqlQuery( + value = + "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt " + + "FROM search_index_retry_queue WHERE status = 'PENDING' " + + "OR (status = 'PENDING_RETRY_1' AND (claimedAt IS NULL OR " + + "claimedAt <= DATE_SUB(NOW(), INTERVAL :firstRetryBackoffSeconds SECOND))) " + + "OR (status = 'PENDING_RETRY_2' AND (claimedAt IS NULL OR " + + "claimedAt <= DATE_SUB(NOW(), INTERVAL :secondRetryBackoffSeconds SECOND))) " + + "LIMIT :limit", + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = + "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt " + + "FROM search_index_retry_queue WHERE status = 'PENDING' " + + "OR (status = 'PENDING_RETRY_1' AND (claimedAt IS NULL OR " + + "claimedAt <= NOW() - (:firstRetryBackoffSeconds * INTERVAL '1 second'))) " + + "OR (status = 'PENDING_RETRY_2' AND (claimedAt IS NULL OR " + + "claimedAt <= NOW() - (:secondRetryBackoffSeconds * INTERVAL '1 second'))) " + + "LIMIT :limit", + connectionType = POSTGRES) + @RegisterRowMapper(SearchIndexRetryRecordMapper.class) + List findRetryCandidates( + @Bind("firstRetryBackoffSeconds") int firstRetryBackoffSeconds, + @Bind("secondRetryBackoffSeconds") int secondRetryBackoffSeconds, + @Bind("limit") int limit); + @SqlUpdate( "UPDATE search_index_retry_queue SET status = :newStatus " + "WHERE entityId = :entityId AND entityFqn = :entityFqn AND status = :currentStatus") @@ -13342,7 +13561,7 @@ int claimRecord( @SqlUpdate( "UPDATE search_index_retry_queue SET status = :status, failureReason = :failureReason, " - + "retryCount = retryCount + 1, claimedAt = NULL " + + "retryCount = retryCount + 1, claimedAt = NOW() " + "WHERE entityId = :entityId AND entityFqn = :entityFqn") int updateFailureAndRetryCount( @Bind("entityId") String entityId, @@ -13351,10 +13570,15 @@ int updateFailureAndRetryCount( @Bind("status") String status); default List claimPending(int batchSize) { + return claimPending(batchSize, 0, 0); + } + + default List claimPending( + int batchSize, int firstRetryBackoffSeconds, int secondRetryBackoffSeconds) { int fetchSize = Math.max(batchSize * 5, batchSize); List candidates = new ArrayList<>( - findByStatuses(List.of("PENDING", "PENDING_RETRY_1", "PENDING_RETRY_2"), fetchSize)); + findRetryCandidates(firstRetryBackoffSeconds, secondRetryBackoffSeconds, fetchSize)); // Shuffle so concurrent worker threads attempt different rows first, // reducing wasted optimistic-lock failures on the same candidates. Collections.shuffle(candidates); @@ -15688,70 +15912,4 @@ List getByFqnPrefix( @SqlUpdate("DELETE FROM asset_entity WHERE id = :id") void delete(@Bind("id") String id); } - - interface McpConversationDAO { - @ConnectionAwareSqlUpdate( - value = "INSERT INTO mcp_conversation (json) VALUES (:json)", - connectionType = MYSQL) - @ConnectionAwareSqlUpdate( - value = "INSERT INTO mcp_conversation (json) VALUES (:json::jsonb)", - connectionType = POSTGRES) - void insert(@Bind("json") String json); - - @SqlQuery("SELECT json FROM mcp_conversation WHERE id = :id") - String getById(@BindUUID("id") UUID id); - - @SqlQuery( - "SELECT json FROM mcp_conversation WHERE userId = :userId " - + "ORDER BY updatedAt DESC LIMIT :limit OFFSET :offset") - List listByUser( - @BindUUID("userId") UUID userId, @Bind("limit") int limit, @Bind("offset") int offset); - - @ConnectionAwareSqlUpdate( - value = "UPDATE mcp_conversation SET json = :json WHERE id = :id", - connectionType = MYSQL) - @ConnectionAwareSqlUpdate( - value = "UPDATE mcp_conversation SET json = :json::jsonb WHERE id = :id", - connectionType = POSTGRES) - void update(@BindUUID("id") UUID id, @Bind("json") String json); - - @SqlQuery("SELECT COUNT(*) FROM mcp_conversation WHERE userId = :userId") - int countByUser(@BindUUID("userId") UUID userId); - - @SqlUpdate("DELETE FROM mcp_conversation WHERE id = :id") - void delete(@BindUUID("id") UUID id); - } - - interface McpMessageDAO { - @ConnectionAwareSqlUpdate( - value = "INSERT INTO mcp_message (json) VALUES (:json)", - connectionType = MYSQL) - @ConnectionAwareSqlUpdate( - value = "INSERT INTO mcp_message (json) VALUES (:json::jsonb)", - connectionType = POSTGRES) - void insert(@Bind("json") String json); - - @SqlQuery( - "SELECT json FROM mcp_message WHERE conversationId = :conversationId " - + "ORDER BY messageIndex ASC LIMIT :limit OFFSET :offset") - List listByConversation( - @BindUUID("conversationId") UUID conversationId, - @Bind("limit") int limit, - @Bind("offset") int offset); - - @SqlQuery( - "SELECT json FROM mcp_message WHERE conversationId = :conversationId " - + "ORDER BY messageIndex DESC LIMIT :limit") - List listRecentByConversation( - @BindUUID("conversationId") UUID conversationId, @Bind("limit") int limit); - - @SqlQuery("SELECT COUNT(*) FROM mcp_message WHERE conversationId = :conversationId") - int countByConversation(@BindUUID("conversationId") UUID conversationId); - - @SqlUpdate("DELETE FROM mcp_message WHERE id = :id") - void delete(@BindUUID("id") UUID id); - - @SqlUpdate("DELETE FROM mcp_message WHERE conversationId = :conversationId") - void deleteByConversation(@BindUUID("conversationId") UUID conversationId); - } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java index 224dfb0c4b30..2b945d304c6c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java @@ -13,7 +13,6 @@ import java.util.concurrent.RejectedExecutionException; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Jdbi; -import org.jdbi.v3.sqlobject.transaction.Transaction; import org.openmetadata.schema.attachments.Asset; import org.openmetadata.schema.entity.data.ContextFile; import org.openmetadata.schema.entity.data.ContextFileContent; @@ -76,23 +75,11 @@ public ContextFileContentRepository getContentRepository() { public void setFields( ContextFile file, EntityUtil.Fields fields, RelationIncludes relationIncludes) { file.setFolder(fields.contains("folder") ? getFolder(file) : file.getFolder()); - if (fields.contains("memoryCount")) { - file.setMemoryCount( - findTo( - file.getId(), - CONTEXT_FILE_ENTITY, - Relationship.MENTIONED_IN, - Entity.CONTEXT_MEMORY) - .size()); - } } @Override public void clearFields(ContextFile file, EntityUtil.Fields fields) { file.setFolder(fields.contains("folder") ? file.getFolder() : null); - if (!fields.contains("memoryCount")) { - file.setMemoryCount(null); - } } @Override @@ -150,33 +137,6 @@ public void storeRelationships(ContextFile file) { } } - // Knowledge-pill cleanup runs in the *AdditionalChildren hooks rather than postDelete because - // those fire while the file -> memory MENTIONED_IN edges still exist. postDelete runs after - // cleanup() has already deleted those edges on a hard delete, so a findTo there would match - // nothing and orphan the pills. The pills track the file's lifecycle: soft-deleted with it, - // hard-deleted with it, restored with it. Mirrors KnowledgePageRepository. - @Override - @Transaction - protected void softDeleteAdditionalChildren(UUID fileId, String deletedBy) { - contextMemoryRepository().deleteExtractedMemories(fileId, CONTEXT_FILE_ENTITY, false); - } - - @Override - @Transaction - protected void hardDeleteAdditionalChildren(UUID fileId, String deletedBy) { - contextMemoryRepository().deleteExtractedMemories(fileId, CONTEXT_FILE_ENTITY, true); - } - - @Override - @Transaction - protected void restoreAdditionalChildren(UUID fileId, String updatedBy) { - contextMemoryRepository().restoreExtractedMemories(fileId, CONTEXT_FILE_ENTITY); - } - - private ContextMemoryRepository contextMemoryRepository() { - return (ContextMemoryRepository) Entity.getEntityRepository(Entity.CONTEXT_MEMORY); - } - @Override public void restorePatchAttributes(ContextFile original, ContextFile updated) { updated.withFolder(original.getFolder()); @@ -249,9 +209,6 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { recordChange("fileType", original.getFileType(), updated.getFileType()); recordChange( "processingStatus", original.getProcessingStatus(), updated.getProcessingStatus()); - recordChange("processingError", original.getProcessingError(), updated.getProcessingError()); - recordChange( - "extractionStats", original.getExtractionStats(), updated.getExtractionStats(), true); recordChange("extractedText", original.getExtractedText(), updated.getExtractedText()); recordChange("pageCount", original.getPageCount(), updated.getPageCount()); updateFolder(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextMemoryRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextMemoryRepository.java index d628760138d1..8a07d6cdb0b0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextMemoryRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextMemoryRepository.java @@ -23,28 +23,18 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; -import org.jdbi.v3.sqlobject.transaction.Transaction; -import org.openmetadata.schema.configuration.AIDeletionPolicy; import org.openmetadata.schema.entity.context.ContextMemory; -import org.openmetadata.schema.entity.context.ContextMemorySourceType; import org.openmetadata.schema.entity.context.ContextMemoryStatus; -import org.openmetadata.schema.entity.context.MemoryProcessingStatus; -import org.openmetadata.schema.entity.context.MemoryStats; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.Relationship; import org.openmetadata.schema.type.change.ChangeSource; -import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; -import org.openmetadata.service.drive.memory.MemoryProcessingEngine; -import org.openmetadata.service.drive.memory.MemoryReconciler; import org.openmetadata.service.resources.context.ContextMemoryResource; import org.openmetadata.service.search.vector.ContextMemoryBodyTextContributor; -import org.openmetadata.service.util.AISettingsUtil; import org.openmetadata.service.util.EntityUtil; import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.EntityUtil.RelationIncludes; @@ -56,26 +46,10 @@ public class ContextMemoryRepository extends EntityRepository { static final String FIELD_PRIMARY_ENTITY = "primaryEntity"; static final String FIELD_RELATED_ENTITIES = "relatedEntities"; - static final String FIELD_SOURCE_FILE = "sourceFile"; - static final String FIELD_SOURCE_ENTITY = "sourceEntity"; - static final String FIELD_DERIVED_ENTITIES = "derivedEntities"; - static final String FIELD_REUSED_ENTITIES = "reusedEntities"; private static final String PATCH_FIELDS = - FIELD_PRIMARY_ENTITY - + "," - + FIELD_RELATED_ENTITIES - + ",rootMemory,parentMemory," - + FIELD_SOURCE_FILE - + "," - + FIELD_SOURCE_ENTITY; + FIELD_PRIMARY_ENTITY + "," + FIELD_RELATED_ENTITIES + ",rootMemory,parentMemory"; private static final String UPDATE_FIELDS = - FIELD_PRIMARY_ENTITY - + "," - + FIELD_RELATED_ENTITIES - + ",rootMemory,parentMemory," - + FIELD_SOURCE_FILE - + "," - + FIELD_SOURCE_ENTITY; + FIELD_PRIMARY_ENTITY + "," + FIELD_RELATED_ENTITIES + ",rootMemory,parentMemory"; static { ContextMemoryBodyTextContributor.INSTANCE.register(); @@ -100,21 +74,6 @@ protected void setFields(ContextMemory entity, Fields fields, RelationIncludes r if (fields.contains(FIELD_RELATED_ENTITIES)) { entity.setRelatedEntities(getRelatedEntities(entity)); } - if (fields.contains(FIELD_SOURCE_ENTITY) || fields.contains(FIELD_SOURCE_FILE)) { - EntityReference source = getSourceEntity(entity); - if (fields.contains(FIELD_SOURCE_ENTITY)) { - entity.setSourceEntity(source); - } - if (fields.contains(FIELD_SOURCE_FILE)) { - entity.setSourceFile(asContextFileRef(source)); - } - } - if (fields.contains(FIELD_DERIVED_ENTITIES)) { - entity.setDerivedEntities(getDerivedEntities(entity)); - } - if (fields.contains(FIELD_REUSED_ENTITIES)) { - entity.setReusedEntities(getReusedEntities(entity)); - } } @Override @@ -125,18 +84,6 @@ protected void clearFields(ContextMemory entity, Fields fields) { if (!fields.contains(FIELD_RELATED_ENTITIES)) { entity.setRelatedEntities(null); } - if (!fields.contains(FIELD_SOURCE_ENTITY)) { - entity.setSourceEntity(null); - } - if (!fields.contains(FIELD_SOURCE_FILE)) { - entity.setSourceFile(null); - } - if (!fields.contains(FIELD_DERIVED_ENTITIES)) { - entity.setDerivedEntities(null); - } - if (!fields.contains(FIELD_REUSED_ENTITIES)) { - entity.setReusedEntities(null); - } } @Override @@ -146,7 +93,6 @@ public void setFieldsInBulk(Fields fields, List entities) { } fetchAndSetPrimaryEntities(entities, fields); fetchAndSetRelatedEntities(entities, fields); - fetchAndSetSources(entities, fields); fetchAndSetFields(entities, fields); setInheritedFields(entities, fields); for (ContextMemory entity : entities) { @@ -265,83 +211,6 @@ private List getRelatedEntities(ContextMemory entity) { return findFrom(entity.getId(), Entity.CONTEXT_MEMORY, Relationship.RELATED_TO, null); } - /** The single Context Center source (file or page) a memory was extracted from, via MENTIONED_IN. */ - private EntityReference getSourceEntity(ContextMemory entity) { - List refs = - findFrom(entity.getId(), Entity.CONTEXT_MEMORY, Relationship.MENTIONED_IN, null); - return nullOrEmpty(refs) ? null : refs.getFirst(); - } - - /** Back-compat view: the deprecated sourceFile is the source only when it is a ContextFile. */ - private EntityReference asContextFileRef(EntityReference source) { - return source != null && Entity.CONTEXT_FILE.equals(source.getType()) ? source : null; - } - - /** - * Returns the glossary terms and metrics created by the Memory Agent from this memory. - * Edge direction: from=term/metric → to=memory via DERIVED_FROM; findFrom resolves from-side. - */ - private List getDerivedEntities(ContextMemory entity) { - final List terms = - findFrom( - entity.getId(), Entity.CONTEXT_MEMORY, Relationship.DERIVED_FROM, Entity.GLOSSARY_TERM); - final List metrics = - findFrom(entity.getId(), Entity.CONTEXT_MEMORY, Relationship.DERIVED_FROM, Entity.METRIC); - final List combined = new ArrayList<>(terms); - combined.addAll(metrics); - return combined; - } - - /** - * Returns the glossary terms and metrics reused (not created) by the Memory Agent from this memory. - * Edge direction: from=memory → to=term/metric via RELATED_TO; findTo resolves to-side. - */ - private List getReusedEntities(ContextMemory entity) { - final List terms = - findTo( - entity.getId(), Entity.CONTEXT_MEMORY, Relationship.RELATED_TO, Entity.GLOSSARY_TERM); - final List metrics = - findTo(entity.getId(), Entity.CONTEXT_MEMORY, Relationship.RELATED_TO, Entity.METRIC); - final List combined = new ArrayList<>(terms); - combined.addAll(metrics); - return combined; - } - - private void fetchAndSetSources(List entities, Fields fields) { - if (!fields.contains(FIELD_SOURCE_ENTITY) && !fields.contains(FIELD_SOURCE_FILE)) { - return; - } - Map sourceById = batchFetchSources(entities); - for (ContextMemory memory : entities) { - EntityReference source = sourceById.get(memory.getId()); - if (fields.contains(FIELD_SOURCE_ENTITY)) { - memory.setSourceEntity(source); - } - if (fields.contains(FIELD_SOURCE_FILE)) { - memory.setSourceFile(asContextFileRef(source)); - } - } - } - - private Map batchFetchSources(List entities) { - Map sourceById = new HashMap<>(); - List records = - daoCollection - .relationshipDAO() - .findFromBatch( - entityListToStrings(entities), - Relationship.MENTIONED_IN.ordinal(), - Include.NON_DELETED); - Map refById = resolveReferencesByType(records); - for (CollectionDAO.EntityRelationshipObject record : records) { - EntityReference ref = refById.get(record.getFromId()); - if (ref != null) { - sourceById.putIfAbsent(UUID.fromString(record.getToId()), ref); - } - } - return sourceById; - } - @Override public void setFullyQualifiedName(ContextMemory entity) { if (!nullOrEmpty(entity.getFullyQualifiedName())) { @@ -365,13 +234,6 @@ public void prepare(ContextMemory entity, boolean update) { Entity.getEntityReference(entity.getPrimaryEntity(), Include.NON_DELETED); entity.setPrimaryEntity(primaryEntity); } - if (entity.getSourceEntity() == null && entity.getSourceFile() != null) { - entity.setSourceEntity(entity.getSourceFile()); - } - if (entity.getSourceEntity() != null) { - entity.setSourceEntity( - Entity.getEntityReference(entity.getSourceEntity(), Include.NON_DELETED)); - } entity.setRelatedEntities(EntityUtil.populateEntityReferences(entity.getRelatedEntities())); if (entity.getRootMemory() != null) { @@ -387,21 +249,6 @@ public void prepare(ContextMemory entity, boolean update) { } validateSharedPrincipals(entity); setCreatorAsDefaultOwner(entity, update); - - // A new memory queues a Memory Agent run (scheduled in postCreate); stamp Queued here so the - // pill shows a memory-pending state immediately, until the agent flips it to Processing then - // Processed/Failed. Update re-queueing is handled in the updater on a content change. - if (!update && AISettingsUtil.isMemoryAgentEnabled(AISettingsUtil.get())) { - markMemoryQueued(entity); - } - } - - /** Sets the memory's ontology status to Queued (preserving prior telemetry) and clears any error. */ - private void markMemoryQueued(ContextMemory entity) { - MemoryStats stats = - entity.getMemoryStats() == null ? new MemoryStats() : entity.getMemoryStats(); - stats.withStatus(MemoryProcessingStatus.Queued).withError(null); - entity.setMemoryStats(stats); } private void validateNotSelfReference(ContextMemory entity, UUID referencedId, String field) { @@ -494,87 +341,12 @@ public void storeRelationships(ContextMemory entity) { Entity.CONTEXT_MEMORY, Relationship.PARENT_OF); } - - if (entity.getSourceEntity() != null) { - addRelationship( - entity.getSourceEntity().getId(), - entity.getId(), - entity.getSourceEntity().getType(), - Entity.CONTEXT_MEMORY, - Relationship.MENTIONED_IN); - } } private static List asRefList(EntityReference ref) { return ref == null ? List.of() : List.of(ref); } - // ------------------------------------------------------------------ - // Memory Agent lifecycle hooks - // ------------------------------------------------------------------ - - @Override - protected void postCreate(ContextMemory entity) { - super.postCreate(entity); - scheduleMemory(entity); - } - - @Override - protected void postUpdate(ContextMemory original, ContextMemory updated) { - super.postUpdate(original, updated); - if (extractionManagedFieldChanged(original, updated)) { - scheduleMemory(updated); - } - } - - private void scheduleMemory(final ContextMemory entity) { - if (AISettingsUtil.isMemoryAgentEnabled(AISettingsUtil.get())) { - MemoryProcessingEngine.instance().schedule(entity.getId()); - } - } - - // Knowledge-pill cascade hooks fire BEFORE relationshipDAO().deleteAll(id) so the - // DERIVED_FROM edges are still queryable when the reconciler runs (see design spec §9). - @Override - @Transaction - protected void softDeleteAdditionalChildren(final UUID memoryId, final String deletedBy) { - cancelAndCascadeMemory(memoryId, false); - } - - @Override - @Transaction - protected void hardDeleteAdditionalChildren(final UUID memoryId, final String deletedBy) { - cancelAndCascadeMemory(memoryId, true); - } - - private void cancelAndCascadeMemory(final UUID memoryId, final boolean hardDelete) { - MemoryProcessingEngine.instance().cancel(memoryId); - cascadeMemory(memoryId, hardDelete); - } - - @Override - @Transaction - protected void restoreAdditionalChildren(final UUID memoryId, final String restoredBy) { - final ContextMemory memory = get(null, memoryId, getFields(""), Include.ALL, false); - memoryReconciler().onMemoryRestored(memory); - } - - private void cascadeMemory(final UUID memoryId, final boolean hardDelete) { - final ContextMemory memory = get(null, memoryId, getFields(""), Include.ALL, false); - final AIDeletionPolicy policy = AISettingsUtil.deletionPolicy(AISettingsUtil.get()); - memoryReconciler().onMemoryDeleted(memory, hardDelete, policy); - } - - private MemoryReconciler memoryReconciler() { - final GlossaryTermRepository termRepo = - (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM); - final MetricRepository metricRepo = - (MetricRepository) Entity.getEntityRepository(Entity.METRIC); - final GlossaryRepository glossaryRepo = - (GlossaryRepository) Entity.getEntityRepository(Entity.GLOSSARY); - return new MemoryReconciler(termRepo, metricRepo, glossaryRepo); - } - // ------------------------------------------------------------------ // Lifecycle enforcement // ------------------------------------------------------------------ @@ -629,7 +401,6 @@ public ContextMemoryUpdater( @Override public void entitySpecificUpdate(boolean consolidatingChanges) { - flipToManualOnUserEdit(); recordChange("title", original.getTitle(), updated.getTitle()); recordChange("summary", original.getSummary(), updated.getSummary()); recordChange("question", original.getQuestion(), updated.getQuestion()); @@ -696,155 +467,9 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { Relationship.PARENT_OF, Entity.CONTEXT_MEMORY, original.getId()); - updateSourceEntityRelationship(); - - maybeRequeueMemory(); - recordMemoryStats(); // usageCount and lastUsedAt are AI-retrieval telemetry, intentionally excluded from // version history so routine retrieval does not churn the entity version. } - - /** - * Re-queues ontology derivation when an edit changes the memory's ontology-relevant content, so - * the pill shows Queued again until the agent (rescheduled in postUpdate) re-derives. Gated to a - * real content change so a machine status stamp (Processing/Processed/Failed) does not reset - * itself to Queued. Runs before {@link #recordMemoryStats()} so the new status is recorded. - */ - private void maybeRequeueMemory() { - if (extractionManagedFieldChanged() - && AISettingsUtil.isMemoryAgentEnabled(AISettingsUtil.get())) { - markMemoryQueued(updated); - } - } - - /** - * memoryStats is engine-managed telemetry. Preserve the stored value when an update omits it - * so a user PUT never wipes it, and persist a fresh stamp with updateVersion=false so the - * Memory Agent does not churn the memory's version history on every derivation run. - */ - private void recordMemoryStats() { - if (updated.getMemoryStats() == null) { - updated.setMemoryStats(original.getMemoryStats()); - } - recordChange( - "memoryStats", - original.getMemoryStats(), - updated.getMemoryStats(), - true, - EntityUtil.objectMatch, - false); - } - - /** - * A user editing the content of a machine-generated pill through the PATCH endpoint takes - * ownership of it: the sourceType flips to Manual so re-extraction never clobbers the human - * edit. updatedBy cannot tell this apart (the extraction engine also writes as admin) — the - * operation does, since the engine only ever creates/PUTs, never PATCHes. The flip is gated on - * an actual content change so unrelated PATCHes (tagging, starring, re-scoping, sharing) leave - * the pill under engine management. - */ - private void flipToManualOnUserEdit() { - if (operation == Operation.PATCH - && updated.getSourceType() == original.getSourceType() - && isAutomatedSource(original.getSourceType()) - && extractionManagedFieldChanged()) { - updated.setSourceType(ContextMemorySourceType.MANUAL); - } - } - - /** True when a PATCH edited a field the extraction reconciler would otherwise overwrite. */ - private boolean extractionManagedFieldChanged() { - return ContextMemoryRepository.extractionManagedFieldChanged(original, updated); - } - - private void updateSourceEntityRelationship() { - // Preserve the stored source when an update omits it. sourceEntity is a relationship-derived - // field that a partial fetch leaves null (e.g. the ontology hash stamp and re-extraction load - // the memory via getFields("")), and a null here would otherwise delete the MENTIONED_IN edge - // that links the pill to its source file/page -- orphaning it from memoryCount, the - // sourceEntityId listing, and the article's derived ontologies. A genuine re-parent still - // works: it supplies a non-null ref, so this guard does not fire. - if (updated.getSourceEntity() == null) { - updated.setSourceEntity(original.getSourceEntity()); - } - // Plural form with single-element lists so the stale edge is removed under its OWN entity - // type and the new one added under its own. The singular updateFromRelationship took one - // fromType for both delete and add, which orphaned the old edge when the source changed type - // (e.g. ContextFile -> Page). Mirrors how primaryEntity is reconciled above. - updateFromRelationships( - FIELD_SOURCE_ENTITY, - Entity.CONTEXT_MEMORY, - asRefList(original.getSourceEntity()), - asRefList(updated.getSourceEntity()), - Relationship.MENTIONED_IN, - Entity.CONTEXT_MEMORY, - original.getId()); - } - } - - private static boolean isAutomatedSource(ContextMemorySourceType type) { - return type == ContextMemorySourceType.FILE_EXTRACTION - || type == ContextMemorySourceType.PAGE_EXTRACTION; - } - - private static boolean extractionManagedFieldChanged( - ContextMemory original, ContextMemory updated) { - return !Objects.equals(original.getTitle(), updated.getTitle()) - || !Objects.equals(original.getQuestion(), updated.getQuestion()) - || !Objects.equals(original.getAnswer(), updated.getAnswer()) - || !Objects.equals(original.getSummary(), updated.getSummary()) - || !Objects.equals(original.getMemoryType(), updated.getMemoryType()); - } - - /** Loads the knowledge pills currently linked to a Context Center source (file or page). */ - public List listExtractedMemories(UUID sourceId, String sourceType) { - List refs = - findTo(sourceId, sourceType, Relationship.MENTIONED_IN, Entity.CONTEXT_MEMORY); - if (refs.isEmpty()) { - return new ArrayList<>(); - } - // Batch-load in one query instead of a get() per ref (avoids N+1). Reconciliation only reads - // stored fields (question/status/answer/...), so the relationship-free fetch is sufficient. - List ids = refs.stream().map(EntityReference::getId).toList(); - return find(ids, Include.NON_DELETED); - } - - /** Deletes every knowledge pill linked to a Context Center source, propagating the delete flag. */ - public void deleteExtractedMemories(UUID sourceId, String sourceType, boolean hardDelete) { - List refs = - findTo(sourceId, sourceType, Relationship.MENTIONED_IN, Entity.CONTEXT_MEMORY); - for (EntityReference ref : refs) { - delete(Entity.ADMIN_USER_NAME, ref.getId(), false, hardDelete); - } - } - - /** - * Restores the soft-deleted knowledge pills linked to a Context Center source when that source is - * restored. Uses Include.ALL because the pills are deleted at lookup time; restoreEntity is a - * no-op on any that are already active. - */ - public void restoreExtractedMemories(UUID sourceId, String sourceType) { - List refs = - findTo(sourceId, sourceType, Relationship.MENTIONED_IN, Entity.CONTEXT_MEMORY, Include.ALL); - for (EntityReference ref : refs) { - restoreEntity(Entity.ADMIN_USER_NAME, ref.getId()); - } - } - - /** - * Persists new {@link MemoryStats} on a memory WITHOUT bumping its version. The engine calls - * this after every derivation run. Using {@code updateVersion=false} inside {@link - * ContextMemoryUpdater#recordMemoryStats()} means the JSON store is updated but the version - * counter stays flat (no history churn). {@code postUpdate} DOES still fire ({@code - * entityChanged=true}). The recursion loop is broken solely by the hash-gate in {@link - * org.openmetadata.service.drive.memory.MemoryProcessingEngine}: after the stamp, {@code - * sourceHash == hashOf(memory)}, so a re-triggered run skips derivation. The hash-gate is - * load-bearing — do NOT remove it. - */ - public void stampMemoryStats(final ContextMemory memory, final MemoryStats stats) { - final ContextMemory updated = JsonUtils.deepCopy(memory, ContextMemory.class); - updated.setMemoryStats(stats); - update(null, memory, updated, Entity.ADMIN_USER_NAME); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseRepository.java index c0ed634d6dac..863f59e7c6b9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseRepository.java @@ -796,7 +796,7 @@ protected void createEntityWithoutRecursion(CSVPrinter printer, List .withCertification(certification) .withRetentionPeriod(csvRecord.get(8)) .withSourceUrl(csvRecord.get(9)) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, schema.getDomains())) .withExtension(getExtension(printer, csvRecord, 11)); if (processRecord) { createEntity(printer, csvRecord, schema, DATABASE_SCHEMA); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseSchemaRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseSchemaRepository.java index d110150f4872..9cbbe0afe43f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseSchemaRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseSchemaRepository.java @@ -971,7 +971,7 @@ protected void createEntityWithoutRecursion(CSVPrinter printer, List .withRetentionPeriod(csvRecord.get(8)) .withSourceUrl(csvRecord.get(9)) .withColumns(nullOrEmpty(table.getColumns()) ? new ArrayList<>() : table.getColumns()) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, table.getDomains())) .withExtension(getExtension(printer, csvRecord, 11)); if (processRecord) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseServiceRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseServiceRepository.java index de18061482bb..bf27676f9d7c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseServiceRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DatabaseServiceRepository.java @@ -287,7 +287,7 @@ protected void createEntityWithoutRecursion(CSVPrinter printer, List .withOwners(getOwners(printer, csvRecord, 3)) .withTags(tagLabels) .withCertification(certification) - .withDomains(getDomains(printer, csvRecord, 8)) + .withDomains(getDomains(printer, csvRecord, 8, database.getDomains())) .withExtension(getExtension(printer, csvRecord, 9)); if (processRecord) { @@ -371,7 +371,7 @@ private void createDatabaseEntity(CSVPrinter printer, CSVRecord csvRecord, Strin .withTags(tagLabels) .withCertification(certification) .withSourceUrl(csvRecord.get(9)) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, database.getDomains())) .withExtension(getExtension(printer, csvRecord, 11)); if (processRecord) { @@ -448,7 +448,7 @@ protected void createSchemaEntity(CSVPrinter printer, CSVRecord csvRecord, Strin .withCertification(certification) .withRetentionPeriod(csvRecord.get(8)) .withSourceUrl(csvRecord.get(9)) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, schema.getDomains())) .withExtension(getExtension(printer, csvRecord, 11)) .withUpdatedAt(System.currentTimeMillis()) .withUpdatedBy(importedBy); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DirectoryRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DirectoryRepository.java index 2ded30b9c82b..c71ec234914c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DirectoryRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DirectoryRepository.java @@ -249,48 +249,57 @@ public void setFieldsInBulk(EntityUtil.Fields fields, List entities) if (nullOrEmpty(entities)) { return; } - fetchAndSetDefaultService(entities); - fetchAndSetParents(entities, fields); + fetchAndSetServiceAndParent(entities); fetchAndSetStatistics(entities, fields); fetchAndSetFields(entities, fields); setInheritedFields(entities, fields); for (Directory entity : entities) { clearFieldsInternal(entity, fields); + if (!fields.contains(FIELD_PARENT)) { + entity.withParent(null); + } } } - private void fetchAndSetDefaultService(List directories) { - Map serviceMap = batchFetchFromByType(directories, Entity.DRIVE_SERVICE); - directories.forEach(directory -> directory.withService(serviceMap.get(directory.getId()))); - } - - private void fetchAndSetParents(List directories, EntityUtil.Fields fields) { - if (!fields.contains(FIELD_PARENT)) { - return; - } - Map parentMap = batchFetchFromByType(directories, DIRECTORY); - directories.forEach(directory -> directory.withParent(parentMap.get(directory.getId()))); - } - - private Map batchFetchFromByType( - List directories, String fromEntityType) { - Map resultMap = new HashMap<>(); + /** + * Resolves both the drive service and the parent directory from a single CONTAINS batch query. + * Every directory has a service->directory edge, and nested directories additionally have a + * parent->directory edge, so one findFromBatch returns both; they are partitioned by the from + * entity type. Parent is always resolved (not only when requested) because setInheritedFields + * needs it to inherit a nested directory's domain from its parent directory instead of the drive + * service, matching the single-entity setFields path. It is nulled out after inheritance if not + * requested. + */ + private void fetchAndSetServiceAndParent(List directories) { List records = daoCollection .relationshipDAO() .findFromBatch(entityListToStrings(directories), Relationship.CONTAINS.ordinal()); + Map serviceMap = new HashMap<>(); + Map parentMap = new HashMap<>(); Map refById = new HashMap<>(); for (CollectionDAO.EntityRelationshipObject record : records) { - if (fromEntityType.equals(record.getFromEntity())) { + String fromType = record.getFromEntity(); + Map target = + switch (fromType) { + case Entity.DRIVE_SERVICE -> serviceMap; + case DIRECTORY -> parentMap; + default -> null; + }; + if (target != null) { UUID directoryId = UUID.fromString(record.getToId()); UUID fromId = UUID.fromString(record.getFromId()); EntityReference ref = refById.computeIfAbsent( - fromId, id -> getEntityReferenceById(fromEntityType, id, Include.NON_DELETED)); - resultMap.put(directoryId, ref); + fromId, id -> getEntityReferenceById(fromType, id, Include.NON_DELETED)); + target.put(directoryId, ref); } } - return resultMap; + directories.forEach( + directory -> + directory + .withService(serviceMap.get(directory.getId())) + .withParent(parentMap.get(directory.getId()))); } private void fetchAndSetStatistics(List directories, EntityUtil.Fields fields) { @@ -600,7 +609,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro List.of( Pair.of(8, TagLabel.TagSource.CLASSIFICATION), Pair.of(9, TagLabel.TagSource.GLOSSARY)))) - .withDomains(getDomains(printer, csvRecord, 10)) + .withDomains(getDomains(printer, csvRecord, 10, newDirectory.getDomains())) .withDataProducts(getDataProducts(printer, csvRecord, 11)); if (processRecord) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DriveServiceRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DriveServiceRepository.java index 59ebb4aff53b..91ba74d4c8fe 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DriveServiceRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DriveServiceRepository.java @@ -205,10 +205,10 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro .withFullyQualifiedName(directoryFqn); } - // Update directory fields from CSV + // Update directory fields from CSV (header order: name, displayName, description, ...) directory - .withDescription(csvRecord.get(1)) - .withDisplayName(csvRecord.get(2)) + .withDisplayName(csvRecord.get(1)) + .withDescription(csvRecord.get(2)) .withOwners(getOwners(printer, csvRecord, 3)) .withTags( getTagLabels( @@ -217,7 +217,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro List.of( Pair.of(4, TagLabel.TagSource.CLASSIFICATION), Pair.of(5, TagLabel.TagSource.GLOSSARY)))) - .withDomains(getDomains(printer, csvRecord, 6)) + .withDomains(getDomains(printer, csvRecord, 6, directory.getDomains())) .withExtension(getExtension(printer, csvRecord, 7)); if (processRecord) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityDAO.java index 25a6bad4ef98..a36021c63104 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityDAO.java @@ -636,27 +636,33 @@ int listCount( @Define("mysqlCond") String mysqlCond, @Define("postgresCond") String postgresCond); + // Deferred join: the cursor page is resolved index-only on (name, id) inside the derived table, + // then
.json is fetched by primary key for only the :limit paged rows. Selecting json in + // the ORDER BY ... LIMIT scan makes MySQL pack the LONGTEXT blob into the filesort as an addon + // field, which exhausts sort_buffer_size and throws ER_OUT_OF_SORTMEMORY ("Out of sort memory") + // on wide entities (e.g. table_entity with many columns) once a single sort row exceeds the + // buffer. See idx_
_name_id and #28888. @ConnectionAwareSqlQuery( value = - "SELECT json FROM (" - + "SELECT
.name,
.id,
.json FROM
AND " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + "(
.name < :beforeName OR (
.name = :beforeName AND
.id < :beforeId)) " - + // Pagination by entity name or id (when entity name same) - "ORDER BY
.name DESC,
.id DESC " - + // Pagination by entity name or id (when entity name same) - "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id", + + "ORDER BY
.name DESC,
.id DESC " + + "LIMIT :limit" + + ") last_rows_subquery ON
.id = last_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = MYSQL) @ConnectionAwareSqlQuery( value = - "SELECT json FROM (" - + "SELECT
.name,
.id,
.json FROM
AND " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + "(
.name < :beforeName OR (
.name = :beforeName AND
.id < :beforeId)) " - + // Pagination by entity id or name (when entity have same name) - "ORDER BY
.name DESC,
.id DESC " - + // Pagination by entity id or name (when entity have same name) - "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id", + + "ORDER BY
.name DESC,
.id DESC " + + "LIMIT :limit" + + ") last_rows_subquery ON
.id = last_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = POSTGRES) List listBefore( @Define("table") String table, @@ -669,17 +675,25 @@ List listBefore( @ConnectionAwareSqlQuery( value = - "SELECT
.json FROM
AND " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + "(
.name > :afterName OR (
.name = :afterName AND
.id > :afterId)) " + "ORDER BY
.name,
.id " - + "LIMIT :limit", + + "LIMIT :limit" + + ") next_rows_subquery ON
.id = next_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = MYSQL) @ConnectionAwareSqlQuery( value = - "SELECT
.json FROM
AND " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + "(
.name > :afterName OR (
.name = :afterName AND
.id > :afterId)) " + "ORDER BY
.name,
.id " - + "LIMIT :limit", + + "LIMIT :limit" + + ") next_rows_subquery ON
.id = next_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = POSTGRES) List listAfter( @Define("table") String table, @@ -707,30 +721,33 @@ int listCountDistinct( @Define("postgresCond") String postgresCond, @Define("distinctColumn") String distinctColumn); + // Deferred join (see listBefore/listAfter above): resolve the cursor page index-only on (name, + // id) in the derived table (groupBy collapses any JOIN fan-out to one id per row), then fetch + // json by primary key for only the paged rows so the json blob never enters the filesort. Callers + // must group on the (name, id) key, not on
.json. @ConnectionAwareSqlQuery( value = - "SELECT json FROM (" - + "SELECT
.name,
.id,
.json FROM
AND " - + "(
.name < :beforeName OR (
.name = :beforeName AND
.id < :beforeId)) " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + + "(
.name < :beforeName OR (
.name = :beforeName AND
.id < :beforeId)) " + " " - + // Pagination by entity id or name (when entity have same name) - "ORDER BY
.name DESC,
.id DESC " - + // Pagination by entity id or name (when entity have same name) - "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id", + + "ORDER BY
.name DESC,
.id DESC " + + "LIMIT :limit" + + ") last_rows_subquery ON
.id = last_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = MYSQL) @ConnectionAwareSqlQuery( value = - "SELECT json FROM (" - + "SELECT
.name,
.id,
.json FROM
AND " - + "(
.name < :beforeName OR (
.name = :beforeName AND
.id < :beforeId)) " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + + "(
.name < :beforeName OR (
.name = :beforeName AND
.id < :beforeId)) " + " " - + // Pagination by entity fullyQualifiedName or name (when entity does not have fqn) - "ORDER BY
.name DESC,
.id DESC " - + // Pagination ordering by entity fullyQualifiedName or name (when entity does not - // have fqn) - "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id", + + "ORDER BY
.name DESC,
.id DESC " + + "LIMIT :limit" + + ") last_rows_subquery ON
.id = last_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = POSTGRES) List listBefore( @Define("table") String table, @@ -743,19 +760,27 @@ List listBefore( @ConnectionAwareSqlQuery( value = - "SELECT
.json FROM
AND " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + "(
.name > :afterName OR (
.name = :afterName AND
.id > :afterId)) " + " " + "ORDER BY
.name,
.id " - + "LIMIT :limit", + + "LIMIT :limit" + + ") next_rows_subquery ON
.id = next_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = MYSQL) @ConnectionAwareSqlQuery( value = - "SELECT
.json FROM
AND " - + "(
.name > :afterName OR (
.name = :afterName AND
.id > :afterId)) " + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + + "(
.name > :afterName OR (
.name = :afterName AND
.id > :afterId)) " + " " + "ORDER BY
.name,
.id " - + "LIMIT :limit", + + "LIMIT :limit" + + ") next_rows_subquery ON
.id = next_rows_subquery.id " + + "ORDER BY
.name,
.id", connectionType = POSTGRES) List listAfter( @Define("table") String table, @@ -766,15 +791,18 @@ List listAfter( @Bind("afterId") String afterId, @Define("groupBy") String groupBy); + // Deferred join (see the ConnectionAware listBefore/listAfter above): resolve the cursor page + // index-only on (name, id), then fetch json by primary key for only the :limit paged rows so the + // ORDER BY ... LIMIT filesort never materializes the json blob and cannot exhaust sort memory. @SqlQuery( - "SELECT json FROM (" - + "SELECT id,name, json FROM
AND " - + "(name < :beforeName OR (name = :beforeName AND id < :beforeId)) " - + // Pagination by entity id or name (when entity have same name) - "ORDER BY name DESC, id DESC " - + // Pagination by entity id or name (when entity have same name) - "LIMIT :limit" - + ") last_rows_subquery ORDER BY name,id") + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + + "(
.name < :beforeName OR (
.name = :beforeName AND
.id < :beforeId)) " + + "ORDER BY
.name DESC,
.id DESC " + + "LIMIT :limit" + + ") last_rows_subquery ON
.id = last_rows_subquery.id " + + "ORDER BY
.name,
.id") List listBefore( @Define("table") String table, @BindMap Map params, @@ -784,7 +812,14 @@ List listBefore( @Bind("beforeId") String beforeId); @SqlQuery( - "SELECT json FROM
AND (
.name > :afterName OR (
.name = :afterName AND
.id > :afterId)) ORDER BY name,id LIMIT :limit") + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
AND " + + "(
.name > :afterName OR (
.name = :afterName AND
.id > :afterId)) " + + "ORDER BY
.name,
.id " + + "LIMIT :limit" + + ") next_rows_subquery ON
.id = next_rows_subquery.id " + + "ORDER BY
.name,
.id") List listAfter( @Define("table") String table, @BindMap Map params, @@ -819,7 +854,17 @@ List migrationListAfterWithOffset( @Define("nameHashColumn") String nameHashColumnName, @Bind("limit") int limit); - @SqlQuery("SELECT json FROM
ORDER BY name, id LIMIT :limit OFFSET :offset") + // Deferred join (see listAfter/listBefore above): sort the offset window index-only on (name, id) + // and fetch json by primary key for only the returned rows, so the json blob never enters the + // filesort and cannot exhaust sort memory on large tables. + @SqlQuery( + "SELECT
.json FROM
" + + "INNER JOIN (" + + "SELECT
.id FROM
" + + "ORDER BY
.name,
.id " + + "LIMIT :limit OFFSET :offset" + + ") offset_subquery ON
.id = offset_subquery.id " + + "ORDER BY
.name,
.id") List listAfter( @Define("table") String table, @BindMap Map params, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java index 47a99c024d31..f34fb150cfc7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java @@ -2485,7 +2485,17 @@ public ResultList listAfter( String beforeCursor; String afterCursor = null; - beforeCursor = after == null || after.isEmpty() ? null : getCursorValue(entities.get(0)); + if (after == null || after.isEmpty()) { + beforeCursor = null; // genuine first page — no page before it + } else if (entities.isEmpty()) { + // Valid cursor but every row past it was deleted concurrently, so the page is empty. Echo + // the caller's own cursor as beforeCursor rather than null: a null before reads as "first + // page" and dead-ends backward navigation, whereas echoing lets the caller page back to + // the rows that still exist. Also guards entities.getFirst() from IndexOutOfBounds (500). + beforeCursor = after; + } else { + beforeCursor = getCursorValue(entities.getFirst()); + } if (entities.size() > limitParam) { // If extra result exists, then next page exists - return after cursor entities.remove(limitParam); @@ -2592,6 +2602,14 @@ public ResultList listBefore( // the same logical filter under a different cache field than listAfter / listAfterWithOffset. int total = ListCountCache.getOrCompute(entityType, filter, () -> dao.listCount(filter)); + if (limitParam <= 0) { + // limit == 0 → count-only request. Mirror listAfter and skip the query/cursor math: with + // limitParam 0 the "extra row" branch below removes the only fetched row and then calls + // getFirst() on an empty list, throwing IndexOutOfBounds (HTTP 500) on reverse count + // requests. + return getResultList(new ArrayList<>(), null, null, total); + } + // Reverse scrolling - Get one extra result used for computing before cursor Map cursorMap = parseCursorMap(RestUtil.decodeCursor(before)); String beforeName = FullyQualifiedName.unquoteName(cursorMap.get("name")); @@ -2607,9 +2625,13 @@ public ResultList listBefore( if (entities.size() > limitParam) { // If extra result exists, then previous page exists - return before cursor entities.remove(0); - beforeCursor = getCursorValue(entities.get(0)); + beforeCursor = getCursorValue(entities.getFirst()); } - afterCursor = getCursorValue(entities.get(entities.size() - 1)); + // entities can be empty when the caller holds a valid before-cursor but all earlier rows were + // deleted concurrently, so the page is empty. Echo the caller's cursor as afterCursor rather + // than null: a null after reads as end-of-pagination and dead-ends forward navigation, whereas + // echoing lets the caller page forward to rows that still exist. Also guards getLast() (500). + afterCursor = entities.isEmpty() ? before : getCursorValue(entities.getLast()); return getResultList(entities, beforeCursor, afterCursor, total); } @@ -4909,6 +4931,7 @@ void invalidate(T entity) { EntityCacheRepair.scheduleRepair( entityType, entity.getId(), entity.getFullyQualifiedName(), null); invalidateCache(entity); + CacheBundle.invalidateEntity(entityType, entity.getId(), entity.getFullyQualifiedName()); } @Transaction @@ -10276,6 +10299,7 @@ private void invalidateCachesAfterStore() { // so the next GET on this instance can't race an in-flight async repopulate. EntityRepository.this.writeThroughCache(updated, true); RequestEntityCache.invalidate(entityType, id, fqn); + CacheBundle.invalidateEntity(entityType, id, fqn); EntityCacheRepair.scheduleRepair(entityType, id, fqn, originalFqn); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FileRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FileRepository.java index 895600cea1f1..0154ce8b41ee 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FileRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FileRepository.java @@ -417,7 +417,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro List.of( Pair.of(12, TagLabel.TagSource.CLASSIFICATION), Pair.of(13, TagLabel.TagSource.GLOSSARY)))) - .withDomains(getDomains(printer, csvRecord, 14)) + .withDomains(getDomains(printer, csvRecord, 14, newFile.getDomains())) .withDataProducts(getDataProducts(printer, csvRecord, 15)); if (processRecord) { createEntity(printer, csvRecord, newFile, FILE); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryRepository.java index c424ad6f56b6..94b0c9c9f880 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryRepository.java @@ -89,7 +89,6 @@ import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.EntityUtil.RelationIncludes; import org.openmetadata.service.util.FullyQualifiedName; -import org.openmetadata.service.util.MemoryOwnership; @Slf4j public class GlossaryRepository extends EntityRepository { @@ -676,13 +675,6 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { compareAndUpdate("name", () -> updateName(updated)); // Mutually exclusive cannot be updated updated.setMutuallyExclusive(original.getMutuallyExclusive()); - MemoryOwnership.releaseIfHumanEdited(updated, operation.isPatch(), managedFieldChanged()); - } - - private boolean managedFieldChanged() { - return !Objects.equals(original.getName(), updated.getName()) - || !Objects.equals(original.getDisplayName(), updated.getDisplayName()) - || !Objects.equals(original.getDescription(), updated.getDescription()); } public void updateName(Glossary updated) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryTermRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryTermRepository.java index 62898b97d41c..d5f2c7508e9d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryTermRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryTermRepository.java @@ -127,7 +127,6 @@ import org.openmetadata.service.util.EntityUtil.RelationIncludes; import org.openmetadata.service.util.FullyQualifiedName; import org.openmetadata.service.util.IntakeFormValidator; -import org.openmetadata.service.util.MemoryOwnership; import org.openmetadata.service.util.RequestEntityCache; import org.openmetadata.service.util.RestUtil; import org.openmetadata.service.workflows.searchIndex.ReindexingUtil; @@ -138,7 +137,6 @@ public class GlossaryTermRepository extends EntityRepository { "Entity Details is unavailable in Elastic Search. Please reindex to get more Information."; private static final String UPDATE_FIELDS = "references,relatedTerms,synonyms,style"; private static final String PATCH_FIELDS = "references,relatedTerms,synonyms,style"; - static final String FIELD_DERIVED_FROM = "derivedFrom"; final FeedRepository feedRepository = Entity.getFeedRepository(); private InheritedFieldEntitySearch inheritedFieldEntitySearch; @@ -258,20 +256,6 @@ public void setFields(GlossaryTerm entity, Fields fields, RelationIncludes relat fields.contains("usageCount") ? getUsageCount(entity) : entity.getUsageCount()); entity.withChildrenCount( fields.contains("childrenCount") ? getChildrenCount(entity) : entity.getChildrenCount()); - if (fields.contains(FIELD_DERIVED_FROM)) { - entity.setDerivedFrom(getDerivedFrom(entity)); - } - } - - /** - * Returns the context memory from which the Memory Agent created this glossary term. - * Edge direction: from=term → to=memory via DERIVED_FROM; findTo resolves the to-side (memory). - */ - private EntityReference getDerivedFrom(GlossaryTerm entity) { - final List refs = - findTo( - entity.getId(), Entity.GLOSSARY_TERM, Relationship.DERIVED_FROM, Entity.CONTEXT_MEMORY); - return nullOrEmpty(refs) ? null : refs.getFirst(); } @Override @@ -386,9 +370,6 @@ public void clearFields(GlossaryTerm entity, Fields fields) { entity.setRelatedTerms(fields.contains("relatedTerms") ? entity.getRelatedTerms() : null); entity.withUsageCount(fields.contains("usageCount") ? entity.getUsageCount() : null); entity.withChildrenCount(fields.contains("childrenCount") ? entity.getChildrenCount() : null); - if (!fields.contains(FIELD_DERIVED_FROM)) { - entity.setDerivedFrom(null); - } } @Override @@ -2095,13 +2076,6 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { compareAndUpdateAny(() -> updateNameAndParent(updated), "name", "parent", "glossary"); // Mutually exclusive cannot be updated updated.setMutuallyExclusive(original.getMutuallyExclusive()); - MemoryOwnership.releaseIfHumanEdited(updated, operation.isPatch(), managedFieldChanged()); - } - - private boolean managedFieldChanged() { - return !Objects.equals(original.getName(), updated.getName()) - || !Objects.equals(original.getDisplayName(), updated.getDisplayName()) - || !Objects.equals(original.getDescription(), updated.getDescription()); } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/KnowledgePageRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/KnowledgePageRepository.java index 9b04dbd7501a..7dd9b39fee5b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/KnowledgePageRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/KnowledgePageRepository.java @@ -32,7 +32,6 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Jdbi; -import org.jdbi.v3.sqlobject.transaction.Transaction; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.feed.CloseTask; import org.openmetadata.schema.api.feed.ResolveTask; @@ -41,7 +40,6 @@ import org.openmetadata.schema.entity.data.Article; import org.openmetadata.schema.entity.data.Page; import org.openmetadata.schema.entity.data.PageHierarchy; -import org.openmetadata.schema.entity.data.PageProcessingStatus; import org.openmetadata.schema.entity.data.PageType; import org.openmetadata.schema.entity.data.QuickLink; import org.openmetadata.schema.entity.feed.Thread; @@ -60,16 +58,13 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; -import org.openmetadata.service.drive.PageContextProcessingEngineHolder; import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.governance.workflows.WorkflowHandler; -import org.openmetadata.service.llm.LLMClientHolder; import org.openmetadata.service.resources.feeds.MessageParser; import org.openmetadata.service.resources.knowledge.KnowledgePageResource; import org.openmetadata.service.search.PropagationDescriptor; import org.openmetadata.service.search.vector.PageBodyTextContributor; import org.openmetadata.service.security.AuthorizationException; -import org.openmetadata.service.util.AISettingsUtil; import org.openmetadata.service.util.EntityUtil; import org.openmetadata.service.util.EntityUtil.RelationIncludes; import org.openmetadata.service.util.FullyQualifiedName; @@ -89,7 +84,6 @@ public class KnowledgePageRepository extends EntityRepository { private static final String KNOWLEDGE_UPDATE_FIELDS = "page,relatedEntities,parent,children"; public static final String RELATED_ENTITIES = "relatedEntities"; public static final String EDITORS = "editors"; - public static final String MEMORY_COUNT = "memoryCount"; public static final String KNOWLEDGE_PAGE_TERM_SEARCH_INDEX = "page"; private final CollectionDAO.KnowledgePageDAO daoExtension; private final CollectionDAO.AssetDAO assetDAO; @@ -136,15 +130,6 @@ public void setFields( fields.contains(FIELD_PARENT) ? getParent(knowledgePage) : knowledgePage.getParent()); knowledgePage.setChildren( fields.contains("children") ? getChildren(knowledgePage) : knowledgePage.getChildren()); - if (fields.contains(MEMORY_COUNT)) { - knowledgePage.setMemoryCount( - findTo( - knowledgePage.getId(), - KNOWLEDGE_PAGE_ENTITY, - Relationship.MENTIONED_IN, - Entity.CONTEXT_MEMORY) - .size()); - } if (knowledgePage.getPageType().equals(PageType.ARTICLE)) { Article article = new Article(); if (knowledgePage.getPage() != null) { @@ -402,7 +387,7 @@ public void clearFields(Page entity, EntityUtil.Fields fields) { } @Override - public void prepare(Page knowledgePage, boolean update) { + public void prepare(Page knowledgePage, boolean b) { // Validate Related Entities List relatedEntities = knowledgePage.getRelatedEntities(); if (!nullOrEmpty(relatedEntities)) { @@ -418,12 +403,6 @@ public void prepare(Page knowledgePage, boolean update) { EntityUtil.populateEntityReferences(article.getRelatedArticles()); knowledgePage.setPage(article); - - // A new article with a body queues extraction in postCreate; stamp Queued in this same create - // so the status is persisted atomically rather than through a racing out-of-band write. - if (!update && !nullOrEmpty(knowledgePage.getDescription()) && isExtractionEnabled()) { - knowledgePage.setProcessingStatus(PageProcessingStatus.Queued); - } } } @@ -644,10 +623,6 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { // Update Related Terms updateRelatedEntities(original, updated); - recordExtractionStats(original, updated); - - recordProcessingStatus(original, updated); - // Updated Quick Link if (original.getPageType().equals(PageType.QUICK_LINK)) { QuickLink originalLink = JsonUtils.convertValue(original.getPage(), QuickLink.class); @@ -669,65 +644,6 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { updateParent(original, updated); } - /** - * extractionStats is engine-managed: the extraction throttle stamps it, and it is absent from - * CreatePage. Preserve the stored value when an update omits it so a body edit through PUT never - * wipes it, and persist a fresh stamp with updateVersion=false (the same treatment lifeCycle - * gets) so machine extraction does not churn the article's version history on every run. - */ - private void recordExtractionStats(Page original, Page updated) { - if (updated.getExtractionStats() == null) { - updated.setExtractionStats(original.getExtractionStats()); - } - recordChange( - "extractionStats", - original.getExtractionStats(), - updated.getExtractionStats(), - true, - EntityUtil.objectMatch, - false); - } - - /** - * processingStatus / processingError are machine-managed like extractionStats. An edit that - * changes an article's body (re)queues extraction, so stamp Queued here — in the user's own - * transaction — because a later out-of-band write would race the body change and could clobber - * it. Any other update preserves the stored values when the request omits them (so a body edit - * through PUT never wipes them), and both fields record with updateVersion=false so machine - * status transitions never churn the article's version history. - */ - private void recordProcessingStatus(Page original, Page updated) { - boolean bodyRequeued = - PageType.ARTICLE.equals(updated.getPageType()) - && !Objects.equals(original.getDescription(), updated.getDescription()) - && isExtractionEnabled(); - if (bodyRequeued) { - updated.setProcessingStatus(PageProcessingStatus.Queued); - updated.setProcessingError(null); - } else { - if (updated.getProcessingStatus() == null) { - updated.setProcessingStatus(original.getProcessingStatus()); - } - if (updated.getProcessingError() == null) { - updated.setProcessingError(original.getProcessingError()); - } - } - recordChange( - "processingStatus", - original.getProcessingStatus(), - updated.getProcessingStatus(), - false, - EntityUtil.objectMatch, - false); - recordChange( - "processingError", - original.getProcessingError(), - updated.getProcessingError(), - false, - EntityUtil.objectMatch, - false); - } - private void updateParent(Page original, Page updated) { UUID oldParentId = getId(original.getParent()); UUID newParentId = getId(updated.getParent()); @@ -901,75 +817,6 @@ public void postUpdate(Page original, Page updated) { } catch (EntityNotFoundException ignored) { } // No ApprovalTask is present, and thus we don't need to worry about this. } - - if (isArticleBodyChanged(original, updated)) { - schedulePillExtraction(updated.getId()); - } - } - - @Override - protected void postCreate(Page entity) { - super.postCreate(entity); - if (PageType.ARTICLE.equals(entity.getPageType()) && !nullOrEmpty(entity.getDescription())) { - schedulePillExtraction(entity.getId()); - } - } - - @Override - protected void postDelete(Page entity, boolean hardDelete) { - super.postDelete(entity, hardDelete); - if (LLMClientHolder.isEnabled()) { - PageContextProcessingEngineHolder.get().cancel(entity.getId()); - } - } - - // Knowledge-pill cleanup runs in the *AdditionalChildren hooks rather than postDelete because - // those fire while the page -> memory MENTIONED_IN edges still exist. postDelete runs after - // cleanup() has already deleted those edges on a hard delete, so a findTo there would match - // nothing and orphan the pills. The pills track the page's lifecycle: soft-deleted with it, - // hard-deleted with it, restored with it. Mirrors DashboardRepository's chart cascade. - @Override - @Transaction - protected void softDeleteAdditionalChildren(UUID pageId, String deletedBy) { - contextMemoryRepository().deleteExtractedMemories(pageId, KNOWLEDGE_PAGE_ENTITY, false); - } - - @Override - @Transaction - protected void hardDeleteAdditionalChildren(UUID pageId, String deletedBy) { - contextMemoryRepository().deleteExtractedMemories(pageId, KNOWLEDGE_PAGE_ENTITY, true); - } - - @Override - @Transaction - protected void restoreAdditionalChildren(UUID pageId, String updatedBy) { - contextMemoryRepository().restoreExtractedMemories(pageId, KNOWLEDGE_PAGE_ENTITY); - } - - private ContextMemoryRepository contextMemoryRepository() { - return (ContextMemoryRepository) Entity.getEntityRepository(Entity.CONTEXT_MEMORY); - } - - /** True when an article's markdown body changed — the only edit that warrants re-extraction. */ - private boolean isArticleBodyChanged(Page original, Page updated) { - return PageType.ARTICLE.equals(updated.getPageType()) - && !Objects.equals(original.getDescription(), updated.getDescription()); - } - - /** - * Hands the page to the in-memory throttle, which coalesces autosaves and runs extraction once the - * body settles. A no-op when the LLM is disabled, mirroring the file pipeline. - */ - private void schedulePillExtraction(UUID pageId) { - if (isExtractionEnabled()) { - PageContextProcessingEngineHolder.get().schedule(pageId); - } - } - - /** True when the LLM is configured and article (page) memory extraction is toggled on. */ - private boolean isExtractionEnabled() { - return LLMClientHolder.isEnabled() - && AISettingsUtil.isPageExtractionEnabled(AISettingsUtil.get()); } private void closeApprovalTask(Page entity, String comment) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java index 75193d690253..eaf3e230f90f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -25,6 +26,10 @@ public class ListFilter extends Filter { public static final String NULL_PARAM = "null"; + private static final String TASK_STATUS_GROUP_OPEN = "open"; + private static final String TASK_STATUS_GROUP_ACTIVE = "active"; + private static final String TASK_STATUS_GROUP_CLOSED = "closed"; + public ListFilter() { this(Include.NON_DELETED); } @@ -66,6 +71,7 @@ public String getCondition(String tableName) { conditions.add(getFileTypeCondition(tableName)); conditions.add(getAssignee()); conditions.add(getCreatedByCondition()); + conditions.add(getUpdatedByCondition(tableName)); conditions.add(getAboutEntityCondition()); conditions.add(getMentionedUserCondition()); conditions.add(getEventSubscriptionAlertType()); @@ -89,8 +95,6 @@ public String getCondition(String tableName) { conditions.add(getEntityStatusCondition(tableName)); conditions.add(getServerIdCondition()); conditions.add(getNameFilterCondition()); - conditions.add(getSourceFileCondition()); - conditions.add(getSourceEntityCondition()); conditions.add(getPrimaryEntityCondition()); conditions.add(getFolderCondition()); String condition = addCondition(conditions); @@ -132,39 +136,6 @@ public ResourceContext getParentResourceContext() { return null; } - /** Filters context memories down to the knowledge pills extracted from a given context file. */ - private String getSourceFileCondition() { - String sourceFileId = queryParams.get("sourceFileId"); - String result = ""; - if (!nullOrEmpty(sourceFileId)) { - queryParams.put("sourceFileIdParam", sourceFileId); - result = - String.format( - "(id IN (SELECT entity_relationship.toId FROM entity_relationship " - + "WHERE entity_relationship.fromEntity = 'contextFile' " - + "AND entity_relationship.fromId = :sourceFileIdParam " - + "AND entity_relationship.relation = %d))", - Relationship.MENTIONED_IN.ordinal()); - } - return result; - } - - /** Filters context memories down to the knowledge pills extracted from any source entity. */ - private String getSourceEntityCondition() { - String sourceEntityId = queryParams.get("sourceEntityId"); - String result = ""; - if (!nullOrEmpty(sourceEntityId)) { - queryParams.put("sourceEntityIdParam", sourceEntityId); - result = - String.format( - "(id IN (SELECT entity_relationship.toId FROM entity_relationship " - + "WHERE entity_relationship.fromId = :sourceEntityIdParam " - + "AND entity_relationship.relation = %d))", - Relationship.MENTIONED_IN.ordinal()); - } - return result; - } - /** * Filters context memories down to the knowledge pills whose primaryEntity is the given asset. * Edge direction: primaryEntity --APPLIED_TO--> contextMemory, so the memory is the {@code toId}. @@ -314,6 +285,23 @@ private String getCreatedByCondition() { inCondition, Relationship.CREATED.ordinal()); } + /** + * Filter by the user recorded in the entity's {@code updatedBy} column (the last writer). For a + * soft-deleted entity this is the user who archived it, since an archived entity cannot be edited. + * Matches the generated {@code updatedBy} column directly (plain username, comma-separated list + * supported). Qualifies the column with the table name when available so it stays unambiguous if a + * joined table ever exposes its own {@code updatedBy}. + */ + private String getUpdatedByCondition(String tableName) { + String updatedBy = queryParams.get("updatedBy"); + if (nullOrEmpty(updatedBy)) { + return ""; + } + String columnName = tableName == null ? "updatedBy" : tableName + ".updatedBy"; + String inCondition = buildIndexedBindParams("updatedBy", updatedBy); + return String.format("%s IN (%s)", columnName, inCondition); + } + private String getWorkflowDefinitionIdCondition() { String workflowDefinitionId = queryParams.get("workflowDefinitionId"); return workflowDefinitionId == null ? "" : "workflowDefinitionId = :workflowDefinitionId"; @@ -751,10 +739,9 @@ public String getDisabledCondition() { } } else { if (disabled) { - disabledCondition = "((c.json#>'{disabled}')::boolean) = TRUE)"; + disabledCondition = "(json->>'disabled')::boolean = TRUE"; } else { - disabledCondition = - "(c.json#>'{disabled}' IS NULL OR ((c.json#>'{disabled}'):boolean) = FALSE"; + disabledCondition = "(json->>'disabled' IS NULL OR (json->>'disabled')::boolean = FALSE)"; } } return disabledCondition; @@ -1126,40 +1113,54 @@ public static String escape(String name) { private String getTaskStatusCondition(String tableName) { String statusGroup = queryParams.get("taskStatusGroup"); + String column = tableName == null ? "status" : tableName + ".status"; + String typeCol = tableName == null ? "type" : tableName + ".type"; + String condition = null; if (statusGroup != null) { - String column = tableName == null ? "status" : tableName + ".status"; - if ("open".equalsIgnoreCase(statusGroup)) { - return String.format("%s IN ('Open', 'InProgress', 'Pending')", column); - } else if ("active".equalsIgnoreCase(statusGroup)) { - // ManualRevoke means access is still live at the source waiting for a human to confirm - // the revoke — non-terminal, so belongs in 'active'. Keep in sync with - // {@code CreateTask.isTerminalTaskStatus} and {@code - // TaskRepository.NON_TERMINAL_TASK_STATUSES}. - return String.format( - "%s IN ('Open', 'InProgress', 'Pending', 'Approved', 'Granted', 'ManualRevoke')", - column); - } else if ("closed".equalsIgnoreCase(statusGroup)) { - // 'Approved' is intentionally a member of both 'active' and 'closed' because the - // same status maps to different lifecycle meanings depending on the task type: - // - Glossary/DescriptionUpdate/etc.: 'Approved' is the terminal state and must - // surface in the existing Closed tab. - // - DataAccessRequest: 'Approved' means "awaiting grant" — non-terminal — and - // callers reach those tasks via the 'active' group instead. - // Removing 'Approved' here would regress the Closed tab UX for the older workflows. - // A future refactor could make status group resolution task-type aware. - return String.format( - "%s IN ('Approved', 'Rejected', 'Completed', 'Cancelled', 'Failed', 'Revoked', 'Expired')", - column); - } + condition = buildTaskStatusGroupCondition(statusGroup, column, typeCol); } + if (condition == null) { + condition = buildExplicitTaskStatusCondition(column); + } + return condition; + } + /** + * Row-aware bucket predicates driven by {@link TaskBucketSql}. See that class for the bucket + * definitions and drift-guard test. Every {@code (type, status)} combination lands in exactly + * one of {@code open}/{@code closed} so {@code All = Open + Closed} reconciles for the mixed + * inbox. Keep in sync with {@link CollectionDAO.TaskDAO#getTaskCountSummary}. + */ + private String buildTaskStatusGroupCondition(String statusGroup, String column, String typeCol) { + return switch (statusGroup.toLowerCase(Locale.ROOT)) { + case TASK_STATUS_GROUP_OPEN -> String.format( + "(%1$s IN (%2$s) OR (%3$s = '%4$s' AND %1$s = '%5$s'))", + column, + TaskBucketSql.SHARED_OPEN_STATUSES, + typeCol, + TaskBucketSql.TASK_TYPE_DAR, + TaskBucketSql.STATUS_APPROVED); + case TASK_STATUS_GROUP_ACTIVE -> String.format( + "%s IN (%s)", column, TaskBucketSql.ACTIVE_STATUSES); + case TASK_STATUS_GROUP_CLOSED -> String.format( + "(%1$s IN (%2$s) OR (%3$s <> '%4$s' AND %1$s = '%5$s'))", + column, + TaskBucketSql.SHARED_TERMINAL_STATUSES, + typeCol, + TaskBucketSql.TASK_TYPE_DAR, + TaskBucketSql.STATUS_APPROVED); + default -> null; + }; + } + + private String buildExplicitTaskStatusCondition(String column) { String taskStatus = queryParams.get("taskStatus"); - if (nullOrEmpty(taskStatus)) { - return ""; + String result = ""; + if (!nullOrEmpty(taskStatus)) { + String inCondition = buildIndexedBindParams("taskStatus", taskStatus); + result = String.format("%s IN (%s)", column, inCondition); } - String column = tableName == null ? "status" : tableName + ".status"; - String inCondition = buildIndexedBindParams("taskStatus", taskStatus); - return String.format("%s IN (%s)", column, inCondition); + return result; } // Restricts tasks to a [startTs, endTs] window on createdAt. Inlines the diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/McpConversationRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/McpConversationRepository.java deleted file mode 100644 index da7530e2a7ac..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/McpConversationRepository.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.jdbi3; - -import java.util.List; -import java.util.UUID; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.api.chat.CreateMcpConversation; -import org.openmetadata.schema.entity.chat.McpConversation; -import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.exception.CatalogExceptionMessage; -import org.openmetadata.service.exception.EntityNotFoundException; - -@Slf4j -public class McpConversationRepository { - private final CollectionDAO.McpConversationDAO dao; - - public McpConversationRepository(CollectionDAO.McpConversationDAO dao) { - this.dao = dao; - } - - public McpConversation create(CreateMcpConversation request, EntityReference user) { - UUID id = UUID.randomUUID(); - long now = System.currentTimeMillis(); - McpConversation conversation = - new McpConversation() - .withId(id) - .withUser(user) - .withCreatedAt(now) - .withUpdatedAt(now) - .withCreatedBy(user.getName()) - .withUpdatedBy(user.getName()) - .withTitle(request.getTitle()) - .withMessageCount(0); - dao.insert(JsonUtils.pojoToJson(conversation)); - return conversation; - } - - public McpConversation getById(UUID id) { - String json = dao.getById(id); - if (json == null) { - throw EntityNotFoundException.byMessage( - CatalogExceptionMessage.entityNotFound("McpConversation", id.toString())); - } - return JsonUtils.readValue(json, McpConversation.class); - } - - public List listByUser(UUID userId, int limit, int offset) { - List rows = dao.listByUser(userId, limit, offset); - return JsonUtils.readObjects(rows, McpConversation.class); - } - - public McpConversation update(McpConversation conversation) { - conversation.setUpdatedAt(System.currentTimeMillis()); - dao.update(conversation.getId(), JsonUtils.pojoToJson(conversation)); - return conversation; - } - - public int countByUser(UUID userId) { - return dao.countByUser(userId); - } - - public void delete(UUID id) { - dao.delete(id); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/McpMessageRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/McpMessageRepository.java deleted file mode 100644 index ddab314ffc8e..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/McpMessageRepository.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.jdbi3; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.api.chat.CreateMcpMessage; -import org.openmetadata.schema.entity.chat.McpMessage; -import org.openmetadata.schema.utils.JsonUtils; - -@Slf4j -public class McpMessageRepository { - private final CollectionDAO.McpMessageDAO dao; - - public McpMessageRepository(CollectionDAO.McpMessageDAO dao) { - this.dao = dao; - } - - public McpMessage create(CreateMcpMessage request, UUID conversationId, int messageIndex) { - UUID id = UUID.randomUUID(); - McpMessage message = - new McpMessage() - .withId(id) - .withConversationId(conversationId) - .withSender(request.getSender()) - .withIndex(messageIndex) - .withTimestamp(request.getTimestamp()) - .withContent(request.getContent()) - .withTokens(request.getTokens()); - dao.insert(JsonUtils.pojoToJson(message)); - return message; - } - - public List listByConversation(UUID conversationId, int limit, int offset) { - List rows = dao.listByConversation(conversationId, limit, offset); - return JsonUtils.readObjects(rows, McpMessage.class); - } - - public List listRecentByConversation(UUID conversationId, int limit) { - List rows = dao.listRecentByConversation(conversationId, limit); - List messages = new ArrayList<>(JsonUtils.readObjects(rows, McpMessage.class)); - Collections.reverse(messages); - return messages; - } - - public int countByConversation(UUID conversationId) { - return dao.countByConversation(conversationId); - } - - public void delete(UUID id) { - dao.delete(id); - } - - public void deleteByConversation(UUID conversationId) { - dao.deleteByConversation(conversationId); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java index 254589f8325a..5f32298bb71a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java @@ -33,7 +33,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.UUID; @@ -46,7 +45,9 @@ import org.openmetadata.csv.CsvExportProgressCallback; import org.openmetadata.csv.CsvImportProgressCallback; import org.openmetadata.csv.EntityCsv; +import org.openmetadata.schema.api.data.MetricDimension; import org.openmetadata.schema.api.data.MetricExpression; +import org.openmetadata.schema.api.data.MetricMeasure; import org.openmetadata.schema.entity.data.Metric; import org.openmetadata.schema.entity.teams.Team; import org.openmetadata.schema.type.EntityReference; @@ -72,13 +73,12 @@ import org.openmetadata.service.util.EntityFieldUtils; import org.openmetadata.service.util.EntityUtil; import org.openmetadata.service.util.EntityUtil.RelationIncludes; -import org.openmetadata.service.util.MemoryOwnership; +import org.openmetadata.service.util.FullyQualifiedName; @Slf4j public class MetricRepository extends EntityRepository { - private static final String UPDATE_FIELDS = "relatedMetrics,assets"; - private static final String PATCH_FIELDS = "relatedMetrics,assets"; - static final String FIELD_DERIVED_FROM = "derivedFrom"; + private static final String UPDATE_FIELDS = "relatedMetrics,assets,dimensions,measures,filters"; + private static final String PATCH_FIELDS = "relatedMetrics,assets,dimensions,measures,filters"; static final String FIELD_ASSETS = "assets"; public MetricRepository() { @@ -99,6 +99,28 @@ public MetricRepository() { @Override public void setFullyQualifiedName(Metric metric) { metric.setFullyQualifiedName(metric.getName()); + setDimensionFQNs(metric.getFullyQualifiedName(), metric.getDimensions()); + setMeasureFQNs(metric.getFullyQualifiedName(), metric.getMeasures()); + } + + private void setDimensionFQNs(String metricFqn, List dimensions) { + if (nullOrEmpty(dimensions)) { + return; + } + final String prefix = FullyQualifiedName.add(metricFqn, "dimension"); + for (final MetricDimension dimension : dimensions) { + dimension.setFullyQualifiedName(FullyQualifiedName.add(prefix, dimension.getName())); + } + } + + private void setMeasureFQNs(String metricFqn, List measures) { + if (nullOrEmpty(measures)) { + return; + } + final String prefix = FullyQualifiedName.add(metricFqn, "measure"); + for (final MetricMeasure measure : measures) { + measure.setFullyQualifiedName(FullyQualifiedName.add(prefix, measure.getName())); + } } @Override @@ -131,18 +153,12 @@ public void setFields( metric.setRelatedMetrics( fields.contains("relatedMetrics") ? getRelatedMetrics(metric) : metric.getRelatedMetrics()); metric.setAssets(fields.contains(FIELD_ASSETS) ? getAssets(metric) : metric.getAssets()); - if (fields.contains(FIELD_DERIVED_FROM)) { - metric.setDerivedFrom(getDerivedFrom(metric)); - } } @Override protected void clearFields(Metric entity, EntityUtil.Fields fields) { entity.setRelatedMetrics(fields.contains("relatedMetrics") ? entity.getRelatedMetrics() : null); entity.setAssets(fields.contains(FIELD_ASSETS) ? entity.getAssets() : null); - if (!fields.contains(FIELD_DERIVED_FROM)) { - entity.setDerivedFrom(null); - } } /** @@ -153,16 +169,6 @@ private List getAssets(Metric metric) { return findTo(metric.getId(), METRIC, Relationship.APPLIED_TO, null); } - /** - * Returns the context memory from which the Memory Agent created this metric. - * Edge direction: from=metric → to=memory via DERIVED_FROM; findTo resolves the to-side (memory). - */ - private EntityReference getDerivedFrom(Metric metric) { - final List refs = - findTo(metric.getId(), Entity.METRIC, Relationship.DERIVED_FROM, Entity.CONTEXT_MEMORY); - return nullOrEmpty(refs) ? null : refs.getFirst(); - } - // Individual field fetchers registered in constructor private void fetchAndSetRelatedMetrics(List metrics, EntityUtil.Fields fields) { if (!fields.contains("relatedMetrics") || metrics == null || metrics.isEmpty()) { @@ -510,17 +516,16 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { updated.getMetricExpression()); } }); + compareAndUpdate( + "dimensions", + () -> recordChange("dimensions", original.getDimensions(), updated.getDimensions())); + compareAndUpdate( + "measures", + () -> recordChange("measures", original.getMeasures(), updated.getMeasures())); + compareAndUpdate( + "filters", () -> recordChange("filters", original.getFilters(), updated.getFilters())); compareAndUpdate("relatedMetrics", () -> updateRelatedMetrics(original, updated)); compareAndUpdate(FIELD_ASSETS, () -> updateAssets(original, updated)); - MemoryOwnership.releaseIfHumanEdited(updated, operation.isPatch(), managedFieldChanged()); - } - - private boolean managedFieldChanged() { - return !Objects.equals(original.getName(), updated.getName()) - || !Objects.equals(original.getDisplayName(), updated.getDisplayName()) - || !Objects.equals(original.getDescription(), updated.getDescription()) - || !Objects.equals(original.getMetricType(), updated.getMetricType()) - || !Objects.equals(original.getMetricExpression(), updated.getMetricExpression()); } private void updateRelatedMetrics(Metric original, Metric updated) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PersonaRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PersonaRepository.java index c230ac393a7e..cccc9ab61c44 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PersonaRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PersonaRepository.java @@ -14,29 +14,83 @@ package org.openmetadata.service.jdbi3; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import static org.openmetadata.service.Entity.PERSONA; import static org.openmetadata.service.Entity.USER; +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Objects; +import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.sqlobject.transaction.Transaction; import org.openmetadata.schema.entity.teams.Persona; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.PersonaContextDefinition; import org.openmetadata.schema.type.Relationship; import org.openmetadata.schema.type.change.ChangeSource; +import org.openmetadata.schema.type.personaContext.ContextRule; +import org.openmetadata.schema.type.personaContext.ContextSection; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.aicontext.PersonaContextBuilder; +import org.openmetadata.service.aicontext.PersonaContextCache; import org.openmetadata.service.resources.teams.PersonaResource; +import org.openmetadata.service.security.policyevaluator.SubjectCache; import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.EntityUtil.RelationIncludes; @Slf4j public class PersonaRepository extends EntityRepository { - static final String PERSONA_UPDATE_FIELDS = "users,default"; - static final String PERSONA_PATCH_FIELDS = "users,default"; + static final String PERSONA_UPDATE_FIELDS = "users,default,contextDefinition"; + static final String PERSONA_PATCH_FIELDS = "users,default,contextDefinition"; + static final String FIELD_CONTEXT_DEFINITION = "contextDefinition"; static final String FIELD_USERS = "users"; + private static final int DEFAULT_MAX_ASSETS = 200; + private static final int MAX_RULES = 25; + private static final int MIN_CHARACTER_BUDGET = 10_000; + private static final int MAX_CHARACTER_BUDGET = 2_000_000; + private static final int MIN_CACHE_TTL_MINUTES = 1; + private static final int MAX_CACHE_TTL_MINUTES = 1_440; + private static final Set ASSET_SECTIONS = + Set.of( + ContextSection.DESCRIPTION, + ContextSection.SCHEMA, + ContextSection.CONSTRAINTS, + ContextSection.JOINS, + ContextSection.TAGS, + ContextSection.GLOSSARY_TERMS, + ContextSection.ARTICLES, + ContextSection.METRICS, + ContextSection.LINEAGE, + ContextSection.PROFILE, + ContextSection.DATA_QUALITY); + private static final Set ARTICLE_SECTIONS = + Set.of( + ContextSection.TITLE_SUMMARY, + ContextSection.FULL_BODY, + ContextSection.TAGS, + ContextSection.GLOSSARY_TERMS, + ContextSection.RELATED_ASSETS); + private static final Set METRIC_SECTIONS = + Set.of( + ContextSection.DEFINITION, + ContextSection.FORMULA_EXPRESSION, + ContextSection.UNIT_GRAIN, + ContextSection.OWNER, + ContextSection.TAGS, + ContextSection.RELATED_ASSETS); + private static final Set GLOSSARY_TERM_SECTIONS = + Set.of( + ContextSection.DEFINITION, + ContextSection.SYNONYMS, + ContextSection.RELATED_TERMS, + ContextSection.TAGS, + ContextSection.RELATED_ASSETS); public PersonaRepository() { super( @@ -57,12 +111,15 @@ public void setFields(Persona persona, Fields fields, RelationIncludes relationI @Override public void clearFields(Persona persona, Fields fields) { + persona.setContextDefinition( + fields.contains(FIELD_CONTEXT_DEFINITION) ? persona.getContextDefinition() : null); persona.setUsers(fields.contains(FIELD_USERS) ? persona.getUsers() : null); } @Override public void prepare(Persona persona, boolean update) { validateUsers(persona.getUsers()); + validateContextDefinition(persona.getContextDefinition()); if (Boolean.TRUE.equals(persona.getDefault())) { unsetExistingDefaultPersona(persona.getId().toString()); } @@ -129,6 +186,118 @@ public Persona getSystemDefaultPersona() { return null; } + static void validateContextDefinition(PersonaContextDefinition definition) { + if (definition == null) { + return; + } + definition.setLastGeneratedAt(null); + definition.setCacheState(null); + definition.setLastError(null); + if (definition.getCharacterBudget() == null + || definition.getCharacterBudget() < MIN_CHARACTER_BUDGET + || definition.getCharacterBudget() > MAX_CHARACTER_BUDGET) { + throw new IllegalArgumentException( + "Persona context characterBudget must be between 10000 and 2000000"); + } + if (definition.getCacheTtlMinutes() == null + || definition.getCacheTtlMinutes() < MIN_CACHE_TTL_MINUTES + || definition.getCacheTtlMinutes() > MAX_CACHE_TTL_MINUTES) { + throw new IllegalArgumentException( + "Persona context cacheTtlMinutes must be between 1 and 1440"); + } + if (listOrEmpty(definition.getRules()).size() > MAX_RULES) { + throw new IllegalArgumentException("Persona context supports at most 25 rules"); + } + Set ruleIds = new HashSet<>(); + Set ruleNames = new HashSet<>(); + for (ContextRule rule : listOrEmpty(definition.getRules())) { + if (rule.getId() == null) { + rule.setId(UUID.randomUUID()); + } + if (!ruleIds.add(rule.getId())) { + throw new IllegalArgumentException( + "Persona context rule IDs must be unique: " + rule.getId()); + } + rule.setMatchedCount(null); + String ruleName = rule.getName() == null ? "" : rule.getName().trim(); + if (nullOrEmpty(ruleName)) { + throw new IllegalArgumentException("Persona context rule name must not be empty"); + } + rule.setName(ruleName); + if (!ruleNames.add(ruleName.toLowerCase(Locale.ROOT))) { + throw new IllegalArgumentException( + "Persona context rule names must be unique: " + ruleName); + } + String ruleEntityType = rule.getEntityType(); + if (!PersonaContextBuilder.supportsEntityType(ruleEntityType)) { + throw new IllegalArgumentException( + "Unsupported persona context entity type: " + ruleEntityType); + } + if (PersonaContextBuilder.isKnowledgeEntityType(ruleEntityType)) { + rule.setFullyRendered(true); + } + if (nullOrEmpty(rule.getSections())) { + rule.setSections(defaultSections(ruleEntityType)); + } + if (rule.getMaxAssets() == null) { + rule.setMaxAssets(DEFAULT_MAX_ASSETS); + } else if (rule.getMaxAssets() < 1 || rule.getMaxAssets() > 1000) { + throw new IllegalArgumentException( + "Persona context rule maxAssets must be between 1 and 1000: " + ruleName); + } + Set allowedSections = allowedSections(ruleEntityType); + if (!allowedSections.containsAll(rule.getSections())) { + throw new IllegalArgumentException( + "Persona context rule contains sections that do not apply to " + ruleEntityType); + } + if (!nullOrEmpty(rule.getQueryFilter())) { + JsonNode queryFilter = JsonUtils.readTree(rule.getQueryFilter()); + if (queryFilter == null || !queryFilter.isObject()) { + throw new IllegalArgumentException( + "Persona context queryFilter must be a JSON object for rule: " + rule.getName()); + } + } + } + } + + private static Set allowedSections(String entityType) { + return switch (entityType) { + case Entity.PAGE -> ARTICLE_SECTIONS; + case Entity.METRIC -> METRIC_SECTIONS; + case Entity.GLOSSARY_TERM -> GLOSSARY_TERM_SECTIONS; + default -> ASSET_SECTIONS; + }; + } + + private static Set defaultSections(String entityType) { + return switch (entityType) { + case Entity.PAGE -> Set.of( + ContextSection.TITLE_SUMMARY, ContextSection.FULL_BODY, ContextSection.TAGS); + case Entity.METRIC -> Set.of( + ContextSection.DEFINITION, ContextSection.FORMULA_EXPRESSION, ContextSection.UNIT_GRAIN); + case Entity.GLOSSARY_TERM -> Set.of(ContextSection.DEFINITION); + default -> Set.of( + ContextSection.DESCRIPTION, + ContextSection.SCHEMA, + ContextSection.CONSTRAINTS, + ContextSection.JOINS, + ContextSection.TAGS, + ContextSection.GLOSSARY_TERMS, + ContextSection.ARTICLES, + ContextSection.METRICS); + }; + } + + @Override + protected void postCreate(Persona persona) { + super.postCreate(persona); + if (Boolean.TRUE.equals(persona.getDefault())) { + SubjectCache.invalidateAllUserContexts(); + } else { + invalidateUserContexts(persona.getUsers(), List.of()); + } + } + @Override @Transaction protected void preDelete(Persona persona, String deletedBy) { @@ -162,6 +331,39 @@ protected void preDelete(Persona persona, String deletedBy) { for (EntityReference team : listOrEmpty(teams)) { invalidateCacheForEntity(Entity.TEAM, team.getId(), team.getFullyQualifiedName()); } + if (Boolean.TRUE.equals(persona.getDefault()) || !teams.isEmpty()) { + SubjectCache.invalidateAllUserContexts(); + } else { + invalidateUserContexts(users, defaultUsers); + } + } + + @Override + protected void postUpdate(Persona original, Persona updated) { + super.postUpdate(original, updated); + PersonaContextCache.getInstance().invalidate(original, updated); + } + + @Override + protected void postDelete(Persona persona, boolean hardDelete) { + PersonaContextCache.getInstance().invalidate(persona); + super.postDelete(persona, hardDelete); + } + + private boolean userAssignmentsMatch( + List originalUsers, List updatedUsers) { + Set originalUserIds = new HashSet<>(); + Set updatedUserIds = new HashSet<>(); + listOrEmpty(originalUsers).forEach(user -> originalUserIds.add(user.getId())); + listOrEmpty(updatedUsers).forEach(user -> updatedUserIds.add(user.getId())); + return originalUserIds.equals(updatedUserIds); + } + + private void invalidateUserContexts( + List originalUsers, List updatedUsers) { + List affectedUsers = new ArrayList<>(listOrEmpty(originalUsers)); + affectedUsers.addAll(listOrEmpty(updatedUsers)); + SubjectCache.invalidateUserContexts(affectedUsers); } /** Handles entity updated from PUT and POST operation. */ @@ -174,12 +376,21 @@ public PersonaUpdater(Persona original, Persona updated, Operation operation) { public void entitySpecificUpdate(boolean consolidatingChanges) { compareAndUpdate("users", () -> updateUsers(original, updated)); compareAndUpdate("default", () -> updateDefault(original, updated)); + compareAndUpdate( + "contextDefinition", + () -> + recordChange( + "contextDefinition", + original.getContextDefinition(), + updated.getContextDefinition(), + true)); } @Transaction private void updateUsers(Persona origPersona, Persona updatedPersona) { List origUsers = listOrEmpty(origPersona.getUsers()); List updatedUsers = listOrEmpty(updatedPersona.getUsers()); + boolean assignmentsChanged = !userAssignmentsMatch(origUsers, updatedUsers); updateToRelationships( "users", PERSONA, @@ -189,6 +400,9 @@ private void updateUsers(Persona origPersona, Persona updatedPersona) { origUsers, updatedUsers, false); + if (assignmentsChanged) { + deferReactOperation(() -> invalidateUserContexts(origUsers, updatedUsers)); + } } private void updateDefault(Persona origPersona, Persona updatedPersona) { @@ -196,6 +410,7 @@ private void updateDefault(Persona origPersona, Persona updatedPersona) { Boolean updatedDefault = updatedPersona.getDefault(); if (!Objects.equals(origDefault, updatedDefault)) { recordChange("default", origDefault, updatedDefault); + deferReactOperation(SubjectCache::invalidateAllUserContexts); } } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SecurityServiceRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SecurityServiceRepository.java index 9051b4461a23..85295545088c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SecurityServiceRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SecurityServiceRepository.java @@ -219,7 +219,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro .withTags( getTagLabels( printer, csvRecord, List.of(Pair.of(5, TagLabel.TagSource.CLASSIFICATION)))) - .withDomains(getDomains(printer, csvRecord, 6)); + .withDomains(getDomains(printer, csvRecord, 6, newSecurityService.getDomains())); if (processRecord) { createEntity(printer, csvRecord, newSecurityService, Entity.SECURITY_SERVICE); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServiceEntityRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServiceEntityRepository.java index 4a10bbdf3e1b..a72394e9df6a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServiceEntityRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServiceEntityRepository.java @@ -14,6 +14,7 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import static org.openmetadata.service.Entity.FIELD_DISPLAY_NAME; +import static org.openmetadata.service.Entity.FIELD_STYLE; import static org.openmetadata.service.Entity.INGESTION_PIPELINE; import static org.openmetadata.service.util.EntityUtil.objectMatch; @@ -77,6 +78,11 @@ public List getSearchPropagationDescriptors() { FIELD_DISPLAY_NAME, PropagationDescriptor.PropagationType.NESTED_FIELD, "service.displayName")); + if (supportsStyle) { + descriptors.add( + new PropagationDescriptor( + FIELD_STYLE, PropagationDescriptor.PropagationType.EXTERNAL_HANDLER, null)); + } return descriptors; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SpreadsheetRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SpreadsheetRepository.java index 050c1470bcb5..baede311a40c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SpreadsheetRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SpreadsheetRepository.java @@ -425,7 +425,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro List.of( Pair.of(9, TagLabel.TagSource.CLASSIFICATION), Pair.of(10, TagLabel.TagSource.GLOSSARY)))) - .withDomains(getDomains(printer, csvRecord, 11)) + .withDomains(getDomains(printer, csvRecord, 11, newSpreadsheet.getDomains())) .withDataProducts(getDataProducts(printer, csvRecord, 12)) .withCreatedTime( nullOrEmpty(csvRecord.get(15)) ? null : Long.parseLong(csvRecord.get(15))) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/StoredProcedureRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/StoredProcedureRepository.java index 3c3166e40797..dbd011ef5bdd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/StoredProcedureRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/StoredProcedureRepository.java @@ -2,7 +2,6 @@ import static org.openmetadata.schema.type.Include.ALL; import static org.openmetadata.service.Entity.DATABASE_SCHEMA; -import static org.openmetadata.service.Entity.FIELD_SERVICE; import static org.openmetadata.service.Entity.STORED_PROCEDURE; import java.util.ArrayList; @@ -150,39 +149,33 @@ public void setFieldsInBulk(EntityUtil.Fields fields, List stor return; } - // For stored procedures, we need to handle the service field specially - // because it comes through DatabaseSchema - if (fields.contains(FIELD_SERVICE) - || fields.contains("databaseSchema") - || fields.contains("database") - || fields.contains("service")) { - - Map schemaRefs = - batchFetchContainers(storedProcedures, DATABASE_SCHEMA, Include.ALL); - if (!schemaRefs.isEmpty()) { - List schemaIds = - schemaRefs.values().stream().map(EntityReference::getId).distinct().toList(); - var schemaRepository = - (DatabaseSchemaRepository) Entity.getEntityRepository(DATABASE_SCHEMA); - List schemas = - schemaRepository.getDao().findEntitiesByIds(new ArrayList<>(schemaIds), Include.ALL); - schemaRepository.setFieldsInBulk(EntityUtil.Fields.EMPTY_FIELDS, schemas); - Map schemaById = new HashMap<>(); - for (DatabaseSchema schema : schemas) { - schemaById.put(schema.getId(), schema); - } + // databaseSchema, database and service are default container fields for a stored procedure + // (service is derived from the parent schema) and must always be populated regardless of the + // requested fields - mirrors DatabaseSchemaRepository.fetchAndSetDefaultFields. + Map schemaRefs = + batchFetchContainers(storedProcedures, DATABASE_SCHEMA, Include.ALL); + if (!schemaRefs.isEmpty()) { + List schemaIds = + schemaRefs.values().stream().map(EntityReference::getId).distinct().toList(); + var schemaRepository = (DatabaseSchemaRepository) Entity.getEntityRepository(DATABASE_SCHEMA); + List schemas = + schemaRepository.getDao().findEntitiesByIds(new ArrayList<>(schemaIds), Include.ALL); + schemaRepository.setFieldsInBulk(EntityUtil.Fields.EMPTY_FIELDS, schemas); + Map schemaById = new HashMap<>(); + for (DatabaseSchema schema : schemas) { + schemaById.put(schema.getId(), schema); + } - for (StoredProcedure sp : storedProcedures) { - EntityReference schemaRef = schemaRefs.get(sp.getId()); - if (schemaRef == null) { - continue; - } - DatabaseSchema schema = schemaById.get(schemaRef.getId()); - if (schema != null) { - sp.withDatabaseSchema(schemaRef) - .withDatabase(schema.getDatabase()) - .withService(schema.getService()); - } + for (StoredProcedure sp : storedProcedures) { + EntityReference schemaRef = schemaRefs.get(sp.getId()); + if (schemaRef == null) { + continue; + } + DatabaseSchema schema = schemaById.get(schemaRef.getId()); + if (schema != null) { + sp.withDatabaseSchema(schemaRef) + .withDatabase(schema.getDatabase()) + .withService(schema.getService()); } } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java index cdd7b929a0e5..fa21c3ac47b2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/SystemRepository.java @@ -51,6 +51,7 @@ import org.openmetadata.schema.auth.LdapConfiguration; import org.openmetadata.schema.configuration.AssetCertificationSettings; import org.openmetadata.schema.configuration.ExecutorConfiguration; +import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; import org.openmetadata.schema.configuration.HistoryCleanUpConfiguration; import org.openmetadata.schema.configuration.LLMConfiguration; import org.openmetadata.schema.configuration.LLMEmbeddingsConfig; @@ -92,6 +93,7 @@ import org.openmetadata.service.events.scheduled.ServicesStatusJobHandler; import org.openmetadata.service.exception.CustomExceptionMessage; import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.fernet.Fernet; import org.openmetadata.service.governance.workflows.WorkflowHandler; import org.openmetadata.service.jdbi3.CollectionDAO.SystemDAO; @@ -193,31 +195,34 @@ public Settings getConfigWithKey(String key) { if (fetchedSettings == null) { return null; } + return prepareFetchedSettings(fetchedSettings); + } catch (Exception ex) { + LOG.error("Error while trying fetch Settings ", ex); + } + return null; + } - if (fetchedSettings.getConfigType() == SettingsType.EMAIL_CONFIGURATION) { - SmtpSettings emailConfig = (SmtpSettings) fetchedSettings.getConfigValue(); - if (!nullOrEmpty(emailConfig.getPassword())) { - emailConfig.setPassword(PasswordEntityMasker.PASSWORD_MASK); - } - fetchedSettings.setConfigValue(emailConfig); + private Settings prepareFetchedSettings(Settings fetchedSettings) { + if (fetchedSettings.getConfigType() == SettingsType.EMAIL_CONFIGURATION) { + SmtpSettings emailConfig = (SmtpSettings) fetchedSettings.getConfigValue(); + if (!nullOrEmpty(emailConfig.getPassword())) { + emailConfig.setPassword(PasswordEntityMasker.PASSWORD_MASK); } + fetchedSettings.setConfigValue(emailConfig); + } - // Apply LDAP default values to prevent JSON PATCH errors when updating fields that were - // previously null - if (fetchedSettings.getConfigType() == SettingsType.AUTHENTICATION_CONFIGURATION) { - AuthenticationConfiguration authConfig = - (AuthenticationConfiguration) fetchedSettings.getConfigValue(); - if (authConfig != null && authConfig.getLdapConfiguration() != null) { - ensureLdapConfigDefaultValues(authConfig.getLdapConfiguration()); - fetchedSettings.setConfigValue(authConfig); - } + // Apply LDAP default values to prevent JSON PATCH errors when updating fields that were + // previously null + if (fetchedSettings.getConfigType() == SettingsType.AUTHENTICATION_CONFIGURATION) { + AuthenticationConfiguration authConfig = + (AuthenticationConfiguration) fetchedSettings.getConfigValue(); + if (authConfig != null && authConfig.getLdapConfiguration() != null) { + ensureLdapConfigDefaultValues(authConfig.getLdapConfiguration()); + fetchedSettings.setConfigValue(authConfig); } - - return fetchedSettings; - } catch (Exception ex) { - LOG.error("Error while trying fetch Settings ", ex); } - return null; + + return fetchedSettings; } public AssetCertificationSettings getAssetCertificationSettings() { @@ -431,23 +436,52 @@ private Map hardenMapping(Map mapping) { } public Response patchSetting(String settingName, JsonPatch patch) { - Settings original = getConfigWithKey(settingName); - // Apply JSON patch to the original entity to get the updated entity + if (SettingsType.GLOSSARY_TERM_RELATION_SETTINGS.value().equalsIgnoreCase(settingName)) { + return patchGlossaryTermRelationSettings(patch); + } + + String expectedJson = dao.getConfigJsonWithKey(settingName); + if (expectedJson == null) { + throw EntityNotFoundException.byName(settingName); + } + Settings original = + prepareFetchedSettings( + CollectionDAO.SettingsRowMapper.getSettings( + SettingsType.fromValue(settingName), expectedJson)); JsonValue updated = JsonUtils.applyPatch(original.getConfigValue(), patch); - // Convert JsonValue back to a regular Java object - // JsonValue is from Jakarta JSON API, we need to convert it to a Jackson-compatible object String jsonString = updated.toString(); Object updatedConfigValue = JsonUtils.readValue(jsonString, Object.class); original.setConfigValue(updatedConfigValue); - try { - updateSetting(original); - } catch (Exception ex) { - LOG.error(FAILED_TO_UPDATE_SETTINGS, ex.getMessage()); - return Response.status(500, INTERNAL_SERVER_ERROR_WITH_REASON + ex.getMessage()).build(); - } + updateSettingIfCurrent(original, expectedJson); return (new RestUtil.PutResponse<>(Response.Status.OK, original, ENTITY_UPDATED)).toResponse(); } + private Response patchGlossaryTermRelationSettings(JsonPatch patch) { + String expectedJson = dao.getGlossaryTermRelationSettingsJson(); + if (expectedJson == null) { + throw EntityNotFoundException.byName(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS.value()); + } + + GlossaryTermRelationSettings current = + JsonUtils.readValue(expectedJson, GlossaryTermRelationSettings.class); + JsonValue patched = JsonUtils.applyPatch(current, patch); + GlossaryTermRelationSettings updated = + JsonUtils.readValue(patched.toString(), GlossaryTermRelationSettings.class); + String updatedJson = JsonUtils.pojoToJson(updated); + int updatedRows = dao.updateGlossaryTermRelationSettingsIfCurrent(expectedJson, updatedJson); + if (updatedRows == 0) { + throw new PreconditionFailedException( + "Glossary term relation settings changed while the JSON Patch was being applied"); + } + + SettingsCache.invalidateSettings(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS.value()); + Settings response = + new Settings() + .withConfigType(SettingsType.GLOSSARY_TERM_RELATION_SETTINGS) + .withConfigValue(updated); + return (new RestUtil.PutResponse<>(Response.Status.OK, response, ENTITY_UPDATED)).toResponse(); + } + private void postUpdate(SettingsType settingsType) { if (settingsType == SettingsType.WORKFLOW_SETTINGS) { WorkflowHandler workflowHandler = WorkflowHandler.getInstance(); @@ -461,54 +495,31 @@ private void postUpdate(SettingsType settingsType) { public void updateSetting(Settings setting) { try { - if (setting.getConfigType() == SettingsType.EMAIL_CONFIGURATION) { - SmtpSettings emailConfig = - JsonUtils.convertValue(setting.getConfigValue(), SmtpSettings.class); - if (!nullOrEmpty(emailConfig.getPassword())) { - setting.setConfigValue(encryptEmailSetting(emailConfig)); - } - } else if (setting.getConfigType() == SettingsType.OPEN_METADATA_BASE_URL_CONFIGURATION) { - OpenMetadataBaseUrlConfiguration omBaseUrl = - JsonUtils.convertValue( - setting.getConfigValue(), OpenMetadataBaseUrlConfiguration.class); - setting.setConfigValue(omBaseUrl); - } else if (setting.getConfigType() == SettingsType.SLACK_APP_CONFIGURATION) { - SlackAppConfiguration appConfiguration = - JsonUtils.convertValue(setting.getConfigValue(), SlackAppConfiguration.class); - setting.setConfigValue(encryptSlackAppSetting(appConfiguration)); - } else if (setting.getConfigType() == SettingsType.SLACK_BOT) { - String appConfiguration = JsonUtils.convertValue(setting.getConfigValue(), String.class); - setting.setConfigValue(encryptSlackDefaultBotSetting(appConfiguration)); - } else if (setting.getConfigType() == SettingsType.SLACK_INSTALLER) { - String appConfiguration = JsonUtils.convertValue(setting.getConfigValue(), String.class); - setting.setConfigValue(encryptSlackDefaultInstallerSetting(appConfiguration)); - } else if (setting.getConfigType() == SettingsType.SLACK_STATE) { - String slackState = JsonUtils.convertValue(setting.getConfigValue(), String.class); - setting.setConfigValue(encryptSlackStateSetting(slackState)); - } else if (setting.getConfigType() == SettingsType.CUSTOM_UI_THEME_PREFERENCE) { - JsonUtils.validateJsonSchema(setting.getConfigValue(), UiThemePreference.class); - } else if (setting.getConfigType() == SettingsType.SEARCH_SETTINGS) { - JsonUtils.validateJsonSchema(setting.getConfigValue(), SearchSettings.class); - } else if (setting.getConfigType() == SettingsType.SCIM_CONFIGURATION) { - ScimConfiguration scimConfig = - JsonUtils.convertValue(setting.getConfigValue(), ScimConfiguration.class); - JsonUtils.validateJsonSchema(setting.getConfigValue(), ScimConfiguration.class); - setting.setConfigValue(scimConfig); - } else if (setting.getConfigType() == SettingsType.AUTHENTICATION_CONFIGURATION) { - AuthenticationConfiguration authConfig = - JsonUtils.convertValue(setting.getConfigValue(), AuthenticationConfiguration.class); - setting.setConfigValue(authConfig); - } else if (setting.getConfigType() == SettingsType.AUTHORIZER_CONFIGURATION) { - AuthorizerConfiguration authorizerConfig = - JsonUtils.convertValue(setting.getConfigValue(), AuthorizerConfiguration.class); - JsonUtils.validateJsonSchema(authorizerConfig, AuthorizerConfiguration.class); - setting.setConfigValue(authorizerConfig); + String updatedJson = prepareSettingForUpdate(setting); + dao.insertSettings(setting.getConfigType().toString(), updatedJson); + settingUpdated(setting.getConfigType()); + } catch (Exception ex) { + LOG.error("Failing in Updating Setting.", ex); + throw new CustomExceptionMessage( + Response.Status.INTERNAL_SERVER_ERROR, + "FAILED_TO_UPDATE_SLACK_OR_EMAIL", + ex.getMessage()); + } + } + + private void updateSettingIfCurrent(Settings setting, String expectedJson) { + try { + String updatedJson = prepareSettingForUpdate(setting); + int updated = + dao.updateSettingsIfCurrent( + setting.getConfigType().toString(), expectedJson, updatedJson); + if (updated == 0) { + throw new PreconditionFailedException( + "Setting changed while the JSON Patch was being applied"); } - dao.insertSettings( - setting.getConfigType().toString(), JsonUtils.pojoToJson(setting.getConfigValue())); - // Invalidate Cache - SettingsCache.invalidateSettings(setting.getConfigType().value()); - postUpdate(setting.getConfigType()); + settingUpdated(setting.getConfigType()); + } catch (PreconditionFailedException ex) { + throw ex; } catch (Exception ex) { LOG.error("Failing in Updating Setting.", ex); throw new CustomExceptionMessage( @@ -518,6 +529,57 @@ public void updateSetting(Settings setting) { } } + private String prepareSettingForUpdate(Settings setting) { + if (setting.getConfigType() == SettingsType.EMAIL_CONFIGURATION) { + SmtpSettings emailConfig = + JsonUtils.convertValue(setting.getConfigValue(), SmtpSettings.class); + if (!nullOrEmpty(emailConfig.getPassword())) { + setting.setConfigValue(encryptEmailSetting(emailConfig)); + } + } else if (setting.getConfigType() == SettingsType.OPEN_METADATA_BASE_URL_CONFIGURATION) { + OpenMetadataBaseUrlConfiguration omBaseUrl = + JsonUtils.convertValue(setting.getConfigValue(), OpenMetadataBaseUrlConfiguration.class); + setting.setConfigValue(omBaseUrl); + } else if (setting.getConfigType() == SettingsType.SLACK_APP_CONFIGURATION) { + SlackAppConfiguration appConfiguration = + JsonUtils.convertValue(setting.getConfigValue(), SlackAppConfiguration.class); + setting.setConfigValue(encryptSlackAppSetting(appConfiguration)); + } else if (setting.getConfigType() == SettingsType.SLACK_BOT) { + String appConfiguration = JsonUtils.convertValue(setting.getConfigValue(), String.class); + setting.setConfigValue(encryptSlackDefaultBotSetting(appConfiguration)); + } else if (setting.getConfigType() == SettingsType.SLACK_INSTALLER) { + String appConfiguration = JsonUtils.convertValue(setting.getConfigValue(), String.class); + setting.setConfigValue(encryptSlackDefaultInstallerSetting(appConfiguration)); + } else if (setting.getConfigType() == SettingsType.SLACK_STATE) { + String slackState = JsonUtils.convertValue(setting.getConfigValue(), String.class); + setting.setConfigValue(encryptSlackStateSetting(slackState)); + } else if (setting.getConfigType() == SettingsType.CUSTOM_UI_THEME_PREFERENCE) { + JsonUtils.validateJsonSchema(setting.getConfigValue(), UiThemePreference.class); + } else if (setting.getConfigType() == SettingsType.SEARCH_SETTINGS) { + JsonUtils.validateJsonSchema(setting.getConfigValue(), SearchSettings.class); + } else if (setting.getConfigType() == SettingsType.SCIM_CONFIGURATION) { + ScimConfiguration scimConfig = + JsonUtils.convertValue(setting.getConfigValue(), ScimConfiguration.class); + JsonUtils.validateJsonSchema(setting.getConfigValue(), ScimConfiguration.class); + setting.setConfigValue(scimConfig); + } else if (setting.getConfigType() == SettingsType.AUTHENTICATION_CONFIGURATION) { + AuthenticationConfiguration authConfig = + JsonUtils.convertValue(setting.getConfigValue(), AuthenticationConfiguration.class); + setting.setConfigValue(authConfig); + } else if (setting.getConfigType() == SettingsType.AUTHORIZER_CONFIGURATION) { + AuthorizerConfiguration authorizerConfig = + JsonUtils.convertValue(setting.getConfigValue(), AuthorizerConfiguration.class); + JsonUtils.validateJsonSchema(authorizerConfig, AuthorizerConfiguration.class); + setting.setConfigValue(authorizerConfig); + } + return JsonUtils.pojoToJson(setting.getConfigValue()); + } + + private void settingUpdated(SettingsType settingsType) { + SettingsCache.invalidateSettings(settingsType.value()); + postUpdate(settingsType); + } + public Settings getSlackbotConfigInternal() { try { Settings setting = dao.getConfigWithKey(SettingsType.SLACK_BOT.value()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java index 32d02d1432ed..92e73cc166c0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java @@ -144,7 +144,7 @@ public class TableRepository extends EntityRepository
{ public static final String PATCH_FIELDS = "tableConstraints,tablePartition,columns"; // Table fields that can be updated in a PUT request public static final String UPDATE_FIELDS = - "tableConstraints,tablePartition,dataModel,sourceUrl,columns"; + "tableConstraints,tablePartition,dataModel,sourceUrl,columns,schemaDefinition"; public static final String FIELD_RELATION_COLUMN_TYPE = "table.columns.column"; public static final String FIELD_RELATION_TABLE_TYPE = "table"; @@ -2337,7 +2337,17 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { if (updatedTable.getDataModel() == null && origTable.getDataModel() != null) { updatedTable.withDataModel(origTable.getDataModel()); } + if (updatedTable.getSchemaDefinition() == null && origTable.getSchemaDefinition() != null) { + updatedTable.withSchemaDefinition(origTable.getSchemaDefinition()); + } + compareAndUpdate( + "schemaDefinition", + () -> + recordChange( + "schemaDefinition", + original.getSchemaDefinition(), + updated.getSchemaDefinition())); compareAndUpdate( "columns", () -> { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskBucketSql.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskBucketSql.java new file mode 100644 index 000000000000..c5d7db6fc8ab --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskBucketSql.java @@ -0,0 +1,59 @@ +/* + * Copyright 2021 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.jdbi3; + +/** + * Compile-time SQL fragments for the task-status bucket predicates used by + * {@link ListFilter#buildTaskStatusGroupCondition} and + * {@link CollectionDAO.TaskDAO#getTaskCountSummary}. JDBI {@code @SqlQuery} annotations require + * compile-time constant strings, so both sites cannot reference the {@code TaskEntityStatus} / + * {@code TaskEntityType} enum values directly at build time. {@code TaskBucketSqlDriftTest} + * asserts the constants below stay in sync with the schema-generated enums — an enum rename + * fails the test before the two SQL sites can drift apart. + * + *

Bucket definitions ({@code type} is the task-type column): + * + *

    + *
  • {@code open} = {@code status IN SHARED_OPEN_STATUSES} OR + * {@code (type = DataAccessRequest AND status = Approved)} + *
  • {@code closed} = {@code status IN SHARED_TERMINAL_STATUSES} OR + * {@code (type <> DataAccessRequest AND status = Approved)} + *
  • {@code active} = {@code status IN ACTIVE_STATUSES} (superset of {@code open}; kept for + * DAR-scoped callers that pre-narrow the query) + *
+ * + *

Bucket predicates are row-aware on {@code type}: {@code Approved} is terminal for non-DAR + * task types (Glossary/DescriptionUpdate/etc.) and non-terminal for DataAccessRequest (means + * "awaiting grant"). {@code Granted} and {@code ManualRevoke} live in {@code SHARED_OPEN_STATUSES} + * so any hypothetical future task type reaching those statuses still lands in a bucket rather + * than silently breaking the {@code openCount + completedCount = total} invariant. + */ +public final class TaskBucketSql { + + public static final String SHARED_OPEN_STATUSES = + "'Open', 'InProgress', 'Pending', 'Granted', 'ManualRevoke'"; + + public static final String SHARED_TERMINAL_STATUSES = + "'Rejected', 'Completed', 'Cancelled', 'Failed', 'Revoked', 'Expired'"; + + public static final String ACTIVE_STATUSES = + "'Open', 'InProgress', 'Pending', 'Approved', 'Granted', 'ManualRevoke'"; + + public static final String TASK_TYPE_DAR = "DataAccessRequest"; + + public static final String STATUS_APPROVED = "Approved"; + + public static final String STATUS_IN_PROGRESS = "InProgress"; + + public static final String STATUS_GRANTED = "Granted"; + + private TaskBucketSql() {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index 6376056fd9ab..c81eee0dcbcf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -39,6 +39,7 @@ import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Jdbi; import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.entity.teams.Team; import org.openmetadata.schema.governance.workflows.WorkflowDefinition; import org.openmetadata.schema.tests.TestCase; import org.openmetadata.schema.type.ChangeDescription; @@ -356,6 +357,7 @@ public void prepare(Task task, boolean update) { TaskFieldValidator.validateDataAccessCapabilities(task); if (!update) { + TaskFieldValidator.validateDataAccessRequestDuration(task); validateNoDuplicateActiveDataAccessRequest(task); } @@ -439,11 +441,12 @@ private void setDefaultAssigneesFromEntityOwners(Task task) { try { List owners = Entity.getOwners(about); if (!nullOrEmpty(owners)) { - task.setAssignees(owners); + List expandedAssignees = expandTeamsToUsers(owners); + task.setAssignees(expandedAssignees); LOG.debug( "Task {} defaulting assignees to entity owners: {}", task.getTaskId(), - owners.stream().map(EntityReference::getName).toList()); + expandedAssignees.stream().map(EntityReference::getName).toList()); } } catch (Exception e) { LOG.debug( @@ -454,6 +457,31 @@ private void setDefaultAssigneesFromEntityOwners(Task task) { } } + private List expandTeamsToUsers(List refs) { + List result = new ArrayList<>(); + for (EntityReference ref : refs) { + if (!Entity.TEAM.equals(ref.getType())) { + result.add(ref); + continue; + } + try { + Team team = Entity.getEntity(Entity.TEAM, ref.getId(), "users", Include.NON_DELETED); + if (!nullOrEmpty(team.getUsers())) { + result.addAll(team.getUsers()); + } + // A team with no members intentionally contributes no assignees: for workflow-managed tasks + // (e.g. Data Access Requests) an empty assignee list triggers the node's + // emptyAssigneeStrategy + // (assignAdmins) in SetApprovalAssigneesImpl, so it routes to platform admins rather than + // being pinned to a member-less team. + } catch (Exception e) { + LOG.debug( + "Failed to expand team {} to users: {}", ref.getFullyQualifiedName(), e.getMessage()); + } + } + return result; + } + /** * Inherit domains from the target entity that this task is about. * Tasks must belong to the same domains as their target entity for proper data isolation. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java index 6be94bfc84f5..86270530d463 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java @@ -1516,6 +1516,10 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { compareAndUpdate( "authenticationMechanism", () -> updateAuthenticationMechanism(original, updated)); compareAndUpdateAny(() -> SubjectCache.invalidateUser(updated.getName()), "roles", "teams"); + compareAndUpdateAny( + () -> SubjectCache.invalidateUserContext(updated.getName()), + "personas", + "defaultPersona"); } private void updateAllowImpersonation() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceRepository.java index 1da86af80e00..b058dee28a23 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceRepository.java @@ -4,6 +4,7 @@ import static org.openmetadata.service.governance.workflows.Workflow.GLOBAL_NAMESPACE; import static org.openmetadata.service.governance.workflows.WorkflowVariableHandler.getNamespacedVariableName; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -54,6 +55,14 @@ public void updateWorkflowInstance( WorkflowInstance workflowInstance = JsonUtils.readValue(timeSeriesDao.getById(workflowInstanceId), WorkflowInstance.class); + // Preserve a terminal SUPERSEDED status set upstream by the supersede path — the process-end + // execution listener also lands here and would otherwise recompute the status to FINISHED. + if (workflowInstance.getStatus() == WorkflowInstance.WorkflowStatus.SUPERSEDED) { + workflowInstance.setEndedAt(endedAt); + getTimeSeriesDao().update(JsonUtils.pojoToJson(workflowInstance), workflowInstanceId); + return; + } + workflowInstance.setEndedAt(endedAt); WorkflowInstanceStateRepository workflowInstanceStateRepository = @@ -100,4 +109,26 @@ public void markInstanceAsFailed(UUID workflowInstanceId, String reason) { getTimeSeriesDao().update(JsonUtils.pojoToJson(updatedInstance), workflowInstanceId); } + + /** Marks a workflow instance as SUPERSEDED when a newer run replaces it. */ + public void markInstanceAsSuperseded(UUID workflowInstanceId, String reason) { + WorkflowInstance workflowInstance = + JsonUtils.readValue(timeSeriesDao.getById(workflowInstanceId), WorkflowInstance.class); + + Map variables = workflowInstance.getVariables(); + if (variables == null) { + variables = new HashMap<>(); + } + variables.put(TERMINATION_REASON_VARIABLE_KEY, reason); + + WorkflowInstance updatedInstance = + workflowInstance + .withStatus(WorkflowInstance.WorkflowStatus.SUPERSEDED) + .withVariables(variables) + .withEndedAt(System.currentTimeMillis()); + + getTimeSeriesDao().update(JsonUtils.pojoToJson(updatedInstance), workflowInstanceId); + } + + private static final String TERMINATION_REASON_VARIABLE_KEY = "terminationReason"; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceStateRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceStateRepository.java index f59b9cdd86a8..e483c34f5978 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceStateRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorkflowInstanceStateRepository.java @@ -199,6 +199,31 @@ public void markInstanceStatesAsFailed(UUID workflowInstanceId, String reason) { } } + /** + * Marks all states of a workflow instance as SUPERSEDED when a newer run replaces it. The + * exception field is left untouched — supersede is not a failure, so the reason lives on the + * WorkflowInstance's variables map, not in an exception field. + */ + public void markInstanceStatesAsSuperseded(UUID workflowInstanceId, String reason) { + try { + List instanceStates = listAllStatesForInstance(workflowInstanceId); + + for (WorkflowInstanceState state : instanceStates) { + WorkflowInstanceState updatedState = + state.withStatus(WorkflowInstance.WorkflowStatus.SUPERSEDED); + + getTimeSeriesDao().update(JsonUtils.pojoToJson(updatedState), state.getId()); + } + + } catch (Exception e) { + LOG.warn( + "Failed to mark states as superseded for instance {} (reason={}): {}", + workflowInstanceId, + reason, + e.getMessage()); + } + } + public List listAllStatesForInstance(UUID workflowInstanceId) { List states = new ArrayList<>(); List jsons = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorksheetRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorksheetRepository.java index d0c261f34b0b..68d5362fecbb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorksheetRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/WorksheetRepository.java @@ -455,7 +455,7 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro List.of( Pair.of(11, TagLabel.TagSource.CLASSIFICATION), Pair.of(12, TagLabel.TagSource.GLOSSARY)))) - .withDomains(getDomains(printer, csvRecord, 13)) + .withDomains(getDomains(printer, csvRecord, 13, newWorksheet.getDomains())) .withDataProducts(getDataProducts(printer, csvRecord, 14)); if (processRecord) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/llm/BedrockCompletionClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/llm/BedrockCompletionClient.java index dd15d7be3e35..a639169b13f8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/llm/BedrockCompletionClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/llm/BedrockCompletionClient.java @@ -60,6 +60,7 @@ public BedrockCompletionClient(LLMConfiguration config) { BedrockRuntimeClient.builder() .credentialsProvider(AwsCredentialsUtil.buildCredentialsProvider(awsConfig)) .region(Region.of(awsConfig.getRegion())) + .overrideConfiguration(AwsCredentialsUtil.throttleResilientOverrideConfiguration()) .build(); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/llm/KnowledgePill.java b/openmetadata-service/src/main/java/org/openmetadata/service/llm/KnowledgePill.java deleted file mode 100644 index 38f7a6feca90..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/llm/KnowledgePill.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openmetadata.service.llm; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * DTO for a single knowledge pill as returned by the LLM during file extraction — deliberately - * not the {@link org.openmetadata.schema.entity.context.ContextMemory} entity. It is the - * anti-corruption boundary between untrusted model JSON and the trusted entity model, kept - * intentionally narrow and tolerant. {@code ContextMemoryExtractor.toMemory} maps a validated pill - * into a {@code ContextMemory}, adding the server-owned envelope (id, name, FQN, status, sourceType, - * sourceFile, shareConfig, updatedBy/At). Deserializing the model's JSON straight into - * {@code ContextMemory} is intentionally avoided because: - * - *

    - *
  • Field scope. Only the five fields the model is asked to produce live here (see - * {@code ContextMemoryExtractor.SYSTEM_PROMPT}); the entity's identity/status/source fields - * are server-generated, never model-supplied, so they must not leak into the model contract. - *
  • Unknown-field tolerance. {@code @JsonIgnoreProperties(ignoreUnknown = true)} lets a - * model that emits a stray key still parse. {@code ContextMemory} is generated with - * {@code additionalProperties:false} and parsed by a default {@code ObjectMapper} - * ({@code FAIL_ON_UNKNOWN_PROPERTIES} on), so a single unexpected key would fail the whole - * array parse. - *
  • Enum leniency. {@code memoryType} is a raw String, not the {@code ContextMemoryType} - * enum, so an off-spec value (casing/variant) degrades to {@code NOTE} in - * {@code ContextMemoryExtractor.parseType} instead of throwing on deserialization. - *
- * - *

See {@code docs/company-context-knowledge-pills.md} (§9, "The KnowledgePill DTO boundary"). - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public record KnowledgePill( - @JsonProperty("title") String title, - @JsonProperty("question") String question, - @JsonProperty("answer") String answer, - @JsonProperty("summary") String summary, - @JsonProperty("memoryType") String memoryType) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ChatEvent.java b/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ChatEvent.java deleted file mode 100644 index df09ad9dc491..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ChatEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.mcpclient; - -import com.fasterxml.jackson.annotation.JsonInclude; -import java.util.Map; -import java.util.UUID; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public record ChatEvent(String event, Object data) { - - public static ChatEvent conversationCreated(UUID conversationId) { - return new ChatEvent("conversation_created", Map.of("conversationId", conversationId)); - } - - public static ChatEvent text(String content) { - return new ChatEvent("text", Map.of("content", content)); - } - - public static ChatEvent toolCallStart(String name, Map input) { - return new ChatEvent("tool_call_start", Map.of("name", name, "input", input)); - } - - public static ChatEvent toolCallEnd(String name, Object result) { - return new ChatEvent("tool_call_end", Map.of("name", name, "result", result)); - } - - public static ChatEvent messageComplete(Object message) { - return new ChatEvent("message_complete", Map.of("message", message)); - } - - public static ChatEvent titleUpdated(String title) { - return new ChatEvent("title_updated", Map.of("title", title)); - } - - public static ChatEvent error(String message) { - return new ChatEvent("error", Map.of("message", message)); - } - - public static ChatEvent done() { - return new ChatEvent("done", Map.of()); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ClientDisconnectedException.java b/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ClientDisconnectedException.java deleted file mode 100644 index 9c23ab3f8968..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ClientDisconnectedException.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.mcpclient; - -import java.io.IOException; - -/** - * Raised when writing to the SSE output stream fails, indicating the client has disconnected. The - * chat loop uses this to stop issuing further (billable) LLM calls and to skip writes to the now - * broken stream. - */ -public class ClientDisconnectedException extends RuntimeException { - public ClientDisconnectedException(String message, IOException cause) { - super(message, cause); - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpChatServiceHolder.java b/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpChatServiceHolder.java deleted file mode 100644 index 236ef7422c94..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpChatServiceHolder.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.mcpclient; - -import org.openmetadata.schema.configuration.LLMConfiguration; -import org.openmetadata.schema.configuration.McpChatSettings; -import org.openmetadata.service.Entity; - -/** - * Holds the single shared {@link McpClientService} built from {@code aiSettings.mcpChat} and the - * platform {@code llmConfiguration}. Re-initialized at bootstrap and on every AI settings save so - * the chat feature toggles at runtime without an app install. Holds {@code null} when MCP chat is - * disabled. - */ -public final class McpChatServiceHolder { - private static volatile McpClientService instance; - private static volatile boolean enabled; - - private McpChatServiceHolder() {} - - public static synchronized void initialize(LLMConfiguration llmConfig, McpChatSettings settings) { - enabled = settings != null && Boolean.TRUE.equals(settings.getEnabled()); - closeQuietly(instance); - instance = - enabled - ? new McpClientService(Entity.getCollectionDAO(), llmConfig, settings.getSystemPrompt()) - : null; - } - - public static McpClientService get() { - return instance; - } - - public static boolean isEnabled() { - return enabled; - } - - /** Test seam: inject a deterministic service (and force-enable) for integration tests. */ - public static synchronized void setForTesting(McpClientService service) { - closeQuietly(instance); - instance = service; - enabled = service != null; - } - - private static void closeQuietly(McpClientService service) { - if (service != null) { - service.close(); - } - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpClientService.java b/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpClientService.java deleted file mode 100644 index c09601f9585a..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpClientService.java +++ /dev/null @@ -1,637 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.mcpclient; - -import static org.openmetadata.service.security.DefaultAuthorizer.getSubjectContext; - -import jakarta.ws.rs.core.SecurityContext; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.api.chat.CreateMcpConversation; -import org.openmetadata.schema.api.chat.CreateMcpMessage; -import org.openmetadata.schema.configuration.LLMConfiguration; -import org.openmetadata.schema.entity.chat.McpConversation; -import org.openmetadata.schema.entity.chat.McpMessage; -import org.openmetadata.schema.entity.chat.TokenUsage; -import org.openmetadata.schema.entity.chat.content.ChatContentType; -import org.openmetadata.schema.entity.chat.content.MessageBlock; -import org.openmetadata.schema.entity.chat.content.TextMessage; -import org.openmetadata.schema.entity.chat.content.ToolCall; -import org.openmetadata.schema.entity.teams.User; -import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.clients.llm.LlmClient; -import org.openmetadata.service.clients.llm.LlmClientFactory; -import org.openmetadata.service.clients.llm.LlmException; -import org.openmetadata.service.clients.llm.LlmMessage; -import org.openmetadata.service.clients.llm.LlmResponse; -import org.openmetadata.service.clients.llm.LlmToolCall; -import org.openmetadata.service.exception.EntityNotFoundException; -import org.openmetadata.service.jdbi3.CollectionDAO; -import org.openmetadata.service.jdbi3.McpConversationRepository; -import org.openmetadata.service.jdbi3.McpMessageRepository; -import org.openmetadata.service.security.auth.CatalogSecurityContext; - -@Slf4j -public class McpClientService implements AutoCloseable { - private static final int MAX_TOOL_ITERATIONS = 10; - private static final int LLM_CONTEXT_MESSAGE_LIMIT = 20; - private static final int CONVERSATION_LOAD_LIMIT = 100; - private static final int TITLE_EXECUTOR_QUEUE_CAPACITY = 50; - - private static final String TOOLS_UNAVAILABLE_MESSAGE = - "Tool execution is not available. The MCP Server is not installed or configured."; - private static final String TOOL_LIMIT_MESSAGE = - "I was unable to complete the request within the allowed tool call limit."; - private static final String TOOL_LIMIT_NOTICE = - "[Response truncated: reached the tool-call limit before completing.]"; - private static final String ERROR_MESSAGE = - "Sorry, an error occurred while processing your request. Please try again."; - - private final McpConversationRepository conversationRepository; - private final McpMessageRepository messageRepository; - private final String systemPrompt; - private final LlmClient llmClient; - private final ExecutorService titleExecutor = - new ThreadPoolExecutor( - 0, - 2, - 60L, - TimeUnit.SECONDS, - new LinkedBlockingQueue<>(TITLE_EXECUTOR_QUEUE_CAPACITY), - runnable -> { - Thread thread = new Thread(runnable, "mcp-title-gen"); - thread.setDaemon(true); - return thread; - }, - new ThreadPoolExecutor.DiscardPolicy()); - - private volatile ToolExecutor toolExecutor; - private volatile List> toolDefinitions = Collections.emptyList(); - private volatile List> lastToolDefinitionsSource; - - public McpClientService(CollectionDAO dao, LLMConfiguration llmConfig, String systemPrompt) { - this.conversationRepository = new McpConversationRepository(dao.mcpConversationDAO()); - this.messageRepository = new McpMessageRepository(dao.mcpMessageDAO()); - this.systemPrompt = systemPrompt; - this.llmClient = createLlmClient(llmConfig); - } - - private static LlmClient createLlmClient(LLMConfiguration config) { - boolean enabled = - config != null && Boolean.TRUE.equals(config.getEnabled()) && config.getProvider() != null; - LlmClient client = null; - if (enabled) { - try { - client = LlmClientFactory.create(config); - } catch (IllegalArgumentException e) { - LOG.error("Failed to initialize LLM client; MCP chat will be disabled: {}", e.getMessage()); - } - } - return client; - } - - public boolean isChatEnabled() { - return llmClient != null; - } - - @Override - public void close() { - titleExecutor.shutdownNow(); - if (llmClient != null) { - try { - llmClient.close(); - } catch (RuntimeException e) { - LOG.warn("Failed to close LLM client", e); - } - } - } - - public void updateTools(ToolExecutor executor, List> definitions) { - this.toolExecutor = executor; - if (definitions != lastToolDefinitionsSource) { - lastToolDefinitionsSource = definitions; - this.toolDefinitions = Collections.unmodifiableList(new ArrayList<>(definitions)); - } - } - - public record ChatResponse(UUID conversationId, McpMessage message) {} - - private record ConversationContext(McpConversation conversation, boolean isNew) {} - - private record ChatTurn( - String assistantText, List toolCalls, TokenUsage tokens, boolean hitToolLimit) {} - - public ChatResponse chat( - SecurityContext securityContext, UUID conversationId, String userMessage) { - return runChat(securityContext, conversationId, userMessage, ChatEventEmitter.NOOP); - } - - public void chatStream( - SecurityContext securityContext, - UUID conversationId, - String userMessage, - ChatEventEmitter emitter) { - runChat(securityContext, conversationId, userMessage, emitter); - } - - private ChatResponse runChat( - SecurityContext securityContext, - UUID conversationId, - String userMessage, - ChatEventEmitter emitter) { - requireChatEnabled(); - EntityReference userRef = getSubjectContext(securityContext).user().getEntityReference(); - ConversationContext context = - openConversation(securityContext, conversationId, userRef, emitter); - McpConversation conversation = context.conversation(); - int messageIndex = - storeUserMessage(conversation.getId(), userMessage, conversation.getMessageCount()); - - ChatResponse result; - try { - ChatTurn turn = generateAssistantTurn(securityContext, conversation.getId(), emitter); - McpMessage assistantMessage = storeAssistantMessage(conversation.getId(), turn, messageIndex); - finalizeConversation( - conversation, userRef, userMessage, context.isNew(), messageIndex + 1, emitter); - emitter.emit(ChatEvent.messageComplete(assistantMessage)); - emitter.emit(ChatEvent.done()); - result = new ChatResponse(conversation.getId(), assistantMessage); - } catch (ClientDisconnectedException e) { - result = handleDisconnect(conversation, userRef, messageIndex); - } - return result; - } - - private ConversationContext openConversation( - SecurityContext securityContext, - UUID conversationId, - EntityReference userRef, - ChatEventEmitter emitter) { - ConversationContext context; - if (conversationId == null) { - McpConversation created = conversationRepository.create(new CreateMcpConversation(), userRef); - emitter.emit(ChatEvent.conversationCreated(created.getId())); - context = new ConversationContext(created, true); - } else { - context = new ConversationContext(getConversation(securityContext, conversationId), false); - } - return context; - } - - private ChatTurn generateAssistantTurn( - SecurityContext securityContext, UUID conversationId, ChatEventEmitter emitter) { - CatalogSecurityContext catalogContext = toCatalogSecurityContext(securityContext); - List llmMessages = buildLlmMessages(conversationId); - ChatTurn turn; - try { - turn = runToolLoop(llmMessages, catalogContext, emitter); - } catch (LlmException e) { - LOG.error("LLM call failed for conversation {}", conversationId, e); - emitter.emit(ChatEvent.error(ERROR_MESSAGE)); - turn = new ChatTurn(ERROR_MESSAGE, new ArrayList<>(), emptyTokenUsage(), false); - } - return turn; - } - - private ChatTurn runToolLoop( - List llmMessages, - CatalogSecurityContext catalogContext, - ChatEventEmitter emitter) { - ToolExecutor executor = this.toolExecutor; - List> tools = this.toolDefinitions; - List toolCalls = new ArrayList<>(); - StringBuilder textCollector = new StringBuilder(); - int inputTokens = 0; - int outputTokens = 0; - boolean completed = false; - int iteration = 0; - while (iteration < MAX_TOOL_ITERATIONS && !completed) { - LlmResponse response = - llmClient.sendMessagesStreaming( - llmMessages, tools, chunk -> emitter.emit(ChatEvent.text(chunk))); - inputTokens += response.inputTokens(); - outputTokens += response.outputTokens(); - appendContent(textCollector, response.content()); - completed = - applyResponse( - response, executor, catalogContext, llmMessages, toolCalls, textCollector, emitter); - iteration++; - } - return buildTurn(textCollector, toolCalls, inputTokens, outputTokens, !completed); - } - - private boolean applyResponse( - LlmResponse response, - ToolExecutor executor, - CatalogSecurityContext catalogContext, - List llmMessages, - List toolCalls, - StringBuilder textCollector, - ChatEventEmitter emitter) { - boolean completed; - if (!response.hasToolCalls()) { - completed = true; - } else if (executor == null) { - appendToolsUnavailable(textCollector); - completed = true; - } else { - llmMessages.add(LlmMessage.assistantWithToolCalls(response.content(), response.toolCalls())); - executeToolCalls( - response.toolCalls(), executor, catalogContext, llmMessages, toolCalls, emitter); - completed = false; - } - return completed; - } - - private void executeToolCalls( - List toolCalls, - ToolExecutor executor, - CatalogSecurityContext catalogContext, - List llmMessages, - List collectedCalls, - ChatEventEmitter emitter) { - for (LlmToolCall toolCall : toolCalls) { - Map inputArgs = parseToolArguments(toolCall.arguments()); - emitter.emit(ChatEvent.toolCallStart(toolCall.name(), inputArgs)); - String resultContent = executeToolSafely(executor, catalogContext, toolCall); - llmMessages.add(LlmMessage.toolResult(toolCall.id(), resultContent)); - Object parsedResult = parseToolResult(resultContent); - emitter.emit(ChatEvent.toolCallEnd(toolCall.name(), parsedResult)); - collectedCalls.add( - new ToolCall().withName(toolCall.name()).withInput(inputArgs).withResult(parsedResult)); - } - } - - private String executeToolSafely( - ToolExecutor executor, CatalogSecurityContext catalogContext, LlmToolCall toolCall) { - String result; - try { - result = executor.executeTool(catalogContext, toolCall.name(), toolCall.arguments()); - } catch (RuntimeException e) { - LOG.warn("Tool '{}' execution failed", toolCall.name(), e); - result = "Tool execution failed: " + e.getMessage(); - } - return result; - } - - private ChatTurn buildTurn( - StringBuilder textCollector, - List toolCalls, - int inputTokens, - int outputTokens, - boolean hitToolLimit) { - if (hitToolLimit) { - LOG.warn("MCP chat reached the tool-call iteration limit of {}", MAX_TOOL_ITERATIONS); - } - String assistantText = resolveAssistantText(textCollector, hitToolLimit); - TokenUsage tokens = - new TokenUsage() - .withInputTokens(inputTokens) - .withOutputTokens(outputTokens) - .withTotalTokens(inputTokens + outputTokens); - return new ChatTurn(assistantText, toolCalls, tokens, hitToolLimit); - } - - private String resolveAssistantText(StringBuilder textCollector, boolean hitToolLimit) { - String text; - if (textCollector.isEmpty()) { - text = hitToolLimit ? TOOL_LIMIT_MESSAGE : ""; - } else if (hitToolLimit) { - text = textCollector + "\n\n" + TOOL_LIMIT_NOTICE; - } else { - text = textCollector.toString(); - } - return text; - } - - private void appendToolsUnavailable(StringBuilder textCollector) { - if (textCollector.isEmpty()) { - textCollector.append(TOOLS_UNAVAILABLE_MESSAGE); - } - } - - private void appendContent(StringBuilder collector, String content) { - if (content != null && !content.isBlank()) { - if (!collector.isEmpty()) { - collector.append("\n\n"); - } - collector.append(content); - } - } - - private ChatResponse handleDisconnect( - McpConversation conversation, EntityReference userRef, int messageCount) { - LOG.info("Client disconnected during MCP chat for conversation {}", conversation.getId()); - conversation.setMessageCount(messageCount); - conversation.setUpdatedBy(userRef.getName()); - conversationRepository.update(conversation); - return null; - } - - private int storeUserMessage(UUID conversationId, String userMessage, int messageIndex) { - storeMessage( - conversationId, - CreateMcpMessage.Sender.HUMAN, - List.of(textBlock(userMessage)), - null, - messageIndex); - return messageIndex + 1; - } - - private McpMessage storeAssistantMessage(UUID conversationId, ChatTurn turn, int messageIndex) { - MessageBlock block = textBlock(turn.assistantText()).withTools(turn.toolCalls()); - return storeMessage( - conversationId, - CreateMcpMessage.Sender.ASSISTANT, - List.of(block), - turn.tokens(), - messageIndex); - } - - private MessageBlock textBlock(String message) { - return new MessageBlock() - .withType(ChatContentType.GENERIC) - .withTextMessage( - new TextMessage().withType(TextMessage.TextMessageType.MARKDOWN).withMessage(message)); - } - - private void finalizeConversation( - McpConversation conversation, - EntityReference userRef, - String userMessage, - boolean isNew, - int messageCount, - ChatEventEmitter emitter) { - conversation.setMessageCount(messageCount); - conversation.setUpdatedBy(userRef.getName()); - boolean needsTitle = isNew && conversation.getTitle() == null; - if (needsTitle) { - String quickTitle = truncateTitle(userMessage); - conversation.setTitle(quickTitle); - emitter.emit(ChatEvent.titleUpdated(quickTitle)); - } - conversationRepository.update(conversation); - if (needsTitle) { - scheduleTitleGeneration(conversation.getId(), userMessage); - } - } - - public McpConversation createConversation( - SecurityContext securityContext, CreateMcpConversation request) { - EntityReference userRef = getSubjectContext(securityContext).user().getEntityReference(); - return conversationRepository.create( - request != null ? request : new CreateMcpConversation(), userRef); - } - - public int getConversationCount(SecurityContext securityContext) { - User user = getSubjectContext(securityContext).user(); - return conversationRepository.countByUser(user.getId()); - } - - public int getMessageCount(SecurityContext securityContext, UUID conversationId) { - getConversation(securityContext, conversationId); - return messageRepository.countByConversation(conversationId); - } - - public McpConversation getConversation(SecurityContext securityContext, UUID conversationId) { - McpConversation conversation = conversationRepository.getById(conversationId); - verifyOwnership(securityContext, conversation); - return conversation; - } - - public List listConversations( - SecurityContext securityContext, int limit, int offset) { - User user = getSubjectContext(securityContext).user(); - return conversationRepository.listByUser(user.getId(), limit, offset); - } - - public McpConversation getConversationWithMessages( - SecurityContext securityContext, UUID conversationId) { - McpConversation conversation = getConversation(securityContext, conversationId); - List messages = - messageRepository.listRecentByConversation(conversationId, CONVERSATION_LOAD_LIMIT); - conversation.setMcpMessages(messages); - return conversation; - } - - public List listMessages( - SecurityContext securityContext, UUID conversationId, int limit, int offset) { - getConversation(securityContext, conversationId); - return messageRepository.listByConversation(conversationId, limit, offset); - } - - public void deleteConversation(SecurityContext securityContext, UUID conversationId) { - getConversation(securityContext, conversationId); - messageRepository.deleteByConversation(conversationId); - conversationRepository.delete(conversationId); - } - - private McpMessage storeMessage( - UUID conversationId, - CreateMcpMessage.Sender sender, - List content, - TokenUsage tokens, - int messageIndex) { - CreateMcpMessage createMessage = - new CreateMcpMessage() - .withSender(sender) - .withContent(content) - .withTimestamp(System.currentTimeMillis()) - .withTokens(tokens); - return messageRepository.create(createMessage, conversationId, messageIndex); - } - - private List buildLlmMessages(UUID conversationId) { - List llmMessages = new ArrayList<>(); - llmMessages.add(LlmMessage.system(systemPrompt)); - - List history = - messageRepository.listRecentByConversation(conversationId, LLM_CONTEXT_MESSAGE_LIMIT); - - for (McpMessage msg : history) { - boolean isHuman = msg.getSender() == CreateMcpMessage.Sender.HUMAN; - LlmMessage.Role role = isHuman ? LlmMessage.Role.user : LlmMessage.Role.assistant; - - String textContent = extractTextFromMessage(msg); - if (!isHuman) { - String toolSummary = extractToolSummaryFromMessage(msg); - if (toolSummary != null) { - String combined = - (textContent != null ? textContent + "\n\n" : "") - + "[Tools used: " - + toolSummary - + "]"; - llmMessages.add(new LlmMessage(role, combined, null, null)); - continue; - } - } - if (textContent != null) { - llmMessages.add(new LlmMessage(role, textContent, null, null)); - } - } - - return llmMessages; - } - - private String extractTextFromMessage(McpMessage message) { - String text = null; - if (message.getContent() != null) { - for (MessageBlock block : message.getContent()) { - if (text == null - && block.getTextMessage() != null - && block.getTextMessage().getMessage() != null) { - text = block.getTextMessage().getMessage(); - } - } - } - return text; - } - - private String extractToolSummaryFromMessage(McpMessage message) { - List toolNames = new ArrayList<>(); - if (message.getContent() != null) { - for (MessageBlock block : message.getContent()) { - if (block.getTools() != null) { - for (ToolCall tc : block.getTools()) { - toolNames.add(tc.getName()); - } - } - } - } - return toolNames.isEmpty() ? null : String.join(", ", toolNames); - } - - @SuppressWarnings("unchecked") - private Map parseToolArguments(String arguments) { - Map parsed = new HashMap<>(); - if (arguments != null && !arguments.isBlank()) { - try { - parsed = JsonUtils.readValue(arguments, Map.class); - } catch (RuntimeException e) { - LOG.warn("Failed to parse tool arguments: {}", arguments, e); - } - } - return parsed; - } - - private Object parseToolResult(String resultContent) { - Object parsed; - if (resultContent == null || resultContent.isBlank()) { - parsed = Collections.emptyMap(); - } else { - parsed = readToolResultJson(resultContent); - } - return parsed; - } - - private Object readToolResultJson(String resultContent) { - Object parsed; - try { - parsed = JsonUtils.readValue(resultContent, Object.class); - } catch (RuntimeException e) { - parsed = resultContent; - } - return parsed; - } - - private void verifyOwnership(SecurityContext securityContext, McpConversation conversation) { - User user = getSubjectContext(securityContext).user(); - if (!conversation.getUser().getId().equals(user.getId())) { - throw new EntityNotFoundException("Conversation not found: " + conversation.getId()); - } - } - - private CatalogSecurityContext toCatalogSecurityContext(SecurityContext securityContext) { - return new CatalogSecurityContext( - securityContext.getUserPrincipal(), - securityContext.isSecure() ? "https" : "http", - securityContext.getAuthenticationScheme(), - Collections.emptySet()); - } - - private void requireChatEnabled() { - if (llmClient == null) { - throw new IllegalStateException( - "LLM is not configured. Enable and configure a provider under 'llmConfiguration' in the platform configuration."); - } - } - - private TokenUsage emptyTokenUsage() { - return new TokenUsage().withInputTokens(0).withOutputTokens(0).withTotalTokens(0); - } - - private void scheduleTitleGeneration(UUID conversationId, String userMessage) { - titleExecutor.execute(() -> generateAndPersistTitle(conversationId, userMessage)); - } - - private void generateAndPersistTitle(UUID conversationId, String userMessage) { - try { - String title = generateTitle(userMessage); - if (title != null) { - McpConversation conversation = conversationRepository.getById(conversationId); - conversation.setTitle(title); - conversationRepository.update(conversation); - } - } catch (RuntimeException e) { - LOG.warn("Failed to update conversation title for {}", conversationId, e); - } - } - - private String generateTitle(String userMessage) { - String title; - try { - List titleMessages = - List.of( - LlmMessage.system( - "Generate a short title (5-7 words max) for a conversation starting with this" - + " message. Reply with only the title text, no quotes or extra" - + " punctuation."), - LlmMessage.user(userMessage)); - LlmResponse response = llmClient.sendMessages(titleMessages, null); - title = normalizeTitle(response.content()); - } catch (LlmException e) { - LOG.warn("Failed to generate conversation title", e); - title = truncateTitle(userMessage); - } - return title; - } - - private String normalizeTitle(String title) { - String normalized = title; - if (normalized != null) { - normalized = normalized.trim().replaceAll("^\"|\"$", ""); - if (normalized.length() > 100) { - normalized = normalized.substring(0, 97) + "..."; - } - } - return normalized; - } - - private String truncateTitle(String message) { - String truncated = null; - if (message != null) { - truncated = message.length() > 100 ? message.substring(0, 97) + "..." : message; - } - return truncated; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ToolExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ToolExecutor.java deleted file mode 100644 index 3ab8868ac6a1..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/ToolExecutor.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.mcpclient; - -import org.openmetadata.service.security.auth.CatalogSecurityContext; - -@FunctionalInterface -public interface ToolExecutor { - String executeTool(CatalogSecurityContext securityContext, String toolName, String arguments); -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v200/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v200/Migration.java index 6d335b2d3633..8cba7a9c1ff0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v200/Migration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v200/Migration.java @@ -2,10 +2,12 @@ import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; import static org.openmetadata.service.migration.utils.v1130.MigrationUtil.addTableColumnSearchSettings; +import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addCreateTaskOperationToApplicationBotPolicy; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addCreateTaskRuleToDataConsumerPolicy; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addTaskAuthorPolicyToDataConsumerRole; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addTaskRuleToDataConsumerPolicy; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.backfillAnnouncementRelationships; +import static org.openmetadata.service.migration.utils.v200.MigrationUtil.backfillSearchRankingSettings; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.migrateLegacyActivityThreadsToActivityStream; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.migrateSuggestionsToTaskEntity; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.migrateThreadTasksToTaskEntity; @@ -33,6 +35,7 @@ public void runDataMigration() { // Reprocessing of an already-applied 1.13.0 with no new SQL skips // runDataMigration() per PR #26571, so this dual-invoke is required to // close that path. The helper is idempotent — safe on every run. + backfillSearchRankingSettings(); addTableColumnSearchSettings(); migrateSuggestionsToTaskEntity(handle, MYSQL); migrateThreadTasksToTaskEntity(handle, MYSQL); @@ -41,6 +44,7 @@ public void runDataMigration() { addTaskAuthorPolicyToDataConsumerRole(collectionDAO); addCreateTaskRuleToDataConsumerPolicy(collectionDAO); addTaskRuleToDataConsumerPolicy(collectionDAO); + addCreateTaskOperationToApplicationBotPolicy(collectionDAO); SearchIndexMappingsSeeder.seedIfAbsent(); // Wrap WorkflowHandler init + task workflow steps so a handler failure logs and continues diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v200/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v200/Migration.java index 66ab5b4848e6..8a9997ab8ca0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v200/Migration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v200/Migration.java @@ -2,10 +2,12 @@ import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; import static org.openmetadata.service.migration.utils.v1130.MigrationUtil.addTableColumnSearchSettings; +import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addCreateTaskOperationToApplicationBotPolicy; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addCreateTaskRuleToDataConsumerPolicy; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addTaskAuthorPolicyToDataConsumerRole; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.addTaskRuleToDataConsumerPolicy; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.backfillAnnouncementRelationships; +import static org.openmetadata.service.migration.utils.v200.MigrationUtil.backfillSearchRankingSettings; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.migrateLegacyActivityThreadsToActivityStream; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.migrateSuggestionsToTaskEntity; import static org.openmetadata.service.migration.utils.v200.MigrationUtil.migrateThreadTasksToTaskEntity; @@ -33,6 +35,7 @@ public void runDataMigration() { // Reprocessing of an already-applied 1.13.0 with no new SQL skips // runDataMigration() per PR #26571, so this dual-invoke is required to // close that path. The helper is idempotent — safe on every run. + backfillSearchRankingSettings(); addTableColumnSearchSettings(); migrateSuggestionsToTaskEntity(handle, POSTGRES); migrateThreadTasksToTaskEntity(handle, POSTGRES); @@ -41,6 +44,7 @@ public void runDataMigration() { addTaskAuthorPolicyToDataConsumerRole(collectionDAO); addCreateTaskRuleToDataConsumerPolicy(collectionDAO); addTaskRuleToDataConsumerPolicy(collectionDAO); + addCreateTaskOperationToApplicationBotPolicy(collectionDAO); SearchIndexMappingsSeeder.seedIfAbsent(); // Wrap WorkflowHandler init + task workflow steps so a handler failure logs and continues diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v200/MigrationUtil.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v200/MigrationUtil.java index 98cf7c50819c..c258be27dd53 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v200/MigrationUtil.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v200/MigrationUtil.java @@ -7,6 +7,7 @@ import static org.openmetadata.service.governance.workflows.Workflow.UPDATED_BY_VARIABLE; import static org.openmetadata.service.governance.workflows.WorkflowVariableHandler.getNamespacedVariableName; import static org.openmetadata.service.governance.workflows.elements.TriggerFactory.getTriggerWorkflowId; +import static org.openmetadata.service.migration.utils.v160.MigrationUtil.addOperationsToPolicyRule; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -16,13 +17,19 @@ import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collections; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Handle; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.search.AssetTypeConfiguration; +import org.openmetadata.schema.api.search.RankingConfiguration; +import org.openmetadata.schema.api.search.RankingStage; +import org.openmetadata.schema.api.search.SearchSettings; import org.openmetadata.schema.entity.activity.ActivityEvent; import org.openmetadata.schema.entity.feed.Announcement; import org.openmetadata.schema.entity.feed.Thread; @@ -32,6 +39,7 @@ import org.openmetadata.schema.entity.teams.Role; import org.openmetadata.schema.governance.workflows.WorkflowDefinition; import org.openmetadata.schema.governance.workflows.elements.WorkflowNodeDefinitionInterface; +import org.openmetadata.schema.settings.Settings; import org.openmetadata.schema.type.ActivityEventType; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; @@ -62,6 +70,7 @@ import org.openmetadata.service.jdbi3.TaskRepository; import org.openmetadata.service.jdbi3.WorkflowDefinitionRepository; import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.SearchSettingsMergeUtil; import org.openmetadata.service.resources.databases.DatasourceConfig; import org.openmetadata.service.resources.feeds.MessageParser; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver; @@ -100,6 +109,115 @@ protected boolean removeEldestEntry(Map.Entry> eld private MigrationUtil() {} + public static void backfillSearchRankingSettings() { + Settings searchSettings = SearchSettingsMergeUtil.getSearchSettingsFromDatabase(); + if (searchSettings == null) { + LOG.warn( + "Search settings not found in database. " + + "Default settings will be loaded on next startup with ranking settings."); + } else { + SearchSettings currentSettings = SearchSettingsMergeUtil.loadSearchSettings(searchSettings); + SearchSettings defaultSettings = SearchSettingsMergeUtil.loadSearchSettingsFromFile(); + AssetTypeConfiguration defaultConfiguration = + defaultSettings != null ? defaultSettings.getDefaultConfiguration() : null; + + if (currentSettings == null) { + LOG.warn("Stored searchSettings could not be loaded; skipping ranking settings backfill"); + } else if (defaultConfiguration == null || defaultConfiguration.getRanking() == null) { + LOG.warn("Default ranking settings not found in packaged searchSettings.json"); + } else { + AssetTypeConfiguration currentDefaultConfiguration = + currentSettings.getDefaultConfiguration(); + if (currentDefaultConfiguration == null) { + currentSettings.setDefaultConfiguration(defaultConfiguration); + SearchSettingsMergeUtil.saveSearchSettings(searchSettings, currentSettings); + LOG.info("Backfilled default search configuration with ranking settings"); + } else if (currentDefaultConfiguration.getRanking() == null) { + currentDefaultConfiguration.setRanking(defaultConfiguration.getRanking()); + SearchSettingsMergeUtil.saveSearchSettings(searchSettings, currentSettings); + LOG.info("Backfilled search ranking settings into stored searchSettings"); + } else if (mergeMissingDefaultRankingStages( + currentDefaultConfiguration.getRanking(), defaultConfiguration.getRanking())) { + SearchSettingsMergeUtil.saveSearchSettings(searchSettings, currentSettings); + LOG.info("Backfilled missing search ranking stages into stored searchSettings"); + } else { + LOG.info("Search ranking settings already exist in stored searchSettings"); + } + } + } + } + + private static boolean mergeMissingDefaultRankingStages( + RankingConfiguration currentRanking, RankingConfiguration defaultRanking) { + if (currentRanking == null + || defaultRanking == null + || Boolean.FALSE.equals(currentRanking.getEnabled())) { + return false; + } + + List defaultStages = listOrEmpty(defaultRanking.getStages()); + if (defaultStages.isEmpty()) { + return false; + } + + List currentStages = new ArrayList<>(listOrEmpty(currentRanking.getStages())); + Set currentStageNames = new HashSet<>(); + for (RankingStage stage : currentStages) { + if (!nullOrEmpty(stage.getName())) { + currentStageNames.add(stage.getName()); + } + } + + boolean merged = false; + for (int index = 0; index < defaultStages.size(); index++) { + RankingStage defaultStage = defaultStages.get(index); + if (nullOrEmpty(defaultStage.getName()) + || currentStageNames.contains(defaultStage.getName())) { + continue; + } + currentStages.add(rankingStageInsertIndex(currentStages, defaultStages, index), defaultStage); + currentStageNames.add(defaultStage.getName()); + merged = true; + LOG.info("Backfilled missing search ranking stage: {}", defaultStage.getName()); + } + + if (merged) { + currentRanking.setStages(currentStages); + } + return merged; + } + + private static int rankingStageInsertIndex( + List currentStages, List defaultStages, int defaultStageIndex) { + for (int index = defaultStageIndex - 1; index >= 0; index--) { + int currentIndex = rankingStageIndex(currentStages, defaultStages.get(index).getName()); + if (currentIndex >= 0) { + return currentIndex + 1; + } + } + + for (int index = defaultStageIndex + 1; index < defaultStages.size(); index++) { + int currentIndex = rankingStageIndex(currentStages, defaultStages.get(index).getName()); + if (currentIndex >= 0) { + return currentIndex; + } + } + + return currentStages.size(); + } + + private static int rankingStageIndex(List stages, String stageName) { + if (nullOrEmpty(stageName)) { + return -1; + } + for (int index = 0; index < stages.size(); index++) { + if (stageName.equals(stages.get(index).getName())) { + return index; + } + } + return -1; + } + /** * Ensure {@code TaskAuthorPolicy} is seeded and attached to the {@code DataConsumer} role on * upgrades. Role→Policy attachments are modelled as {@code Relationship.HAS} edges in {@code @@ -241,6 +359,23 @@ public static void addTaskRuleToDataConsumerPolicy(CollectionDAO collectionDAO) } } + /** + * Backfill the {@code CreateTask} operation onto an existing tenant's {@code ApplicationBotPolicy}. + * The operation is added to the seed JSON in this release but seed policies are + * create-if-not-exists, so without this migration upgraded deployments would leave application + * bots (e.g. the AI automation bot) unable to file suggestions as task entities — {@link + * org.openmetadata.service.resources.tasks.TaskResource} rejects the create with 403. Idempotent: + * {@link org.openmetadata.service.migration.utils.v160.MigrationUtil#addOperationsToPolicyRule} + * skips the operation when it is already present. + */ + public static void addCreateTaskOperationToApplicationBotPolicy(CollectionDAO collectionDAO) { + addOperationsToPolicyRule( + "ApplicationBotPolicy", + "ApplicationBotRule-Allow", + List.of(MetadataOperation.CREATE_TASK), + collectionDAO); + } + private static Policy ensureTaskAuthorPolicySeeded(PolicyRepository repository) { Policy existing = null; try { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIContextResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIContextResource.java new file mode 100644 index 000000000000..4176b0662852 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIContextResource.java @@ -0,0 +1,151 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.resources.ai; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.ServiceUnavailableException; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; +import java.util.List; +import org.openmetadata.service.Entity; +import org.openmetadata.service.aicontext.AIContextFinder; +import org.openmetadata.service.aicontext.AIContextFinder.FoundContext; +import org.openmetadata.service.aicontext.AIContextFinderAccess; +import org.openmetadata.service.aicontext.AttachedKnowledgeBatch; +import org.openmetadata.service.limits.Limits; +import org.openmetadata.service.resources.Collection; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.DefaultAuthorizer; +import org.openmetadata.service.security.policyevaluator.SubjectContext; + +@Path("/v1/ai/context") +@Tag( + name = "AI Context", + description = + "Question-anchored AI context discovery: semantically search the company-knowledge layer " + + "(glossary terms, metrics, articles) and route each hit to the candidate data assets " + + "it points to. Asset-anchored context is served per entity at /v1/{entities}/name/{fqn}/context.") +@Produces(MediaType.APPLICATION_JSON) +@Collection(name = "aiContext") +public class AIContextResource { + private final Authorizer authorizer; + + public AIContextResource(Authorizer authorizer, Limits limits) { + this.authorizer = authorizer; + } + + @GET + @Path("/find") + @Operation( + operationId = "findAiContext", + summary = "Find company knowledge relevant to a question, routed to candidate assets", + description = + "REST surface of the find_context MCP tool. Runs a semantic search over the knowledge " + + "layer (glossary terms, metrics, articles) and returns the matching definitions " + + "together with the candidate data assets each item routes to (glossary terms via " + + "tag usage, metrics via APPLIED_TO, articles via HAS). Candidate assets are " + + "filtered to those the caller can view.", + responses = { + @ApiResponse( + responseCode = "200", + description = "Knowledge items and the candidate assets they route to", + content = @Content(schema = @Schema(implementation = FoundContext.class))), + @ApiResponse(responseCode = "503", description = "Vector embeddings are not enabled") + }) + public Response find( + @Context SecurityContext securityContext, + @Parameter(description = "Natural-language question to find knowledge for") + @QueryParam("q") + @NotBlank + String query, + @Parameter(description = "Maximum knowledge items to return") + @QueryParam("size") + @DefaultValue("10") + @Min(1) + @Max(50) + int size) { + validateVectorSearchEnabled(); + AIContextFinderAccess.authorizeKnowledgeAccess(authorizer, securityContext); + SubjectContext subjectContext = DefaultAuthorizer.getSubjectContext(securityContext); + FoundContext found = new AIContextFinder(subjectContext).find(query, size); + FoundContext visible = + AIContextFinderAccess.filterCandidates(found, authorizer, securityContext); + return Response.ok(visible).build(); + } + + @POST + @Path("/attachedKnowledge") + @Consumes(MediaType.APPLICATION_JSON) + @Operation( + operationId = "getAttachedKnowledgeBatch", + summary = "Batch-resolve the knowledge attached to a set of assets", + description = + "For each asset (fqn + entityType), returns the knowledge linked to it: glossary terms " + + "from asset and column tags, metrics applied to it, and articles about it. " + + "Deliberately lightweight (no profile, lineage, or budgeting; item content capped) " + + "so search layers can annotate a whole result page in one call. Assets the caller " + + "cannot view are skipped.", + responses = { + @ApiResponse( + responseCode = "200", + description = "Per-asset attached knowledge items", + content = + @Content( + schema = @Schema(implementation = AttachedKnowledgeBatch.AssetKnowledge.class))) + }) + public Response attachedKnowledge( + @Context SecurityContext securityContext, + @Parameter(description = "Assets to resolve, as {fullyQualifiedName, entityType} pairs") + @NotNull + @Size(min = 1, max = AttachedKnowledgeBatch.MAX_ASSETS) + List assets) { + AIContextFinderAccess.authorizeKnowledgeAccess(authorizer, securityContext); + List viewable = + assets.stream() + .filter( + asset -> + AIContextFinderAccess.canView( + asset.entityType(), + asset.fullyQualifiedName(), + authorizer, + securityContext)) + .toList(); + return Response.ok(AttachedKnowledgeBatch.resolve(viewable)).build(); + } + + private void validateVectorSearchEnabled() { + if (!Entity.getSearchRepository().isVectorEmbeddingEnabled()) { + throw new ServiceUnavailableException( + "Semantic search is not enabled. Configure vector embeddings in the OpenMetadata server settings."); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceFrameworkResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceFrameworkResource.java index 85d59b44a9ed..e3b5e633c212 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceFrameworkResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceFrameworkResource.java @@ -33,20 +33,14 @@ import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.core.UriInfo; import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import java.util.UUID; import org.openmetadata.schema.api.ai.CreateAIGovernanceFramework; -import org.openmetadata.schema.entity.ai.AIFrameworkControl; +import org.openmetadata.schema.api.ai.ForkAIGovernanceFrameworkRequest; import org.openmetadata.schema.entity.ai.AIGovernanceFramework; import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.OpenMetadataApplicationConfig; -import org.openmetadata.service.jdbi3.AIFrameworkControlRepository; import org.openmetadata.service.jdbi3.AIGovernanceFrameworkRepository; import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.limits.Limits; @@ -67,7 +61,6 @@ public class AIGovernanceFrameworkResource public static final String COLLECTION_PATH = "/v1/aiGovernanceFrameworks/"; private final AIGovernanceFrameworkMapper mapper = new AIGovernanceFrameworkMapper(); static final String FIELDS = "owners,tags,extension,domains,stewards,autoApply"; - private static final int CONTROL_PAGE_SIZE = 1000; public AIGovernanceFrameworkResource(Authorizer authorizer, Limits limits) { super(Entity.AI_GOVERNANCE_FRAMEWORK, authorizer, limits); @@ -171,22 +164,7 @@ public Response getCoverage( @PathParam("id") UUID id) { AIGovernanceFramework framework = getInternal(uriInfo, securityContext, id, "", Include.NON_DELETED, null); - AIFrameworkControlRepository controlRepo = - (AIFrameworkControlRepository) Entity.getEntityRepository(Entity.AI_FRAMEWORK_CONTROL); - ListFilter filter = new ListFilter(Include.NON_DELETED); - List allControls = listControls(uriInfo, controlRepo, "", filter); - String frameworkName = framework.getName(); - List controls = new ArrayList<>(); - for (AIFrameworkControl control : allControls) { - if (control.getFramework() != null - && frameworkName.equals(control.getFramework().getName())) { - controls.add(control); - } - } - - Map response = FrameworkCoverageComputer.compute(framework, controls); - - return Response.ok(response).build(); + return Response.ok(repository.getCoverage(uriInfo, framework)).build(); } @POST @@ -200,101 +178,12 @@ public Response fork( @Context UriInfo uriInfo, @Context SecurityContext securityContext, @PathParam("id") UUID id, - ForkRequest request) { + @Valid ForkAIGovernanceFrameworkRequest request) { AIGovernanceFramework source = getInternal(uriInfo, securityContext, id, FIELDS, Include.NON_DELETED, null); - String user = securityContext.getUserPrincipal().getName(); - String newName = - request != null && request.getName() != null && !request.getName().isBlank() - ? request.getName() - : source.getName() + "_fork"; - - AIGovernanceFramework copy = new AIGovernanceFramework(); - copy.setId(UUID.randomUUID()); - copy.setName(newName); - copy.setDisplayName( - request != null && request.getDisplayName() != null - ? request.getDisplayName() - : "Fork of " - + (source.getDisplayName() == null ? source.getName() : source.getDisplayName())); - copy.setDescription(source.getDescription()); - copy.setReference(source.getReference()); - copy.setRegion(source.getRegion()); - copy.setSource(org.openmetadata.schema.entity.ai.FrameworkSource.ForkedFrom); - copy.setForkedFrom(source.getEntityReference()); - copy.setEnabled(false); - copy.setAssessmentCadence(source.getAssessmentCadence()); - copy.setAutoApply(source.getAutoApply()); - copy.setUpdatedAt(System.currentTimeMillis()); - copy.setUpdatedBy(user); - AIGovernanceFramework created = repository.create(uriInfo, copy); - - AIFrameworkControlRepository controlRepo = - (AIFrameworkControlRepository) Entity.getEntityRepository(Entity.AI_FRAMEWORK_CONTROL); - ListFilter controlFilter = new ListFilter(Include.NON_DELETED); - if (source.getFullyQualifiedName() != null) { - controlFilter.addQueryParam("framework", source.getFullyQualifiedName()); - } - List sourceControls = - listControls(uriInfo, controlRepo, FIELDS, controlFilter); - - List> copiedControls = new ArrayList<>(); - for (AIFrameworkControl original : sourceControls) { - AIFrameworkControl childCopy = JsonUtils.deepCopy(original, AIFrameworkControl.class); - childCopy.setId(UUID.randomUUID()); - childCopy.setFullyQualifiedName(null); - childCopy.setVersion(null); - childCopy.setFramework(created.getEntityReference()); - childCopy.setUpdatedAt(System.currentTimeMillis()); - childCopy.setUpdatedBy(user); - controlRepo.create(uriInfo, childCopy); - Map entry = new LinkedHashMap<>(); - entry.put("code", childCopy.getCode()); - entry.put("name", childCopy.getName()); - copiedControls.add(entry); - } - - Map response = new LinkedHashMap<>(); - response.put("framework", created); - response.put("copiedControlsCount", copiedControls.size()); - - return Response.ok(response).build(); - } - - private List listControls( - UriInfo uriInfo, AIFrameworkControlRepository controlRepo, String fields, ListFilter filter) { - List result = new ArrayList<>(); - String after = null; - do { - ResultList page = - controlRepo.listAfter( - uriInfo, controlRepo.getFields(fields), filter, CONTROL_PAGE_SIZE, after); - result.addAll(page.getData()); - after = page.getPaging() == null ? null : page.getPaging().getAfter(); - } while (after != null); - - return result; - } - - public static class ForkRequest { - private String name; - private String displayName; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + return Response.ok( + repository.fork(uriInfo, source, request, securityContext.getUserPrincipal().getName())) + .build(); } @DELETE diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceResource.java index eb4243357fbc..0dc9a83c860f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceResource.java @@ -17,7 +17,6 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.json.JsonPatch; import jakarta.validation.Valid; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DefaultValue; @@ -32,35 +31,14 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.core.UriInfo; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; import java.util.UUID; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.EntityInterface; -import org.openmetadata.schema.type.EntityStatus; -import org.openmetadata.schema.type.MetadataOperation; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.schema.api.ai.AIGovernanceBulkTriageRequest; +import org.openmetadata.schema.api.ai.AIGovernanceTransitionRequest; +import org.openmetadata.schema.api.ai.IntakeChecksResponse; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.security.Authorizer; -import org.openmetadata.service.security.policyevaluator.OperationContext; -import org.openmetadata.service.security.policyevaluator.ResourceContext; -import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; -/** - * Cross-cutting convenience endpoints that power the AI Governance Studio. The - * canonical CRUD endpoints for AIApplication / LLMModel / McpServer live in their - * own Resource classes; this resource is the one front door the Studio UI calls - * for actions that span asset types (intake check rollups, shadow triage, - * registration-state transitions, etc). - */ -@Slf4j -@SuppressWarnings("unchecked") @Path("/v1/aiGovernance") @Tag( name = "AI Governance", @@ -71,13 +49,10 @@ @Collection(name = "aiGovernance") public class AIGovernanceResource { - private static final Set SUPPORTED_TYPES = - Set.of(Entity.AI_APPLICATION, Entity.LLM_MODEL, Entity.MCP_SERVER); - - private final Authorizer authorizer; + private final AIGovernanceWorkflowService service; public AIGovernanceResource(Authorizer authorizer, Limits limits) { - this.authorizer = authorizer; + this.service = new AIGovernanceWorkflowService(authorizer); } @GET @@ -102,9 +77,7 @@ public Response getIntakeChecksByFqn( @PathParam("entityType") String entityType, @Parameter(description = "Fully qualified name of the asset") @PathParam("fqn") String fqn) { - authorizeViewByFqn(securityContext, entityType, fqn); - EntityInterface entity = loadEntityByFqn(entityType, fqn); - return Response.ok(IntakeChecks.compute(entity)).build(); + return Response.ok(service.getIntakeChecksByFqn(securityContext, entityType, fqn)).build(); } @POST @@ -119,16 +92,10 @@ public Response submitForReview( @Context SecurityContext securityContext, @PathParam("entityType") String entityType, @PathParam("id") String id) { - EntityInterface entity = - transitionRegistration( - securityContext, - entityType, - id, - "PendingApproval", - securityContext.getUserPrincipal().getName(), - null); - - return Response.ok(entity).build(); + return Response.ok( + service.submitForReview( + securityContext, entityType, id, securityContext.getUserPrincipal().getName())) + .build(); } @POST @@ -142,17 +109,15 @@ public Response approve( @Context SecurityContext securityContext, @PathParam("entityType") String entityType, @PathParam("id") String id, - @Valid TransitionRequest request) { - EntityInterface entity = - transitionRegistration( - securityContext, - entityType, - id, - "Approved", - securityContext.getUserPrincipal().getName(), - request == null ? null : request.getComment()); - - return Response.ok(entity).build(); + @Valid AIGovernanceTransitionRequest request) { + return Response.ok( + service.approve( + securityContext, + entityType, + id, + securityContext.getUserPrincipal().getName(), + request == null ? null : request.getComment())) + .build(); } @POST @@ -166,17 +131,15 @@ public Response reject( @Context SecurityContext securityContext, @PathParam("entityType") String entityType, @PathParam("id") String id, - @Valid TransitionRequest request) { - EntityInterface entity = - transitionRegistration( - securityContext, - entityType, - id, - "Rejected", - securityContext.getUserPrincipal().getName(), - request == null ? null : request.getComment()); - - return Response.ok(entity).build(); + @Valid AIGovernanceTransitionRequest request) { + return Response.ok( + service.reject( + securityContext, + entityType, + id, + securityContext.getUserPrincipal().getName(), + request == null ? null : request.getComment())) + .build(); } @GET @@ -189,19 +152,10 @@ public Response reject( public Response getActivity( @Context UriInfo uriInfo, @Context SecurityContext securityContext, - @jakarta.ws.rs.QueryParam("entityType") String entityType, - @jakarta.ws.rs.QueryParam("entityId") String entityId, - @jakarta.ws.rs.QueryParam("limit") @jakarta.ws.rs.DefaultValue("50") int limit) { - if (entityType != null && entityId != null) { - authorizeViewById(securityContext, entityType, entityId); - } else if (entityType != null) { - authorizeViewResourceType(securityContext, entityType); - } else { - authorizeViewAcrossSupportedTypes(securityContext); - } - List> events = GovernanceActivity.compute(entityType, entityId, limit); - - return Response.ok(Map.of("events", events)).build(); + @QueryParam("entityType") String entityType, + @QueryParam("entityId") String entityId, + @QueryParam("limit") @DefaultValue("50") int limit) { + return Response.ok(service.getActivity(securityContext, entityType, entityId, limit)).build(); } @GET @@ -212,10 +166,7 @@ public Response getActivity( description = "Returns the dashboard widgets in one shot: estate stats, risk × impact matrix counts, framework readiness percentages, top-N Shadow AI detections, top-N pending approvals. Computes from the AI Application / LLM Model / MCP Server entities directly so the UI can render in a single round-trip.") public Response getDashboard(@Context UriInfo uriInfo, @Context SecurityContext securityContext) { - authorizeViewAcrossSupportedTypes(securityContext); - Map response = DashboardRollup.compute(); - - return Response.ok(response).build(); + return Response.ok(service.getDashboard(securityContext)).build(); } @GET @@ -230,11 +181,7 @@ public Response getPolicyStatus( @Context SecurityContext securityContext, @PathParam("entityType") String entityType, @PathParam("id") String id) { - authorizeViewById(securityContext, entityType, id); - EntityInterface entity = loadEntity(entityType, id); - List> rules = PolicyEvaluator.evaluate(entity, entityType); - - return Response.ok(Map.of("rules", rules)).build(); + return Response.ok(service.getPolicyStatus(securityContext, entityType, id)).build(); } @GET @@ -250,14 +197,8 @@ public Response getPolicyViolations( @PathParam("policyId") UUID policyId, @QueryParam("since") Long since, @QueryParam("limit") @DefaultValue("50") int limit) { - authorizer.authorize( - securityContext, - new OperationContext(Entity.AI_GOVERNANCE_POLICY, MetadataOperation.VIEW_ALL), - new ResourceContext<>(Entity.AI_GOVERNANCE_POLICY, policyId, null)); - authorizeViewAcrossSupportedTypes(securityContext); - List> violations = PolicyEvaluator.recentViolations(policyId, since, limit); - - return Response.ok(Map.of("data", violations)).build(); + return Response.ok(service.getPolicyViolations(securityContext, policyId, since, limit)) + .build(); } @POST @@ -270,313 +211,7 @@ public Response getPolicyViolations( public Response bulkTriage( @Context UriInfo uriInfo, @Context SecurityContext securityContext, - @Valid BulkTriageRequest request) { - List> results = new ArrayList<>(); - if (request != null && request.getItems() != null) { - String user = securityContext.getUserPrincipal().getName(); - String targetStatus = - "Dismiss".equalsIgnoreCase(request.getAction()) ? "Rejected" : "PendingApproval"; - for (BulkTriageItem item : request.getItems()) { - Map rowResult = new LinkedHashMap<>(); - rowResult.put("entityType", item.getEntityType()); - rowResult.put("id", item.getId()); - try { - transitionRegistration( - securityContext, - item.getEntityType(), - item.getId(), - targetStatus, - user, - request.getReason()); - rowResult.put("status", "ok"); - } catch (Exception error) { - rowResult.put("status", "error"); - rowResult.put("message", error.getMessage()); - LOG.warn("Bulk triage failed for {}:{}", item.getEntityType(), item.getId(), error); - } - results.add(rowResult); - } - } - return Response.ok(Map.of("results", results)).build(); - } - - // ─── helpers ──────────────────────────────────────────────────────────── - - private EntityInterface loadEntityByFqn(String entityType, String fqn) { - assertSupported(entityType); - EntityRepository repository = Entity.getEntityRepository(entityType); - return repository.getByName(null, fqn, repository.getFields("owners,tags,domains,extension")); - } - - private EntityInterface loadEntity(String entityType, String id) { - assertSupported(entityType); - EntityRepository repository = Entity.getEntityRepository(entityType); - return repository.get( - null, java.util.UUID.fromString(id), repository.getFields("owners,tags,domains,extension")); - } - - private void assertSupported(String entityType) { - if (!SUPPORTED_TYPES.contains(entityType)) { - throw new IllegalArgumentException( - "Unsupported AI governance entityType '" - + entityType - + "'. Supported types: " - + SUPPORTED_TYPES); - } - } - - /** - * Mutate an asset's registrationStatus and re-PATCH. Handles both the - * AIApplication / McpServer governanceMetadata path and the LlmModel - * flat governanceStatus enum. - */ - private EntityInterface transitionRegistration( - SecurityContext securityContext, - String entityType, - String id, - String newStatus, - String user, - String comment) { - EntityInterface entity = loadEntity(entityType, id); - String originalJson = JsonUtils.pojoToJson(entity); - applyStatusTransition(entity, newStatus, user, comment); - String updatedJson = JsonUtils.pojoToJson(entity); - JsonPatch patch = JsonUtils.getJsonPatch(originalJson, updatedJson); - authorizePatch(securityContext, entityType, entity.getId(), patch); - - EntityRepository repository = Entity.getEntityRepository(entityType); - return repository.patch(null, entity.getId(), user, patch).entity(); - } - - private void authorizeViewByFqn(SecurityContext securityContext, String entityType, String fqn) { - assertSupported(entityType); - authorizer.authorize( - securityContext, - new OperationContext(entityType, MetadataOperation.VIEW_ALL), - new ResourceContext<>(entityType, null, fqn)); - } - - private void authorizeViewById(SecurityContext securityContext, String entityType, String id) { - assertSupported(entityType); - authorizer.authorize( - securityContext, - new OperationContext(entityType, MetadataOperation.VIEW_ALL), - new ResourceContext<>(entityType, UUID.fromString(id), null)); - } - - private void authorizeViewAcrossSupportedTypes(SecurityContext securityContext) { - for (String entityType : SUPPORTED_TYPES) { - authorizeViewResourceType(securityContext, entityType); - } - } - - private void authorizeViewResourceType(SecurityContext securityContext, String entityType) { - assertSupported(entityType); - authorizer.authorize( - securityContext, - new OperationContext(entityType, MetadataOperation.VIEW_ALL), - new ResourceContext<>(entityType)); - } - - private void authorizePatch( - SecurityContext securityContext, String entityType, UUID id, JsonPatch patch) { - assertSupported(entityType); - authorizer.authorize( - securityContext, - new OperationContext(entityType, patch), - new ResourceContext<>(entityType, id, null, ResourceContextInterface.Operation.PATCH)); - } - - @SuppressWarnings("unchecked") - private void applyStatusTransition( - EntityInterface entity, String newStatus, String user, String comment) { - entity.setEntityStatus(mapToEntityStatus(newStatus)); - if (entity instanceof org.openmetadata.schema.entity.ai.LLMModel llm) { - llm.setGovernanceStatus(mapToGovernanceStatus(newStatus)); - return; - } - Map governance = readGovernance(entity); - if (governance == null) { - governance = new LinkedHashMap<>(); - } - long now = System.currentTimeMillis(); - governance.put("registrationStatus", newStatus); - if ("PendingApproval".equals(newStatus)) { - governance.putIfAbsent("registeredBy", user); - governance.putIfAbsent("registeredAt", now); - } - if ("Approved".equals(newStatus)) { - governance.put("approvedBy", user); - governance.put("approvedAt", now); - } - if (comment != null && !comment.isBlank()) { - governance.put("approvalComments", comment); - } - writeGovernance(entity, governance); - } - - private static EntityStatus mapToEntityStatus(String newStatus) { - EntityStatus result; - switch (newStatus) { - case "Approved": - result = EntityStatus.APPROVED; - break; - case "PendingApproval": - result = EntityStatus.IN_REVIEW; - break; - case "Rejected": - result = EntityStatus.REJECTED; - break; - default: - result = EntityStatus.DRAFT; - } - return result; - } - - private static org.openmetadata.schema.entity.ai.LLMModel.GovernanceStatus mapToGovernanceStatus( - String newStatus) { - org.openmetadata.schema.entity.ai.LLMModel.GovernanceStatus result; - switch (newStatus) { - case "Approved": - result = org.openmetadata.schema.entity.ai.LLMModel.GovernanceStatus.APPROVED; - break; - case "PendingApproval": - result = org.openmetadata.schema.entity.ai.LLMModel.GovernanceStatus.PENDING_REVIEW; - break; - case "Rejected": - result = org.openmetadata.schema.entity.ai.LLMModel.GovernanceStatus.REJECTED; - break; - default: - result = org.openmetadata.schema.entity.ai.LLMModel.GovernanceStatus.UNAUTHORIZED; - } - return result; - } - - @SuppressWarnings("unchecked") - private Map readGovernance(EntityInterface entity) { - if (entity instanceof org.openmetadata.schema.entity.ai.AIApplication app) { - return JsonUtils.getObjectMapper().convertValue(app.getGovernanceMetadata(), Map.class); - } - if (entity instanceof org.openmetadata.schema.entity.ai.McpServer server) { - return JsonUtils.getObjectMapper().convertValue(server.getGovernanceMetadata(), Map.class); - } - return null; - } - - private void writeGovernance(EntityInterface entity, Map governance) { - if (entity instanceof org.openmetadata.schema.entity.ai.AIApplication app) { - app.setGovernanceMetadata( - JsonUtils.getObjectMapper() - .convertValue( - governance, org.openmetadata.schema.entity.ai.GovernanceMetadata.class)); - return; - } - if (entity instanceof org.openmetadata.schema.entity.ai.McpServer server) { - server.setGovernanceMetadata( - JsonUtils.getObjectMapper() - .convertValue( - governance, org.openmetadata.schema.entity.ai.McpGovernanceMetadata.class)); - } - } - - // ─── request / response payloads ──────────────────────────────────────── - - public static class TransitionRequest { - private String comment; - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - } - - public static class BulkTriageRequest { - private String action; - private String reason; - private List items; - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getReason() { - return reason; - } - - public void setReason(String reason) { - this.reason = reason; - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } - } - - public static class BulkTriageItem { - private String entityType; - private String id; - - public String getEntityType() { - return entityType; - } - - public void setEntityType(String entityType) { - this.entityType = entityType; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - } - - public static class IntakeChecksResponse { - private List checks; - - public List getChecks() { - return checks; - } - - public void setChecks(List checks) { - this.checks = checks; - } - } - - public static class IntakeCheck { - private String name; - private boolean passing; - private String evidenceRef; - - public IntakeCheck(String name, boolean passing, String evidenceRef) { - this.name = name; - this.passing = passing; - this.evidenceRef = evidenceRef; - } - - public String getName() { - return name; - } - - public boolean isPassing() { - return passing; - } - - public String getEvidenceRef() { - return evidenceRef; - } + @Valid AIGovernanceBulkTriageRequest request) { + return Response.ok(service.bulkTriage(securityContext, request)).build(); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceWorkflowService.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceWorkflowService.java new file mode 100644 index 000000000000..1d82e12f2d2f --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AIGovernanceWorkflowService.java @@ -0,0 +1,318 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.resources.ai; + +import jakarta.json.JsonPatch; +import jakarta.ws.rs.core.SecurityContext; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.ai.AIGovernanceActivityResponse; +import org.openmetadata.schema.api.ai.AIGovernanceBulkTriageItem; +import org.openmetadata.schema.api.ai.AIGovernanceBulkTriageRequest; +import org.openmetadata.schema.api.ai.AIGovernanceBulkTriageResponse; +import org.openmetadata.schema.api.ai.AIGovernanceBulkTriageResult; +import org.openmetadata.schema.api.ai.AIGovernanceDashboardResponse; +import org.openmetadata.schema.api.ai.AIGovernancePolicyStatusResponse; +import org.openmetadata.schema.api.ai.AIGovernancePolicyViolationsResponse; +import org.openmetadata.schema.api.ai.IntakeChecksResponse; +import org.openmetadata.schema.entity.ai.AIApplication; +import org.openmetadata.schema.entity.ai.AIGovernanceRegistration; +import org.openmetadata.schema.entity.ai.GovernanceMetadata; +import org.openmetadata.schema.entity.ai.LLMModel; +import org.openmetadata.schema.entity.ai.McpGovernanceMetadata; +import org.openmetadata.schema.entity.ai.McpServer; +import org.openmetadata.schema.type.EntityStatus; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; + +@Slf4j +final class AIGovernanceWorkflowService { + + private static final Set SUPPORTED_TYPES = + Set.of(Entity.AI_APPLICATION, Entity.LLM_MODEL, Entity.MCP_SERVER); + private static final String STATUS_PENDING_APPROVAL = "PendingApproval"; + private static final String STATUS_APPROVED = "Approved"; + private static final String STATUS_REJECTED = "Rejected"; + + private final Authorizer authorizer; + + AIGovernanceWorkflowService(Authorizer authorizer) { + this.authorizer = authorizer; + } + + IntakeChecksResponse getIntakeChecksByFqn( + SecurityContext securityContext, String entityType, String fqn) { + authorizeViewByFqn(securityContext, entityType, fqn); + return IntakeChecks.compute(loadEntityByFqn(entityType, fqn)); + } + + EntityInterface submitForReview( + SecurityContext securityContext, String entityType, String id, String user) { + return transitionRegistration( + securityContext, entityType, id, STATUS_PENDING_APPROVAL, user, null); + } + + EntityInterface approve( + SecurityContext securityContext, String entityType, String id, String user, String comment) { + return transitionRegistration(securityContext, entityType, id, STATUS_APPROVED, user, comment); + } + + EntityInterface reject( + SecurityContext securityContext, String entityType, String id, String user, String comment) { + return transitionRegistration(securityContext, entityType, id, STATUS_REJECTED, user, comment); + } + + AIGovernanceActivityResponse getActivity( + SecurityContext securityContext, String entityType, String entityId, int limit) { + if (entityType != null && entityId != null) { + authorizeViewById(securityContext, entityType, entityId); + } else if (entityType != null) { + authorizeViewResourceType(securityContext, entityType); + } else { + authorizeViewAcrossSupportedTypes(securityContext); + } + return GovernanceActivity.compute(entityType, entityId, limit); + } + + AIGovernanceDashboardResponse getDashboard(SecurityContext securityContext) { + authorizeViewAcrossSupportedTypes(securityContext); + return DashboardRollup.compute(); + } + + AIGovernancePolicyStatusResponse getPolicyStatus( + SecurityContext securityContext, String entityType, String id) { + authorizeViewById(securityContext, entityType, id); + return new AIGovernancePolicyStatusResponse() + .withRules(PolicyEvaluator.evaluate(loadEntity(entityType, id), entityType)); + } + + AIGovernancePolicyViolationsResponse getPolicyViolations( + SecurityContext securityContext, UUID policyId, Long since, int limit) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.AI_GOVERNANCE_POLICY, MetadataOperation.VIEW_ALL), + new ResourceContext<>(Entity.AI_GOVERNANCE_POLICY, policyId, null)); + authorizeViewAcrossSupportedTypes(securityContext); + return new AIGovernancePolicyViolationsResponse() + .withData(PolicyEvaluator.recentViolations(policyId, since, limit)); + } + + AIGovernanceBulkTriageResponse bulkTriage( + SecurityContext securityContext, AIGovernanceBulkTriageRequest request) { + List results = new ArrayList<>(); + if (request != null && request.getItems() != null) { + String user = securityContext.getUserPrincipal().getName(); + String targetStatus = + "Dismiss".equalsIgnoreCase(request.getAction()) + ? STATUS_REJECTED + : STATUS_PENDING_APPROVAL; + for (AIGovernanceBulkTriageItem item : request.getItems()) { + AIGovernanceBulkTriageResult result = + new AIGovernanceBulkTriageResult() + .withEntityType(item.getEntityType()) + .withId(item.getId()); + try { + transitionRegistration( + securityContext, + item.getEntityType(), + item.getId(), + targetStatus, + user, + request.getReason()); + result.setStatus("ok"); + } catch (Exception error) { + result.setStatus("error"); + result.setMessage(error.getMessage()); + LOG.warn("Bulk triage failed for {}:{}", item.getEntityType(), item.getId(), error); + } + results.add(result); + } + } + return new AIGovernanceBulkTriageResponse().withResults(results); + } + + private EntityInterface loadEntityByFqn(String entityType, String fqn) { + assertSupported(entityType); + EntityRepository repository = Entity.getEntityRepository(entityType); + return repository.getByName(null, fqn, repository.getFields("owners,tags,domains,extension")); + } + + private EntityInterface loadEntity(String entityType, String id) { + assertSupported(entityType); + EntityRepository repository = Entity.getEntityRepository(entityType); + return repository.get( + null, UUID.fromString(id), repository.getFields("owners,tags,domains,extension")); + } + + private void assertSupported(String entityType) { + if (!SUPPORTED_TYPES.contains(entityType)) { + throw new IllegalArgumentException( + "Unsupported AI governance entityType '" + + entityType + + "'. Supported types: " + + SUPPORTED_TYPES); + } + } + + private EntityInterface transitionRegistration( + SecurityContext securityContext, + String entityType, + String id, + String newStatus, + String user, + String comment) { + EntityInterface entity = loadEntity(entityType, id); + String originalJson = JsonUtils.pojoToJson(entity); + applyStatusTransition(entity, newStatus, user, comment); + String updatedJson = JsonUtils.pojoToJson(entity); + JsonPatch patch = JsonUtils.getJsonPatch(originalJson, updatedJson); + authorizePatch(securityContext, entityType, entity.getId(), patch); + + EntityRepository repository = Entity.getEntityRepository(entityType); + return repository.patch(null, entity.getId(), user, patch).entity(); + } + + private void authorizeViewByFqn(SecurityContext securityContext, String entityType, String fqn) { + assertSupported(entityType); + authorizer.authorize( + securityContext, + new OperationContext(entityType, MetadataOperation.VIEW_ALL), + new ResourceContext<>(entityType, null, fqn)); + } + + private void authorizeViewById(SecurityContext securityContext, String entityType, String id) { + assertSupported(entityType); + authorizer.authorize( + securityContext, + new OperationContext(entityType, MetadataOperation.VIEW_ALL), + new ResourceContext<>(entityType, UUID.fromString(id), null)); + } + + private void authorizeViewAcrossSupportedTypes(SecurityContext securityContext) { + for (String entityType : SUPPORTED_TYPES) { + authorizeViewResourceType(securityContext, entityType); + } + } + + private void authorizeViewResourceType(SecurityContext securityContext, String entityType) { + assertSupported(entityType); + authorizer.authorize( + securityContext, + new OperationContext(entityType, MetadataOperation.VIEW_ALL), + new ResourceContext<>(entityType)); + } + + private void authorizePatch( + SecurityContext securityContext, String entityType, UUID id, JsonPatch patch) { + assertSupported(entityType); + authorizer.authorize( + securityContext, + new OperationContext(entityType, patch), + new ResourceContext<>(entityType, id, null, ResourceContextInterface.Operation.PATCH)); + } + + private void applyStatusTransition( + EntityInterface entity, String newStatus, String user, String comment) { + entity.setEntityStatus(mapToEntityStatus(newStatus)); + if (entity instanceof LLMModel llm) { + llm.setGovernanceStatus(mapToGovernanceStatus(newStatus)); + } else if (entity instanceof AIApplication app) { + GovernanceMetadata governance = + app.getGovernanceMetadata() == null + ? new GovernanceMetadata() + : app.getGovernanceMetadata(); + governance.setRegistrationStatus(GovernanceMetadata.RegistrationStatus.fromValue(newStatus)); + stampRegistrationMilestones(governance, newStatus, user, comment); + app.setGovernanceMetadata(governance); + } else if (entity instanceof McpServer server) { + McpGovernanceMetadata governance = + server.getGovernanceMetadata() == null + ? new McpGovernanceMetadata() + : server.getGovernanceMetadata(); + governance.setRegistrationStatus( + McpGovernanceMetadata.RegistrationStatus.fromValue(newStatus)); + stampRegistrationMilestones(governance, newStatus, user, comment); + server.setGovernanceMetadata(governance); + } + } + + private static void stampRegistrationMilestones( + AIGovernanceRegistration governance, String newStatus, String user, String comment) { + long now = System.currentTimeMillis(); + if (STATUS_PENDING_APPROVAL.equals(newStatus)) { + if (governance.getRegisteredBy() == null) { + governance.setRegisteredBy(user); + } + if (governance.getRegisteredAt() == null) { + governance.setRegisteredAt(now); + } + } + if (STATUS_APPROVED.equals(newStatus)) { + if (governance.getApprovedBy() == null) { + governance.setApprovedBy(user); + } + if (governance.getApprovedAt() == null) { + governance.setApprovedAt(now); + } + } + if (comment != null && !comment.isBlank()) { + governance.setApprovalComments(comment); + } + } + + private static EntityStatus mapToEntityStatus(String newStatus) { + EntityStatus result; + switch (newStatus) { + case STATUS_APPROVED: + result = EntityStatus.APPROVED; + break; + case STATUS_PENDING_APPROVAL: + result = EntityStatus.IN_REVIEW; + break; + case STATUS_REJECTED: + result = EntityStatus.REJECTED; + break; + default: + result = EntityStatus.DRAFT; + } + return result; + } + + private static LLMModel.GovernanceStatus mapToGovernanceStatus(String newStatus) { + LLMModel.GovernanceStatus result; + switch (newStatus) { + case STATUS_APPROVED: + result = LLMModel.GovernanceStatus.APPROVED; + break; + case STATUS_PENDING_APPROVAL: + result = LLMModel.GovernanceStatus.PENDING_REVIEW; + break; + case STATUS_REJECTED: + result = LLMModel.GovernanceStatus.REJECTED; + break; + default: + result = LLMModel.GovernanceStatus.UNAUTHORIZED; + } + return result; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditPackGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditPackGenerator.java index 00e95d943828..8717bdcfdf76 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditPackGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditPackGenerator.java @@ -17,81 +17,93 @@ import java.util.ArrayList; import java.util.Base64; import java.util.HexFormat; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.UUID; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.ai.AIApplication; import org.openmetadata.schema.entity.ai.AuditReport; import org.openmetadata.schema.entity.ai.AuditReportArtifact; import org.openmetadata.schema.entity.ai.AuditReportFormat; import org.openmetadata.schema.entity.ai.AuditReportManifest; import org.openmetadata.schema.entity.ai.AuditReportScope; import org.openmetadata.schema.entity.ai.AuditReportStatus; +import org.openmetadata.schema.entity.ai.GovernanceMetadata; +import org.openmetadata.schema.entity.ai.McpGovernanceMetadata; +import org.openmetadata.schema.entity.ai.McpServer; +import org.openmetadata.schema.type.AICompliance; +import org.openmetadata.schema.type.AIComplianceRecord; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.bundles.searchIndex.distributed.ServerIdentityResolver; import org.openmetadata.service.jdbi3.AuditReportRepository; import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.ListFilter; +import org.openmetadata.service.util.AsyncService; import org.openmetadata.service.util.EntityUtil; /** - * Synchronous-async audit-pack generator. The Resource hands a freshly-created - * AuditReport to {@link #submit(UUID)}; the executor walks the scope, builds a - * JSON document, encodes it as a data:application/json;base64 URL, and PATCHes - * the report to Completed. Errors PATCH the report to Failed with the message. + * Async audit-pack generator. The Resource hands a freshly-created AuditReport to + * {@link #submit(UUID)}; a shared virtual thread walks the scope, builds a JSON + * document, encodes it as a data:application/json;base64 URL, and PATCHes the report + * to Completed. Errors PATCH the report to Failed with the message. + * + *

Runs on the shared {@link AsyncService} rather than a private pool so it is not + * capped per-pod and participates in server lifecycle. Because the AuditReport row is the + * durable job record, jobs survive a pod restart: {@link #recoverInterruptedReports()} + * (wired into server startup) re-drives {@code Queued} reports the crash left un-run and + * reclaims {@code Running} reports orphaned mid-flight. Each job is claimed with an atomic + * conditional {@code Queued -> Running} update (stamping the owning {@code runningOn} node), so + * concurrent recovery across pods generates the pack exactly once. Re-submitting a duplicate + * request returns the in-flight report via an indexed {@code requestSignature} lookup + * ({@link #findActiveDuplicate(AuditReport)}) instead of generating the same pack twice. * *

Storage strategy is deliberately simple in v1: the artifact bytes are * embedded directly in the artifacts[] entry's downloadUrl. PDF rendering is * deferred — Pdf/Both reports complete as JSON-only with a note in the manifest. */ @Slf4j -final class AuditPackGenerator { +public final class AuditPackGenerator { private static final String ADMIN_USER = "admin"; private static final int PAGE_SIZE = 500; - private static final ExecutorService EXECUTOR = - Executors.newFixedThreadPool( - 2, - new ThreadFactory() { - private final AtomicInteger counter = new AtomicInteger(1); + /** + * A {@code Running} report whose {@code startedAt} is older than this is treated as orphaned by + * a crashed pod and re-queued on recovery. Audit assembly is in-memory JSON that completes in + * seconds, so a generous window avoids reclaiming a genuinely in-flight job. + */ + private static final long STALE_RUNNING_MILLIS = 15 * 60 * 1000L; - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r, "audit-pack-" + counter.getAndIncrement()); - thread.setDaemon(true); - return thread; - } - }); + private static final int RECOVERY_SCAN_CAP = 10000; private AuditPackGenerator() {} static void submit(UUID reportId) { - EXECUTOR.execute(() -> run(reportId)); + AsyncService.getInstance().execute(() -> run(reportId)); } private static void run(UUID reportId) { - AuditReportRepository repository = - (AuditReportRepository) Entity.getEntityRepository(Entity.AUDIT_REPORT); + long started = System.currentTimeMillis(); + int claimed = + Entity.getCollectionDAO() + .auditReportDAO() + .claimQueued(reportId.toString(), currentServerId(), started); + if (claimed == 0) { + // No longer Queued, or another pod atomically won the claim — nothing to do. + return; + } + AuditReportRepository repository = auditReportRepository(); AuditReport report; try { report = repository.get(null, reportId, repository.getFields("id,name,scope,format")); } catch (Exception e) { - LOG.warn("Audit pack generator could not fetch report {}: {}", reportId, e.getMessage()); + LOG.warn( + "Audit pack generator could not fetch claimed report {}: {}", reportId, e.getMessage()); return; } - if (report.getStatus() != AuditReportStatus.Queued) { - return; - } - long started = System.currentTimeMillis(); - transition(reportId, AuditReportStatus.Running, started, null, null, null); try { AuditPackPayload payload = assemble(report); String json = JsonUtils.pojoToJson(payload.body); @@ -111,124 +123,206 @@ private static void run(UUID reportId) { manifest.setControlCount(payload.controlCount); manifest.setComplianceRecordCount(payload.complianceRecordCount); - transition( - reportId, - AuditReportStatus.Completed, - null, - System.currentTimeMillis(), - artifacts, - manifest); + completeRunning(reportId, artifacts, manifest); } catch (Exception failure) { LOG.warn("Audit pack generation failed for {}", reportId, failure); - transition( - reportId, - AuditReportStatus.Failed, - null, - System.currentTimeMillis(), - null, - null, - failure.getMessage()); + failRunning(reportId, failureMessage(failure)); } } - private static void transition( - UUID reportId, - AuditReportStatus status, - Long startedAt, - Long completedAt, - List artifacts, - AuditReportManifest manifest) { - transition(reportId, status, startedAt, completedAt, artifacts, manifest, null); - } - - private static void transition( - UUID reportId, - AuditReportStatus status, - Long startedAt, - Long completedAt, - List artifacts, - AuditReportManifest manifest, - String failureReason) { - AuditReportRepository repository = - (AuditReportRepository) Entity.getEntityRepository(Entity.AUDIT_REPORT); + /** + * Re-drives audit reports left non-terminal by a pod restart or crash: {@code Queued} reports + * were never picked up (the previous in-memory queue did not survive), and {@code Running} + * reports older than {@link #STALE_RUNNING_MILLIS} were orphaned mid-run. Both are safe to + * regenerate — an audit pack is a deterministic snapshot. Wired into server startup. + */ + public static void recoverInterruptedReports() { try { - AuditReport current = - repository.get(null, reportId, repository.getFields("id,name,artifacts,manifest")); - String originalJson = JsonUtils.pojoToJson(current); - current.setStatus(status); - if (startedAt != null) { - current.setStartedAt(startedAt); + long now = System.currentTimeMillis(); + List interrupted = collectInterruptedReports(now); + for (AuditReport report : interrupted) { + requeueAndSubmit(report, now); } - if (completedAt != null) { - current.setCompletedAt(completedAt); + if (!interrupted.isEmpty()) { + LOG.info( + "Audit pack recovery: re-submitted {} interrupted report(s) on startup", + interrupted.size()); } - if (artifacts != null) { - current.setArtifacts(artifacts); + } catch (Exception recoveryError) { + LOG.warn("Audit pack recovery sweep failed: {}", recoveryError.getMessage()); + } + } + + /** Computes and stamps the request signature backing indexed idempotent-submission dedup. */ + static void stampRequestSignature(AuditReport report) { + report.setRequestSignature(sha256(signatureOf(report).getBytes(StandardCharsets.UTF_8))); + } + + /** + * Returns the in-flight ({@code Queued}/{@code Running}) report whose request signature matches + * {@code candidate} via an indexed O(1) lookup, so a retried submission returns the existing job + * instead of generating the same pack twice. {@code candidate} must already carry its + * {@code requestSignature} (see {@link #stampRequestSignature}). + */ + static AuditReport findActiveDuplicate(AuditReport candidate) { + AuditReport result = null; + try { + String signature = candidate.getRequestSignature(); + if (signature != null) { + String json = + Entity.getCollectionDAO().auditReportDAO().findActiveByRequestSignature(signature); + if (json != null) { + result = JsonUtils.readValue(json, AuditReport.class); + } } - if (manifest != null) { - current.setManifest(manifest); + } catch (Exception lookupError) { + LOG.warn("Audit pack duplicate lookup failed: {}", lookupError.getMessage()); + } + return result; + } + + private static List collectInterruptedReports(long now) { + AuditReportRepository repository = auditReportRepository(); + List result = new ArrayList<>(); + ListFilter filter = new ListFilter(Include.NON_DELETED); + String after = null; + int scanned = 0; + do { + ResultList page = + repository.listAfter(null, EntityUtil.Fields.EMPTY_FIELDS, filter, PAGE_SIZE, after); + for (AuditReport report : page.getData()) { + if (isInterrupted(report, now)) { + result.add(report); + } } - if (failureReason != null) { - current.setFailureReason(failureReason); + scanned += page.getData().size(); + after = page.getPaging() == null ? null : page.getPaging().getAfter(); + } while (after != null && scanned < RECOVERY_SCAN_CAP); + return result; + } + + static boolean isInterrupted(AuditReport report, long now) { + boolean result = false; + AuditReportStatus status = report.getStatus(); + if (status == AuditReportStatus.Queued) { + result = true; + } else if (status == AuditReportStatus.Running) { + Long startedAt = report.getStartedAt(); + result = startedAt == null || now - startedAt > STALE_RUNNING_MILLIS; + } + return result; + } + + private static void requeueAndSubmit(AuditReport report, long now) { + if (report.getStatus() == AuditReportStatus.Running) { + int requeued = + Entity.getCollectionDAO() + .auditReportDAO() + .requeueStaleRunning( + report.getId().toString(), now - STALE_RUNNING_MILLIS, now, ADMIN_USER); + if (requeued == 0) { + return; } - String updatedJson = JsonUtils.pojoToJson(current); - jakarta.json.JsonPatch patch = JsonUtils.getJsonPatch(originalJson, updatedJson); - repository.patch(null, reportId, ADMIN_USER, patch); - } catch (Exception transitionError) { - LOG.warn("Failed to transition audit report {}: {}", reportId, transitionError.getMessage()); } + submit(report.getId()); + } + + static String signatureOf(AuditReport report) { + return String.join( + "|", + enumValue(report.getScope()), + refId(report.getScopeTarget()), + refId(report.getFramework()), + enumValue(report.getFormat()), + String.valueOf(report.getAsOfDate()), + String.valueOf(Boolean.TRUE.equals(report.getIncludeRedacted())), + report.getUpdatedBy() == null ? "" : report.getUpdatedBy()); + } + + private static String enumValue(Object enumConstant) { + return enumConstant == null ? "" : enumConstant.toString(); + } + + private static String refId(EntityReference ref) { + return ref == null || ref.getId() == null ? "" : ref.getId().toString(); + } + + private static String currentServerId() { + return ServerIdentityResolver.getInstance().getServerId(); + } + + private static AuditReportRepository auditReportRepository() { + return (AuditReportRepository) Entity.getEntityRepository(Entity.AUDIT_REPORT); + } + + private static void completeRunning( + UUID reportId, List artifacts, AuditReportManifest manifest) { + Entity.getCollectionDAO() + .auditReportDAO() + .completeRunning( + reportId.toString(), + currentServerId(), + System.currentTimeMillis(), + JsonUtils.pojoToJson(artifacts), + JsonUtils.pojoToJson(manifest), + ADMIN_USER); + } + + private static void failRunning(UUID reportId, String failureReason) { + Entity.getCollectionDAO() + .auditReportDAO() + .failRunning( + reportId.toString(), + currentServerId(), + System.currentTimeMillis(), + failureReason, + ADMIN_USER); + } + + private static String failureMessage(Exception failure) { + String message = failure.getMessage(); + return message == null ? failure.getClass().getSimpleName() : message; } private static AuditPackPayload assemble(AuditReport report) { AuditPackPayload payload = new AuditPackPayload(); - payload.body.put("reportId", report.getId() == null ? null : report.getId().toString()); - payload.body.put("name", report.getName()); - payload.body.put("scope", report.getScope() == null ? null : report.getScope().value()); - payload.body.put("framework", report.getFramework()); - payload.body.put("scopeTarget", report.getScopeTarget()); - payload.body.put("asOfDate", report.getAsOfDate()); - payload.body.put("generatedAt", System.currentTimeMillis()); - - List> assets = new ArrayList<>(); + List assets = new ArrayList<>(); AuditReportScope scope = report.getScope() == null ? AuditReportScope.Estate : report.getScope(); collectAssets(Entity.AI_APPLICATION, scope, report, assets); collectAssets(Entity.LLM_MODEL, scope, report, assets); collectAssets(Entity.MCP_SERVER, scope, report, assets); - payload.body.put("assets", assets); + payload.body = + new AuditPackDocument( + report.getId() == null ? null : report.getId().toString(), + report.getName(), + report.getScope() == null ? null : report.getScope().value(), + report.getFramework(), + report.getScopeTarget(), + report.getAsOfDate(), + System.currentTimeMillis(), + assets); payload.assetCount = assets.size(); payload.complianceRecordCount = countComplianceRecords(assets); payload.frameworkCount = report.getFramework() == null ? 0 : 1; return payload; } - @SuppressWarnings("unchecked") - private static int countComplianceRecords(List> assets) { + private static int countComplianceRecords(List assets) { int total = 0; - for (Map asset : assets) { - Object governance = asset.get("governanceMetadata"); - if (governance instanceof Map g) { - Object aiCompliance = ((Map) g).get("aiCompliance"); - if (aiCompliance instanceof Map c) { - Object records = ((Map) c).get("complianceRecords"); - if (records instanceof List list) { - total += list.size(); - } - } - } + for (AuditPackAsset asset : assets) { + total += asset.complianceRecordCount(); } return total; } private static void collectAssets( - String entityType, - AuditReportScope scope, - AuditReport report, - List> out) { + String entityType, AuditReportScope scope, AuditReport report, List out) { try { ListFilter filter = new ListFilter(Include.NON_DELETED); - List entities = listAssets(entityType, filter); + List entities = + listAssets(entityType, filter, fieldsForScope(entityType, scope)); for (EntityInterface entity : entities) { if (scope == AuditReportScope.Asset && report.getScopeTarget() != null) { if (!report.getScopeTarget().getId().equals(entity.getId())) { @@ -236,35 +330,33 @@ private static void collectAssets( } } if (scope == AuditReportScope.Domain && report.getScopeTarget() != null) { - Object domains = entity.getDomains(); - if (!matchesDomain(domains, report.getScopeTarget().getId())) { + if (!matchesDomain(entity.getDomains(), report.getScopeTarget().getId())) { continue; } } - Map entry = new LinkedHashMap<>(); - entry.put("entityType", entityType); - entry.put("id", entity.getId() == null ? null : entity.getId().toString()); - entry.put("name", entity.getName()); - entry.put("displayName", entity.getDisplayName()); - entry.put("fullyQualifiedName", entity.getFullyQualifiedName()); - Map entityMap = - JsonUtils.readValue(JsonUtils.pojoToJson(entity), Map.class); - entry.put("governanceMetadata", entityMap.get("governanceMetadata")); - entry.put("updatedAt", entity.getUpdatedAt()); - out.add(entry); + out.add( + new AuditPackAsset( + entityType, + entity.getId() == null ? null : entity.getId().toString(), + entity.getName(), + entity.getDisplayName(), + entity.getFullyQualifiedName(), + governanceMetadata(entity), + entity.getUpdatedAt())); } } catch (Exception e) { LOG.debug("Audit pack scope walk for {} returned empty: {}", entityType, e.getMessage()); } } - private static List listAssets(String entityType, ListFilter filter) { + private static List listAssets( + String entityType, ListFilter filter, EntityUtil.Fields fields) { List result = new ArrayList<>(); EntityRepository repo = Entity.getEntityRepository(entityType); String after = null; do { ResultList page = - repo.listAfter(null, EntityUtil.Fields.EMPTY_FIELDS, filter, PAGE_SIZE, after); + repo.listAfter(null, fields, filter, PAGE_SIZE, after); result.addAll(page.getData()); after = page.getPaging() == null ? null : page.getPaging().getAfter(); } while (after != null); @@ -272,17 +364,47 @@ private static List listAssets(String entityType, ListFilter fi return result; } - @SuppressWarnings("unchecked") - private static boolean matchesDomain(Object domains, UUID targetDomainId) { - if (!(domains instanceof List list)) { + /** + * Domain-scoped packs filter on {@link EntityInterface#getDomains()}; {@code domains} + * is a relationship field that stays null unless explicitly requested, so a Domain + * pack loaded with {@code EMPTY_FIELDS} would match nothing. Estate/Asset scopes read + * only the always-present governance fields and need no relationship fields. + */ + private static EntityUtil.Fields fieldsForScope(String entityType, AuditReportScope scope) { + EntityUtil.Fields result = EntityUtil.Fields.EMPTY_FIELDS; + if (scope == AuditReportScope.Domain) { + result = Entity.getEntityRepository(entityType).getFields("domains"); + } + return result; + } + + private static Object governanceMetadata(EntityInterface entity) { + Object result = null; + if (entity instanceof AIApplication app) { + result = app.getGovernanceMetadata(); + } else if (entity instanceof McpServer server) { + result = server.getGovernanceMetadata(); + } + return result; + } + + private static AICompliance aiCompliance(Object governanceMetadata) { + AICompliance result = null; + if (governanceMetadata instanceof GovernanceMetadata governance) { + result = governance.getAiCompliance(); + } else if (governanceMetadata instanceof McpGovernanceMetadata governance) { + result = governance.getAiCompliance(); + } + return result; + } + + private static boolean matchesDomain(List domains, UUID targetDomainId) { + if (domains == null) { return false; } - for (Object item : list) { - if (item instanceof Map ref) { - Object id = ((Map) ref).get("id"); - if (id != null && id.toString().equals(targetDomainId.toString())) { - return true; - } + for (EntityReference domain : domains) { + if (domain != null && domain.getId() != null && domain.getId().equals(targetDomainId)) { + return true; } } return false; @@ -298,10 +420,36 @@ private static String sha256(byte[] data) { } private static final class AuditPackPayload { - Map body = new LinkedHashMap<>(); + AuditPackDocument body; int assetCount; int frameworkCount; int controlCount; int complianceRecordCount; } + + private record AuditPackDocument( + String reportId, + String name, + String scope, + EntityReference framework, + EntityReference scopeTarget, + Long asOfDate, + long generatedAt, + List assets) {} + + private record AuditPackAsset( + String entityType, + String id, + String name, + String displayName, + String fullyQualifiedName, + Object governanceMetadata, + Long updatedAt) { + private int complianceRecordCount() { + AICompliance aiCompliance = aiCompliance(governanceMetadata); + List records = + aiCompliance == null ? null : aiCompliance.getComplianceRecords(); + return records == null ? 0 : records.size(); + } + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditReportResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditReportResource.java index 616d64f7bb6b..80ad18a135b0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditReportResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/AuditReportResource.java @@ -119,6 +119,14 @@ public Response create( @Valid CreateAuditReport create) { AuditReport report = mapper.createToEntity(create, securityContext.getUserPrincipal().getName()); + AuditPackGenerator.stampRequestSignature(report); + + AuditReport inFlight = AuditPackGenerator.findActiveDuplicate(report); + if (inFlight != null) { + AuditReport existing = + repository.get(uriInfo, inFlight.getId(), repository.getFields(FIELDS)); + return Response.ok(existing).build(); + } Response response = create(uriInfo, securityContext, report); if (report.getId() != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/DashboardRollup.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/DashboardRollup.java index fa801e89f7fb..6a263e495c5a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/DashboardRollup.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/DashboardRollup.java @@ -15,6 +15,7 @@ import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import java.util.ArrayList; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -22,8 +23,22 @@ import lombok.Builder; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.ai.AIGovernanceAssetSummary; +import org.openmetadata.schema.api.ai.AIGovernanceDashboardResponse; +import org.openmetadata.schema.api.ai.AIGovernanceEstateStats; +import org.openmetadata.schema.api.ai.AIGovernanceFrameworkReadiness; +import org.openmetadata.schema.api.ai.AIGovernanceRiskMatrixCell; +import org.openmetadata.schema.api.ai.AIGovernanceTopEntity; +import org.openmetadata.schema.entity.ai.AIApplication; import org.openmetadata.schema.entity.ai.AIGovernanceFramework; -import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.schema.entity.ai.GovernanceMetadata; +import org.openmetadata.schema.entity.ai.LLMModel; +import org.openmetadata.schema.entity.ai.McpGovernanceMetadata; +import org.openmetadata.schema.entity.ai.McpServer; +import org.openmetadata.schema.type.AICompliance; +import org.openmetadata.schema.type.AIComplianceRecord; +import org.openmetadata.schema.type.AIDetection; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.EntityRepository; @@ -33,8 +48,8 @@ /** * Computes the AI governance dashboard rollup the Overview tab consumes in * a single round-trip. Pulls AI Applications, LLM Models, and MCP Servers - * from their repositories, projects each onto a normalized governance map - * via Jackson, then aggregates stats / risk-matrix / framework readiness / + * from their repositories, projects each onto a normalized governance record, + * then aggregates stats / risk-matrix / framework readiness / * top-N lists in memory. * *

For estates over ~10k assets this should move to Elasticsearch @@ -49,24 +64,23 @@ final class DashboardRollup { private static final int PAGE_SIZE = 1000; private static final int TOP_N = 5; private static final String COMPLIANT = "Compliant"; + private static final String[] RISK_SEVERITY = {"Unacceptable", "High", "Limited", "Minimal"}; private DashboardRollup() {} - static Map compute() { + static AIGovernanceDashboardResponse compute() { List assets = new ArrayList<>(); collectAssets(Entity.AI_APPLICATION, "owners,domains,governanceMetadata", assets); collectAssets(Entity.MCP_SERVER, "owners,domains,governanceMetadata", assets); collectAssets(Entity.LLM_MODEL, "owners,domains,governanceStatus,detection", assets); - Map response = new LinkedHashMap<>(); - response.put("estateStats", estateStats(assets)); - response.put("frameworkReadiness", frameworkReadiness(assets)); - response.put("riskMatrix", riskMatrix(assets)); - response.put("topShadow", topByStatus(assets, "Unregistered")); - response.put("topApprovals", topByStatus(assets, "PendingApproval")); - response.put("generatedAt", System.currentTimeMillis()); - - return response; + return new AIGovernanceDashboardResponse() + .withEstateStats(estateStats(assets)) + .withFrameworkReadiness(frameworkReadiness(assets)) + .withRiskMatrix(riskMatrix(assets)) + .withTopShadow(topByStatus(assets, "Unregistered", shadowRanking())) + .withTopApprovals(topByStatus(assets, "PendingApproval", approvalRanking())) + .withGeneratedAt(System.currentTimeMillis()); } private static void collectAssets(String entityType, String fields, List out) { @@ -89,7 +103,7 @@ private static void collectAssets(String entityType, String fields, List estateStats(List assets) { + private static AIGovernanceEstateStats estateStats(List assets) { int total = assets.size(); int registered = 0; int shadow = 0; @@ -121,16 +135,14 @@ private static Map estateStats(List assets) { unacceptable++; } } - Map stats = new LinkedHashMap<>(); - stats.put("total", total); - stats.put("registered", registered); - stats.put("approved", approved); - stats.put("shadow", shadow); - stats.put("pending", pending); - stats.put("highRisk", highRisk); - stats.put("unacceptable", unacceptable); - - return stats; + return new AIGovernanceEstateStats() + .withTotal(total) + .withRegistered(registered) + .withApproved(approved) + .withShadow(shadow) + .withPending(pending) + .withHighRisk(highRisk) + .withUnacceptable(unacceptable); } /** @@ -139,40 +151,41 @@ private static Map estateStats(List assets) { * enabled (nearest {@code nextDeadline}, breaking ties on lowest readiness) so the * UI can badge it; nothing is focused when no enabled framework has assessments. */ - private static List> frameworkReadiness(List assets) { - List> result = buildReadinessEntries(frameworkCounts(assets)); + private static List frameworkReadiness(List assets) { + List result = buildReadinessEntries(frameworkCounts(assets)); String focusKey = pickFocusFramework(result, enabledFrameworkDeadlines()); - for (Map entry : result) { - String key = entry.get("framework").toString().toUpperCase(Locale.ROOT); - entry.put("focus", key.equals(focusKey)); + for (AIGovernanceFrameworkReadiness entry : result) { + String key = entry.getFramework().toUpperCase(Locale.ROOT); + entry.setFocus(key.equals(focusKey)); } return result; } - private static Map frameworkCounts(List assets) { - Map bucketByFramework = new LinkedHashMap<>(); + private static Map frameworkCounts(List assets) { + Map bucketByFramework = new LinkedHashMap<>(); for (RolledAsset asset : assets) { - for (Map.Entry entry : asset.frameworkStatuses().entrySet()) { - int[] counts = bucketByFramework.computeIfAbsent(entry.getKey(), k -> new int[2]); - counts[1] += 1; - if (COMPLIANT.equals(entry.getValue())) { - counts[0] += 1; - } + for (FrameworkStatusSnapshot status : asset.frameworkStatuses()) { + bucketByFramework.merge( + status.framework(), + new FrameworkReadinessCounts(COMPLIANT.equals(status.status()) ? 1 : 0, 1), + FrameworkReadinessCounts::plus); } } return bucketByFramework; } - private static List> buildReadinessEntries(Map counts) { - List> result = new ArrayList<>(); + private static List buildReadinessEntries( + Map counts) { + List result = new ArrayList<>(); counts.forEach( (framework, count) -> { - Map entry = new LinkedHashMap<>(); - entry.put("framework", framework); - entry.put("compliant", count[0]); - entry.put("inScope", count[1]); - entry.put("readiness", count[1] == 0 ? 0.0 : (double) count[0] / count[1]); - result.add(entry); + result.add( + new AIGovernanceFrameworkReadiness() + .withFramework(framework) + .withCompliant(count.compliant()) + .withInScope(count.inScope()) + .withReadiness(count.readiness()) + .withFocus(false)); }); return result; } @@ -208,16 +221,16 @@ private static void collectEnabledFramework(EntityInterface entity, Map> readiness, Map enabledDeadlines) { + List readiness, Map enabledDeadlines) { String focusKey = null; long bestDeadline = Long.MAX_VALUE; double bestReadiness = Double.MAX_VALUE; - for (Map entry : readiness) { - String key = entry.get("framework").toString().toUpperCase(Locale.ROOT); + for (AIGovernanceFrameworkReadiness entry : readiness) { + String key = entry.getFramework().toUpperCase(Locale.ROOT); if (enabledDeadlines.containsKey(key)) { Long deadline = enabledDeadlines.get(key); long effectiveDeadline = deadline == null ? Long.MAX_VALUE : deadline; - double readinessValue = ((Number) entry.get("readiness")).doubleValue(); + double readinessValue = entry.getReadiness(); if (effectiveDeadline < bestDeadline || (effectiveDeadline == bestDeadline && readinessValue < bestReadiness)) { bestDeadline = effectiveDeadline; @@ -234,8 +247,8 @@ private static String pickFocusFramework( * carries the {@code topEntity} (the asset with the most affected users in that * cell) so the UI can name the headline asset alongside the count. */ - private static List> riskMatrix(List assets) { - String[] risks = {"Unacceptable", "High", "Limited", "Minimal"}; + private static List riskMatrix(List assets) { + String[] risks = RISK_SEVERITY; int[] bucketCaps = {1000, 10000, 100000, Integer.MAX_VALUE}; String[] bucketLabels = {"<1k", "1k–10k", "10k–100k", ">100k"}; int[][] counts = new int[risks.length][bucketCaps.length]; @@ -250,15 +263,16 @@ private static List> riskMatrix(List assets) { } } - List> cells = new ArrayList<>(); + List cells = new ArrayList<>(); for (int r = 0; r < risks.length; r++) { for (int c = 0; c < bucketCaps.length; c++) { - Map cell = new LinkedHashMap<>(); - cell.put("risk", risks[r]); - cell.put("impactBucket", bucketLabels[c]); - cell.put("count", counts[r][c]); + AIGovernanceRiskMatrixCell cell = + new AIGovernanceRiskMatrixCell() + .withRisk(risks[r]) + .withImpactBucket(bucketLabels[c]) + .withCount(counts[r][c]); if (top[r][c] != null) { - cell.put("topEntity", top[r][c].toTopEntity()); + cell.setTopEntity(top[r][c].toTopEntity()); } cells.add(cell); } @@ -305,20 +319,55 @@ private static String safeName(RolledAsset asset) { return asset.name() == null ? "" : asset.name(); } - static List> topByStatus( - List assets, String registrationStatus) { + static List topByStatus( + List assets, String registrationStatus, Comparator ranking) { return assets.stream() .filter(asset -> registrationStatus.equals(asset.registrationStatus())) - .sorted( - (left, right) -> { - int compared = Integer.compare(right.affectedUsers(), left.affectedUsers()); - return compared != 0 ? compared : safeName(left).compareTo(safeName(right)); - }) + .sorted(ranking) .limit(TOP_N) - .map(asset -> asset.toSummary()) + .map(RolledAsset::toSummary) .toList(); } + /** + * Shadow AI assets have no compliance records yet (so {@code affectedUsers} is 0 for all + * of them); rank by EU-risk severity first, then most-recently-detected, so the headline + * detections surface rather than an arbitrary alphabetical slice. + */ + static Comparator shadowRanking() { + return Comparator.comparingInt((RolledAsset asset) -> severityRank(asset.euRisk())) + .thenComparingLong(asset -> recencyKey(asset.detectedAt())) + .thenComparingInt(asset -> -asset.affectedUsers()) + .thenComparing(DashboardRollup::safeName); + } + + /** + * Pending approvals rank by EU-risk severity, then longest-waiting (oldest submission) + * first, so the most urgent Risk Council items are surfaced instead of an alphabetical + * slice. + */ + static Comparator approvalRanking() { + return Comparator.comparingInt((RolledAsset asset) -> severityRank(asset.euRisk())) + .thenComparingLong(asset -> waitingKey(asset.registeredAt())) + .thenComparingInt(asset -> -asset.affectedUsers()) + .thenComparing(DashboardRollup::safeName); + } + + private static int severityRank(String euRisk) { + int index = indexOf(RISK_SEVERITY, euRisk); + return index >= 0 ? index : RISK_SEVERITY.length; + } + + /** Sort key that surfaces the most recently detected asset first (nulls last). */ + private static long recencyKey(Long timestamp) { + return timestamp == null ? Long.MAX_VALUE : -timestamp; + } + + /** Sort key that surfaces the longest-waiting submission first (nulls last). */ + private static long waitingKey(Long timestamp) { + return timestamp == null ? Long.MAX_VALUE : timestamp; + } + /** Normalized rolled-up view of an AI asset for rollup math. */ @Builder static final class RolledAsset { @@ -330,7 +379,7 @@ static final class RolledAsset { private final String registrationStatus; private final String euRisk; private final int affectedUsers; - private final Map frameworkStatuses; + private final List frameworkStatuses; private final Long registeredAt; private final String detectedVia; private final Long detectedAt; @@ -353,200 +402,209 @@ int affectedUsers() { return affectedUsers; } - Map frameworkStatuses() { - return frameworkStatuses; + Long detectedAt() { + return detectedAt; } - Map toSummary() { - Map summary = new LinkedHashMap<>(); - summary.put("entityType", entityType); - summary.put("id", id); - summary.put("name", name); - summary.put("displayName", displayName); - summary.put("fullyQualifiedName", fqn); - summary.put("registrationStatus", registrationStatus); - summary.put("euRisk", euRisk); - summary.put("affectedUsers", affectedUsers); - summary.put("registeredAt", registeredAt); - summary.put("detectedVia", detectedVia); - summary.put("detectedAt", detectedAt); - summary.put("submittedBy", submittedBy); - summary.put("submittedAt", registeredAt); - summary.put("team", team); + Long registeredAt() { + return registeredAt; + } - return summary; + List frameworkStatuses() { + return frameworkStatuses; } - Map toTopEntity() { - Map entity = new LinkedHashMap<>(); - entity.put("name", name); - entity.put("displayName", displayName); - entity.put("fullyQualifiedName", fqn); - entity.put("entityType", entityType); + AIGovernanceAssetSummary toSummary() { + return new AIGovernanceAssetSummary() + .withEntityType(entityType) + .withId(id) + .withName(name) + .withDisplayName(displayName) + .withFullyQualifiedName(fqn) + .withRegistrationStatus(registrationStatus) + .withEuRisk(euRisk) + .withAffectedUsers(affectedUsers) + .withRegisteredAt(registeredAt) + .withDetectedVia(detectedVia) + .withDetectedAt(detectedAt) + .withSubmittedBy(submittedBy) + .withSubmittedAt(registeredAt) + .withTeam(team); + } - return entity; + AIGovernanceTopEntity toTopEntity() { + return new AIGovernanceTopEntity() + .withName(name) + .withDisplayName(displayName) + .withFullyQualifiedName(fqn) + .withEntityType(entityType); } - @SuppressWarnings("unchecked") static RolledAsset from(String entityType, EntityInterface entity) { - Map json = - (Map) JsonUtils.getObjectMapper().convertValue(entity, Map.class); - Map governance = pickGovernance(entityType, json); - String registrationStatus = registrationStatus(entityType, json, governance); - Map frameworks = new LinkedHashMap<>(); - String euRisk = extractCompliance(governance, frameworks); - int users = affectedUsers(governance); - Map detection = - governance == null ? null : asMap(governance.get("detection")); + GovernanceSnapshot governance = governance(entity); + List frameworks = new ArrayList<>(); + String euRisk = extractCompliance(governance.aiCompliance(), frameworks); + int users = affectedUsers(governance.aiCompliance()); + AIDetection detection = governance.detection(); return RolledAsset.builder() .entityType(entityType) - .id(asString(json.get("id"))) - .name(asString(json.get("name"))) - .displayName(asString(json.get("displayName"))) - .fqn(asString(json.get("fullyQualifiedName"))) - .registrationStatus(registrationStatus) + .id(entity.getId() == null ? null : entity.getId().toString()) + .name(entity.getName()) + .displayName(entity.getDisplayName()) + .fqn(entity.getFullyQualifiedName()) + .registrationStatus(registrationStatus(governance.registrationStatus())) .euRisk(euRisk) .affectedUsers(users) .frameworkStatuses(frameworks) - .registeredAt(governance == null ? null : numberToLong(governance.get("registeredAt"))) - .detectedVia(detection == null ? null : asString(detection.get("source"))) - .detectedAt(detection == null ? null : numberToLong(detection.get("detectedAt"))) - .submittedBy(governance == null ? null : asString(governance.get("registeredBy"))) - .team(firstDomainName(json.get("domains"))) + .registeredAt(governance.registeredAt()) + .detectedVia(detection == null ? null : enumValue(detection.getSource())) + .detectedAt(detection == null ? null : detection.getDetectedAt()) + .submittedBy(governance.registeredBy()) + .team(firstDomainName(entity.getDomains())) .build(); } private static String extractCompliance( - Map governance, Map frameworks) { + AICompliance aiCompliance, List frameworks) { String euRisk = null; - Map aiCompliance = - governance == null ? null : asMap(governance.get("aiCompliance")); - List records = - aiCompliance == null ? null : asList(aiCompliance.get("complianceRecords")); - if (records != null) { - for (Object recordObj : records) { - Map record = asMap(recordObj); - if (record != null) { - Object framework = record.get("framework"); - Object status = record.get("status"); - if (framework != null && status != null) { - frameworks.putIfAbsent(framework.toString(), status.toString()); - } - Map eu = asMap(record.get("euAIAct")); - if (euRisk == null && eu != null && eu.get("riskClassification") != null) { - euRisk = eu.get("riskClassification").toString(); - } + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + String framework = enumValue(record.getFramework()); + String status = enumValue(record.getStatus()); + if (framework != null && status != null) { + addFrameworkStatus(frameworks, framework, status); + } + if (euRisk == null + && record.getEuAIAct() != null + && record.getEuAIAct().getRiskClassification() != null) { + euRisk = record.getEuAIAct().getRiskClassification().value(); } } } return euRisk; } - private static int affectedUsers(Map governance) { + private static void addFrameworkStatus( + List frameworks, String framework, String status) { + for (FrameworkStatusSnapshot existing : frameworks) { + if (existing.framework().equals(framework)) { + return; + } + } + frameworks.add(new FrameworkStatusSnapshot(framework, status)); + } + + private static int affectedUsers(AICompliance aiCompliance) { int users = 0; - Map aiCompliance = - governance == null ? null : asMap(governance.get("aiCompliance")); - List records = - aiCompliance == null ? null : asList(aiCompliance.get("complianceRecords")); - if (records != null) { - for (Object recordObj : records) { - Map record = asMap(recordObj); - Map scope = - record == null ? null : asMap(record.get("scopeAndDeployment")); - if (scope != null && scope.get("affectedUserCount") instanceof Number number) { - users = Math.max(users, number.intValue()); + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + if (record.getScopeAndDeployment() != null + && record.getScopeAndDeployment().getAffectedUserCount() != null) { + users = Math.max(users, record.getScopeAndDeployment().getAffectedUserCount()); } } } return users; } - private static String registrationStatus( - String entityType, Map json, Map governance) { - String result = "Registered"; - if (Entity.LLM_MODEL.equals(entityType)) { - Object status = json.get("governanceStatus"); - if (status != null) { - result = mapLlmStatus(status.toString()); - } - } else if (governance != null && governance.get("registrationStatus") != null) { - result = governance.get("registrationStatus").toString(); - } - return result; + private static String registrationStatus(String status) { + return status == null ? "Registered" : status; } - private static String mapLlmStatus(String status) { + private static String mapLlmStatus(LLMModel.GovernanceStatus status) { String result; - switch (status) { - case "Approved": - result = "Approved"; - break; - case "PendingReview": - result = "PendingApproval"; - break; - case "Rejected": - result = "Rejected"; - break; - case "Unauthorized": - result = "Unregistered"; - break; - default: - result = "Registered"; + if (status == null) { + result = null; + } else { + switch (status) { + case APPROVED: + result = "Approved"; + break; + case PENDING_REVIEW: + result = "PendingApproval"; + break; + case REJECTED: + result = "Rejected"; + break; + case UNAUTHORIZED: + result = "Unregistered"; + break; + default: + result = "Registered"; + } } return result; } - private static Map pickGovernance(String entityType, Map json) { - Map result = null; - if (Entity.LLM_MODEL.equals(entityType)) { - Map shim = new LinkedHashMap<>(); - Object status = json.get("governanceStatus"); - if (status != null) { - shim.put("registrationStatus", mapLlmStatus(status.toString())); - } - if (json.get("detection") != null) { - shim.put("detection", json.get("detection")); - } - if (!nullOrEmpty(shim)) { - result = shim; - } - } else { - result = asMap(json.get("governanceMetadata")); + private static GovernanceSnapshot governance(EntityInterface entity) { + GovernanceSnapshot result = GovernanceSnapshot.EMPTY; + if (entity instanceof AIApplication app) { + result = governance(app.getGovernanceMetadata()); + } else if (entity instanceof McpServer server) { + result = governance(server.getGovernanceMetadata()); + } else if (entity instanceof LLMModel llm) { + result = + new GovernanceSnapshot( + mapLlmStatus(llm.getGovernanceStatus()), null, null, llm.getDetection(), null); } return result; } - } - @SuppressWarnings("unchecked") - private static Map asMap(Object value) { - return value instanceof Map ? (Map) value : null; - } + private static GovernanceSnapshot governance(GovernanceMetadata governance) { + return governance == null + ? GovernanceSnapshot.EMPTY + : new GovernanceSnapshot( + enumValue(governance.getRegistrationStatus()), + governance.getRegisteredBy(), + governance.getRegisteredAt(), + governance.getDetection(), + governance.getAiCompliance()); + } - @SuppressWarnings("unchecked") - private static List asList(Object value) { - return value instanceof List ? (List) value : null; + private static GovernanceSnapshot governance(McpGovernanceMetadata governance) { + return governance == null + ? GovernanceSnapshot.EMPTY + : new GovernanceSnapshot( + enumValue(governance.getRegistrationStatus()), + governance.getRegisteredBy(), + governance.getRegisteredAt(), + governance.getDetection(), + governance.getAiCompliance()); + } } - private static String asString(Object value) { + private static String enumValue(Object value) { return value == null ? null : value.toString(); } - private static Long numberToLong(Object value) { - return value instanceof Number number ? number.longValue() : null; + private record FrameworkReadinessCounts(int compliant, int inScope) { + private FrameworkReadinessCounts plus(FrameworkReadinessCounts other) { + return new FrameworkReadinessCounts(compliant + other.compliant(), inScope + other.inScope()); + } + + private double readiness() { + return inScope == 0 ? 0.0 : (double) compliant / inScope; + } + } + + private record FrameworkStatusSnapshot(String framework, String status) {} + + private record GovernanceSnapshot( + String registrationStatus, + String registeredBy, + Long registeredAt, + AIDetection detection, + AICompliance aiCompliance) { + private static final GovernanceSnapshot EMPTY = + new GovernanceSnapshot("Registered", null, null, null, null); } - private static String firstDomainName(Object domainsValue) { + private static String firstDomainName(List domains) { String result = null; - List domains = asList(domainsValue); if (!nullOrEmpty(domains)) { - Map first = asMap(domains.getFirst()); - if (first != null) { - result = - first.get("displayName") != null - ? first.get("displayName").toString() - : asString(first.get("name")); - } + EntityReference first = domains.getFirst(); + result = first.getDisplayName() != null ? first.getDisplayName() : first.getName(); } return result; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/FrameworkCoverageComputer.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/FrameworkCoverageComputer.java index a5e71c1834fa..8bb5f4d6ccca 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/FrameworkCoverageComputer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/FrameworkCoverageComputer.java @@ -13,16 +13,27 @@ package org.openmetadata.service.resources.ai; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.ai.FrameworkControlCoverage; +import org.openmetadata.schema.api.ai.FrameworkCoverageResponse; +import org.openmetadata.schema.api.ai.FrameworkCoverageSummary; +import org.openmetadata.schema.entity.ai.AIApplication; import org.openmetadata.schema.entity.ai.AIFrameworkControl; import org.openmetadata.schema.entity.ai.AIGovernanceFramework; import org.openmetadata.schema.entity.ai.FrameworkAutoApplyRules; +import org.openmetadata.schema.entity.ai.GovernanceMetadata; +import org.openmetadata.schema.entity.ai.LLMModel; +import org.openmetadata.schema.entity.ai.McpGovernanceMetadata; +import org.openmetadata.schema.entity.ai.McpServer; +import org.openmetadata.schema.type.AICompliance; +import org.openmetadata.schema.type.AIComplianceRecord; +import org.openmetadata.schema.type.ComplianceFramework; import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.schema.type.RemediationAction; +import org.openmetadata.schema.type.RemediationStatus; +import org.openmetadata.schema.type.ScopeAndDeployment; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.AIApplicationRepository; @@ -51,26 +62,25 @@ * in-scope assets' records. {@code assetsInScope} is the in-scope total. */ @Slf4j -@SuppressWarnings("unchecked") -final class FrameworkCoverageComputer { +public final class FrameworkCoverageComputer { private static final int PAGE_SIZE = 1000; private FrameworkCoverageComputer() {} - static Map compute( + public static FrameworkCoverageResponse compute( AIGovernanceFramework framework, List controls) { return compute(framework, controls, collectInScopeAssets(framework)); } - static Map compute( + static FrameworkCoverageResponse compute( AIGovernanceFramework framework, List controls, List assets) { - Map response = new LinkedHashMap<>(); - response.put("frameworkId", framework.getId() == null ? null : framework.getId().toString()); - response.put("frameworkName", framework.getName()); - response.put("assetsInScope", assets.size()); + FrameworkCoverageResponse response = new FrameworkCoverageResponse(); + response.setFrameworkId(framework.getId()); + response.setFrameworkName(framework.getName()); + response.setAssetsInScope(assets.size()); String frameworkName = framework.getName(); List assetCompliance = @@ -79,46 +89,40 @@ static Map compute( int partialAssetCount = 0; int nonCompliantAssetCount = 0; for (AssetCompliance compliance : assetCompliance) { - Map record = compliance.record(); + ComplianceRecordSnapshot record = compliance.record(); if (record == null) { nonCompliantAssetCount++; continue; } - String status = String.valueOf(record.getOrDefault("status", "UnderReview")); - if ("Compliant".equals(status)) { + if ("Compliant".equals(record.status())) { compliantAssetCount++; - } else if ("PartiallyCompliant".equals(status)) { + } else if ("PartiallyCompliant".equals(record.status())) { partialAssetCount++; - } else if ("NonCompliant".equals(status) || "UnderReview".equals(status)) { + } else if ("NonCompliant".equals(record.status()) || "UnderReview".equals(record.status())) { nonCompliantAssetCount++; } } - List> entries = new ArrayList<>(); + List entries = new ArrayList<>(); for (AIFrameworkControl control : controls) { - Map entry = new LinkedHashMap<>(); String code = control.getCode() == null ? control.getName() : control.getCode(); ControlCoverage coverage = controlCoverage(assetCompliance, frameworkName, code); - entry.put("code", code); - entry.put("displayName", control.getDisplayName()); - entry.put("category", control.getCategory()); - entry.put("status", deriveControlStatus(coverage.nonCompliant(), coverage.partial())); - entry.put( - "affectedAssetCount", + FrameworkControlCoverage entry = new FrameworkControlCoverage(); + entry.setCode(code); + entry.setDisplayName(control.getDisplayName()); + entry.setCategory(control.getCategory()); + entry.setStatus(deriveControlStatus(coverage.nonCompliant(), coverage.partial())); + entry.setAffectedAssetCount( deriveAffectedAssetCount(coverage.nonCompliant(), coverage.partial())); - entry.put("evidenceCount", coverage.evidence()); + entry.setEvidenceCount(coverage.evidence()); entries.add(entry); } - response.put("controls", entries); - response.put( - "summary", - Map.of( - "compliant", - compliantAssetCount, - "partial", - partialAssetCount, - "nonCompliant", - nonCompliantAssetCount)); + response.setControls(entries); + response.setSummary( + new FrameworkCoverageSummary() + .withCompliant(compliantAssetCount) + .withPartial(partialAssetCount) + .withNonCompliant(nonCompliantAssetCount)); return response; } @@ -129,18 +133,17 @@ private static ControlCoverage controlCoverage( int partial = 0; int nonCompliant = 0; for (AssetCompliance compliance : assetCompliance) { - Map record = compliance.record(); + ComplianceRecordSnapshot record = compliance.record(); if (record == null) { nonCompliant++; continue; } - if (hasEvidence(record)) { + if (record.hasEvidence()) { evidence++; } - String status = String.valueOf(record.getOrDefault("status", "UnderReview")); - if ("NonCompliant".equals(status) || "UnderReview".equals(status)) { + if ("NonCompliant".equals(record.status()) || "UnderReview".equals(record.status())) { nonCompliant++; - } else if ("PartiallyCompliant".equals(status) + } else if ("PartiallyCompliant".equals(record.status()) || hasPendingRemediation(compliance.remediationActions(), frameworkName, controlCode)) { partial++; } @@ -149,14 +152,15 @@ private static ControlCoverage controlCoverage( return new ControlCoverage(evidence, partial, nonCompliant); } - private static String deriveControlStatus(int nonCompliant, int partial) { - String result; + private static FrameworkControlCoverage.Status deriveControlStatus( + int nonCompliant, int partial) { + FrameworkControlCoverage.Status result; if (nonCompliant > 0) { - result = "Gap"; + result = FrameworkControlCoverage.Status.GAP; } else if (partial > 0) { - result = "Partial"; + result = FrameworkControlCoverage.Status.PARTIAL; } else { - result = "Met"; + result = FrameworkControlCoverage.Status.MET; } return result; @@ -167,35 +171,28 @@ private static int deriveAffectedAssetCount(int nonCompliant, int partial) { } private static AssetCompliance assetCompliance(EntityInterface asset, String frameworkName) { - Map raw = rawAsset(asset); - Map governance = governanceOf(raw); + GovernanceSnapshot governance = governance(asset); return new AssetCompliance( - findComplianceRecord(governance, frameworkName), remediationActions(raw, governance)); + findComplianceRecord(governance.aiCompliance(), frameworkName), + governance.remediationActions()); } - private static Map findComplianceRecord( + private static ComplianceRecordSnapshot findComplianceRecord( EntityInterface asset, String frameworkName) { - return findComplianceRecord(governanceOf(asset), frameworkName); + return findComplianceRecord(governance(asset).aiCompliance(), frameworkName); } - private static Map findComplianceRecord( - Map governance, String frameworkName) { - Map result = null; - if (governance != null) { - Object aiCompliance = governance.get("aiCompliance"); - if (aiCompliance instanceof Map compliance) { - Object records = ((Map) compliance).get("complianceRecords"); - if (records instanceof List list) { - for (Object item : list) { - if (item instanceof Map record) { - Map recordMap = (Map) record; - Object recordFramework = recordMap.get("framework"); - if (frameworkMatches(recordFramework, frameworkName)) { - result = recordMap; - break; - } - } - } + private static ComplianceRecordSnapshot findComplianceRecord( + AICompliance aiCompliance, String frameworkName) { + ComplianceRecordSnapshot result = null; + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + if (frameworkMatches(record.getFramework(), frameworkName)) { + result = + new ComplianceRecordSnapshot( + record.getStatus() == null ? "UnderReview" : record.getStatus().value(), + hasEvidence(record)); + break; } } } @@ -203,19 +200,17 @@ private static Map findComplianceRecord( return result; } - private static boolean hasEvidence(Map record) { - Object verification = record.get("verification"); - return verification instanceof Map v - && ((Map) v).get("certificateUrl") != null; + private static boolean hasEvidence(AIComplianceRecord record) { + return record.getVerification() != null && record.getVerification().getCertificateUrl() != null; } private static boolean hasPendingRemediation( - List> remediationActions, String frameworkName, String controlCode) { + List remediationActions, String frameworkName, String controlCode) { boolean result = false; - for (Map action : remediationActions) { - if (frameworkMatches(action.get("frameworkRef"), frameworkName) - && controlMatches(action.get("controlCode"), controlCode) - && !"Done".equals(String.valueOf(action.get("status")))) { + for (RemediationAction action : remediationActions) { + if (frameworkMatches(action.getFrameworkRef(), frameworkName) + && controlMatches(action.getControlCode(), controlCode) + && action.getStatus() != RemediationStatus.Done) { result = true; break; } @@ -224,67 +219,13 @@ && controlMatches(action.get("controlCode"), controlCode) return result; } - private static boolean controlMatches(Object actionControlCode, String controlCode) { - return actionControlCode instanceof String value && value.equalsIgnoreCase(controlCode); - } - - private static boolean frameworkMatches(Object recordFramework, String frameworkName) { - boolean result = false; - if (recordFramework instanceof String value && value.equalsIgnoreCase(frameworkName)) { - result = true; - } else if (recordFramework instanceof Map ref) { - Object name = ((Map) ref).get("name"); - if (name instanceof String nameStr && nameStr.equalsIgnoreCase(frameworkName)) { - result = true; - } - } - - return result; - } - - private static Map governanceOf(EntityInterface asset) { - return governanceOf(rawAsset(asset)); + private static boolean controlMatches(String actionControlCode, String controlCode) { + return actionControlCode != null && actionControlCode.equalsIgnoreCase(controlCode); } - private static Map rawAsset(EntityInterface asset) { - Map result = null; - try { - result = JsonUtils.readValue(JsonUtils.pojoToJson(asset), Map.class); - } catch (Exception ignored) { - // Best-effort — empty entity state returns null - } - - return result; - } - - private static Map governanceOf(Map raw) { - Map result = null; - if (raw != null) { - Object governance = raw.get("governanceMetadata"); - if (governance instanceof Map g) { - result = (Map) g; - } - } - - return result; - } - - private static List> remediationActions( - Map raw, Map governance) { - List> result = new ArrayList<>(); - addRemediationActions(result, governance == null ? null : governance.get("remediationActions")); - addRemediationActions(result, raw == null ? null : raw.get("remediationActions")); - return result; - } - - private static void addRemediationActions(List> result, Object actions) { - if (actions instanceof List list) { - for (Object action : list) { - if (action instanceof Map actionMap) { - result.add((Map) actionMap); - } - } - } + private static boolean frameworkMatches( + ComplianceFramework recordFramework, String frameworkName) { + return recordFramework != null && recordFramework.value().equalsIgnoreCase(frameworkName); } private static List collectInScopeAssets(AIGovernanceFramework framework) { @@ -365,10 +306,10 @@ private static boolean matchesScope(EntityInterface entity, FrameworkAutoApplyRu if (rules == null) { result = true; } else { - Map governance = governanceOf(entity); + GovernanceSnapshot governance = governance(entity); boolean regionsOk = matchesRegions(governance, rules); boolean riskOk = matchesRiskClasses(governance, rules); - boolean stageOk = matchesDeploymentStages(entity, rules); + boolean stageOk = matchesDeploymentStages(governance, rules); result = regionsOk && riskOk && stageOk; } @@ -376,13 +317,13 @@ private static boolean matchesScope(EntityInterface entity, FrameworkAutoApplyRu } private static boolean matchesRegions( - Map governance, FrameworkAutoApplyRules rules) { + GovernanceSnapshot governance, FrameworkAutoApplyRules rules) { boolean result; List required = rules.getRegions(); if (required == null || required.isEmpty()) { result = true; } else { - List assetRegions = extractRegions(governance); + List assetRegions = extractRegions(governance.aiCompliance()); result = anyMatch(required, assetRegions); } @@ -390,7 +331,7 @@ private static boolean matchesRegions( } private static boolean matchesRiskClasses( - Map governance, FrameworkAutoApplyRules rules) { + GovernanceSnapshot governance, FrameworkAutoApplyRules rules) { boolean result; List required = rules.getRiskClasses(); if (required == null || required.isEmpty()) { @@ -404,41 +345,26 @@ private static boolean matchesRiskClasses( } private static boolean matchesDeploymentStages( - EntityInterface entity, FrameworkAutoApplyRules rules) { + GovernanceSnapshot governance, FrameworkAutoApplyRules rules) { boolean result; List required = rules.getDeploymentStages(); if (required == null || required.isEmpty()) { result = true; } else { - String stage = extractDeploymentStage(entity); + String stage = governance.deploymentStage(); result = stage != null && required.contains(stage); } return result; } - private static List extractRegions(Map governance) { + private static List extractRegions(AICompliance aiCompliance) { List result = new ArrayList<>(); - if (governance != null) { - Object aiCompliance = governance.get("aiCompliance"); - if (aiCompliance instanceof Map compliance) { - Object records = ((Map) compliance).get("complianceRecords"); - if (records instanceof List list) { - for (Object item : list) { - if (item instanceof Map record) { - Object scope = ((Map) record).get("scopeAndDeployment"); - if (scope instanceof Map s) { - Object regions = ((Map) s).get("deploymentRegions"); - if (regions instanceof List regionsList) { - for (Object r : regionsList) { - if (r instanceof String region) { - result.add(region); - } - } - } - } - } - } + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + ScopeAndDeployment scope = record.getScopeAndDeployment(); + if (scope != null && scope.getDeploymentRegions() != null) { + result.addAll(scope.getDeploymentRegions()); } } } @@ -446,31 +372,16 @@ private static List extractRegions(Map governance) { return result; } - private static List extractRiskClasses(Map governance) { + private static List extractRiskClasses(GovernanceSnapshot governance) { List result = new ArrayList<>(); - if (governance != null) { - Object risk = governance.get("riskAssessment"); - if (risk instanceof Map riskMap) { - Object level = ((Map) riskMap).get("riskLevel"); - if (level instanceof String levelStr) { - result.add(levelStr); - } - } - Object aiCompliance = governance.get("aiCompliance"); - if (aiCompliance instanceof Map compliance) { - Object records = ((Map) compliance).get("complianceRecords"); - if (records instanceof List list) { - for (Object item : list) { - if (item instanceof Map record) { - Object euAct = ((Map) record).get("euAIAct"); - if (euAct instanceof Map euMap) { - Object cls = ((Map) euMap).get("riskClassification"); - if (cls instanceof String clsStr) { - result.add(clsStr); - } - } - } - } + if (governance.riskLevel() != null) { + result.add(governance.riskLevel()); + } + AICompliance aiCompliance = governance.aiCompliance(); + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + if (record.getEuAIAct() != null && record.getEuAIAct().getRiskClassification() != null) { + result.add(record.getEuAIAct().getRiskClassification().value()); } } } @@ -478,21 +389,52 @@ private static List extractRiskClasses(Map governance) { return result; } - private static String extractDeploymentStage(EntityInterface entity) { - String result = null; - try { - Map raw = JsonUtils.readValue(JsonUtils.pojoToJson(entity), Map.class); - Object stage = raw.get("developmentStage"); - if (stage instanceof String stageStr) { - result = stageStr; - } - } catch (Exception ignored) { - // null is acceptable + private static GovernanceSnapshot governance(EntityInterface asset) { + GovernanceSnapshot result = GovernanceSnapshot.EMPTY; + if (asset instanceof AIApplication app) { + result = governance(app.getGovernanceMetadata(), enumValue(app.getDevelopmentStage())); + } else if (asset instanceof McpServer server) { + result = governance(server.getGovernanceMetadata(), enumValue(server.getDevelopmentStage())); + } else if (asset instanceof LLMModel llm) { + result = new GovernanceSnapshot(null, actions(llm.getRemediationActions()), null, null); } - return result; } + private static GovernanceSnapshot governance( + GovernanceMetadata governance, String deploymentStage) { + return governance == null + ? new GovernanceSnapshot(null, List.of(), null, deploymentStage) + : new GovernanceSnapshot( + governance.getAiCompliance(), + actions(governance.getRemediationActions()), + governance.getRiskAssessment() == null + ? null + : enumValue(governance.getRiskAssessment().getRiskLevel()), + deploymentStage); + } + + private static GovernanceSnapshot governance( + McpGovernanceMetadata governance, String deploymentStage) { + return governance == null + ? new GovernanceSnapshot(null, List.of(), null, deploymentStage) + : new GovernanceSnapshot( + governance.getAiCompliance(), + actions(governance.getRemediationActions()), + governance.getRiskAssessment() == null + ? null + : enumValue(governance.getRiskAssessment().getRiskLevel()), + deploymentStage); + } + + private static List actions(List actions) { + return actions == null ? List.of() : actions; + } + + private static String enumValue(Object value) { + return value == null ? null : value.toString(); + } + private static boolean anyMatch(List required, List assetValues) { boolean result = false; if (assetValues != null && !assetValues.isEmpty()) { @@ -508,7 +450,18 @@ private static boolean anyMatch(List required, List assetValues) } private record AssetCompliance( - Map record, List> remediationActions) {} + ComplianceRecordSnapshot record, List remediationActions) {} + + private record ComplianceRecordSnapshot(String status, boolean hasEvidence) {} + + private record GovernanceSnapshot( + AICompliance aiCompliance, + List remediationActions, + String riskLevel, + String deploymentStage) { + private static final GovernanceSnapshot EMPTY = + new GovernanceSnapshot(null, List.of(), null, null); + } private record ControlCoverage(int evidence, int partial, int nonCompliant) {} } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/GovernanceActivity.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/GovernanceActivity.java index f9a06c1fc8ba..768ff650bdac 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/GovernanceActivity.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/GovernanceActivity.java @@ -14,13 +14,21 @@ import java.util.ArrayList; import java.util.Comparator; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.ai.AIGovernanceActivityEvent; +import org.openmetadata.schema.api.ai.AIGovernanceActivityResponse; +import org.openmetadata.schema.entity.ai.AIApplication; +import org.openmetadata.schema.entity.ai.GovernanceMetadata; +import org.openmetadata.schema.entity.ai.LLMModel; +import org.openmetadata.schema.entity.ai.McpGovernanceMetadata; +import org.openmetadata.schema.entity.ai.McpServer; +import org.openmetadata.schema.type.AICompliance; +import org.openmetadata.schema.type.AIComplianceRecord; +import org.openmetadata.schema.type.AIDetection; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; @@ -37,7 +45,6 @@ * iteration can replace this with a real ChangeEvent stream filter. */ @Slf4j -@SuppressWarnings("unchecked") final class GovernanceActivity { private static final Set SUPPORTED_TYPES = @@ -46,9 +53,10 @@ final class GovernanceActivity { private GovernanceActivity() {} - static List> compute(String entityType, String entityId, int limit) { + static AIGovernanceActivityResponse compute(String entityType, String entityId, int limit) { List assets = new ArrayList<>(); - if (entityType != null && entityId != null) { + boolean singleEntity = entityType != null && entityId != null; + if (singleEntity) { EntityInterface single = loadSingle(entityType, entityId); if (single != null) { assets.add(single); @@ -61,14 +69,14 @@ static List> compute(String entityType, String entityId, int collect(Entity.LLM_MODEL, assets); } - List> events = new ArrayList<>(); + List events = new ArrayList<>(); for (EntityInterface entity : assets) { - events.addAll(eventsFor(entity)); + events.addAll(eventsFor(entity, singleEntity)); } - events.sort(Comparator.comparing((Map e) -> (Long) e.get("at")).reversed()); + events.sort(Comparator.comparing(AIGovernanceActivityEvent::getAt).reversed()); int effective = Math.min(limit > 0 ? limit : 50, events.size()); - return events.subList(0, effective); + return new AIGovernanceActivityResponse().withEvents(events.subList(0, effective)); } private static EntityInterface loadSingle(String entityType, String entityId) { @@ -107,17 +115,26 @@ private static String fieldList(String entityType) { : "owners,governanceMetadata"; } - static List> eventsFor(EntityInterface entity) { - List> events = new ArrayList<>(); + static List eventsFor(EntityInterface entity) { + return eventsFor(entity, true); + } + + /** + * @param reconstructHistory when true, an approved LLM model's original submission time is + * recovered from its version history ({@code listVersions}). The estate/type feed passes + * false to avoid an N+1 version lookup per approved model; a single-entity timeline passes + * true so both submission and approval events are shown. + */ + static List eventsFor( + EntityInterface entity, boolean reconstructHistory) { + List events = new ArrayList<>(); String entityType = entity.getEntityReference() == null ? null : entity.getEntityReference().getType(); - Map json = - (Map) JsonUtils.getObjectMapper().convertValue(entity, Map.class); - Map governance = governance(entityType, entity, json); + ActivityGovernance governance = governance(entity, reconstructHistory); - if (governance != null) { - Map detection = asMap(governance.get("detection")); - if (detection != null && detection.get("detectedAt") instanceof Number number) { + if (!governance.isEmpty()) { + AIDetection detection = governance.detection(); + if (detection != null && detection.getDetectedAt() != null) { events.add( event( entity, @@ -125,12 +142,12 @@ static List> eventsFor(EntityInterface entity) { "ShadowAIDetected", String.format( "Detected via %s", - detection.get("source") == null ? "manual upload" : detection.get("source")), - number.longValue(), - governance.get("registeredBy"))); + detection.getSource() == null ? "manual upload" : detection.getSource()), + detection.getDetectedAt(), + governance.registeredBy())); } - Long registeredAt = numberToLong(governance.get("registeredAt")); + Long registeredAt = governance.registeredAt(); if (registeredAt != null) { events.add( event( @@ -139,10 +156,10 @@ static List> eventsFor(EntityInterface entity) { "SubmittedForReview", "Submitted to Risk Council for review", registeredAt, - governance.get("registeredBy"))); + governance.registeredBy())); } - Long approvedAt = numberToLong(governance.get("approvedAt")); + Long approvedAt = governance.approvedAt(); if (approvedAt != null) { events.add( event( @@ -151,21 +168,15 @@ static List> eventsFor(EntityInterface entity) { "Approved", "Approved by Risk Council", approvedAt, - governance.get("approvedBy"))); + governance.approvedBy())); } - Map aiCompliance = asMap(governance.get("aiCompliance")); - List records = - aiCompliance == null ? null : asList(aiCompliance.get("complianceRecords")); - if (records != null) { - for (Object recordObj : records) { - Map record = asMap(recordObj); - if (record == null) { - continue; - } - Long assessedAt = numberToLong(record.get("assessedAt")); + AICompliance aiCompliance = governance.aiCompliance(); + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + Long assessedAt = record.getAssessedAt(); if (assessedAt != null) { - String framework = String.valueOf(record.get("framework")); + String framework = enumValue(record.getFramework()); events.add( event( entity, @@ -173,11 +184,11 @@ static List> eventsFor(EntityInterface entity) { "Assessed", String.format("%s assessment completed", framework), assessedAt, - record.get("assessedBy"))); + record.getAssessedBy())); } - Long nextReview = numberToLong(record.get("nextReviewDate")); + Long nextReview = record.getNextReviewDate(); if (nextReview != null) { - String framework = String.valueOf(record.get("framework")); + String framework = enumValue(record.getFramework()); long loggedAt = assessedAt != null ? assessedAt : reviewFallback(governance, entity); events.add( scheduledEvent( @@ -195,20 +206,21 @@ static List> eventsFor(EntityInterface entity) { return events; } - private static Map event( + private static AIGovernanceActivityEvent event( EntityInterface entity, String entityType, String type, String text, long at, Object who) { - Map event = new LinkedHashMap<>(); - event.put("entityType", entityType); - event.put("entityId", entity.getId() == null ? null : entity.getId().toString()); - event.put("entityName", entity.getName()); - event.put("entityDisplayName", entity.getDisplayName()); - event.put("entityFqn", entity.getFullyQualifiedName()); - event.put("type", type); - event.put("text", text); - event.put("at", at); - event.put("createdAt", at); + AIGovernanceActivityEvent event = + new AIGovernanceActivityEvent() + .withEntityType(entityType) + .withEntityId(entity.getId() == null ? null : entity.getId().toString()) + .withEntityName(entity.getName()) + .withEntityDisplayName(entity.getDisplayName()) + .withEntityFqn(entity.getFullyQualifiedName()) + .withType(type) + .withText(text) + .withAt(at) + .withCreatedAt(at); if (who != null) { - event.put("who", who); + event.setWho(who.toString()); } return event; } @@ -218,7 +230,7 @@ private static Map event( * is when the event was logged so the feed sorts chronologically, while * {@code scheduledAt} carries the future date the event refers to. */ - private static Map scheduledEvent( + private static AIGovernanceActivityEvent scheduledEvent( EntityInterface entity, String entityType, String type, @@ -226,13 +238,13 @@ private static Map scheduledEvent( long at, long scheduledAt, Object who) { - Map event = event(entity, entityType, type, text, at, who); - event.put("scheduledAt", scheduledAt); + AIGovernanceActivityEvent event = event(entity, entityType, type, text, at, who); + event.setScheduledAt(scheduledAt); return event; } - private static long reviewFallback(Map governance, EntityInterface entity) { - Long registeredAt = governance == null ? null : numberToLong(governance.get("registeredAt")); + private static long reviewFallback(ActivityGovernance governance, EntityInterface entity) { + Long registeredAt = governance.registeredAt(); long result; if (registeredAt != null) { result = registeredAt; @@ -244,98 +256,128 @@ private static long reviewFallback(Map governance, EntityInterfa return result; } - private static Map governance( - String entityType, EntityInterface entity, Map entityJson) { - Map result = null; - if (Entity.LLM_MODEL.equals(entityType)) { - Map shim = new LinkedHashMap<>(); - if (entityJson.get("detection") != null) { - shim.put("detection", entityJson.get("detection")); - } - addLlmGovernanceTimeline(entity, entityJson, shim); - if (!shim.isEmpty()) { - result = shim; - } - } else { - result = asMap(entityJson.get("governanceMetadata")); + private static ActivityGovernance governance(EntityInterface entity, boolean reconstructHistory) { + ActivityGovernance result = ActivityGovernance.EMPTY; + if (entity instanceof AIApplication app) { + result = governance(app.getGovernanceMetadata()); + } else if (entity instanceof McpServer server) { + result = governance(server.getGovernanceMetadata()); + } else if (entity instanceof LLMModel llm) { + result = llmGovernance(llm, reconstructHistory); } return result; } - private static void addLlmGovernanceTimeline( - EntityInterface entity, Map entityJson, Map shim) { - Object status = entityJson.get("governanceStatus"); - Object updatedAt = entityJson.get("updatedAt"); - Object updatedBy = entityJson.get("updatedBy"); - if (status != null && updatedAt instanceof Number) { - if ("PendingReview".equals(status.toString())) { - shim.put("registeredAt", updatedAt); - putIfNotNull(shim, "registeredBy", updatedBy); - } else if ("Approved".equals(status.toString())) { - shim.put("approvedAt", updatedAt); - putIfNotNull(shim, "approvedBy", updatedBy); - addLlmSubmissionFromHistory(entity, shim); + private static ActivityGovernance governance(GovernanceMetadata governance) { + return governance == null + ? ActivityGovernance.EMPTY + : new ActivityGovernance( + governance.getDetection(), + governance.getRegisteredBy(), + governance.getRegisteredAt(), + governance.getApprovedBy(), + governance.getApprovedAt(), + governance.getAiCompliance()); + } + + private static ActivityGovernance governance(McpGovernanceMetadata governance) { + return governance == null + ? ActivityGovernance.EMPTY + : new ActivityGovernance( + governance.getDetection(), + governance.getRegisteredBy(), + governance.getRegisteredAt(), + governance.getApprovedBy(), + governance.getApprovedAt(), + governance.getAiCompliance()); + } + + private static ActivityGovernance llmGovernance(LLMModel llm, boolean reconstructHistory) { + String registeredBy = null; + Long registeredAt = null; + String approvedBy = null; + Long approvedAt = null; + if (llm.getGovernanceStatus() != null && llm.getUpdatedAt() != null) { + if (llm.getGovernanceStatus() == LLMModel.GovernanceStatus.PENDING_REVIEW) { + registeredAt = llm.getUpdatedAt(); + registeredBy = llm.getUpdatedBy(); + } else if (llm.getGovernanceStatus() == LLMModel.GovernanceStatus.APPROVED) { + approvedAt = llm.getUpdatedAt(); + approvedBy = llm.getUpdatedBy(); + if (reconstructHistory) { + LlmSubmission submission = llmSubmissionFromHistory(llm); + registeredAt = submission.registeredAt(); + registeredBy = submission.registeredBy(); + } } } + return new ActivityGovernance( + llm.getDetection(), registeredBy, registeredAt, approvedBy, approvedAt, null); } - private static void addLlmSubmissionFromHistory( - EntityInterface entity, Map shim) { - if (entity == null || entity.getId() == null || shim.containsKey("registeredAt")) { - return; + private static LlmSubmission llmSubmissionFromHistory(LLMModel llm) { + LlmSubmission result = LlmSubmission.EMPTY; + if (llm == null || llm.getId() == null) { + return result; } try { EntityRepository repository = Entity.getEntityRepository(Entity.LLM_MODEL); - List versions = repository.listVersions(entity.getId()).getVersions(); + List versions = repository.listVersions(llm.getId()).getVersions(); if (versions == null) { - return; + return result; } for (Object version : versions) { - Map versionJson = asVersionMap(version); - if (versionJson != null - && "PendingReview".equals(asString(versionJson.get("governanceStatus"))) - && versionJson.get("updatedAt") instanceof Number) { - shim.put("registeredAt", versionJson.get("updatedAt")); - putIfNotNull(shim, "registeredBy", versionJson.get("updatedBy")); - return; + LLMModel versionModel = asLlmVersion(version); + if (versionModel != null + && versionModel.getGovernanceStatus() == LLMModel.GovernanceStatus.PENDING_REVIEW + && versionModel.getUpdatedAt() != null) { + result = new LlmSubmission(versionModel.getUpdatedBy(), versionModel.getUpdatedAt()); + break; } } } catch (Exception error) { LOG.debug( - "Activity feed: unable to reconstruct LLM submission history for {}", - entity.getId(), - error); - } - } - - private static void putIfNotNull(Map map, String key, Object value) { - if (value != null) { - map.put(key, value); + "Activity feed: unable to reconstruct LLM submission history for {}", llm.getId(), error); } + return result; } - @SuppressWarnings("unchecked") - private static Map asVersionMap(Object value) { - if (value instanceof String json) { - return (Map) JsonUtils.readValue(json, Map.class); + private static LLMModel asLlmVersion(Object value) { + LLMModel result = null; + if (value instanceof LLMModel model) { + result = model; + } else if (value instanceof String json) { + result = JsonUtils.readValue(json, LLMModel.class); + } else if (value != null) { + result = JsonUtils.getObjectMapper().convertValue(value, LLMModel.class); } - return asMap(value); + return result; } - private static Map asMap(Object value) { - return value instanceof Map ? (Map) value : null; + private static String enumValue(Object value) { + return value == null ? null : value.toString(); } - private static List asList(Object value) { - return value instanceof List ? (List) value : null; - } + private record ActivityGovernance( + AIDetection detection, + String registeredBy, + Long registeredAt, + String approvedBy, + Long approvedAt, + AICompliance aiCompliance) { + private static final ActivityGovernance EMPTY = + new ActivityGovernance(null, null, null, null, null, null); - private static Long numberToLong(Object value) { - return value instanceof Number n ? n.longValue() : null; + private boolean isEmpty() { + return detection == null + && registeredAt == null + && approvedAt == null + && aiCompliance == null; + } } - private static String asString(Object value) { - return value == null ? null : value.toString(); + private record LlmSubmission(String registeredBy, Long registeredAt) { + private static final LlmSubmission EMPTY = new LlmSubmission(null, null); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/IntakeChecks.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/IntakeChecks.java index e01a344d9170..649488772d31 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/IntakeChecks.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/IntakeChecks.java @@ -16,14 +16,17 @@ import java.util.ArrayList; import java.util.List; -import java.util.Map; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.ai.IntakeCheck; +import org.openmetadata.schema.api.ai.IntakeChecksResponse; import org.openmetadata.schema.entity.ai.AIApplication; +import org.openmetadata.schema.entity.ai.GovernanceMetadata; import org.openmetadata.schema.entity.ai.LLMModel; +import org.openmetadata.schema.entity.ai.McpGovernanceMetadata; import org.openmetadata.schema.entity.ai.McpServer; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.service.resources.ai.AIGovernanceResource.IntakeCheck; -import org.openmetadata.service.resources.ai.AIGovernanceResource.IntakeChecksResponse; +import org.openmetadata.schema.type.AICompliance; +import org.openmetadata.schema.type.AIComplianceRecord; +import org.openmetadata.schema.type.AIEvidence; /** * Computes the 5 intake checks the Approvals queue UI surfaces for an AI asset. @@ -41,15 +44,17 @@ private IntakeChecks() {} static IntakeChecksResponse compute(EntityInterface entity) { List checks = new ArrayList<>(); - checks.add(new IntakeCheck(OWNER_ASSIGNED, hasOwner(entity), null)); - checks.add(new IntakeCheck(RISK_CLASSIFIED, hasRisk(entity), null)); - checks.add(new IntakeCheck(FAIRNESS_EVIDENCE, hasFairnessEvidence(entity), null)); - checks.add(new IntakeCheck(DPIA_REFERENCED, hasDpia(entity), null)); - checks.add(new IntakeCheck(TRANSPARENCY_DISCLOSURE, hasTransparency(entity), null)); - IntakeChecksResponse response = new IntakeChecksResponse(); - response.setChecks(checks); - - return response; + checks.add(intakeCheck(OWNER_ASSIGNED, hasOwner(entity), null)); + checks.add(intakeCheck(RISK_CLASSIFIED, hasRisk(entity), null)); + checks.add(intakeCheck(FAIRNESS_EVIDENCE, hasFairnessEvidence(entity), null)); + checks.add(intakeCheck(DPIA_REFERENCED, hasDpia(entity), null)); + checks.add(intakeCheck(TRANSPARENCY_DISCLOSURE, hasTransparency(entity), null)); + + return new IntakeChecksResponse().withChecks(checks); + } + + private static IntakeCheck intakeCheck(String name, boolean passing, String evidenceRef) { + return new IntakeCheck().withName(name).withPassing(passing).withEvidenceRef(evidenceRef); } private static boolean hasOwner(EntityInterface entity) { @@ -57,17 +62,8 @@ private static boolean hasOwner(EntityInterface entity) { } private static boolean hasRisk(EntityInterface entity) { - Map governance = readGovernance(entity); - boolean result = false; - if (governance != null) { - Map risk = asMap(governance.get("riskAssessment")); - if (risk != null && risk.get("riskLevel") != null) { - result = true; - } - if (!result) { - result = euRiskClassificationPresent(governance); - } - } + boolean result = + riskAssessmentDeclared(entity) || euRiskClassificationPresent(aiCompliance(entity)); if (!result && entity instanceof LLMModel llm) { result = llm.getGovernanceStatus() != null; } @@ -82,106 +78,82 @@ private static boolean hasFairnessEvidence(EntityInterface entity) { result = true; } if (!result) { - String url = readEvidenceUrl(entity, "fairnessEvidenceUrl"); - result = url != null && !url.isBlank(); + AIEvidence evidence = evidence(entity); + result = evidence != null && !nullOrEmpty(evidence.getFairnessEvidenceUrl()); } return result; } private static boolean hasDpia(EntityInterface entity) { - String url = readEvidenceUrl(entity, "dpiaUrl"); - return url != null && !url.isBlank(); + AIEvidence evidence = evidence(entity); + return evidence != null && !nullOrEmpty(evidence.getDpiaUrl()); } private static boolean hasTransparency(EntityInterface entity) { - Map governance = readGovernance(entity); + AICompliance aiCompliance = aiCompliance(entity); boolean result = false; - if (governance != null) { - Map aiCompliance = asMap(governance.get("aiCompliance")); - if (aiCompliance != null) { - List records = asList(aiCompliance.get("complianceRecords")); - if (records != null) { - for (Object item : records) { - Map record = asMap(item); - if (record == null) { - continue; - } - Map eu = asMap(record.get("euAIAct")); - Map transparency = - eu == null ? null : asMap(eu.get("transparencyObligations")); - if (transparency != null && Boolean.TRUE.equals(transparency.get("usersInformed"))) { - result = true; - break; - } - } + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + if (record.getEuAIAct() != null + && record.getEuAIAct().getTransparencyObligations() != null + && Boolean.TRUE.equals( + record.getEuAIAct().getTransparencyObligations().getUsersInformed())) { + result = true; + break; } } } return result; } - private static String readEvidenceUrl(EntityInterface entity, String key) { - String url = null; - Map evidence = null; + private static boolean riskAssessmentDeclared(EntityInterface entity) { + boolean result = false; if (entity instanceof AIApplication app && app.getGovernanceMetadata() != null) { - evidence = - JsonUtils.getObjectMapper() - .convertValue(app.getGovernanceMetadata().getEvidence(), Map.class); + GovernanceMetadata governance = app.getGovernanceMetadata(); + result = + governance.getRiskAssessment() != null + && governance.getRiskAssessment().getRiskLevel() != null; } else if (entity instanceof McpServer server && server.getGovernanceMetadata() != null) { - evidence = - JsonUtils.getObjectMapper() - .convertValue(server.getGovernanceMetadata().getEvidence(), Map.class); - } else if (entity instanceof LLMModel llm && llm.getEvidence() != null) { - evidence = JsonUtils.getObjectMapper().convertValue(llm.getEvidence(), Map.class); - } - if (evidence != null && evidence.get(key) instanceof String value) { - url = value; + McpGovernanceMetadata governance = server.getGovernanceMetadata(); + result = + governance.getRiskAssessment() != null + && governance.getRiskAssessment().getRiskLevel() != null; } - return url; - } - - @SuppressWarnings("unchecked") - private static Map readGovernance(EntityInterface entity) { - Object source = null; - if (entity instanceof AIApplication app) { - source = app.getGovernanceMetadata(); - } else if (entity instanceof McpServer server) { - source = server.getGovernanceMetadata(); - } - return source == null - ? null - : (Map) JsonUtils.getObjectMapper().convertValue(source, Map.class); + return result; } - private static boolean euRiskClassificationPresent(Map governance) { - Map aiCompliance = asMap(governance.get("aiCompliance")); + private static boolean euRiskClassificationPresent(AICompliance aiCompliance) { boolean result = false; - if (aiCompliance != null) { - List records = asList(aiCompliance.get("complianceRecords")); - if (records != null) { - for (Object item : records) { - Map record = asMap(item); - if (record == null) { - continue; - } - Map eu = asMap(record.get("euAIAct")); - if (eu != null && eu.get("riskClassification") != null) { - result = true; - break; - } + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + if (record.getEuAIAct() != null && record.getEuAIAct().getRiskClassification() != null) { + result = true; + break; } } } return result; } - @SuppressWarnings("unchecked") - private static Map asMap(Object value) { - return value instanceof Map ? (Map) value : null; + private static AICompliance aiCompliance(EntityInterface entity) { + AICompliance result = null; + if (entity instanceof AIApplication app && app.getGovernanceMetadata() != null) { + result = app.getGovernanceMetadata().getAiCompliance(); + } else if (entity instanceof McpServer server && server.getGovernanceMetadata() != null) { + result = server.getGovernanceMetadata().getAiCompliance(); + } + return result; } - @SuppressWarnings("unchecked") - private static List asList(Object value) { - return value instanceof List ? (List) value : null; + private static AIEvidence evidence(EntityInterface entity) { + AIEvidence result = null; + if (entity instanceof AIApplication app && app.getGovernanceMetadata() != null) { + result = app.getGovernanceMetadata().getEvidence(); + } else if (entity instanceof McpServer server && server.getGovernanceMetadata() != null) { + result = server.getGovernanceMetadata().getEvidence(); + } else if (entity instanceof LLMModel llm) { + result = llm.getEvidence(); + } + return result; } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/PolicyEvaluator.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/PolicyEvaluator.java index 9da3f591a961..7c0a3790dcc8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/PolicyEvaluator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ai/PolicyEvaluator.java @@ -13,18 +13,24 @@ package org.openmetadata.service.resources.ai; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; -import java.util.Map; import java.util.UUID; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.ai.AIGovernancePolicyRuleResult; +import org.openmetadata.schema.api.ai.AIGovernancePolicyViolation; import org.openmetadata.schema.entity.ai.AIApplication; import org.openmetadata.schema.entity.ai.AIGovernancePolicy; +import org.openmetadata.schema.entity.ai.DataClassification; +import org.openmetadata.schema.entity.ai.DataClassification__2; +import org.openmetadata.schema.entity.ai.GovernanceMetadata; import org.openmetadata.schema.entity.ai.LLMModel; +import org.openmetadata.schema.entity.ai.McpGovernanceMetadata; import org.openmetadata.schema.entity.ai.McpServer; +import org.openmetadata.schema.type.AICompliance; +import org.openmetadata.schema.type.AIComplianceRecord; +import org.openmetadata.schema.type.AIEvidence; import org.openmetadata.schema.type.Include; -import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.AIGovernancePolicyRepository; @@ -42,7 +48,6 @@ * referenced {@code AIGovernancePolicy} entries; this evaluator hardcodes a * useful baseline so the Policies tab has content to render today. */ -@SuppressWarnings("unchecked") final class PolicyEvaluator { private static final long FAIRNESS_FRESHNESS_MS = 90L * 24 * 60 * 60 * 1000; @@ -56,27 +61,27 @@ enum Status { NOT_APPLICABLE } - static List> evaluate(EntityInterface entity, String entityType) { - List> rules = new ArrayList<>(); - rules.add(piiAccessRequiresDpia(entity, entityType)); - rules.add(subgroupFairnessQuarterly(entity, entityType)); - rules.add(humanOversight(entity, entityType)); - rules.add(auditLogRetention(entity, entityType)); - rules.add(driftThreshold(entity, entityType)); + static List evaluate(EntityInterface entity, String entityType) { + List rules = new ArrayList<>(); + rules.add(piiAccessRequiresDpia(entity)); + rules.add(subgroupFairnessQuarterly(entity)); + rules.add(humanOversight(entity)); + rules.add(auditLogRetention(entity)); + rules.add(driftThreshold()); return rules; } - private static Map piiAccessRequiresDpia( - EntityInterface entity, String entityType) { - Map governance = governance(entity, entityType); - Map classification = - asMap(governance == null ? null : governance.get("dataClassification")); + private static AIGovernancePolicyRuleResult piiAccessRequiresDpia(EntityInterface entity) { + GovernanceSnapshot governance = governance(entity); boolean accessesPii = - classification != null && Boolean.TRUE.equals(classification.get("accessesPII")); - Map evidence = asMap(governance == null ? null : governance.get("evidence")); - Object dpia = evidence == null ? null : evidence.get("dpiaUrl"); - String dpiaUrl = dpia instanceof String value && !value.isBlank() ? value : null; + governance.dataClassification() != null + && Boolean.TRUE.equals(governance.dataClassification().accessesPii()); + AIEvidence evidence = governance.evidence(); + String dpiaUrl = + evidence != null && evidence.getDpiaUrl() != null && !evidence.getDpiaUrl().isBlank() + ? evidence.getDpiaUrl() + : null; Status status; if (!accessesPii) { status = Status.NOT_APPLICABLE; @@ -93,10 +98,9 @@ private static Map piiAccessRequiresDpia( dpiaUrl == null ? (accessesPii ? "No DPIA on file" : "N/A") : dpiaUrl); } - private static Map subgroupFairnessQuarterly( - EntityInterface entity, String entityType) { - Map governance = governance(entity, entityType); - String euRisk = euRiskClassification(governance); + private static AIGovernancePolicyRuleResult subgroupFairnessQuarterly(EntityInterface entity) { + GovernanceSnapshot governance = governance(entity); + String euRisk = euRiskClassification(governance.aiCompliance()); boolean highRisk = "High".equals(euRisk) || "Unacceptable".equals(euRisk); Long lastEval = lastBiasEval(entity); Status status; @@ -125,9 +129,9 @@ private static Map subgroupFairnessQuarterly( value); } - private static Map humanOversight(EntityInterface entity, String entityType) { - Map governance = governance(entity, entityType); - Boolean oversight = humanOversightFromGovernance(governance); + private static AIGovernancePolicyRuleResult humanOversight(EntityInterface entity) { + GovernanceSnapshot governance = governance(entity); + Boolean oversight = humanOversightFromGovernance(governance.aiCompliance()); Status status; String value; if (oversight == null) { @@ -148,12 +152,15 @@ private static Map humanOversight(EntityInterface entity, String value); } - private static Map auditLogRetention(EntityInterface entity, String entityType) { - Map governance = governance(entity, entityType); - Map classification = - asMap(governance == null ? null : governance.get("dataClassification")); - Object retention = classification == null ? null : classification.get("dataRetentionPeriod"); - String value = retention instanceof String s && !s.isBlank() ? s : null; + private static AIGovernancePolicyRuleResult auditLogRetention(EntityInterface entity) { + GovernanceSnapshot governance = governance(entity); + DataClassificationSnapshot classification = governance.dataClassification(); + String value = + classification != null + && classification.dataRetentionPeriod() != null + && !classification.dataRetentionPeriod().isBlank() + ? classification.dataRetentionPeriod() + : null; Status status = value == null ? Status.BREACHED : Status.PASSING; return rule( @@ -163,7 +170,7 @@ private static Map auditLogRetention(EntityInterface entity, Str value == null ? "Not declared" : value); } - private static Map driftThreshold(EntityInterface entity, String entityType) { + private static AIGovernancePolicyRuleResult driftThreshold() { // No drift field exists at the entity level today. Phase 2 schema work // adds runtime drift metrics; until then this rule is N/A. Status status = Status.NOT_APPLICABLE; @@ -176,62 +183,68 @@ private static Map driftThreshold(EntityInterface entity, String value); } - private static Map rule( + private static AIGovernancePolicyRuleResult rule( String name, String description, Status status, String value) { - Map result = new LinkedHashMap<>(); - result.put("name", name); - result.put("description", description); - result.put( - "status", - switch (status) { - case PASSING -> "Passing"; - case BREACHED -> "Breached"; - case NOT_APPLICABLE -> "NotApplicable"; - }); - result.put("value", value); - - return result; + return new AIGovernancePolicyRuleResult() + .withName(name) + .withDescription(description) + .withStatus( + switch (status) { + case PASSING -> "Passing"; + case BREACHED -> "Breached"; + case NOT_APPLICABLE -> "NotApplicable"; + }) + .withValue(value); } - private static Map governance(EntityInterface entity, String entityType) { - Map result = null; + private static GovernanceSnapshot governance(EntityInterface entity) { + GovernanceSnapshot result = GovernanceSnapshot.EMPTY; if (entity instanceof AIApplication app && app.getGovernanceMetadata() != null) { - result = - (Map) - JsonUtils.getObjectMapper().convertValue(app.getGovernanceMetadata(), Map.class); + result = governance(app.getGovernanceMetadata()); } else if (entity instanceof McpServer server && server.getGovernanceMetadata() != null) { - result = - (Map) - JsonUtils.getObjectMapper().convertValue(server.getGovernanceMetadata(), Map.class); + result = governance(server.getGovernanceMetadata()); } else if (entity instanceof LLMModel llm) { - // LLM has no rich governance block; surface a shim so the rules can - // still inspect detection / evidence when present. - Map shim = new LinkedHashMap<>(); - if (llm.getDetection() != null) { - shim.put( - "detection", JsonUtils.getObjectMapper().convertValue(llm.getDetection(), Map.class)); - } - if (llm.getEvidence() != null) { - shim.put( - "evidence", JsonUtils.getObjectMapper().convertValue(llm.getEvidence(), Map.class)); - } - if (!shim.isEmpty()) { - result = shim; - } + result = new GovernanceSnapshot(null, llm.getEvidence(), null); } return result; } - private static String euRiskClassification(Map governance) { + private static GovernanceSnapshot governance(GovernanceMetadata governance) { + return new GovernanceSnapshot( + governance.getAiCompliance(), + governance.getEvidence(), + dataClassification(governance.getDataClassification())); + } + + private static GovernanceSnapshot governance(McpGovernanceMetadata governance) { + return new GovernanceSnapshot( + governance.getAiCompliance(), + governance.getEvidence(), + dataClassification(governance.getDataClassification())); + } + + private static DataClassificationSnapshot dataClassification( + DataClassification dataClassification) { + return dataClassification == null + ? null + : new DataClassificationSnapshot( + dataClassification.getAccessesPII(), dataClassification.getDataRetentionPeriod()); + } + + private static DataClassificationSnapshot dataClassification( + DataClassification__2 dataClassification) { + return dataClassification == null + ? null + : new DataClassificationSnapshot( + dataClassification.getAccessesPII(), dataClassification.getDataRetentionPeriod()); + } + + private static String euRiskClassification(AICompliance aiCompliance) { String result = null; - Map aiCompliance = - asMap(governance == null ? null : governance.get("aiCompliance")); - if (aiCompliance != null && aiCompliance.get("complianceRecords") instanceof List records) { - for (Object recordObj : records) { - Map record = asMap(recordObj); - Map eu = record == null ? null : asMap(record.get("euAIAct")); - if (eu != null && eu.get("riskClassification") != null) { - result = eu.get("riskClassification").toString(); + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + if (record.getEuAIAct() != null && record.getEuAIAct().getRiskClassification() != null) { + result = record.getEuAIAct().getRiskClassification().value(); break; } } @@ -239,19 +252,23 @@ private static String euRiskClassification(Map governance) { return result; } - private static Boolean humanOversightFromGovernance(Map governance) { + private static Boolean humanOversightFromGovernance(AICompliance aiCompliance) { Boolean result = null; - Map aiCompliance = - asMap(governance == null ? null : governance.get("aiCompliance")); - if (aiCompliance != null && aiCompliance.get("complianceRecords") instanceof List records) { - for (Object recordObj : records) { - Map record = asMap(recordObj); - Map ethical = - record == null ? null : asMap(record.get("ethicalAssessment")); - Map accountability = - ethical == null ? null : asMap(ethical.get("accountabilityMeasures")); - if (accountability != null && accountability.get("subjectToHumanOversight") != null) { - result = Boolean.TRUE.equals(accountability.get("subjectToHumanOversight")); + if (aiCompliance != null && aiCompliance.getComplianceRecords() != null) { + for (AIComplianceRecord record : aiCompliance.getComplianceRecords()) { + if (record.getEthicalAssessment() != null + && record.getEthicalAssessment().getAccountabilityMeasures() != null + && record + .getEthicalAssessment() + .getAccountabilityMeasures() + .getSubjectToHumanOversight() + != null) { + result = + Boolean.TRUE.equals( + record + .getEthicalAssessment() + .getAccountabilityMeasures() + .getSubjectToHumanOversight()); break; } } @@ -271,10 +288,6 @@ private static long relativeDays(long ms) { return ms / (24L * 60 * 60 * 1000); } - private static Map asMap(Object value) { - return value instanceof Map ? (Map) value : null; - } - /** * Walks in-scope AI assets, re-evaluates every rule and returns rows that * map to the named policy. Used by the Policies & Drift page to populate @@ -282,12 +295,12 @@ private static Map asMap(Object value) { * AI assets table; a real time-series store can replace this later without * changing the response shape. */ - static List> recentViolations(UUID policyId, Long since, int limit) { + static List recentViolations(UUID policyId, Long since, int limit) { String ruleNamePattern = ruleNameForPolicy(policyId); long sinceMs = since == null ? 0 : since; int effectiveLimit = Math.max(1, Math.min(limit, 500)); - List> rows = new ArrayList<>(); + List rows = new ArrayList<>(); scanAssets(Entity.AI_APPLICATION, ruleNamePattern, sinceMs, effectiveLimit, rows); if (rows.size() < effectiveLimit) { scanAssets(Entity.LLM_MODEL, ruleNamePattern, sinceMs, effectiveLimit, rows); @@ -304,21 +317,21 @@ private static void scanAssets( String ruleNamePattern, long sinceMs, int limit, - List> rows) { + List rows) { List entities = listEntities(entityType, limit); for (EntityInterface entity : entities) { if (rows.size() >= limit) { return; } - List> rules = evaluate(entity, entityType); - for (Map rule : rules) { + List rules = evaluate(entity, entityType); + for (AIGovernancePolicyRuleResult rule : rules) { if (rows.size() >= limit) { return; } - if (!"Breached".equals(rule.get("status"))) { + if (!"Breached".equals(rule.getStatus())) { continue; } - String ruleName = String.valueOf(rule.get("name")); + String ruleName = rule.getName(); if (ruleNamePattern != null && !ruleName.toLowerCase(Locale.ROOT).contains(ruleNamePattern)) { continue; @@ -327,17 +340,16 @@ private static void scanAssets( if (observedAt == null || observedAt < sinceMs) { continue; } - Map row = new LinkedHashMap<>(); - row.put("entityType", entityType); - row.put("entityId", entity.getId() == null ? null : entity.getId().toString()); - row.put( - "entityName", - entity.getDisplayName() == null ? entity.getName() : entity.getDisplayName()); - row.put("ruleName", ruleName); - row.put("status", "Breached"); - row.put("value", rule.get("value")); - row.put("observedAt", observedAt); - rows.add(row); + rows.add( + new AIGovernancePolicyViolation() + .withEntityType(entityType) + .withEntityId(entity.getId() == null ? null : entity.getId().toString()) + .withEntityName( + entity.getDisplayName() == null ? entity.getName() : entity.getDisplayName()) + .withRuleName(ruleName) + .withStatus("Breached") + .withValue(rule.getValue()) + .withObservedAt(observedAt)); } } } @@ -400,4 +412,13 @@ private static String ruleNameForPolicy(UUID policyId) { } return null; } + + private record GovernanceSnapshot( + AICompliance aiCompliance, + AIEvidence evidence, + DataClassificationSnapshot dataClassification) { + private static final GovernanceSnapshot EMPTY = new GovernanceSnapshot(null, null, null); + } + + private record DataClassificationSnapshot(Boolean accessesPii, String dataRetentionPeriod) {} } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java index 528d8343aee5..6dac84e68761 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java @@ -13,32 +13,38 @@ import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.StreamingOutput; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.TagLabel; -import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.audit.AuditLogEntry; import org.openmetadata.service.audit.AuditLogRepository; +import org.openmetadata.service.csv.CsvExportSpool; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.OperationContext; import org.openmetadata.service.security.policyevaluator.ResourceContext; import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; -import org.openmetadata.service.util.AsyncService; import org.openmetadata.service.util.CSVExportResponse; import org.openmetadata.service.util.WebsocketNotificationHandler; @@ -149,6 +155,20 @@ public ResultList listAuditLogs( private static final int EXPORT_MAX_LIMIT = 100000; private static final int EXPORT_DEFAULT_LIMIT = 10000; + // Audit exports stream to a spool file and hand back a download reference over the websocket (see + // streamExportAsJson + downloadAuditExportResult), so a single export never materializes its + // whole + // payload. This dedicated pool additionally caps how many run at once to bound DB load. + private static final int MAX_CONCURRENT_AUDIT_EXPORTS = 2; + private static final ExecutorService AUDIT_EXPORT_EXECUTOR = + Executors.newFixedThreadPool( + MAX_CONCURRENT_AUDIT_EXPORTS, + runnable -> { + Thread thread = new Thread(runnable, "audit-export"); + thread.setDaemon(true); + return thread; + }); + @GET @Path("/export") @Operation( @@ -239,16 +259,16 @@ public Response exportAuditLogs( // Generate job ID and start async export String jobId = UUID.randomUUID().toString(); - ExecutorService executorService = AsyncService.getInstance().getExecutorService(); - - executorService.submit( + AUDIT_EXPORT_EXECUTOR.submit( () -> { - try { - // Use batched export to avoid long-running queries that could cause - // resource contention with concurrent writes to the audit_log table. - // Progress updates are sent via websocket for long-running exports. - List results = - repository.exportInBatches( + try (OutputStream spool = CsvExportSpool.openForWrite(jobId)) { + // Stream results straight to the spool file (one batch in memory at a time) and hand + // the + // client a download reference over the websocket instead of the inline payload, so + // neither the heap nor the websocket send buffer holds a multi-hundred-MB export. + int exported = + repository.streamExportAsJson( + spool, userName, actorType, serviceName, @@ -261,12 +281,12 @@ public Response exportAuditLogs( (fetched, total, message) -> WebsocketNotificationHandler.sendCsvExportProgressNotification( jobId, securityContext, fetched, total, message)); - - String json = JsonUtils.pojoToJson(results); + LOG.info("Audit export {} spooled {} records", jobId, exported); WebsocketNotificationHandler.sendCsvExportCompleteNotification( - jobId, securityContext, json); + jobId, securityContext, null); } catch (Exception e) { LOG.error("Encountered exception while exporting audit logs.", e); + deleteSpoolQuietly(jobId); WebsocketNotificationHandler.sendCsvExportFailedNotification( jobId, securityContext, e.getMessage() == null ? e.toString() : e.getMessage()); } @@ -276,6 +296,67 @@ public Response exportAuditLogs( return Response.accepted().entity(response).type(MediaType.APPLICATION_JSON).build(); } + @GET + @Path("/export/{jobId}/result") + @Operation( + operationId = "downloadAuditExportResult", + summary = "Download a completed audit log export", + description = + "Streams the spooled result of a completed audit-log export job. Clients call this after " + + "receiving the COMPLETED event on the csvExportChannel websocket.", + responses = { + @ApiResponse(responseCode = "200", description = "Export result stream"), + @ApiResponse(responseCode = "404", description = "Export result not found or expired") + }) + @Produces(MediaType.APPLICATION_JSON) + public Response downloadAuditExportResult( + @Context SecurityContext securityContext, @PathParam("jobId") String jobId) { + OperationContext operationContext = + new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS); + authorizer.authorize(securityContext, operationContext, AuditLogResourceContext.INSTANCE); + Response response; + if (isServerGeneratedJobId(jobId) && CsvExportSpool.exists(jobId)) { + StreamingOutput stream = + output -> { + try (InputStream in = CsvExportSpool.openForRead(jobId)) { + in.transferTo(output); + } + }; + response = + Response.ok(stream, MediaType.APPLICATION_JSON) + .header( + "Content-Disposition", "attachment; filename=\"audit-export-" + jobId + ".json\"") + .build(); + } else { + response = + Response.status(Response.Status.NOT_FOUND) + .entity("Export result not found or expired for job " + jobId) + .build(); + } + return response; + } + + // Job ids are always server-generated UUIDs; reject anything else before it reaches the spool + // path (spoolDir().resolve(prefix + jobId + suffix)) to prevent path traversal. + private static boolean isServerGeneratedJobId(String jobId) { + boolean valid; + try { + UUID.fromString(jobId); + valid = true; + } catch (IllegalArgumentException e) { + valid = false; + } + return valid; + } + + private static void deleteSpoolQuietly(String jobId) { + try { + Files.deleteIfExists(CsvExportSpool.fileForJob(jobId)); + } catch (IOException e) { + LOG.warn("Failed to delete partial audit export spool for {}: {}", jobId, e.getMessage()); + } + } + /** * Authorize audit log access based on service-level, entity-level, or global permissions. * diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/bots/BotResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/bots/BotResource.java index 8f9b6dd92fad..93bced205e46 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/bots/BotResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/bots/BotResource.java @@ -61,7 +61,6 @@ import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.OpenMetadataApplicationConfig; -import org.openmetadata.service.jdbi3.AppRepository; import org.openmetadata.service.jdbi3.BotRepository; import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.jdbi3.UserRepository; @@ -121,9 +120,6 @@ public void initialize(OpenMetadataApplicationConfig config) throws IOException .toList()); // Add or update User Bot UserUtil.addOrUpdateBotUser(user); - if (Boolean.TRUE.equals(botUser.getAllowImpersonation())) { - grantBotImpersonation(userRepository, botUser.getName()); - } } // Then, load the bots and bind them to the users @@ -138,14 +134,6 @@ public void initialize(OpenMetadataApplicationConfig config) throws IOException } } - private void grantBotImpersonation(UserRepository userRepository, String botName) { - User botUser = userRepository.getByName(null, botName, userRepository.getFields("id")); - EntityReference impersonationRole = - Entity.getEntityReferenceByName( - Entity.ROLE, AppRepository.APP_BOT_IMPERSONATION_ROLE, Include.NON_DELETED); - userRepository.updateBotImpersonation(botUser.getId(), true, impersonationRole); - } - @Override public Bot addHref(UriInfo uriInfo, Bot entity) { super.addHref(uriInfo, entity); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryMapper.java index 15492ca2eaa7..0cb2dd27efd2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryMapper.java @@ -40,8 +40,6 @@ public ContextMemory createToEntity(CreateContextMemory create, String user) { .withSourceAssistantMessage(create.getSourceAssistantMessage()) .withRootMemory(create.getRootMemory()) .withParentMemory(create.getParentMemory()) - .withMachineRepresentation(create.getMachineRepresentation()) - .withSourceFile(create.getSourceFile()) - .withSourceEntity(create.getSourceEntity()); + .withMachineRepresentation(create.getMachineRepresentation()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryResource.java index cc4709408cfd..f9f09094f02d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryResource.java @@ -164,18 +164,6 @@ public ResultList list( @Parameter(description = "Sort order: asc or desc") @QueryParam("sortOrder") String sortOrder, @Parameter(description = "Offset for search-backed pagination") @Min(0) @QueryParam("offset") Integer offset, - @Parameter( - description = - "Only return knowledge pills extracted from the context file with this id", - schema = @Schema(type = "string", format = "uuid")) - @QueryParam("sourceFileId") - UUID sourceFileId, - @Parameter( - description = - "Only return knowledge pills extracted from the context entity (file or page) with this id", - schema = @Schema(type = "string", format = "uuid")) - @QueryParam("sourceEntityId") - UUID sourceEntityId, @Parameter( description = "Only return knowledge pills whose primaryEntity (the data asset the pill applies to) has this id", @@ -199,25 +187,24 @@ public ResultList list( before, after, include, - sourceFileId, - sourceEntityId, primaryEntityId); } ListFilter filter = new ListFilter(include); - if (sourceFileId != null) { - filter.addQueryParam("sourceFileId", sourceFileId.toString()); - } - if (sourceEntityId != null) { - filter.addQueryParam("sourceEntityId", sourceEntityId.toString()); - } if (primaryEntityId != null) { filter.addQueryParam("primaryEntityId", primaryEntityId.toString()); } ResultList memories = addHref( uriInfo, - listInternal(uriInfo, securityContext, fieldsParam, filter, limitParam, before, after)); + listInternal( + uriInfo, + securityContext, + fieldsParam, + new ListFilter(include), + limitParam, + before, + after)); List visible = ContextMemoryVisibility.filterByVisibility(memories.getData(), securityContext); if (visible.size() == memories.getData().size()) { @@ -241,11 +228,9 @@ private ResultList listMemoriesFromSearch( String before, String after, Include include, - UUID sourceFileId, - UUID sourceEntityId, UUID primaryEntityId) throws IOException { - validateSearchBackedListParams(before, after, sourceFileId, sourceEntityId, primaryEntityId); + validateSearchBackedListParams(before, after, primaryEntityId); SearchListFilter searchListFilter = buildContextMemorySearchFilter(include, assets, author, pinned, null); SearchSortFilter searchSortFilter = @@ -281,14 +266,14 @@ private static boolean hasSearchBackedListParams( } private static void validateSearchBackedListParams( - String before, String after, UUID sourceFileId, UUID sourceEntityId, UUID primaryEntityId) { + String before, String after, UUID primaryEntityId) { if (!CommonUtil.nullOrEmpty(before) || !CommonUtil.nullOrEmpty(after)) { throw new BadRequestException( "before/after cursor pagination cannot be combined with q/assets/author/pinned/sortBy/offset"); } - if (sourceFileId != null || sourceEntityId != null || primaryEntityId != null) { + if (primaryEntityId != null) { throw new BadRequestException( - "sourceFileId/sourceEntityId/primaryEntityId cannot be combined with q/assets/author/pinned/sortBy/offset"); + "primaryEntityId cannot be combined with q/assets/author/pinned/sortBy/offset"); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/data/DataContractResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/data/DataContractResource.java index abc1f7088bd4..4dd24466f820 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/data/DataContractResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/data/DataContractResource.java @@ -113,6 +113,56 @@ public DataContractResource(Authorizer authorizer, Limits limits) { super(Entity.DATA_CONTRACT, authorizer, limits); } + @GET + @Path("/search") + @Valid + @Operation( + operationId = "searchDataContracts", + summary = "Search data contracts", + description = + "Search data contracts by name or display name. Use `q` parameter to provide the search query.", + responses = { + @ApiResponse( + responseCode = "200", + description = "List of matching data contracts", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = DataContractList.class))) + }) + public ResultList search( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @Parameter(description = "Search query for data contract names or display names") + @QueryParam("q") + String query, + @Parameter( + description = "Fields requested in the returned resource", + schema = @Schema(type = "string", example = FIELDS)) + @QueryParam("fields") + String fieldsParam, + @Parameter(description = "Limit the number of data contracts returned") + @DefaultValue("10") + @Min(value = 1, message = "must be greater than or equal to 1") + @Max(value = 1000, message = "must be less than or equal to 1000") + @QueryParam("limit") + int limitParam, + @Parameter(description = "Offset for pagination") + @DefaultValue("0") + @Min(value = 0, message = "must be greater than or equal to 0") + @QueryParam("offset") + int offsetParam, + @Parameter( + description = "Include all, deleted, or non-deleted entities", + schema = @Schema(implementation = Include.class)) + @QueryParam("include") + @DefaultValue("non-deleted") + Include include) { + ListFilter filter = new ListFilter(include); + return searchInternal( + uriInfo, securityContext, fieldsParam, filter, query, limitParam, offsetParam); + } + // Set the PipelineServiceClient so the repository can manage the Ingestion Pipelines for Test // Suites @Override diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileResource.java index 70d455d6e98c..0d80f9a46a2e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileResource.java @@ -69,7 +69,7 @@ import org.openmetadata.service.attachments.AssetServiceFactory; import org.openmetadata.service.attachments.AzureAssetService; import org.openmetadata.service.attachments.S3AssetService; -import org.openmetadata.service.drive.ContextFileProcessingService; +import org.openmetadata.service.drive.ContextFileExtractionService; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.ContextFileRepository; @@ -99,12 +99,12 @@ public class ContextFileResource extends EntityResource {} @@ -175,11 +174,21 @@ public ResultList list( @QueryParam("orderBy") String orderBy, @Parameter(description = "Filter files by folder ID.") @QueryParam("folderId") - String folderId) { + String folderId, + @Parameter( + description = + "Filter files by the user who last updated them (their username). Combine with " + + "include=deleted to scope the archive page to files archived by that user - " + + "an archived file cannot be edited, so updatedBy stays the user who archived it.") + @QueryParam("updatedBy") + String updatedBy) { ListFilter filter = new ListFilter(include); if (folderId != null && !folderId.isBlank()) { filter.addQueryParam("folderId", folderId); } + if (updatedBy != null && !updatedBy.isBlank()) { + filter.addQueryParam("updatedBy", updatedBy); + } if (orderBy == null || orderBy.isBlank()) { return super.listInternal( uriInfo, securityContext, fieldsParam, filter, limit, before, after); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/events/EventResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/events/EventResource.java index cda0394aab9b..24dcdcb7e7ed 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/events/EventResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/events/EventResource.java @@ -20,7 +20,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; @@ -37,7 +40,7 @@ import org.openmetadata.service.jdbi3.ChangeEventRepository; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.security.Authorizer; -import org.openmetadata.service.util.EntityUtil; +import org.openmetadata.service.util.RestUtil; @Path("/v1/events") @Tag( @@ -70,7 +73,8 @@ public EventResource(Authorizer authorizer) { operationId = "listChangeEvents", summary = "Get change events", description = - "Get a list of change events matching event types, entity type, from a given date", + "Get change events within a time range, one page at a time. Use `limit` to set the page " + + "size and `after` to fetch the next page.", responses = { @ApiResponse( responseCode = "200", @@ -120,15 +124,45 @@ public ResultList get( required = true, schema = @Schema(type = "long", example = "1426349294842")) @QueryParam("timestamp") - long timestamp) { + long timestamp, + @Parameter( + description = + "Only return events up to this unix timestamp in milliseconds. " + + "Defaults to no end limit.", + schema = @Schema(type = "long", example = "1426349294842")) + @DefaultValue("0") + @QueryParam("endTs") + long endTs, + @Parameter( + description = "Limit the number of events returned. (1 to 1000, default = 100)", + schema = @Schema(type = "integer", example = "100")) + @DefaultValue("100") + @Min(value = 1, message = "must be greater than or equal to 1") + @Max(value = 1000, message = "must be less than or equal to 1000") + @QueryParam("limit") + int limitParam, + @Parameter( + description = + "Cursor from the previous response's `paging.after`. Pass it back to get the next " + + "page; keep going until it is empty.", + schema = @Schema(type = "string")) + @QueryParam("after") + String after) { List entityCreatedList = EntityList.getEntityList("entityCreated", entityCreated); List entityUpdatedList = EntityList.getEntityList("entityUpdated", entityUpdated); List entityRestoredList = EntityList.getEntityList("entityRestored", entityRestored); List entityDeletedList = EntityList.getEntityList("entityDeleted", entityDeleted); - List events = - repository.list( - timestamp, entityCreatedList, entityUpdatedList, entityRestoredList, entityDeletedList); - events.sort(EntityUtil.compareChangeEvent); // Sort change events based on time - return new EventList(events, null, null, events.size()); + String decodedCursor = RestUtil.decodeCursor(after); + long afterOffset = decodedCursor == null ? 0 : Long.parseLong(decodedCursor); + long upperBound = endTs <= 0 ? Long.MAX_VALUE : endTs; + return repository.list( + timestamp, + upperBound, + entityCreatedList, + entityUpdatedList, + entityRestoredList, + entityDeletedList, + afterOffset, + limitParam); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/feeds/FeedResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/feeds/FeedResource.java index 05f96e11c7e6..5feb477a05af 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/feeds/FeedResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/feeds/FeedResource.java @@ -57,11 +57,15 @@ import org.openmetadata.schema.api.feed.ResolveTask; import org.openmetadata.schema.api.feed.ThreadCount; import org.openmetadata.schema.entity.feed.Thread; +import org.openmetadata.schema.exception.JsonParsingException; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.Post; +import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.type.TaskStatus; +import org.openmetadata.schema.type.TaskType; import org.openmetadata.schema.type.ThreadType; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; @@ -93,6 +97,8 @@ @Collection(name = "feeds") public class FeedResource { public static final String COLLECTION_PATH = "/v1/feed/"; + private static final String TASK_OLD_VALUE_FIELD = "oldValue"; + private static final String TASK_SUGGESTION_FIELD = "suggestion"; private final FeedMapper mapper = new FeedMapper(); private final PostMapper postMapper = new PostMapper(); private final FeedRepository dao; @@ -448,6 +454,7 @@ public Response createThread( @Context SecurityContext securityContext, @Valid CreateThread create) { rejectLegacyAnnouncementAccess(create.getType() == ThreadType.Announcement); + validateCreateThread(create); authorizeThreadCreate(securityContext, create); Thread thread = mapper.createToEntity(create, securityContext.getUserPrincipal().getName()); addHref(uriInfo, dao.create(thread)); @@ -675,4 +682,74 @@ private void rejectLegacyAnnouncementThread(Thread thread) { rejectLegacyAnnouncementAccess( thread != null && thread.getType() != null && thread.getType() == ThreadType.Announcement); } + + private void validateCreateThread(CreateThread create) { + if (create.getAbout() == null || create.getAbout().isBlank()) { + throw new IllegalArgumentException("Thread about is required."); + } + validateTaskThreadShape(create); + validateLegacyTaskDetails(create); + } + + private void validateTaskThreadShape(CreateThread create) { + if (create.getTaskDetails() == null && create.getType() == ThreadType.Task) { + throw new IllegalArgumentException("Task details are required for task threads."); + } + if (create.getTaskDetails() != null && create.getType() != ThreadType.Task) { + throw new IllegalArgumentException("Task details are only allowed for task threads."); + } + } + + private void validateLegacyTaskDetails(CreateThread create) { + if (create.getTaskDetails() != null) { + TaskType taskType = create.getTaskDetails().getType(); + validateTaskType(taskType); + validateRequestApprovalTask(create.getAbout(), taskType); + validateTagTaskValues(create, taskType); + } + } + + private void validateTaskType(TaskType taskType) { + if (taskType == null) { + throw new IllegalArgumentException("Task type is required for task threads."); + } + if (!isSupportedLegacyFeedTask(taskType)) { + throw new IllegalArgumentException( + String.format("Task type %s is not supported by feed threads.", taskType)); + } + } + + private void validateRequestApprovalTask(String about, TaskType taskType) { + if (taskType == TaskType.RequestApproval) { + MessageParser.EntityLink entityLink = MessageParser.EntityLink.parse(about); + if (entityLink.getLinkType() != MessageParser.EntityLink.LinkType.ENTITY) { + throw new IllegalArgumentException("RequestApproval tasks must target an entity."); + } + } + } + + private void validateTagTaskValues(CreateThread create, TaskType taskType) { + if (EntityUtil.isTagTask(taskType)) { + validateTagTaskValue(create.getTaskDetails().getOldValue(), TASK_OLD_VALUE_FIELD); + validateTagTaskValue(create.getTaskDetails().getSuggestion(), TASK_SUGGESTION_FIELD); + } + } + + private boolean isSupportedLegacyFeedTask(TaskType taskType) { + return EntityUtil.isDescriptionTask(taskType) + || EntityUtil.isTagTask(taskType) + || EntityUtil.isApprovalTask(taskType) + || EntityUtil.isTestCaseFailureResolutionTask(taskType); + } + + private void validateTagTaskValue(String value, String fieldName) { + if (!nullOrEmpty(value) && !value.isBlank()) { + try { + JsonUtils.readObjects(value, TagLabel.class); + } catch (JsonParsingException ex) { + throw new IllegalArgumentException( + String.format("Task %s must be valid JSON for tag tasks.", fieldName), ex); + } + } + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/mcp/McpUsageResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/mcp/McpUsageResource.java index b0d4f0fe8d74..0632d791b53e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/mcp/McpUsageResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/mcp/McpUsageResource.java @@ -45,6 +45,8 @@ import org.openmetadata.schema.entity.app.App; import org.openmetadata.schema.entity.app.AppExtension; import org.openmetadata.schema.entity.app.mcp.McpToolCallUsage; +import org.openmetadata.service.apps.AbstractNativeApplication; +import org.openmetadata.service.apps.ApplicationContext; import org.openmetadata.service.apps.bundles.mcp.McpAppConstants; import org.openmetadata.service.jdbi3.AppRepository; import org.openmetadata.service.resources.Collection; @@ -412,7 +414,10 @@ private Map buildSelf(String userName, long from, long to) { * even if new MCP tool calls are recorded mid-request, preventing duplicate or skipped rows. */ private void forEachRow(long from, long to, Consumer visit) { - App app = new App().withName(McpAppConstants.MCP_APP_NAME); + App app = resolveMcpApp(); + if (app == null) { + return; + } int offset = 0; while (true) { List page = @@ -435,6 +440,12 @@ private void forEachRow(long from, long to, Consumer visit) { } } + private App resolveMcpApp() { + AbstractNativeApplication app = + ApplicationContext.getInstance().getAppIfExists(McpAppConstants.MCP_APP_NAME); + return app != null ? app.getApp() : null; + } + static long resolveStart(Long startTs) { if (startTs != null) { return startTs; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/mcpclient/McpClientResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/mcpclient/McpClientResource.java deleted file mode 100644 index aa8471dc3772..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/mcpclient/McpClientResource.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * Copyright 2025 Collate. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openmetadata.service.resources.mcpclient; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; -import jakarta.validation.constraints.Max; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.Size; -import jakarta.ws.rs.Consumes; -import jakarta.ws.rs.DELETE; -import jakarta.ws.rs.DefaultValue; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.POST; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.PathParam; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.QueryParam; -import jakarta.ws.rs.WebApplicationException; -import jakarta.ws.rs.core.Context; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.SecurityContext; -import jakarta.ws.rs.core.StreamingOutput; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import lombok.Getter; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.openmetadata.schema.api.chat.CreateMcpConversation; -import org.openmetadata.schema.entity.chat.McpConversation; -import org.openmetadata.schema.entity.chat.McpMessage; -import org.openmetadata.schema.utils.JsonUtils; -import org.openmetadata.schema.utils.ResultList; -import org.openmetadata.service.limits.Limits; -import org.openmetadata.service.mcpclient.ChatEvent; -import org.openmetadata.service.mcpclient.ClientDisconnectedException; -import org.openmetadata.service.mcpclient.McpChatServiceHolder; -import org.openmetadata.service.mcpclient.McpClientService; -import org.openmetadata.service.mcpclient.McpClientService.ChatResponse; -import org.openmetadata.service.mcpclient.ToolExecutor; -import org.openmetadata.service.resources.Collection; -import org.openmetadata.service.security.Authorizer; - -@Path("/v1/mcp-client") -@Tag(name = "McpClient") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -@Slf4j -@Collection(name = "McpClient") -public class McpClientResource { - - /** - * JAX-RS instantiates this resource; we publish the singleton so the MCP server (started from a - * separate module) can hand it the tool executor. The executor is then relayed to the per-app - * {@link McpClientService} lazily in {@link #getService()}, decoupling tool-registration order - * from app-installation order. - */ - private static volatile McpClientResource instance; - - private volatile ToolRegistration toolRegistration; - - record ToolRegistration(ToolExecutor executor, List> definitions) {} - - public static McpClientResource getInstance() { - return instance; - } - - @Getter - @Setter - public static class ChatRequest { - private UUID conversationId; - - @NotBlank - @Size(max = 100000) - private String message; - } - - public static class McpConversationList extends ResultList {} - - public static class McpMessageList extends ResultList {} - - public McpClientResource(Authorizer authorizer, Limits limits) { - instance = this; - } - - public void registerToolExecutor( - ToolExecutor toolExecutor, List> toolDefinitions) { - this.toolRegistration = new ToolRegistration(toolExecutor, toolDefinitions); - } - - @GET - @Path("/enabled") - @Operation( - operationId = "isMcpChatEnabled", - summary = "Whether MCP Chat is enabled", - description = - "Returns whether the MCP Chat assistant is enabled in AI settings. Readable by any" - + " authenticated user so the UI can gate the chat entry point.") - public Response isEnabled() { - return Response.ok(Map.of("enabled", McpChatServiceHolder.isEnabled())).build(); - } - - @POST - @Path("/chat") - @Operation( - operationId = "mcpClientChat", - summary = "Chat with the MCP assistant", - description = "Send a message and get a response from the MCP-powered AI assistant.", - responses = { - @ApiResponse( - responseCode = "200", - description = "Chat response", - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = ChatResponse.class))), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public Response chat(@Context SecurityContext securityContext, @Valid ChatRequest request) { - ChatResponse response = - getService().chat(securityContext, request.getConversationId(), request.getMessage()); - return Response.ok(response).build(); - } - - @POST - @Path("/chat/stream") - @Produces("text/event-stream") - @Operation( - operationId = "mcpClientChatStream", - summary = "Chat with the MCP assistant (streaming)", - description = "Send a message and get a streaming response via Server-Sent Events.", - responses = { - @ApiResponse( - responseCode = "200", - description = "SSE event stream", - content = @Content(mediaType = "text/event-stream")), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public Response chatStream(@Context SecurityContext securityContext, @Valid ChatRequest request) { - McpClientService service = getService(); - StreamingOutput streamingOutput = - output -> emitChatStream(service, securityContext, request, output); - return Response.ok(streamingOutput) - .type("text/event-stream") - .header("Cache-Control", "no-cache") - .header("X-Accel-Buffering", "no") - .build(); - } - - private static void emitChatStream( - McpClientService service, - SecurityContext securityContext, - ChatRequest request, - OutputStream output) { - try { - service.chatStream( - securityContext, - request.getConversationId(), - request.getMessage(), - event -> writeSseEvent(output, event.event(), event.data())); - } catch (ClientDisconnectedException e) { - LOG.info("MCP chat stream ended: client disconnected"); - } catch (RuntimeException e) { - LOG.error("MCP chat stream failed", e); - writeSseEventQuietly(output, "error", ChatEvent.error(e.getMessage()).data()); - writeSseEventQuietly(output, "done", ChatEvent.done().data()); - } - } - - @POST - @Path("/conversations") - @Operation( - operationId = "createMcpConversation", - summary = "Create a new conversation", - description = "Create a new empty MCP conversation.", - responses = { - @ApiResponse( - responseCode = "201", - description = "Conversation created", - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = McpConversation.class))), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public Response createConversation( - @Context SecurityContext securityContext, @Valid CreateMcpConversation request) { - McpConversation conversation = getService().createConversation(securityContext, request); - return Response.status(Response.Status.CREATED).entity(conversation).build(); - } - - @GET - @Path("/conversations") - @Operation( - operationId = "listMcpConversations", - summary = "List conversations", - description = "List MCP conversations for the authenticated user.", - responses = { - @ApiResponse( - responseCode = "200", - description = "List of conversations", - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = McpConversationList.class))) - }) - public ResultList listConversations( - @Context SecurityContext securityContext, - @Parameter(description = "Limit the number of conversations returned") - @DefaultValue("20") - @Min(1) - @Max(100) - @QueryParam("limit") - int limit, - @Parameter(description = "Offset for pagination") - @DefaultValue("0") - @Min(0) - @QueryParam("offset") - int offset) { - McpClientService service = getService(); - List conversations = service.listConversations(securityContext, limit, offset); - int total = service.getConversationCount(securityContext); - return new ResultList<>(conversations, offset, total); - } - - @GET - @Path("/conversations/{id}") - @Operation( - operationId = "getMcpConversation", - summary = "Get a conversation", - description = "Get a conversation with its messages populated.", - responses = { - @ApiResponse( - responseCode = "200", - description = "The conversation", - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = McpConversation.class))), - @ApiResponse(responseCode = "404", description = "Conversation not found") - }) - public McpConversation getConversation( - @Context SecurityContext securityContext, - @Parameter(description = "Id of the conversation", schema = @Schema(type = "UUID")) - @PathParam("id") - UUID id) { - return getService().getConversationWithMessages(securityContext, id); - } - - @GET - @Path("/conversations/{id}/messages") - @Operation( - operationId = "listMcpMessages", - summary = "List messages in a conversation", - description = "List messages for a given conversation.", - responses = { - @ApiResponse( - responseCode = "200", - description = "List of messages", - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = McpMessageList.class))), - @ApiResponse(responseCode = "404", description = "Conversation not found") - }) - public ResultList listMessages( - @Context SecurityContext securityContext, - @Parameter(description = "Id of the conversation", schema = @Schema(type = "UUID")) - @PathParam("id") - UUID id, - @Parameter(description = "Limit the number of messages returned") - @DefaultValue("50") - @Min(1) - @Max(1000) - @QueryParam("limit") - int limit, - @Parameter(description = "Offset for pagination") - @DefaultValue("0") - @Min(0) - @QueryParam("offset") - int offset) { - McpClientService service = getService(); - List messages = service.listMessages(securityContext, id, limit, offset); - int total = service.getMessageCount(securityContext, id); - return new ResultList<>(messages, offset, total); - } - - @DELETE - @Path("/conversations/{id}") - @Operation( - operationId = "deleteMcpConversation", - summary = "Delete a conversation", - description = "Delete a conversation and all its messages.", - responses = { - @ApiResponse(responseCode = "204", description = "Conversation deleted"), - @ApiResponse(responseCode = "404", description = "Conversation not found") - }) - public Response deleteConversation( - @Context SecurityContext securityContext, - @Parameter(description = "Id of the conversation", schema = @Schema(type = "UUID")) - @PathParam("id") - UUID id) { - getService().deleteConversation(securityContext, id); - return Response.noContent().build(); - } - - private McpClientService getService() { - if (!McpChatServiceHolder.isEnabled()) { - throw new WebApplicationException( - Response.status(Response.Status.SERVICE_UNAVAILABLE) - .entity(Map.of("message", "MCP Chat is not enabled. Enable it in AI Settings.")) - .build()); - } - McpClientService service = McpChatServiceHolder.get(); - if (service == null) { - throw new WebApplicationException( - Response.status(Response.Status.SERVICE_UNAVAILABLE) - .entity(Map.of("message", "MCP Chat service is initializing. Please try again.")) - .build()); - } - - ToolRegistration reg = this.toolRegistration; - if (reg != null) { - service.updateTools(reg.executor(), reg.definitions()); - } - - return service; - } - - private static void writeSseEvent(OutputStream output, String event, Object data) { - try { - String json = JsonUtils.pojoToJson(data); - String frame = "event: " + event + "\ndata: " + json + "\n\n"; - output.write(frame.getBytes(StandardCharsets.UTF_8)); - output.flush(); - } catch (IOException e) { - throw new ClientDisconnectedException("Failed to write SSE '" + event + "' event", e); - } - } - - private static void writeSseEventQuietly(OutputStream output, String event, Object data) { - try { - writeSseEvent(output, event, data); - } catch (ClientDisconnectedException e) { - LOG.debug("Could not write final SSE '{}' event; client already disconnected", event, e); - } - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/metrics/MetricMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/metrics/MetricMapper.java index 942a55bf3089..5acd73154cc8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/metrics/MetricMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/metrics/MetricMapper.java @@ -17,6 +17,9 @@ public Metric createToEntity(CreateMetric create, String user) { .withAssets(create.getAssets()) .withMetricType(create.getMetricType()) .withUnitOfMeasurement(create.getUnitOfMeasurement()) - .withCustomUnitOfMeasurement(create.getCustomUnitOfMeasurement()); + .withCustomUnitOfMeasurement(create.getCustomUnitOfMeasurement()) + .withDimensions(create.getDimensions()) + .withMeasures(create.getMeasures()) + .withFilters(create.getFilters()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/dashboard/DashboardServiceMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/dashboard/DashboardServiceMapper.java index 045e8b6a2c32..b8ffec6fe904 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/dashboard/DashboardServiceMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/dashboard/DashboardServiceMapper.java @@ -10,6 +10,7 @@ public class DashboardServiceMapper public DashboardService createToEntity(CreateDashboardService create, String user) { return copy(new DashboardService(), create, user) .withServiceType(create.getServiceType()) + .withStyle(create.getStyle()) .withConnection(create.getConnection()) .withIngestionRunner(create.getIngestionRunner()); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/database/DatabaseServiceMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/database/DatabaseServiceMapper.java index ba5a3c66167c..c7c358aa9645 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/database/DatabaseServiceMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/database/DatabaseServiceMapper.java @@ -9,6 +9,7 @@ public class DatabaseServiceMapper implements EntityMapper aiJsonDataFiles = - EntityUtil.getJsonDataResources(".*json/data/settings/aiSettings.json$"); - if (!aiJsonDataFiles.isEmpty()) { - String aiJson = - CommonUtil.getResourceAsStream( - EntityRepository.class.getClassLoader(), aiJsonDataFiles.get(0)); - AISettings defaultAiSettings = JsonUtils.readValue(aiJson, AISettings.class); - if (storedAiSettings == null) { - Settings setting = - new Settings().withConfigType(AI_SETTINGS).withConfigValue(defaultAiSettings); - Entity.getSystemRepository().createNewSetting(setting); - } else { - AISettings existingAiSettings = - JsonUtils.convertValue(storedAiSettings.getConfigValue(), AISettings.class); - AISettings mergedAiSettings = - new AISettingsHandler().mergeAISettings(defaultAiSettings, existingAiSettings); - if (!JsonUtils.pojoToJson(mergedAiSettings) - .equals(JsonUtils.pojoToJson(existingAiSettings))) { - storedAiSettings.setConfigValue(mergedAiSettings); - Entity.getSystemRepository().createOrUpdate(storedAiSettings); - } - } - } - } catch (IOException e) { - LOG.error("Failed to read default AI settings. Message: {}", e.getMessage(), e); - } - // Initialise Certification Settings Settings certificationSettings = Entity.getSystemRepository().getConfigWithKey(ASSET_CERTIFICATION_SETTINGS.toString()); @@ -328,12 +294,13 @@ private static void createDefaultConfiguration(OpenMetadataApplicationConfig app Entity.getSystemRepository().getConfigWithKey(MCP_CONFIGURATION.toString()); if (storedMcpConfig == null) { org.openmetadata.schema.api.configuration.MCPConfiguration mcpConfig = - applicationConfig.getMcpConfiguration() != null - ? applicationConfig.getMcpConfiguration() - : new org.openmetadata.schema.api.configuration.MCPConfiguration(); - Settings setting = - new Settings().withConfigType(MCP_CONFIGURATION).withConfigValue(mcpConfig); - Entity.getSystemRepository().createNewSetting(setting); + applicationConfig.getMcpConfiguration(); + if (mcpConfig != null) { + Settings setting = + new Settings().withConfigType(MCP_CONFIGURATION).withConfigValue(mcpConfig); + + Entity.getSystemRepository().createNewSetting(setting); + } } Settings storedScimConfig = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/AISettingsHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/AISettingsHandler.java deleted file mode 100644 index 2f5f9a431ef6..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/AISettingsHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2021 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.resources.system; - -import org.openmetadata.schema.configuration.AIPrompts; -import org.openmetadata.schema.configuration.AISettings; -import org.openmetadata.schema.configuration.McpChatSettings; -import org.openmetadata.schema.configuration.MemoryAgentSettings; -import org.openmetadata.schema.configuration.MemoryExtractionSettings; -import org.openmetadata.schema.configuration.PromptConfig; - -public class AISettingsHandler { - - public void validateAISettings(AISettings settings) { - // No numeric ranges to validate; structural validity is enforced by the schema. - } - - public AISettings mergeAISettings(AISettings defaults, AISettings incoming) { - AISettings result = defaults; - if (incoming != null) { - result = - new AISettings() - .withEnabled(firstNonNull(incoming.getEnabled(), defaults.getEnabled())) - .withMemoryExtraction( - mergeExtraction(defaults.getMemoryExtraction(), incoming.getMemoryExtraction())) - .withMemoryAgent(mergeAgent(defaults.getMemoryAgent(), incoming.getMemoryAgent())) - .withPrompts(mergePrompts(defaults.getPrompts(), incoming.getPrompts())) - .withMcpChat(mergeMcpChat(defaults.getMcpChat(), incoming.getMcpChat())); - } - return result; - } - - private McpChatSettings mergeMcpChat(McpChatSettings d, McpChatSettings i) { - McpChatSettings result = d; - if (i != null) { - result = - new McpChatSettings() - .withEnabled(firstNonNull(i.getEnabled(), d == null ? null : d.getEnabled())) - .withSystemPrompt( - firstNonNull(i.getSystemPrompt(), d == null ? null : d.getSystemPrompt())); - } - return result; - } - - private MemoryExtractionSettings mergeExtraction( - MemoryExtractionSettings d, MemoryExtractionSettings i) { - MemoryExtractionSettings result = d; - if (i != null) { - result = - new MemoryExtractionSettings() - .withFromFiles(firstNonNull(i.getFromFiles(), d == null ? null : d.getFromFiles())) - .withFromPages(firstNonNull(i.getFromPages(), d == null ? null : d.getFromPages())); - } - return result; - } - - private MemoryAgentSettings mergeAgent(MemoryAgentSettings d, MemoryAgentSettings i) { - MemoryAgentSettings result = d; - if (i != null) { - result = - new MemoryAgentSettings() - .withEnabled(firstNonNull(i.getEnabled(), d == null ? null : d.getEnabled())) - .withDeriveGlossaryTerms( - firstNonNull( - i.getDeriveGlossaryTerms(), d == null ? null : d.getDeriveGlossaryTerms())) - .withDeriveMetrics( - firstNonNull(i.getDeriveMetrics(), d == null ? null : d.getDeriveMetrics())) - .withDeletionPolicy( - firstNonNull(i.getDeletionPolicy(), d == null ? null : d.getDeletionPolicy())); - } - return result; - } - - private AIPrompts mergePrompts(AIPrompts d, AIPrompts i) { - AIPrompts result = d; - if (i != null) { - result = - new AIPrompts() - .withMemoryExtraction( - mergePrompt(d == null ? null : d.getMemoryExtraction(), i.getMemoryExtraction())) - .withMemoryAgent( - mergePrompt(d == null ? null : d.getMemoryAgent(), i.getMemoryAgent())); - } - return result; - } - - private PromptConfig mergePrompt(PromptConfig d, PromptConfig i) { - PromptConfig result = d; - if (i != null && i.getSystemPrompt() != null) { - result = new PromptConfig().withSystemPrompt(i.getSystemPrompt()); - } - return result; - } - - private X firstNonNull(X a, X b) { - return a != null ? a : b; - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SearchSettingsHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SearchSettingsHandler.java index e1996fd3dea7..7895781cb8f8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SearchSettingsHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SearchSettingsHandler.java @@ -3,11 +3,15 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import org.openmetadata.schema.api.search.AssetTypeConfiguration; import org.openmetadata.schema.api.search.FieldBoost; import org.openmetadata.schema.api.search.GlobalSettings; +import org.openmetadata.schema.api.search.RankingConfiguration; +import org.openmetadata.schema.api.search.RankingStage; import org.openmetadata.schema.api.search.SearchSettings; +import org.openmetadata.schema.api.search.StopWordsByLanguage; import org.openmetadata.service.exception.SystemSettingsException; public class SearchSettingsHandler { @@ -22,6 +26,10 @@ public void validateSearchSettings(SearchSettings searchSettings) { // Validate global settings validateGlobalSettings(searchSettings.getGlobalSettings()); + if (searchSettings.getDefaultConfiguration() != null) { + validateAssetTypeConfiguration(searchSettings.getDefaultConfiguration()); + } + // Validate asset type configurations for duplicate fields if (searchSettings.getAssetTypeConfigurations() != null) { for (AssetTypeConfiguration assetConfig : searchSettings.getAssetTypeConfigurations()) { @@ -46,6 +54,71 @@ public void validateAssetTypeConfiguration(AssetTypeConfiguration assetConfig) { validateExtensionField(fieldName, assetConfig.getAssetType()); } } + validateRanking(assetConfig.getRanking(), assetConfig.getAssetType()); + } + + private void validateRanking(RankingConfiguration ranking, String assetType) { + if (ranking == null || Boolean.FALSE.equals(ranking.getEnabled())) { + return; + } + if (ranking.getStages() == null || ranking.getStages().isEmpty()) { + throw new SystemSettingsException( + String.format("Ranking stages cannot be empty for asset type: %s", assetType)); + } + + Set stageNames = new HashSet<>(); + for (RankingStage stage : ranking.getStages()) { + if (stage.getName() == null || stage.getName().trim().isEmpty()) { + throw new SystemSettingsException( + String.format("Ranking stage name cannot be empty for asset type: %s", assetType)); + } + if (!stageNames.add(stage.getName())) { + throw new SystemSettingsException( + String.format( + "Duplicate ranking stage found for stage: %s in asset type: %s", + stage.getName(), assetType)); + } + if (stage.getFields() == null || stage.getFields().isEmpty()) { + throw new SystemSettingsException( + String.format( + "Ranking stage %s must define at least one field for asset type: %s", + stage.getName(), assetType)); + } + if (stage.getWeight() != null && stage.getWeight() <= 0.0) { + throw new SystemSettingsException( + String.format( + "Ranking stage %s weight must be greater than zero for asset type: %s", + stage.getName(), assetType)); + } + } + validateStopWordsByLanguage(ranking, assetType); + if (ranking.getSignals() != null + && ranking.getSignals().getMaxBoost() != null + && ranking.getSignals().getMaxBoost() <= 0.0) { + throw new SystemSettingsException( + String.format("Ranking signal maxBoost must be positive for asset type: %s", assetType)); + } + } + + private void validateStopWordsByLanguage(RankingConfiguration ranking, String assetType) { + StopWordsByLanguage stopWordsByLanguage = ranking.getStopWordsByLanguage(); + if (stopWordsByLanguage == null || stopWordsByLanguage.getAdditionalProperties() == null) { + return; + } + for (Map.Entry> entry : + stopWordsByLanguage.getAdditionalProperties().entrySet()) { + if (entry.getKey() == null || entry.getKey().trim().isEmpty()) { + throw new SystemSettingsException( + String.format( + "Ranking stopword language cannot be empty for asset type: %s", assetType)); + } + if (entry.getValue() == null) { + throw new SystemSettingsException( + String.format( + "Ranking stopwords cannot be null for language: %s in asset type: %s", + entry.getKey(), assetType)); + } + } } private void validateExtensionField(String fieldName, String assetType) { @@ -212,6 +285,11 @@ public SearchSettings mergeSearchSettings( if (incomingSearchSettings.getDefaultConfiguration() == null) { incomingSearchSettings.setDefaultConfiguration( defaultSearchSettings.getDefaultConfiguration()); + } else if (incomingSearchSettings.getDefaultConfiguration().getRanking() == null + && defaultSearchSettings.getDefaultConfiguration() != null) { + incomingSearchSettings + .getDefaultConfiguration() + .setRanking(defaultSearchSettings.getDefaultConfiguration().getRanking()); } // Merge asset type configurations diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SystemResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SystemResource.java index c912b5f7052a..589f6a757395 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SystemResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SystemResource.java @@ -1,7 +1,6 @@ package org.openmetadata.service.resources.system; import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; -import static org.openmetadata.schema.settings.SettingsType.AI_SETTINGS; import static org.openmetadata.schema.settings.SettingsType.AUTHENTICATION_CONFIGURATION; import static org.openmetadata.schema.settings.SettingsType.AUTHORIZER_CONFIGURATION; import static org.openmetadata.schema.settings.SettingsType.GLOSSARY_TERM_RELATION_SETTINGS; @@ -59,11 +58,9 @@ import org.openmetadata.schema.api.search.SearchSettings; import org.openmetadata.schema.api.security.AuthenticationConfiguration; import org.openmetadata.schema.auth.EmailRequest; -import org.openmetadata.schema.configuration.AISettings; import org.openmetadata.schema.configuration.EntityRulesSettings; import org.openmetadata.schema.configuration.GlossaryTermRelationSettings; import org.openmetadata.schema.configuration.GlossaryTermRelationType; -import org.openmetadata.schema.configuration.McpChatSettings; import org.openmetadata.schema.configuration.RelationCardinality; import org.openmetadata.schema.configuration.SecurityConfiguration; import org.openmetadata.schema.settings.Settings; @@ -86,7 +83,6 @@ import org.openmetadata.service.cache.CacheConfig; import org.openmetadata.service.cache.CacheMetrics; import org.openmetadata.service.cache.CacheProvider; -import org.openmetadata.service.clients.llm.LlmConfigHolder; import org.openmetadata.service.clients.pipeline.PipelineServiceClientFactory; import org.openmetadata.service.exception.SystemSettingsException; import org.openmetadata.service.exception.UnhandledServerException; @@ -94,7 +90,6 @@ import org.openmetadata.service.jdbi3.GlossaryTermRepository; import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.jdbi3.SystemRepository; -import org.openmetadata.service.mcpclient.McpChatServiceHolder; import org.openmetadata.service.monitoring.LatencyPhase; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.resources.settings.SettingsCache; @@ -141,7 +136,6 @@ public class SystemResource { private JwtFilter jwtFilter; private SearchSettings defaultSearchSettingsCache = new SearchSettings(); private final SearchSettingsHandler searchSettingsHandler = new SearchSettingsHandler(); - private final AISettingsHandler aiSettingsHandler = new AISettingsHandler(); private boolean isNlqEnabled = false; public SystemResource(Authorizer authorizer) { @@ -208,18 +202,6 @@ public SearchSettings loadDefaultSearchSettings(boolean force) { return searchSettings; } - public AISettings loadDefaultAiSettings() throws IOException { - List jsonDataFiles = - EntityUtil.getJsonDataResources(".*json/data/settings/aiSettings.json$"); - if (jsonDataFiles.isEmpty()) { - throw new IllegalArgumentException("Default AI settings file not found."); - } - String json = - CommonUtil.getResourceAsStream( - EntityRepository.class.getClassLoader(), jsonDataFiles.get(0)); - return JsonUtils.readValue(json, AISettings.class); - } - @GET @Path("/settings") @Operation( @@ -615,36 +597,12 @@ public Response createOrUpdateSetting( settingName.setConfigValue(relationSettings); validateGlossaryTermRelationSettingsUpdate(settingName); } - - if (AI_SETTINGS.value().equalsIgnoreCase(settingName.getConfigType().toString())) { - try { - AISettings defaults = loadDefaultAiSettings(); - AISettings incoming = - JsonUtils.convertValue(settingName.getConfigValue(), AISettings.class); - aiSettingsHandler.validateAISettings(incoming); - settingName.setConfigValue(aiSettingsHandler.mergeAISettings(defaults, incoming)); - } catch (IOException e) { - LOG.error("Failed to read default AI settings. Message: {}", e.getMessage(), e); - throw new SystemSettingsException("Failed to load default AI settings: " + e.getMessage()); - } - } - Response response = systemRepository.createOrUpdate(settingName); SettingsCache.invalidateSettings(settingName.getConfigType().value()); - reinitMcpChatServiceIfNeeded(settingName.getConfigType()); return response; } - private void reinitMcpChatServiceIfNeeded(SettingsType configType) { - if (configType == AI_SETTINGS) { - AISettings aiSettings = - SettingsCache.getSettingOrDefault(AI_SETTINGS, null, AISettings.class); - McpChatSettings mcpChat = aiSettings == null ? null : aiSettings.getMcpChat(); - McpChatServiceHolder.initialize(LlmConfigHolder.get(), mcpChat); - } - } - @PUT @Path("/settings/reset/{name}") @Operation( @@ -675,26 +633,11 @@ public Response resetSettingToDefault( authorizer.authorizeAdmin(securityContext); - Object defaults; - if (SettingsType.SEARCH_SETTINGS.value().equalsIgnoreCase(name)) { - defaults = loadDefaultSearchSettings(true); - } else if (AI_SETTINGS.value().equalsIgnoreCase(name)) { - try { - AISettings defaultAiSettings = loadDefaultAiSettings(); - Settings setting = - new Settings().withConfigType(AI_SETTINGS).withConfigValue(defaultAiSettings); - systemRepository.createOrUpdate(setting); - SettingsCache.invalidateSettings(AI_SETTINGS.value()); - reinitMcpChatServiceIfNeeded(AI_SETTINGS); - defaults = defaultAiSettings; - } catch (IOException e) { - LOG.error("Failed to read default AI settings. Message: {}", e.getMessage(), e); - throw new SystemSettingsException("Failed to load default AI settings: " + e.getMessage()); - } - } else { + if (!SettingsType.SEARCH_SETTINGS.value().equalsIgnoreCase(name)) { throw new SystemSettingsException("Resetting of setting '" + name + "' is not supported."); } - return Response.ok(defaults).build(); + SearchSettings settings = loadDefaultSearchSettings(true); + return Response.ok(settings).build(); } @PUT diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java index 87c9ef2c7d61..cec12d29c93d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java @@ -616,12 +616,19 @@ public ResultList listMyVisibleTasks( String before, @Parameter(description = "Returns list of tasks after this cursor") @QueryParam("after") String after, + @Parameter(description = "Filter by tasks created on or after this timestamp (epoch millis)") + @QueryParam("startTs") + Long startTs, + @Parameter(description = "Filter by tasks created on or before this timestamp (epoch millis)") + @QueryParam("endTs") + Long endTs, @Parameter(description = "Include deleted tasks") @QueryParam("include") @DefaultValue("non-deleted") Include include) { ListFilter filter = buildTaskListFilter(include, status, statusGroup, domain); addCurrentUserVisibleFilters(filter, uriInfo, securityContext); + applyTaskTimeRange(filter, startTs, endTs); return listInternal(uriInfo, securityContext, fieldsParam, filter, limitParam, before, after); } @@ -667,6 +674,12 @@ public ResultList listMyOwnedTasks( String before, @Parameter(description = "Returns list of tasks after this cursor") @QueryParam("after") String after, + @Parameter(description = "Filter by tasks created on or after this timestamp (epoch millis)") + @QueryParam("startTs") + Long startTs, + @Parameter(description = "Filter by tasks created on or before this timestamp (epoch millis)") + @QueryParam("endTs") + Long endTs, @Parameter(description = "Include deleted tasks") @QueryParam("include") @DefaultValue("non-deleted") @@ -685,6 +698,7 @@ public ResultList listMyOwnedTasks( ListFilter filter = buildTaskListFilter(include, status, statusGroup, domain); filter.addQueryParam("ownedByIds", String.join(",", ownerIds)); + applyTaskTimeRange(filter, startTs, endTs); return listInternal(uriInfo, securityContext, fieldsParam, filter, limitParam, before, after); } @@ -728,6 +742,12 @@ public ResultList listMyCreatedTasks( String before, @Parameter(description = "Returns list of tasks after this cursor") @QueryParam("after") String after, + @Parameter(description = "Filter by tasks created on or after this timestamp (epoch millis)") + @QueryParam("startTs") + Long startTs, + @Parameter(description = "Filter by tasks created on or before this timestamp (epoch millis)") + @QueryParam("endTs") + Long endTs, @Parameter(description = "Include deleted tasks") @QueryParam("include") @DefaultValue("non-deleted") @@ -737,6 +757,7 @@ public ResultList listMyCreatedTasks( ListFilter filter = buildTaskListFilter(include, status, statusGroup, domain); filter.addQueryParam("createdById", user.getId().toString()); + applyTaskTimeRange(filter, startTs, endTs); return listInternal(uriInfo, securityContext, fieldsParam, filter, limitParam, before, after); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaMapper.java index 28c357eb08d6..ca7528bc4b6b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaMapper.java @@ -11,6 +11,7 @@ public class PersonaMapper implements EntityMapper { public Persona createToEntity(CreatePersona create, String user) { return copy(new Persona(), create, user) .withUsers(EntityUtil.validateToEntityReferences(create.getUsers(), Entity.USER)) + .withContextDefinition(create.getContextDefinition()) .withDefault(create.getDefault()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaResource.java index 3c9b4cd8a2c6..f65d1b43136b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/teams/PersonaResource.java @@ -14,6 +14,7 @@ package org.openmetadata.service.resources.teams; import static org.openmetadata.common.utils.CommonUtil.listOf; +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import io.dropwizard.jersey.PATCH; import io.swagger.v3.oas.annotations.ExternalDocumentation; @@ -31,6 +32,8 @@ import jakarta.validation.constraints.Min; import jakarta.ws.rs.*; import jakarta.ws.rs.core.*; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.List; import java.util.UUID; import lombok.extern.slf4j.Slf4j; @@ -39,8 +42,18 @@ import org.openmetadata.schema.type.EntityHistory; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.PersonaContext; +import org.openmetadata.schema.type.PersonaContextDefinition; +import org.openmetadata.schema.type.personaContext.ContextRule; +import org.openmetadata.schema.type.personaContext.PersonaContextCacheState; +import org.openmetadata.schema.type.personaContext.RuleResult; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; +import org.openmetadata.service.aicontext.AIContextMarkdown; +import org.openmetadata.service.aicontext.PersonaContextAccess; +import org.openmetadata.service.aicontext.PersonaContextBuilder; +import org.openmetadata.service.aicontext.PersonaContextCache; import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.jdbi3.PersonaRepository; import org.openmetadata.service.limits.Limits; @@ -61,7 +74,7 @@ public class PersonaResource extends EntityResource { private final PersonaMapper mapper = new PersonaMapper(); public static final String COLLECTION_PATH = "/v1/personas"; - static final String FIELDS = "users"; + static final String FIELDS = "users,contextDefinition"; @Override public Persona addHref(UriInfo uriInfo, Persona persona) { @@ -238,6 +251,361 @@ public Persona getByName( return getByNameInternal(uriInfo, securityContext, name, fieldsParam, include); } + @GET + @Path("/{id}/aiContext") + @Operation( + operationId = "getPersonaAiContextConfiguration", + summary = "Get a persona AI context configuration") + public PersonaContextDefinition getAiContextConfiguration( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id) { + authorizer.authorizeAdmin(securityContext); + return configurationWithDerivedState(getPersona(uriInfo, id)); + } + + @PUT + @Path("/{id}/aiContext") + @Operation( + operationId = "updatePersonaAiContextConfiguration", + summary = "Update persona AI context settings") + public PersonaContextDefinition updateAiContextConfiguration( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id, + @Valid PersonaContextDefinition requested) { + authorizer.authorizeAdmin(securityContext); + Persona original = getPersona(uriInfo, id); + PersonaContextDefinition definition = editableDefinition(original); + definition.setEnabled(requested.getEnabled()); + definition.setCharacterBudget(requested.getCharacterBudget()); + definition.setCacheTtlMinutes(requested.getCacheTtlMinutes()); + Persona updated = persistDefinition(uriInfo, securityContext, original, definition); + PersonaContextCache.getInstance().refreshAsync(updated); + return configurationWithDerivedState(updated); + } + + @POST + @Path("/{id}/aiContext/rules") + @Operation( + operationId = "createPersonaAiContextRule", + summary = "Create a persona AI context rule") + public PersonaContextDefinition createAiContextRule( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id, + @Valid ContextRule requestedRule) { + authorizer.authorizeAdmin(securityContext); + Persona original = getPersona(uriInfo, id); + PersonaContextDefinition definition = editableDefinition(original); + ContextRule rule = sanitizedRule(requestedRule); + rule.setId(UUID.randomUUID()); + List rules = new ArrayList<>(listOrEmpty(definition.getRules())); + rules.add(rule); + definition.setRules(rules); + Persona updated = persistDefinition(uriInfo, securityContext, original, definition); + PersonaContextCache.getInstance().refreshAsync(updated); + return configurationWithDerivedState(updated); + } + + @PUT + @Path("/{id}/aiContext/rules/{ruleId:[0-9a-fA-F\\-]{36}}") + @Operation( + operationId = "updatePersonaAiContextRule", + summary = "Update a persona AI context rule") + public PersonaContextDefinition updateAiContextRule( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id, + @PathParam("ruleId") UUID ruleId, + @Valid ContextRule requestedRule) { + authorizer.authorizeAdmin(securityContext); + Persona original = getPersona(uriInfo, id); + PersonaContextDefinition definition = editableDefinition(original); + List rules = new ArrayList<>(listOrEmpty(definition.getRules())); + int ruleIndex = findRule(rules, ruleId); + ContextRule rule = sanitizedRule(requestedRule); + rule.setId(ruleId); + rules.set(ruleIndex, rule); + definition.setRules(rules); + Persona updated = persistDefinition(uriInfo, securityContext, original, definition); + PersonaContextCache.getInstance().refreshAsync(updated); + return configurationWithDerivedState(updated); + } + + @DELETE + @Path("/{id}/aiContext/rules/{ruleId:[0-9a-fA-F\\-]{36}}") + @Operation( + operationId = "deletePersonaAiContextRule", + summary = "Delete a persona AI context rule") + public PersonaContextDefinition deleteAiContextRule( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id, + @PathParam("ruleId") UUID ruleId) { + authorizer.authorizeAdmin(securityContext); + Persona original = getPersona(uriInfo, id); + PersonaContextDefinition definition = editableDefinition(original); + List rules = new ArrayList<>(listOrEmpty(definition.getRules())); + rules.remove(findRule(rules, ruleId)); + definition.setRules(rules); + Persona updated = persistDefinition(uriInfo, securityContext, original, definition); + PersonaContextCache.getInstance().refreshAsync(updated); + return configurationWithDerivedState(updated); + } + + @POST + @Path("/{id}/aiContext/rules/preview") + @Operation( + operationId = "previewPersonaAiContextRule", + summary = "Preview the entities matched by a persona AI context rule") + public PersonaContextBuilder.RulePreview previewAiContextRule( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id, + @Valid ContextRule rule) { + authorizer.authorizeAdmin(securityContext); + getPersona(uriInfo, id); + return PersonaContextBuilder.preview(rule); + } + + @GET + @Path("/{id}/aiContext/document") + @Operation( + operationId = "getPersonaAiContextDocument", + summary = "Get the compiled persona AI context document") + public Response getAiContextDocument( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id) { + authorizer.authorizeAdmin(securityContext); + Persona persona = getPersona(uriInfo, id); + PersonaContextCache.CachedResult cached = PersonaContextCache.getInstance().get(persona, false); + return documentResponse(cached); + } + + @POST + @Path("/{id}/aiContext/document:refresh") + @Operation( + operationId = "refreshPersonaAiContextDocument", + summary = "Force recompilation of a persona AI context document") + public Response refreshAiContextDocument( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @PathParam("id") UUID id) { + authorizer.authorizeAdmin(securityContext); + Persona persona = getPersona(uriInfo, id); + return documentResponse(PersonaContextCache.getInstance().refresh(persona)); + } + + @Override + @GET + @Path("/{id}/context") + @Produces({AIContextMarkdown.TEXT_MARKDOWN, MediaType.APPLICATION_JSON}) + @Operation( + operationId = "getPersonaContextById", + summary = "Get the materialized AI context for a persona by id", + description = + "Materialize every enabled persona context rule into one cached markdown document, or " + + "return the structured result with `?format=json`.") + public Response getAiContextById( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @Parameter(description = "Persona id", required = true) @PathParam("id") UUID id, + @Parameter(description = "Output format: markdown (default) or json") + @QueryParam("format") + @DefaultValue("markdown") + String format, + @Parameter(description = "Bypass the cached materialization; admin and bot only") + @QueryParam("refresh") + @DefaultValue("false") + String refresh) { + Persona persona = + Entity.getEntity(Entity.PERSONA, id, "contextDefinition,users", Include.NON_DELETED); + return renderPersonaContext(persona, securityContext, format, Boolean.parseBoolean(refresh)); + } + + @Override + @GET + @Path("/name/{fqn}/context") + @Produces({AIContextMarkdown.TEXT_MARKDOWN, MediaType.APPLICATION_JSON}) + @Operation( + operationId = "getPersonaContextByName", + summary = "Get the materialized AI context for a persona by name") + public Response getAiContextByName( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @Parameter(description = "Persona fully qualified name", required = true) @PathParam("fqn") + String fqn, + @Parameter(description = "Output format: markdown (default) or json") + @QueryParam("format") + @DefaultValue("markdown") + String format, + @Parameter(description = "Bypass the cached materialization; admin and bot only") + @QueryParam("refresh") + @DefaultValue("false") + String refresh) { + Persona persona = + Entity.getEntityByName(Entity.PERSONA, fqn, "contextDefinition,users", Include.NON_DELETED); + return renderPersonaContext(persona, securityContext, format, Boolean.parseBoolean(refresh)); + } + + @GET + @Path("/me/context") + @Produces({AIContextMarkdown.TEXT_MARKDOWN, MediaType.APPLICATION_JSON}) + @Operation( + operationId = "getMyPersonaContext", + summary = "Get the materialized AI context for the caller's active persona") + public Response getMyPersonaContext( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @Parameter(description = "Output format: markdown (default) or json") + @QueryParam("format") + @DefaultValue("markdown") + String format, + @Parameter(description = "Bypass the cached materialization; admin and bot only") + @QueryParam("refresh") + @DefaultValue("false") + String refresh) { + Persona persona = PersonaContextAccess.activePersona(securityContext); + return renderPersonaContext(persona, securityContext, format, Boolean.parseBoolean(refresh)); + } + + private Response renderPersonaContext( + Persona persona, SecurityContext securityContext, String format, boolean refresh) { + PersonaContextAccess.authorize(securityContext, persona); + if (refresh) { + PersonaContextAccess.authorizeRefresh(securityContext); + } + PersonaContextCache.CachedResult cached = + refresh + ? PersonaContextCache.getInstance().refresh(persona) + : PersonaContextCache.getInstance().get(persona, false); + PersonaContextBuilder.MaterializedPersonaContext value = cached.value(); + Response.ResponseBuilder response = + AIContextMarkdown.FORMAT_JSON.equalsIgnoreCase(format) + ? Response.ok(value.context(), MediaType.APPLICATION_JSON_TYPE) + : Response.ok(value.markdown(), AIContextMarkdown.TEXT_MARKDOWN); + return response.header(PersonaContextCache.CACHE_HEADER, cached.status().name()).build(); + } + + private Persona getPersona(UriInfo uriInfo, UUID id) { + return repository.get(uriInfo, id, getFields(FIELDS), Include.NON_DELETED, false); + } + + private PersonaContextDefinition editableDefinition(Persona persona) { + PersonaContextDefinition definition = + persona.getContextDefinition() == null + ? new PersonaContextDefinition() + : JsonUtils.deepCopy(persona.getContextDefinition(), PersonaContextDefinition.class); + List rules = new ArrayList<>(listOrEmpty(definition.getRules())); + for (int index = 0; index < rules.size(); index++) { + ContextRule rule = rules.get(index); + if (rule.getId() == null) { + String seed = persona.getId() + ":" + index + ":" + rule.getName(); + rule.setId(UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8))); + } + rule.setMatchedCount(null); + } + definition.setRules(rules); + definition.setLastGeneratedAt(null); + definition.setCacheState(null); + definition.setLastError(null); + return definition; + } + + private PersonaContextDefinition configurationWithDerivedState(Persona persona) { + PersonaContextDefinition definition = editableDefinition(persona); + PersonaContextCache.CacheSnapshot snapshot = + PersonaContextCache.getInstance().snapshot(persona); + definition.setCacheState(snapshot.state()); + definition.setLastError(snapshot.error()); + if (snapshot.value() != null) { + PersonaContext context = snapshot.value().context(); + definition.setLastGeneratedAt(context.getGeneratedAt()); + for (ContextRule rule : definition.getRules()) { + listOrEmpty(context.getRules()).stream() + .filter(result -> rule.getName().equals(result.getRuleName())) + .findFirst() + .map(RuleResult::getMatched) + .ifPresent(rule::setMatchedCount); + } + } + return definition; + } + + private Persona persistDefinition( + UriInfo uriInfo, + SecurityContext securityContext, + Persona original, + PersonaContextDefinition definition) { + definition.setLastGeneratedAt(null); + definition.setCacheState(null); + definition.setLastError(null); + Persona updated = JsonUtils.deepCopy(original, Persona.class); + updated.setContextDefinition(definition); + repository.prepareInternal(updated, true); + return repository + .update(uriInfo, original, updated, securityContext.getUserPrincipal().getName()) + .getEntity(); + } + + private static ContextRule sanitizedRule(ContextRule requestedRule) { + ContextRule rule = JsonUtils.deepCopy(requestedRule, ContextRule.class); + rule.setMatchedCount(null); + if (rule.getMaxAssets() == null) { + rule.setMaxAssets(200); + } + return rule; + } + + private static int findRule(List rules, UUID ruleId) { + for (int index = 0; index < rules.size(); index++) { + if (ruleId.equals(rules.get(index).getId())) { + return index; + } + } + throw new NotFoundException("Persona AI context rule not found: " + ruleId); + } + + private static Response documentResponse(PersonaContextCache.CachedResult cached) { + PersonaContextBuilder.MaterializedPersonaContext materialized = cached.value(); + PersonaContext context = materialized.context(); + String markdown = materialized.markdown(); + int entitiesIncluded = + listOrEmpty(context.getRules()).stream() + .mapToInt( + result -> value(result.getRenderedFull()) + value(result.getRenderedCompact())) + .sum(); + PersonaContextDocument document = + new PersonaContextDocument( + markdown, + entitiesIncluded, + listOrEmpty(context.getManifest()).size(), + Math.max(1, (int) Math.ceil(markdown.length() / 4.0)), + markdown.getBytes(StandardCharsets.UTF_8).length, + context.getGeneratedAt(), + Boolean.TRUE.equals(context.getTruncated()), + PersonaContextCacheState.FRESH); + return Response.ok(document) + .header(PersonaContextCache.CACHE_HEADER, cached.status().name()) + .build(); + } + + private static int value(Integer number) { + return number == null ? 0 : number; + } + + public record PersonaContextDocument( + String markdown, + int entitiesIncluded, + int truncatedCount, + int tokensEst, + int bytes, + long generatedAt, + boolean truncated, + PersonaContextCacheState cacheState) {} + @GET @Path("/{id}/versions/{version}") @Operation( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java index f0660a4e3e59..2fd96ff90411 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/DefaultRecreateHandler.java @@ -53,6 +53,11 @@ public DefaultRecreateHandler withJobData(EventPublisherJob jobData) { return this; } + /** The reindex job driving this run, or null for jobless callers (ops CLI createIndexes). */ + protected EventPublisherJob getJobData() { + return jobData; + } + @Override public ReindexContext reCreateIndexes(Set entities) { ReindexContext context = new ReindexContext(); @@ -498,6 +503,11 @@ private Set getAliasesFromMapping(IndexMapping indexMapping, String clus .forEach(aliases::add); } + // Data Insights aliases (e.g., "di-data-assets-testcaseresolutionstatus") are '-' joined + indexMapping.getDataInsightAliases(clusterAlias).stream() + .filter(alias -> alias != null && !alias.isBlank()) + .forEach(aliases::add); + // Add short alias (e.g., "table") String shortAlias = indexMapping.getAlias(clusterAlias); if (!nullOrEmpty(shortAlias)) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java index 70c7c4ab487f..22ea041cccef 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityReindexContext.java @@ -14,6 +14,12 @@ public class EntityReindexContext { String originalIndex; String activeIndex; String stagedIndex; + + /** Staged vector-chunk generation of the run this callback belongs to; null outside staged + * chunk recreates. Binds per-type completion marks to their run (a later, unrelated run's + * callbacks must never complete or promote a stale staged generation). */ + String stagedChunkIndex; + String canonicalAliases; Set existingAliases; Set parentAliases; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java index 8c041f6e3d2c..67a7c28151c9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/RecreateWithEmbeddings.java @@ -1,26 +1,159 @@ package org.openmetadata.service.search; +import java.util.Locale; import java.util.Set; +import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.openmetadata.service.Entity; +import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; @Slf4j public class RecreateWithEmbeddings extends DefaultRecreateHandler { @Override public ReindexContext reCreateIndexes(Set entities) { - Entity.getSearchRepository().initializeVectorSearchService(); - return super.reCreateIndexes(entities); + SearchRepository searchRepository = Entity.getSearchRepository(); + searchRepository.initializeVectorSearchService(); + String stagedChunkIndex = recreateChunkIndexIfFullRun(entities); + ReindexContext context; + try { + context = super.reCreateIndexes(entities); + } catch (RuntimeException e) { + // The run dies before any type can finalize — clear the JVM's staged state so a later, + // unrelated run's callbacks can never complete and promote this dead generation. The bare + // generation index itself is swept by the next staged recreate. + clearStagedChunkStateQuietly(stagedChunkIndex); + throw e; + } + context.setStagedChunkIndex(stagedChunkIndex); + return context; + } + + private void clearStagedChunkStateQuietly(String stagedChunkIndex) { + OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + if (stagedChunkIndex != null && vectorService != null) { + vectorService.clearStagedChunkState(stagedChunkIndex); + } + } + + /** + * A recreate covering every vector-indexable entity type also recreates the dedicated chunk + * index, so chunks of entities that no longer exist (DB restore/wipe — no delete events) don't + * survive the rebuild and keep surfacing in AI retrieval. The recreate is STAGED: the run writes + * into a bare next-generation index (whose empty fingerprint lookups force a full re-embed), and + * the generation is only promoted — one atomic alias swap, old data removed — after every + * vector-indexable type finalizes successfully (see {@link #finalizeReindex}); any failure + * before promotion leaves the old chunks fully live. Guarded two ways: the driving job must + * explicitly request recreateIndex (this handler is also invoked by non-recreate distributed + * runs and by the jobless ops-CLI createIndexes path), and the run must cover every + * vector-indexable entity type (a partial recreate must not stage a sweep of types it will not + * re-embed). + */ + private String recreateChunkIndexIfFullRun(Set entities) { + OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + if (vectorService == null + || entities == null + || getJobData() == null + || !Boolean.TRUE.equals(getJobData().getRecreateIndex())) { + return null; + } + if (coversAllVectorTypes(entities)) { + return vectorService.beginStagedChunkRecreate(); + } else { + LOG.info( + "Partial recreate ({} of {} vector-indexable types) — keeping the chunk index; orphaned " + + "chunks, if any, are only swept by a full recreate", + coveredVectorTypeCount(entities), + AvailableEntityTypes.SET.size()); + } + return null; + } + + /** + * Whether the run covers every vector-indexable entity type, compared case-insensitively: the + * reindex job carries canonical camelCase names ("glossaryTerm") while {@link + * AvailableEntityTypes#SET} is lowercased ("glossaryterm") — a case-sensitive containsAll would + * never match and the chunk recreate would silently never fire. + */ + static boolean coversAllVectorTypes(Set entities) { + return coveredVectorTypeCount(entities) == AvailableEntityTypes.SET.size(); + } + + static long coveredVectorTypeCount(Set entities) { + Set normalized = + entities.stream().map(e -> e.toLowerCase(Locale.ROOT)).collect(Collectors.toSet()); + return AvailableEntityTypes.SET.stream().filter(normalized::contains).count(); + } + + @Override + public void promoteEntityIndex(EntityReindexContext context, boolean reindexSuccess) { + // Distributed full recreates promote entity indexes through this per-entity path instead of + // finalizeReindex — without this hook the staged chunk generation would never reach its + // completion gate on distributed runs. markEntityTypeReindexed is idempotent, so runs that + // invoke both callbacks for a type are harmless. The mark lives in a finally so a throwing + // promotion still reports the type (as failed) — otherwise the staged chunk run would wait + // forever instead of reaching a safe terminal state. + RuntimeException superFailure = null; + try { + super.promoteEntityIndex(context, reindexSuccess); + } catch (RuntimeException e) { + superFailure = e; + } + markChunkTypeOutcomeAndRethrow(context, reindexSuccess, superFailure); } @Override public void finalizeReindex(EntityReindexContext context, boolean reindexSuccess) { - super.finalizeReindex(context, reindexSuccess); + // Same shape as promoteEntityIndex: a throwing finalize must still report the type. + RuntimeException superFailure = null; + try { + super.finalizeReindex(context, reindexSuccess); + } catch (RuntimeException e) { + superFailure = e; + } + markChunkTypeOutcomeAndRethrow(context, reindexSuccess, superFailure); - if (reindexSuccess && Entity.getSearchRepository().isVectorEmbeddingEnabled()) { - LOG.info( - "Reindex finalized for entity type '{}' with vector embeddings enabled", - context.getEntityType()); + if (reindexSuccess) { + SearchRepository searchRepository = Entity.getSearchRepository(); + if (searchRepository.isVectorEmbeddingEnabled()) { + LOG.info( + "Reindex finalized for entity type '{}' with vector embeddings enabled", + context.getEntityType()); + } + } + } + + /** + * Feeds the staged chunk recreate: promotes the staged generation once every vector-indexable + * type has completed successfully; a failed type (including a throwing super callback) keeps the + * old chunks live. Marks are bound to the callback's own run via the context's staged chunk + * generation, so a later run's callbacks can never complete a stale generation. When the super + * callback itself failed, a marking failure is logged rather than thrown so it cannot mask the + * original exception; otherwise (e.g. the promotion swap failing) it propagates and fails the + * job loudly. + */ + private void markChunkTypeOutcomeAndRethrow( + EntityReindexContext context, boolean reindexSuccess, RuntimeException superFailure) { + try { + OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + if (vectorService != null) { + vectorService.markEntityTypeReindexed( + context.getEntityType(), + reindexSuccess && superFailure == null, + context.getStagedChunkIndex()); + } + } catch (RuntimeException markFailure) { + if (superFailure == null) { + throw markFailure; + } + LOG.error( + "Suppressed chunk-outcome failure while the callback for {} was already failing", + context.getEntityType(), + markFailure); + } + if (superFailure != null) { + throw superFailure; } } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/ReindexContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/ReindexContext.java index 7f4beaeac90f..5701f4f7e795 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/ReindexContext.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/ReindexContext.java @@ -16,6 +16,30 @@ public class ReindexContext { private final Map canonicalAliasByEntity = new HashMap<>(); private final Map> parentAliasesByEntity = new HashMap<>(); + /** + * Reserved pseudo-entity key carrying the staged vector-chunk generation through the SAME + * staged-mapping wire the entity staged indexes travel (context -> job record -> distributed + * participants), so workers on other nodes receive it without any new serialization. Never a + * real entity type; filtered out of {@link #getEntities()}. + */ + public static final String STAGED_CHUNK_KEY = "__vectorChunks__"; + + /** + * Staged vector-chunk generation created by this run's reCreateIndexes, or empty when the run + * did not stage one (partial recreates, normal runs). + */ + public Optional getStagedChunkIndex() { + return Optional.ofNullable(stagedIndexByEntity.get(STAGED_CHUNK_KEY)); + } + + public void setStagedChunkIndex(String stagedChunkIndex) { + if (stagedChunkIndex == null) { + stagedIndexByEntity.remove(STAGED_CHUNK_KEY); + } else { + stagedIndexByEntity.put(STAGED_CHUNK_KEY, stagedChunkIndex); + } + } + public void add( String entity, String canonicalIndex, @@ -38,7 +62,9 @@ public Optional getCanonicalIndex(String entity) { } public Set getEntities() { - return Collections.unmodifiableSet(stagedIndexByEntity.keySet()); + Set entities = new java.util.HashSet<>(stagedIndexByEntity.keySet()); + entities.remove(STAGED_CHUNK_KEY); + return Collections.unmodifiableSet(entities); } public Optional getStagedIndex(String entity) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClient.java index 2d0b982ed7a5..9a7ab3f90475 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClient.java @@ -240,6 +240,17 @@ public interface SearchClient } """; + String CASCADE_SERVICE_STYLE_SCRIPT = + """ + if (ctx._source.service != null) { + if (params.style == null) { + ctx._source.service.remove('style'); + } else { + ctx._source.service.style = params.style; + } + } + """; + // FQN-boundary aware, idempotent rewrite of a single tagFQN. A bare // startsWith + replace is NOT idempotent when the new FQN keeps the old one // as a prefix (rename "a" -> "a b"): the glossary rename fires this twice diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java index eca4c68e4a08..4b91034735ac 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchClusterMetrics.java @@ -1,5 +1,6 @@ package org.openmetadata.service.search; +import java.lang.management.ManagementFactory; import java.util.Map; import lombok.Builder; import lombok.Getter; @@ -37,6 +38,14 @@ public class SearchClusterMetrics { 10 * 1024 * 1024L; // Conservative 10MB default (AWS OpenSearch hard limit) // Safe bulk payload threshold: 90% of max_content_length to leave headroom for HTTP framing public static final long DEFAULT_BULK_PAYLOAD_SIZE_BYTES = DEFAULT_MAX_CONTENT_LENGTH * 9 / 10; + // Fraction of the pod's off-heap headroom (container limit - max heap) usable for in-flight bulk + // payloads. Bulk buffers are off-heap, so they escape -Xmx and count against the cgroup limit. + public static final double INFLIGHT_MEMORY_SAFETY_FACTOR = 0.5; + // Conservative per-entity heap footprint, used to bound the buffered entity queue by bytes rather + // than a flat count. Wide tables / large descriptions / sampleData run far above a naive 10 KB; + // genuinely huge entities are still caught by the bulk sink's runtime backpressure. + public static final long ESTIMATED_ENTITY_BYTES = 100 * 1024L; + public static final double QUEUE_HEAP_FRACTION = 0.25; public static SearchClusterMetrics fetchClusterMetrics( SearchRepository searchRepository, long totalEntities, int maxDbConnections) { @@ -254,6 +263,8 @@ private static SearchClusterMetrics calculateRecommendations( int queueBatches = Math.min(recommendedProducerThreads * 2, 20); int recommendedQueueSize = Math.min(10000, recommendedBatchSize * queueBatches); recommendedQueueSize = Math.max(1000, recommendedQueueSize); + recommendedQueueSize = + boundQueueSizeToHeap(recommendedQueueSize, Runtime.getRuntime().maxMemory()); // --- CPU budget: derive internal thread pool sizes from available cores --- // Consumer threads are mostly I/O-bound (waiting on search bulk responses), so they @@ -271,6 +282,9 @@ private static SearchClusterMetrics calculateRecommendations( int recommendedDocBuildThreads = Math.max(1, Math.min(50, (int) Math.floor(cpuBudget * 2))); recommendedConcurrentRequests = Math.min(recommendedConcurrentRequests, Math.max(10, availableCores * 10)); + recommendedConcurrentRequests = + boundConcurrentRequestsToMemory( + recommendedConcurrentRequests, maxPayloadSize, availableOffHeapBudgetBytes()); long recommendedStatsIntervalMs = availableCores <= 2 ? 2000 : availableCores <= 4 ? 1500 : 1000; @@ -416,6 +430,61 @@ private static int extractIntValue(Map map, String key, int defa return defaultValue; } + /** + * Cap in-flight bulk requests so {@code concurrentRequests * maxPayloadSize} fits the pod's + * off-heap headroom. Bulk payloads are held largely in off-heap direct buffers, so they escape + * {@code -Xmx} and count against the container cgroup limit; sizing only against heap lets the + * aggregate exceed the container limit and get OOMKilled (137). Reducing concurrency to fit lets + * reindex adapt to any pod size. + */ + static int boundConcurrentRequestsToMemory( + int concurrentRequests, long maxPayloadSizeBytes, long offHeapBudgetBytes) { + long safeBytes = (long) (offHeapBudgetBytes * INFLIGHT_MEMORY_SAFETY_FACTOR); + long maxByMemory = Math.max(1, safeBytes / Math.max(1, maxPayloadSizeBytes)); + int bounded = (int) Math.min(concurrentRequests, maxByMemory); + if (bounded < concurrentRequests) { + LOG.info( + "Capping concurrent bulk requests {} -> {} to fit off-heap budget {} MB (payload {} MB); " + + "bulk buffers are off-heap and count against the container memory limit", + concurrentRequests, + bounded, + safeBytes / (1024 * 1024), + maxPayloadSizeBytes / (1024 * 1024)); + } + return bounded; + } + + /** + * Cap the buffered entity queue so {@code queueSize * ESTIMATED_ENTITY_BYTES} stays within a + * fraction of the JVM heap, instead of a flat entity count that silently blows heap on big + * entities or small pods. + */ + static int boundQueueSizeToHeap(int queueSize, long maxHeapBytes) { + long heapBudget = (long) (maxHeapBytes * QUEUE_HEAP_FRACTION); + long budgeted = heapBudget / ESTIMATED_ENTITY_BYTES; + if (budgeted < 1000) { + LOG.info( + "Queue floor of 1000 entities exceeds heap budget (~{} fit {}% of heap at {} KB/entity); heap is very small", + budgeted, (int) (QUEUE_HEAP_FRACTION * 100), ESTIMATED_ENTITY_BYTES / 1024); + } + int maxByHeap = (int) Math.max(1000, budgeted); + return Math.min(queueSize, maxByHeap); + } + + private static long availableOffHeapBudgetBytes() { + long headroom = containerMemoryLimitBytes() - Runtime.getRuntime().maxMemory(); + return Math.max(0L, headroom); + } + + private static long containerMemoryLimitBytes() { + long limit = 0L; + if (ManagementFactory.getOperatingSystemMXBean() + instanceof com.sun.management.OperatingSystemMXBean osBean) { + limit = osBean.getTotalMemorySize(); + } + return limit > 0 ? limit : Runtime.getRuntime().maxMemory(); + } + private static SearchClusterMetrics getConservativeDefaults( SearchRepository searchRepository, long totalEntities, int maxDbConnections) { int conservativeBatchSize; @@ -439,7 +508,6 @@ private static SearchClusterMetrics getConservativeDefaults( conservativeConcurrentRequests = Math.min(conservativeConcurrentRequests, Math.max(10, availCores * 10)); int conservativeConsumerThreads = Math.min(20, Math.max(1, availCores - 1)); - int conservativeQueueSize = conservativeBatchSize * conservativeConcurrentRequests * 2; long maxHeap = Runtime.getRuntime().maxMemory(); long totalHeap = Runtime.getRuntime().totalMemory(); @@ -481,6 +549,12 @@ private static SearchClusterMetrics getConservativeDefaults( "Could not fetch max content length from cluster, using default: {}", e.getMessage()); } + conservativeConcurrentRequests = + boundConcurrentRequestsToMemory( + conservativeConcurrentRequests, maxPayloadSize, availableOffHeapBudgetBytes()); + int conservativeQueueSize = + boundQueueSizeToHeap(conservativeBatchSize * conservativeConcurrentRequests * 2, maxHeap); + double cpuBudget = availCores * 0.70; int conservativeFieldFetchThreads = Math.max(2, Math.min(50, availCores * 2)); int conservativeDocBuildThreads = Math.max(1, Math.min(50, (int) Math.floor(cpuBudget * 2))); @@ -540,8 +614,11 @@ public void logRecommendations() { estimatedThroughput / 5); // Assume 5 sec per batch // Memory usage estimate - long queueMemoryMB = (recommendedQueueSize * 10L) / 1024; // Assume 10KB per entity + long queueMemoryMB = ((long) recommendedQueueSize * ESTIMATED_ENTITY_BYTES) / (1024 * 1024); LOG.info("Estimated queue memory usage: ~{} MB", queueMemoryMB); + long inflightBulkMemoryMB = + ((long) recommendedConcurrentRequests * maxPayloadSizeBytes) / (1024 * 1024); + LOG.info("Estimated in-flight bulk memory (mostly off-heap): ~{} MB", inflightBulkMemoryMB); LOG.info( "Note: Settings are conservative to ensure stability. The system will adapt during execution."); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java index c242ba875f72..cb36ddcbd4b3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java @@ -60,6 +60,9 @@ public class SearchIndexRetryWorker implements Managed { private static final int MAX_CASCADE_REINDEX = 5000; private static final int CASCADE_BATCH_SIZE = 200; private static final int MAX_BACKOFF_SECONDS = 60; + private static final int FIRST_RETRY_BACKOFF_SECONDS = 10; + private static final int SECOND_RETRY_BACKOFF_SECONDS = 20; + private static final int MAX_PROCESSING_ATTEMPTS = 3; private static final int CANDIDATE_TYPES_REFRESH_INTERVAL_MS = 60000; private static final long STALE_RECOVERY_INTERVAL_MS = 60_000; private static final long STALE_THRESHOLD_MS = 10 * 60 * 1000; @@ -142,7 +145,10 @@ private void runLoop(int workerId) { } List claimed = - collectionDAO.searchIndexRetryQueueDAO().claimPending(CLAIM_BATCH_SIZE); + collectionDAO + .searchIndexRetryQueueDAO() + .claimPending( + CLAIM_BATCH_SIZE, FIRST_RETRY_BACKOFF_SECONDS, SECOND_RETRY_BACKOFF_SECONDS); if (claimed.isEmpty()) { sleep(POLL_INTERVAL_SECONDS); continue; @@ -199,14 +205,25 @@ private void processRecord(SearchIndexRetryRecord record) { private void handleProcessingError(SearchIndexRetryRecord record, Exception e) { String reason = SearchIndexRetryQueue.failureReason("retryFailed", e); if (isRetryable(e)) { - String nextStatus = nextRetryStatus(record.getRetryCount()); + String nextStatus = retryableNextStatus(record.getRetryCount()); recordRetryFailure(record, reason, nextStatus); - LOG.debug( - "Retry failed for entityId={} entityFqn={} nextStatus={}: {}", - record.getEntityId(), - record.getEntityFqn(), - nextStatus, - e.getMessage()); + if (STATUS_FAILED.equals(nextStatus)) { + Metrics.counter("search.retry.processed", "result", "exhausted").increment(); + LOG.warn( + "Retryable failures hit the {}-attempt ceiling for entityId={} entityFqn={}; " + + "dead-lettering to FAILED: {}", + MAX_PROCESSING_ATTEMPTS, + record.getEntityId(), + record.getEntityFqn(), + e.getMessage()); + } else { + LOG.debug( + "Retry failed for entityId={} entityFqn={} nextStatus={}: {}", + record.getEntityId(), + record.getEntityFqn(), + nextStatus, + e.getMessage()); + } } else { recordRetryFailure(record, reason, STATUS_FAILED); Metrics.counter("search.retry.processed", "result", "non_retryable").increment(); @@ -586,7 +603,7 @@ private boolean waitForClientAvailability(int workerId) { *
  • No status code found → defaults to retryable (conservative) * */ - private boolean isRetryable(Throwable t) { + boolean isRetryable(Throwable t) { if (t instanceof IOException) { return true; } @@ -664,4 +681,20 @@ private String nextRetryStatus(int retryCount) { default -> STATUS_FAILED; }; } + + /** + * Next status for a transient failure, capped at three processing attempts. Retry claims are + * delayed by the queue DAO before the second and third attempts. + */ + String retryableNextStatus(int retryCount) { + String status; + if (retryCount == 0) { + status = STATUS_PENDING_RETRY_1; + } else if (retryCount < MAX_PROCESSING_ATTEMPTS - 1) { + status = STATUS_PENDING_RETRY_2; + } else { + status = STATUS_FAILED; + } + return status; + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRankingHelper.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRankingHelper.java new file mode 100644 index 000000000000..b2d9b6569386 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRankingHelper.java @@ -0,0 +1,371 @@ +package org.openmetadata.service.search; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Pattern; +import org.openmetadata.schema.api.search.AssetTypeConfiguration; +import org.openmetadata.schema.api.search.FieldBoost; +import org.openmetadata.schema.api.search.RankingConfiguration; +import org.openmetadata.schema.api.search.RankingSignals; +import org.openmetadata.schema.api.search.RankingStage; +import org.openmetadata.schema.api.search.SearchSettings; +import org.openmetadata.schema.api.search.StopWordsByLanguage; + +public final class SearchRankingHelper { + private static final Pattern TOKEN_SPLITTER = Pattern.compile("[^\\p{L}\\p{N}]+"); + // Significant-token extraction only removes stop words on word boundaries, so it must split on + // whitespace alone. Splitting on every non-alphanumeric char (TOKEN_SPLITTER) would break + // identifier queries like "sample_data" into "sample data", which then fails to match the + // keyword fqnParts/name compound tokens that keep the identifier intact. + private static final Pattern WHITESPACE_SPLITTER = Pattern.compile("\\s+"); + // n-gram fields are indexed with an edge-n-gram analyzer; querying them with that same analyzer + // re-n-grams the query text, so a long single token explodes into hundreds of clauses and trips + // OpenSearch's maxClauseCount. Query them with a plain analyzer instead (the canonical + // edge-n-gram + // pattern): the query stays one token and still matches the indexed n-grams. + private static final String NGRAM_SEARCH_ANALYZER = "standard"; + + private SearchRankingHelper() {} + + public static RankingConfiguration resolveRanking( + SearchSettings searchSettings, AssetTypeConfiguration assetConfig) { + if (assetConfig != null && assetConfig.getRanking() != null) { + return Boolean.FALSE.equals(assetConfig.getRanking().getEnabled()) + ? null + : assetConfig.getRanking(); + } + + RankingConfiguration defaultRanking = defaultRanking(searchSettings); + if (defaultRanking == null || Boolean.FALSE.equals(defaultRanking.getEnabled())) { + return null; + } + return deriveRanking(defaultRanking, assetConfig); + } + + public static String significantQueryText(String query, RankingConfiguration ranking) { + List tokens = significantTokens(query, ranking, true); + return tokens.isEmpty() ? (query == null ? "" : query.trim()) : String.join(" ", tokens); + } + + public static String significantQueryTextPreservingCase( + String query, RankingConfiguration ranking) { + List tokens = significantTokens(query, ranking, false); + return tokens.isEmpty() ? (query == null ? "" : query.trim()) : String.join(" ", tokens); + } + + public static List exactMatchTexts(String query) { + if (query == null || query.trim().isEmpty()) { + return List.of(); + } + + LinkedHashSet values = new LinkedHashSet<>(); + String trimmed = query.trim(); + addExactTextVariants(values, trimmed); + addExactTextVariants(values, trimmed.toLowerCase(Locale.ROOT)); + return new ArrayList<>(values); + } + + private static void addExactTextVariants(LinkedHashSet values, String query) { + values.add(query); + List tokens = + TOKEN_SPLITTER.splitAsStream(query).filter(token -> !token.isBlank()).toList(); + if (tokens.size() > 1) { + values.add(String.join(" ", tokens)); + values.add(String.join("_", tokens)); + values.add(String.join("-", tokens)); + values.add(String.join(".", tokens)); + values.add(String.join("", tokens)); + } + } + + public static List significantTokens(String query, RankingConfiguration ranking) { + return significantTokens(query, ranking, true); + } + + private static List significantTokens( + String query, RankingConfiguration ranking, boolean normalize) { + if (query == null || query.trim().isEmpty()) { + return List.of(); + } + + Set stopWords = stopWords(ranking); + + LinkedHashSet seenTokens = new LinkedHashSet<>(); + List tokens = new ArrayList<>(); + for (String token : WHITESPACE_SPLITTER.split(query.trim())) { + String normalizedToken = token.toLowerCase(Locale.ROOT); + if (isSignificantToken(normalizedToken, stopWords) && seenTokens.add(normalizedToken)) { + tokens.add(normalize ? normalizedToken : token); + } + } + return tokens; + } + + public static double disMaxTieBreaker(RankingConfiguration ranking) { + return ranking != null && ranking.getDisMaxTieBreaker() != null + ? ranking.getDisMaxTieBreaker() + : 0.05D; + } + + public static float stageWeight(RankingStage stage) { + return stage.getWeight() != null ? stage.getWeight().floatValue() : 1.0F; + } + + public static String minimumShouldMatch(RankingStage stage) { + return !nullOrEmpty(stage.getMinimumShouldMatch()) ? stage.getMinimumShouldMatch() : "2<70%"; + } + + public static String stageSearchAnalyzer(RankingStage stage) { + List fields = stage.getFields(); + boolean allNgramFields = + !nullOrEmpty(fields) && fields.stream().allMatch(field -> field.endsWith(".ngram")); + return allNgramFields ? NGRAM_SEARCH_ANALYZER : null; + } + + public static Double signalMaxBoost(RankingConfiguration ranking) { + RankingSignals signals = ranking != null ? ranking.getSignals() : null; + return signals != null ? signals.getMaxBoost() : null; + } + + public static String signalScoreMode(RankingConfiguration ranking, String fallback) { + RankingSignals signals = ranking != null ? ranking.getSignals() : null; + return signals != null && signals.getScoreMode() != null + ? signals.getScoreMode().value() + : fallback; + } + + public static String signalBoostMode(RankingConfiguration ranking, String fallback) { + RankingSignals signals = ranking != null ? ranking.getSignals() : null; + return signals != null && signals.getBoostMode() != null + ? signals.getBoostMode().value() + : fallback; + } + + private static RankingConfiguration defaultRanking(SearchSettings searchSettings) { + if (searchSettings == null + || searchSettings.getDefaultConfiguration() == null + || searchSettings.getDefaultConfiguration().getRanking() == null) { + return null; + } + return searchSettings.getDefaultConfiguration().getRanking(); + } + + private static RankingConfiguration deriveRanking( + RankingConfiguration defaultRanking, AssetTypeConfiguration assetConfig) { + RankingConfiguration ranking = + new RankingConfiguration() + .withEnabled(defaultRanking.getEnabled()) + .withAlgorithm(defaultRanking.getAlgorithm()) + .withStopWords(defaultRanking.getStopWords()) + .withStopWordsByLanguage(defaultRanking.getStopWordsByLanguage()) + .withDisMaxTieBreaker(defaultRanking.getDisMaxTieBreaker()) + .withSignals(defaultRanking.getSignals()); + + List configuredFields = configuredFields(assetConfig); + List stages = new ArrayList<>(); + List defaultStages = listOrEmpty(defaultRanking.getStages()); + for (RankingStage stage : defaultStages) { + List fields = deriveFieldsForStage(stage, configuredFields); + if (!fields.isEmpty()) { + stages.add(copyStage(stage, fields)); + } + } + ranking.setStages(stages.isEmpty() ? defaultStages : stages); + return ranking; + } + + private static List configuredFields(AssetTypeConfiguration assetConfig) { + if (assetConfig == null || assetConfig.getSearchFields() == null) { + return List.of(); + } + LinkedHashSet fields = new LinkedHashSet<>(); + for (FieldBoost fieldBoost : assetConfig.getSearchFields()) { + if (!nullOrEmpty(fieldBoost.getField())) { + fields.add(fieldBoost.getField()); + } + } + return new ArrayList<>(fields); + } + + private static RankingStage copyStage(RankingStage stage, List fields) { + return new RankingStage() + .withName(stage.getName()) + .withPurpose(stage.getPurpose()) + .withFields(fields) + .withMatchType(stage.getMatchType()) + .withWeight(stage.getWeight()) + .withMinimumShouldMatch(stage.getMinimumShouldMatch()); + } + + private static List deriveFieldsForStage( + RankingStage stage, List configuredFields) { + if (configuredFields.isEmpty()) { + return stage.getFields() == null ? List.of() : stage.getFields(); + } + + String stageName = stage.getName() == null ? "" : stage.getName().toLowerCase(Locale.ROOT); + if (stageName.contains("exact")) { + return exactNameFields(configuredFields, stage.getFields()); + } + if (stageName.contains("partial") || stageName.contains("ngram")) { + return ngramNameFields(configuredFields, stage.getFields()); + } + if (stageName.contains("close") || stageName.contains("name")) { + return closeNameFields(configuredFields, stage.getFields()); + } + if (stageName.contains("description")) { + return descriptionFields(configuredFields, stage.getFields()); + } + return structuralFields(configuredFields, stage.getFields()); + } + + private static List exactNameFields( + List configuredFields, List fallback) { + LinkedHashSet fields = new LinkedHashSet<>(); + addIfConfigured(fields, configuredFields, "displayName.keyword"); + addIfConfigured(fields, configuredFields, "name.keyword"); + addIfConfigured(fields, configuredFields, "fullyQualifiedName.keyword"); + addIfConfigured(fields, configuredFields, "fullyQualifiedName"); + if (hasField(configuredFields, "displayName")) { + fields.add("displayName.keyword"); + } + if (hasField(configuredFields, "name")) { + fields.add("name.keyword"); + } + if (hasField(configuredFields, "fullyQualifiedName")) { + fields.add("fullyQualifiedName"); + } + return withFallback(fields, fallback); + } + + private static List closeNameFields( + List configuredFields, List fallback) { + LinkedHashSet fields = new LinkedHashSet<>(); + for (String field : configuredFields) { + if (isPrimaryNameField(field) && !field.endsWith(".keyword") && !field.endsWith(".ngram")) { + fields.add(field); + } + } + return withFallback(fields, fallback); + } + + private static List ngramNameFields( + List configuredFields, List fallback) { + LinkedHashSet fields = new LinkedHashSet<>(); + for (String field : configuredFields) { + if (field.endsWith(".ngram") && isPrimaryNameField(field)) { + fields.add(field); + } + } + return withFallback(fields, fallback); + } + + private static List descriptionFields( + List configuredFields, List fallback) { + LinkedHashSet fields = new LinkedHashSet<>(); + for (String field : configuredFields) { + if (isDescriptionContextField(field)) { + fields.add(field); + } + } + return withFallback(fields, fallback); + } + + private static List structuralFields( + List configuredFields, List fallback) { + LinkedHashSet fields = new LinkedHashSet<>(); + for (String field : configuredFields) { + if (!isPrimaryNameField(field) + && !isDescriptionContextField(field) + && !field.startsWith("extension.")) { + fields.add(field); + } + } + return withFallback(fields, fallback); + } + + private static List withFallback(LinkedHashSet fields, List fallback) { + if (fields.isEmpty() && fallback != null) { + fields.addAll(fallback); + } + return new ArrayList<>(fields); + } + + private static boolean hasField(List fields, String field) { + return fields.contains(field); + } + + private static void addIfConfigured( + LinkedHashSet fields, List configuredFields, String field) { + if (configuredFields.contains(field)) { + fields.add(field); + } + } + + private static boolean isPrimaryNameField(String field) { + String normalized = field; + if (normalized.endsWith(".keyword")) { + normalized = normalized.substring(0, normalized.length() - ".keyword".length()); + } else if (normalized.endsWith(".ngram")) { + normalized = normalized.substring(0, normalized.length() - ".ngram".length()); + } else if (normalized.endsWith(".compound")) { + normalized = normalized.substring(0, normalized.length() - ".compound".length()); + } + return normalized.equals("name") + || normalized.equals("displayName") + || normalized.equals("fullyQualifiedName"); + } + + private static boolean isDescriptionContextField(String field) { + String lowerField = field.toLowerCase(Locale.ROOT); + return lowerField.contains("description") + || lowerField.equals("querytext") + || lowerField.equals("extractedtext"); + } + + private static Set stopWords(RankingConfiguration ranking) { + if (ranking == null) { + return Set.of(); + } + + LinkedHashSet stopWords = new LinkedHashSet<>(); + addStopWords(stopWords, ranking.getStopWords()); + + StopWordsByLanguage stopWordsByLanguage = ranking.getStopWordsByLanguage(); + if (stopWordsByLanguage != null && stopWordsByLanguage.getAdditionalProperties() != null) { + stopWordsByLanguage + .getAdditionalProperties() + .values() + .forEach(words -> addStopWords(stopWords, words)); + } + return stopWords; + } + + private static void addStopWords(Set stopWords, List words) { + if (words == null) { + return; + } + words.stream() + .filter(word -> word != null && !word.isBlank()) + .map(word -> word.toLowerCase(Locale.ROOT)) + .forEach(stopWords::add); + } + + private static boolean isSignificantToken(String token, Set stopWords) { + if (token.isBlank() || stopWords.contains(token)) { + return false; + } + return token.codePointCount(0, token.length()) > 1 + || !isWeakSingleCharacterToken(token.codePointAt(0)); + } + + private static boolean isWeakSingleCharacterToken(int codePoint) { + return Character.UnicodeScript.of(codePoint) == Character.UnicodeScript.LATIN; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index 0bd56eb22578..3a289e60c172 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -12,6 +12,7 @@ import static org.openmetadata.service.Entity.FIELD_FOLLOWERS; import static org.openmetadata.service.Entity.FIELD_FULLY_QUALIFIED_NAME; import static org.openmetadata.service.Entity.FIELD_NAME; +import static org.openmetadata.service.Entity.FIELD_STYLE; import static org.openmetadata.service.Entity.FIELD_USAGE_SUMMARY; import static org.openmetadata.service.Entity.QUERY; import static org.openmetadata.service.Entity.RAW_COST_ANALYSIS_REPORT_DATA; @@ -19,6 +20,7 @@ import static org.openmetadata.service.Entity.WEB_ANALYTIC_USER_ACTIVITY_REPORT_DATA; import static org.openmetadata.service.search.SearchClient.ADD_FOLLOWERS_SCRIPT; import static org.openmetadata.service.search.SearchClient.CASCADE_CERTIFICATION_SCRIPT; +import static org.openmetadata.service.search.SearchClient.CASCADE_SERVICE_STYLE_SCRIPT; import static org.openmetadata.service.search.SearchClient.DATA_ASSET_SEARCH_ALIAS; import static org.openmetadata.service.search.SearchClient.DEFAULT_UPDATE_SCRIPT; import static org.openmetadata.service.search.SearchClient.GLOBAL_SEARCH_ALIAS; @@ -110,6 +112,7 @@ import org.openmetadata.schema.entity.data.PipelineStatus; import org.openmetadata.schema.entity.data.QueryCostSearchResult; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.type.Style; import org.openmetadata.schema.search.AggregationRequest; import org.openmetadata.schema.search.SearchRequest; import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; @@ -463,6 +466,7 @@ public void createIndexes() { .canonicalIndex(canonicalIndex) .activeIndex(activeIndex) .stagedIndex(stagedIndex) + .stagedChunkIndex(context.getStagedChunkIndex().orElse(null)) .canonicalAliases(canonicalAlias) .existingAliases(existingAliases) .parentAliases(parentAliases) @@ -486,7 +490,9 @@ public void createMissingIndexes() { int created = 0; for (Map.Entry entry : entityIndexMap.entrySet()) { try { - if (!indexExists(entry.getValue())) { + if (indexExists(entry.getValue())) { + reconcileAliases(entry.getValue()); + } else { createIndex(entry.getValue()); created++; LOG.info("Created missing index for entity type: {}", entry.getKey()); @@ -505,6 +511,29 @@ public void createMissingIndexes() { } } + /** + * Attaches the Data Insights aliases declared in indexMapping.json to an index that already + * exists. Only DI aliases are reconciled here (not parent/short aliases, which the reindex + * machinery owns) so startup side effects stay scoped to the newly introduced aliases. Alias + * adds are idempotent, so this is a no-op when the index already carries them. Without it, a DI + * alias introduced in a newer release would never attach to an upgraded cluster, since + * createIndex only creates aliases for indices it creates. + */ + private void reconcileAliases(IndexMapping indexMapping) { + List dataInsightAliases = indexMapping.getDataInsightAliases(clusterAlias); + if (nullOrEmpty(dataInsightAliases)) { + return; + } + try { + searchClient.addIndexAlias(indexMapping, dataInsightAliases.toArray(new String[0])); + } catch (Exception e) { + LOG.warn( + "Failed to reconcile Data Insights aliases for index {}: {}", + indexMapping.getIndexName(clusterAlias), + e.getMessage()); + } + } + public void createOrUpdateIndexTemplates() { LOG.info("Creating/updating index templates for all entities..."); int success = 0; @@ -1587,6 +1616,7 @@ public void updateEntityIndex(EntityInterface entity) { entityType, entityId, changeDescription, indexMapping, entity); propagateGlossaryTags(entityType, entity.getFullyQualifiedName(), changeDescription); propagateCertificationTags(entityType, entity, changeDescription); + propagateServiceStyle(entityType, entity, changeDescription); propagateToRelatedEntities(entityType, changeDescription, indexMapping, entity); propagateTime = System.currentTimeMillis() - startTime; @@ -1861,6 +1891,7 @@ private void propagateEntitiesAfterBulkFlush(Iterable entities) entityType, entity.getId().toString(), changeDescription, indexMapping, entity); propagateGlossaryTags(entityType, entity.getFullyQualifiedName(), changeDescription); propagateCertificationTags(entityType, entity, changeDescription); + propagateServiceStyle(entityType, entity, changeDescription); propagateToRelatedEntities(entityType, changeDescription, indexMapping, entity); propagated++; } catch (Exception e) { @@ -2204,6 +2235,44 @@ private void handleEntityCertificationUpdate(EntityInterface entity, ChangeDescr cascadeCertificationToChildren(entity, certification); } + private void propagateServiceStyle( + String entityType, EntityInterface entity, ChangeDescription change) { + if (!SERVICE_ENTITY_SET.contains(entityType) + || !Entity.entityHasField(entityType, FIELD_STYLE) + || !isStyleUpdated(change)) { + return; + } + cascadeServiceStyleToChildren(entity, entity.getStyle()); + } + + private void cascadeServiceStyleToChildren(EntityInterface service, Style style) { + String type = service.getEntityReference().getType(); + IndexMapping indexMapping = entityIndexMap.get(type); + if (indexMapping == null) { + return; + } + List childAliases = indexMapping.getChildAliases(clusterAlias); + if (nullOrEmpty(childAliases)) { + return; + } + + Map params = new HashMap<>(); + params.put("style", style); + + Pair parentMatch = new ImmutablePair<>(SERVICE_ID, service.getId().toString()); + + try { + searchClient.updateChildren( + childAliases, parentMatch, new ImmutablePair<>(CASCADE_SERVICE_STYLE_SCRIPT, params)); + } catch (Exception e) { + LOG.error( + "Failed to cascade style for service [{}]: {}", + service.getFullyQualifiedName(), + e.getMessage(), + e); + } + } + // Pushes the cert change onto every child search doc denormalized from this // entity. Without this the cert filter on the DQ dashboard (which queries // children like test_case/test_case_result/test_case_resolution_status by @@ -2251,6 +2320,13 @@ private boolean isCertificationUpdated(ChangeDescription change) { .anyMatch(fieldChange -> CERTIFICATION_FIELD.equals(fieldChange.getName())); } + private boolean isStyleUpdated(ChangeDescription change) { + return Stream.concat( + Stream.concat(change.getFieldsUpdated().stream(), change.getFieldsAdded().stream()), + change.getFieldsDeleted().stream()) + .anyMatch(fieldChange -> FIELD_STYLE.equals(fieldChange.getName())); + } + private AssetCertification getCertificationFromEntity(EntityInterface entity) { return (AssetCertification) EntityUtil.getEntityField(entity, CERTIFICATION_FIELD); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticQueryBuilder.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticQueryBuilder.java index 543e75d6363a..2683fca666e6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticQueryBuilder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticQueryBuilder.java @@ -1,9 +1,14 @@ package org.openmetadata.service.search.elasticsearch; +import es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier; +import es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode; +import es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore; +import es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode; import es.co.elastic.clients.elasticsearch._types.query_dsl.Operator; import es.co.elastic.clients.elasticsearch._types.query_dsl.Query; import es.co.elastic.clients.elasticsearch._types.query_dsl.QueryStringQuery; import es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType; +import es.co.elastic.clients.json.JsonData; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -20,6 +25,22 @@ public static Query termQuery(String field, String value) { return Query.of(q -> q.term(t -> t.field(field).value(value))); } + public static Query termQuery(String field, String value, Float boost, String queryName) { + return Query.of( + q -> + q.term( + t -> { + t.field(field).value(value); + if (boost != null) { + t.boost(boost); + } + if (queryName != null) { + t.queryName(queryName); + } + return t; + })); + } + public static Query termQuery(String field, boolean value) { return Query.of(q -> q.term(t -> t.field(field).value(value))); } @@ -36,6 +57,22 @@ public static Query matchPhraseQuery(String field, String value) { return Query.of(q -> q.matchPhrase(m -> m.field(field).query(value))); } + public static Query matchPhraseQuery(String field, String value, Float boost, String queryName) { + return Query.of( + q -> + q.matchPhrase( + m -> { + m.field(field).query(value); + if (boost != null) { + m.boost(boost); + } + if (queryName != null) { + m.queryName(queryName); + } + return m; + })); + } + public static Query wildcardQuery(String field, String value) { return Query.of(q -> q.wildcard(w -> w.field(field).value(value))); } @@ -106,6 +143,85 @@ public static Query multiMatchQuery( })); } + public static Query multiMatchQuery( + String query, + Map fields, + TextQueryType type, + Operator operator, + String tieBreaker, + String fuzziness, + String minimumShouldMatch, + Float boost, + String queryName) { + return multiMatchQuery( + query, + fields, + type, + operator, + tieBreaker, + fuzziness, + minimumShouldMatch, + boost, + queryName, + null); + } + + public static Query multiMatchQuery( + String query, + Map fields, + TextQueryType type, + Operator operator, + String tieBreaker, + String fuzziness, + String minimumShouldMatch, + Float boost, + String queryName, + String analyzer) { + List fieldList = new ArrayList<>(); + fields.forEach( + (field, fieldBoost) -> { + if (fieldBoost != null && fieldBoost != 1.0f) { + fieldList.add(field + "^" + fieldBoost); + } else { + fieldList.add(field); + } + }); + return Query.of( + q -> + q.multiMatch( + m -> { + m.query(query); + m.fields(fieldList); + if (type != null) { + m.type(type); + } + if (operator != null) { + m.operator(operator); + } + if (tieBreaker != null) { + m.tieBreaker(Double.parseDouble(tieBreaker)); + } + if (fuzziness != null && !fuzziness.equals("0")) { + m.fuzziness(fuzziness); + m.prefixLength(1); + m.maxExpansions(10); + } + if (minimumShouldMatch != null) { + m.minimumShouldMatch(minimumShouldMatch); + } + if (boost != null) { + m.boost(boost); + } + if (queryName != null) { + m.queryName(queryName); + } + if (analyzer != null) { + m.analyzer(analyzer); + } + return m; + })); + } + public static Query queryStringQuery(String query) { return Query.of(q -> q.queryString(QueryStringQuery.of(qs -> qs.query(query)))); } @@ -178,6 +294,17 @@ public static BoolQueryBuilder boolQuery() { return new BoolQueryBuilder(); } + public static Query disMaxQuery(List queries, double tieBreaker) { + return Query.of( + q -> + q.disMax( + d -> { + d.queries(queries); + d.tieBreaker(tieBreaker); + return d; + })); + } + public static class BoolQueryBuilder { private final List must = new ArrayList<>(); private final List should = new ArrayList<>(); @@ -252,16 +379,16 @@ public static Query rangeQuery(String field, String gte, String lte, String gt, u -> { u.field(field); if (gte != null) { - u.gte(es.co.elastic.clients.json.JsonData.of(gte)); + u.gte(JsonData.of(gte)); } if (lte != null) { - u.lte(es.co.elastic.clients.json.JsonData.of(lte)); + u.lte(JsonData.of(lte)); } if (gt != null) { - u.gt(es.co.elastic.clients.json.JsonData.of(gt)); + u.gt(JsonData.of(gt)); } if (lt != null) { - u.lt(es.co.elastic.clients.json.JsonData.of(lt)); + u.lt(JsonData.of(lt)); } return u; }))); @@ -277,9 +404,9 @@ public static Query nestedQuery(String path, Query query) { public static Query functionScoreQuery( Query query, - java.util.List functions, - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode scoreMode, - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode boostMode, + List functions, + FunctionScoreMode scoreMode, + FunctionBoostMode boostMode, Float boost) { return Query.of( q -> @@ -302,20 +429,48 @@ public static Query functionScoreQuery( })); } - public static es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore weightFunction( - Query filter, double weight) { - return es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore.of( - f -> f.filter(filter).weight(weight)); + public static Query functionScoreQuery( + Query query, + List functions, + FunctionScoreMode scoreMode, + FunctionBoostMode boostMode, + Float boost, + Double maxBoost) { + return Query.of( + q -> + q.functionScore( + fs -> { + fs.query(query); + if (!functions.isEmpty()) { + fs.functions(functions); + } + if (scoreMode != null) { + fs.scoreMode(scoreMode); + } + if (boostMode != null) { + fs.boostMode(boostMode); + } + if (boost != null) { + fs.boost(boost); + } + if (maxBoost != null) { + fs.maxBoost(maxBoost); + } + return fs; + })); + } + + public static FunctionScore weightFunction(Query filter, double weight) { + return FunctionScore.of(f -> f.filter(filter).weight(weight)); } - public static es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore - fieldValueFactorFunction( - Query filter, - String field, - Double factor, - Double missing, - es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier modifier) { - return es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore.of( + public static FunctionScore fieldValueFactorFunction( + Query filter, + String field, + Double factor, + Double missing, + FieldValueFactorModifier modifier) { + return FunctionScore.of( f -> { f.filter(filter); f.fieldValueFactor( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java index acc62d499599..b99502e9261e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java @@ -7,12 +7,20 @@ import com.fasterxml.jackson.databind.JsonNode; import es.co.elastic.clients.elasticsearch.ElasticsearchClient; +import es.co.elastic.clients.elasticsearch._types.FieldValue; import es.co.elastic.clients.elasticsearch._types.Refresh; +import es.co.elastic.clients.elasticsearch._types.SortOrder; +import es.co.elastic.clients.elasticsearch._types.aggregations.FiltersBucket; +import es.co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery; +import es.co.elastic.clients.elasticsearch._types.query_dsl.Query; import es.co.elastic.clients.elasticsearch.cluster.ClusterStatsResponse; import es.co.elastic.clients.elasticsearch.cluster.GetClusterSettingsResponse; import es.co.elastic.clients.elasticsearch.core.BulkResponse; +import es.co.elastic.clients.elasticsearch.core.SearchResponse; import es.co.elastic.clients.elasticsearch.core.bulk.BulkOperation; +import es.co.elastic.clients.elasticsearch.core.search.Hit; import es.co.elastic.clients.elasticsearch.nodes.NodesStatsResponse; +import es.co.elastic.clients.json.JsonData; import es.co.elastic.clients.json.jackson.JacksonJsonpMapper; import es.co.elastic.clients.transport.rest5_client.Rest5ClientTransport; import es.co.elastic.clients.transport.rest5_client.low_level.Rest5Client; @@ -21,12 +29,15 @@ import jakarta.ws.rs.core.Response; import java.io.IOException; import java.security.KeyStoreException; +import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; import java.util.stream.Stream; import javax.net.ssl.SSLContext; import lombok.Getter; @@ -38,6 +49,7 @@ import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.message.BasicHeader; import org.jetbrains.annotations.NotNull; +import org.openmetadata.common.utils.CommonUtil; import org.openmetadata.schema.api.entityRelationship.SearchEntityRelationshipRequest; import org.openmetadata.schema.api.entityRelationship.SearchEntityRelationshipResult; import org.openmetadata.schema.api.entityRelationship.SearchSchemaEntityRelationshipResult; @@ -50,6 +62,7 @@ import org.openmetadata.schema.dataInsight.DataInsightChartResult; import org.openmetadata.schema.dataInsight.custom.DataInsightCustomChart; import org.openmetadata.schema.dataInsight.custom.DataInsightCustomChartResultList; +import org.openmetadata.schema.entity.data.PageHierarchy; import org.openmetadata.schema.entity.data.QueryCostSearchResult; import org.openmetadata.schema.search.AggregationRequest; import org.openmetadata.schema.search.SearchRequest; @@ -58,7 +71,10 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.LayerPaging; import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.schema.utils.ResultList; import org.openmetadata.search.IndexMapping; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.KnowledgePageRepository; import org.openmetadata.service.search.SearchAggregation; import org.openmetadata.service.search.SearchClient; import org.openmetadata.service.search.SearchHealthStatus; @@ -70,6 +86,8 @@ import org.openmetadata.service.search.queries.QueryBuilderFactory; import org.openmetadata.service.search.security.RBACConditionEvaluator; import org.openmetadata.service.security.policyevaluator.SubjectContext; +import org.openmetadata.service.util.FullyQualifiedName; +import org.openmetadata.service.util.SearchUtils; import org.openmetadata.service.workflows.searchIndex.ReindexingUtil; @Slf4j @@ -407,11 +425,7 @@ public SearchResultListMapper listWithDeepPagination( @Override public SearchLineageResult searchLineage(SearchLineageRequest lineageRequest) throws IOException { - if (lineageGraphBuilder == null) { - throw new UnsupportedOperationException( - "Lineage features are not available in this deployment"); - } - return lineageGraphBuilder.searchLineage(lineageRequest); + return ensureLineageBuilder().searchLineage(lineageRequest); } @Override @@ -428,11 +442,7 @@ public Response searchWithDirectQuery(SearchRequest request, SubjectContext subj @Override public SearchLineageResult searchLineageWithDirection(SearchLineageRequest lineageRequest) throws IOException { - if (lineageGraphBuilder == null) { - throw new UnsupportedOperationException( - "Lineage features are not available in this deployment"); - } - return lineageGraphBuilder.searchLineageWithDirection(lineageRequest); + return ensureLineageBuilder().searchLineageWithDirection(lineageRequest); } @Override @@ -446,39 +456,48 @@ public LineagePaginationInfo getLineagePaginationInfo( Long startTime, Long endTime) throws IOException { - if (lineageGraphBuilder == null) { - throw new UnsupportedOperationException( - "Lineage features are not available in this deployment"); - } - return lineageGraphBuilder.getLineagePaginationInfo( - fqn, - upstreamDepth, - downstreamDepth, - queryFilter, - includeDeleted, - entityType, - startTime, - endTime); + return ensureLineageBuilder() + .getLineagePaginationInfo( + fqn, + upstreamDepth, + downstreamDepth, + queryFilter, + includeDeleted, + entityType, + startTime, + endTime); } @Override public SearchLineageResult searchLineageByEntityCount(EntityCountLineageRequest request) throws IOException { - if (lineageGraphBuilder == null) { - throw new UnsupportedOperationException( - "Lineage features are not available in this deployment"); - } - return lineageGraphBuilder.searchLineageByEntityCount(request); + return ensureLineageBuilder().searchLineageByEntityCount(request); } @Override public SearchLineageResult searchPlatformLineage( String index, String queryFilter, boolean deleted) throws IOException { - if (lineageGraphBuilder == null) { + return ensureLineageBuilder().getPlatformLineage(index, queryFilter, deleted); + } + + private ESLineageGraphBuilder ensureLineageBuilder() { + ESLineageGraphBuilder builder = lineageGraphBuilder; + if (builder == null && newClient != null) { + synchronized (this) { + builder = lineageGraphBuilder; + if (builder == null) { + LOG.info("Initializing ESLineageGraphBuilder with settings now available"); + builder = new ESLineageGraphBuilder(newClient); + lineageGraphBuilder = builder; + LOG.info("ESLineageGraphBuilder initialization completed"); + } + } + } + if (builder == null) { throw new UnsupportedOperationException( "Lineage features are not available in this deployment"); } - return lineageGraphBuilder.getPlatformLineage(index, queryFilter, deleted); + return builder; } @Override @@ -1111,16 +1130,10 @@ public SearchSchemaEntityRelationshipResult getSchemaEntityRelationship( @Override public void initializeLineageBuilders() { - if (lineageGraphBuilder == null && newClient != null) { - synchronized (this) { - if (lineageGraphBuilder == null) { - LOG.info("Initializing ESLineageGraphBuilder with settings now available"); - lineageGraphBuilder = new ESLineageGraphBuilder(newClient); - LOG.info("ESLineageGraphBuilder initialization completed"); - } - } + if (newClient != null) { + ensureLineageBuilder(); } else { - LOG.debug("ESLineageGraphBuilder already initialized or newClient is null"); + LOG.debug("ESLineageGraphBuilder cannot be initialized because newClient is null"); } } @@ -1128,33 +1141,29 @@ public void initializeLineageBuilders() { @Override @lombok.SneakyThrows - public org.openmetadata.schema.utils.ResultList - listPageHierarchy(String parentFqn, String pageType, int offset, int limit) { + public ResultList listPageHierarchy( + String parentFqn, String pageType, int offset, int limit) { return getPageHierarchyFromSearch(parentFqn, pageType, offset, limit); } @Override @lombok.SneakyThrows - public org.openmetadata.schema.utils.ResultList - listPageHierarchyForActivePage(String activeFqn, String pageType, int offset, int limit) { + public ResultList listPageHierarchyForActivePage( + String activeFqn, String pageType, int offset, int limit) { return getPageHierarchyFromSearchForActivePage(activeFqn, pageType, offset, limit); } - private org.openmetadata.schema.utils.ResultList< - org.openmetadata.schema.entity.data.PageHierarchy> - getPageHierarchyFromSearch(String parentFqn, String pageType, int offset, int limit) - throws java.io.IOException { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query boolQuery = - buildPageHierarchyBoolQuery(parentFqn, pageType); + private ResultList getPageHierarchyFromSearch( + String parentFqn, String pageType, int offset, int limit) throws IOException { + Query boolQuery = buildPageHierarchyBoolQuery(parentFqn, pageType); es.co.elastic.clients.elasticsearch.core.SearchRequest searchRequest = es.co.elastic.clients.elasticsearch.core.SearchRequest.of( s -> s.index( - org.openmetadata.service.Entity.getSearchRepository() + Entity.getSearchRepository() .getIndexOrAliasName( - org.openmetadata.service.jdbi3.KnowledgePageRepository - .KNOWLEDGE_PAGE_TERM_SEARCH_INDEX)) + KnowledgePageRepository.KNOWLEDGE_PAGE_TERM_SEARCH_INDEX)) .query(boolQuery) // Stable sort so from/size pagination cannot miss/duplicate hits. // fullyQualifiedName is a keyword field with doc_values and is unique per @@ -1162,62 +1171,41 @@ public void initializeLineageBuilders() { // needed. _id cannot be used as a sort field on ES 9.x / OpenSearch 3.x // without setting indices.id_field_data.enabled=true at the cluster level. .sort( - sort -> - sort.field( - f -> - f.field("fullyQualifiedName") - .order( - es.co.elastic.clients.elasticsearch._types.SortOrder - .Asc))) + sort -> sort.field(f -> f.field("fullyQualifiedName").order(SortOrder.Asc))) .from(offset) .size(limit)); - es.co.elastic.clients.elasticsearch.core.SearchResponse - searchResponse = newClient.search(searchRequest, es.co.elastic.clients.json.JsonData.class); - java.util.List pageHierarchies = - processPageHierarchyHits(searchResponse); + SearchResponse searchResponse = newClient.search(searchRequest, JsonData.class); + List pageHierarchies = processPageHierarchyHits(searchResponse); int total = 0; if (searchResponse != null && searchResponse.hits() != null && searchResponse.hits().total() != null) { total = (int) searchResponse.hits().total().value(); } - return new org.openmetadata.schema.utils.ResultList<>( - pageHierarchies, offset, pageHierarchies.size(), total); + return new ResultList<>(pageHierarchies, offset, pageHierarchies.size(), total); } - private org.openmetadata.schema.utils.ResultList< - org.openmetadata.schema.entity.data.PageHierarchy> - getPageHierarchyFromSearchForActivePage( - String activeFqn, String pageType, int offset, int limit) throws java.io.IOException { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query boolQuery = - buildPageHierarchyBoolQueryForActivePage(activeFqn, pageType); + private ResultList getPageHierarchyFromSearchForActivePage( + String activeFqn, String pageType, int offset, int limit) throws IOException { + Query boolQuery = buildPageHierarchyBoolQueryForActivePage(activeFqn, pageType); es.co.elastic.clients.elasticsearch.core.SearchRequest searchRequest = es.co.elastic.clients.elasticsearch.core.SearchRequest.of( s -> s.index( - org.openmetadata.service.Entity.getSearchRepository() + Entity.getSearchRepository() .getIndexOrAliasName( - org.openmetadata.service.jdbi3.KnowledgePageRepository - .KNOWLEDGE_PAGE_TERM_SEARCH_INDEX)) + KnowledgePageRepository.KNOWLEDGE_PAGE_TERM_SEARCH_INDEX)) .query(boolQuery) // Stable sort by fqn (keyword, unique per page). See note above on _id. .sort( - sort -> - sort.field( - f -> - f.field("fullyQualifiedName") - .order( - es.co.elastic.clients.elasticsearch._types.SortOrder - .Asc))) + sort -> sort.field(f -> f.field("fullyQualifiedName").order(SortOrder.Asc))) .from(offset) .size(limit)); - es.co.elastic.clients.elasticsearch.core.SearchResponse - searchResponse = newClient.search(searchRequest, es.co.elastic.clients.json.JsonData.class); - java.util.List pageHierarchies = - processPageHierarchyHits(searchResponse); + SearchResponse searchResponse = newClient.search(searchRequest, JsonData.class); + List pageHierarchies = processPageHierarchyHits(searchResponse); pageHierarchies = buildPageNestedSearchHierarchy(pageHierarchies); int total = 0; if (searchResponse != null @@ -1225,106 +1213,58 @@ public void initializeLineageBuilders() { && searchResponse.hits().total() != null) { total = (int) searchResponse.hits().total().value(); } - return new org.openmetadata.schema.utils.ResultList<>( - pageHierarchies, offset, pageHierarchies.size(), total); + return new ResultList<>(pageHierarchies, offset, pageHierarchies.size(), total); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildPageHierarchyBoolQuery( - String parentFqn, String pageType) { - es.co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery.Builder boolQueryBuilder = - new es.co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery.Builder(); + private Query buildPageHierarchyBoolQuery(String parentFqn, String pageType) { + BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder(); - if (org.openmetadata.common.utils.CommonUtil.nullOrEmpty(parentFqn)) { + if (CommonUtil.nullOrEmpty(parentFqn)) { boolQueryBuilder.must( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> - q.term( - t -> - t.field("fqnDepth") - .value( - es.co.elastic.clients.elasticsearch._types.FieldValue.of(1))))); + Query.of(q -> q.term(t -> t.field("fqnDepth").value(FieldValue.of(1))))); } else { - int parentDepth = org.openmetadata.service.util.FullyQualifiedName.split(parentFqn).length; + int parentDepth = FullyQualifiedName.split(parentFqn).length; boolQueryBuilder.must( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> q.prefix(p -> p.field("fullyQualifiedName").value(parentFqn + ".")))); + Query.of(q -> q.prefix(p -> p.field("fullyQualifiedName").value(parentFqn + ".")))); boolQueryBuilder.must( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> - q.term( - t -> - t.field("fqnDepth") - .value( - es.co.elastic.clients.elasticsearch._types.FieldValue.of( - parentDepth + 1))))); + Query.of(q -> q.term(t -> t.field("fqnDepth").value(FieldValue.of(parentDepth + 1))))); } - if (!org.openmetadata.common.utils.CommonUtil.nullOrEmpty(pageType)) { + if (!CommonUtil.nullOrEmpty(pageType)) { boolQueryBuilder.must( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> - q.term( - t -> - t.field("pageType") - .value( - es.co.elastic.clients.elasticsearch._types.FieldValue.of( - pageType))))); + Query.of(q -> q.term(t -> t.field("pageType").value(FieldValue.of(pageType))))); } - return es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> q.bool(boolQueryBuilder.build())); + return Query.of(q -> q.bool(boolQueryBuilder.build())); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query - buildPageHierarchyBoolQueryForActivePage(String activeFqn, String pageType) { - es.co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery.Builder boolQueryBuilder = - new es.co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery.Builder(); + private Query buildPageHierarchyBoolQueryForActivePage(String activeFqn, String pageType) { + BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder(); - String rootParentFqn = org.openmetadata.service.util.FullyQualifiedName.split(activeFqn)[0]; + String rootParentFqn = FullyQualifiedName.split(activeFqn)[0]; boolQueryBuilder.should( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> - q.term( - t -> - t.field("fqnDepth") - .value(es.co.elastic.clients.elasticsearch._types.FieldValue.of(1))))); + Query.of(q -> q.term(t -> t.field("fqnDepth").value(FieldValue.of(1))))); boolQueryBuilder.should( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> q.prefix(p -> p.field("fullyQualifiedName").value(rootParentFqn + ".")))); + Query.of(q -> q.prefix(p -> p.field("fullyQualifiedName").value(rootParentFqn + ".")))); boolQueryBuilder.minimumShouldMatch("1"); - if (!org.openmetadata.common.utils.CommonUtil.nullOrEmpty(pageType)) { + if (!CommonUtil.nullOrEmpty(pageType)) { boolQueryBuilder.must( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> - q.term( - t -> - t.field("pageType") - .value( - es.co.elastic.clients.elasticsearch._types.FieldValue.of( - pageType))))); + Query.of(q -> q.term(t -> t.field("pageType").value(FieldValue.of(pageType))))); } - return es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> q.bool(boolQueryBuilder.build())); + return Query.of(q -> q.bool(boolQueryBuilder.build())); } - private java.util.List - processPageHierarchyHits( - es.co.elastic.clients.elasticsearch.core.SearchResponse< - es.co.elastic.clients.json.JsonData> - searchResponse) - throws java.io.IOException { - java.util.List pageHierarchies = - new java.util.ArrayList<>(); + private List processPageHierarchyHits(SearchResponse searchResponse) + throws IOException { + List pageHierarchies = new ArrayList<>(); if (searchResponse != null && searchResponse.hits() != null) { - for (es.co.elastic.clients.elasticsearch.core.search.Hit - hit : searchResponse.hits().hits()) { + for (Hit hit : searchResponse.hits().hits()) { if (hit.source() != null) { - java.util.Map sourceMap = EsUtils.jsonDataToMap(hit.source()); - org.openmetadata.schema.entity.data.PageHierarchy page = - org.openmetadata.service.util.SearchUtils.getPageHierarchy(sourceMap); + Map sourceMap = EsUtils.jsonDataToMap(hit.source()); + PageHierarchy page = SearchUtils.getPageHierarchy(sourceMap); pageHierarchies.add(page); } } @@ -1339,48 +1279,40 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildPageHier * instead of one search per page (N+1). Uses a filters aggregation keyed by page id, * where each bucket matches descendants via the page's fullyQualifiedName prefix. */ - private void populateChildrenCounts( - java.util.List pageHierarchies) - throws java.io.IOException { + private void populateChildrenCounts(List pageHierarchies) throws IOException { if (pageHierarchies.isEmpty()) { return; } - java.util.Map filters = - new java.util.HashMap<>(); - for (org.openmetadata.schema.entity.data.PageHierarchy page : pageHierarchies) { + Map filters = new HashMap<>(); + for (PageHierarchy page : pageHierarchies) { if (page.getId() == null || page.getFullyQualifiedName() == null || page.getFullyQualifiedName().isEmpty()) { continue; } String fqnPrefix = page.getFullyQualifiedName() + "."; - int childDepth = - org.openmetadata.service.util.FullyQualifiedName.split(page.getFullyQualifiedName()) - .length - + 1; + int childDepth = FullyQualifiedName.split(page.getFullyQualifiedName()).length + 1; // Match only direct children: FQN starts with "." AND fqnDepth is // exactly one deeper than the parent. Descendants deeper than that are excluded. filters.put( page.getId().toString(), - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query.of( q -> q.bool( b -> b.must( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query.of( m -> m.prefix( p -> p.field("fullyQualifiedName").value(fqnPrefix)))) .must( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query.of( m -> m.term( t -> t.field("fqnDepth") - .value( - es.co.elastic.clients.elasticsearch._types - .FieldValue.of(childDepth)))))))); + .value(FieldValue.of(childDepth)))))))); page.setChildrenCount(0); } @@ -1392,18 +1324,16 @@ private void populateChildrenCounts( es.co.elastic.clients.elasticsearch.core.SearchRequest.of( s -> s.index( - org.openmetadata.service.Entity.getSearchRepository() + Entity.getSearchRepository() .getIndexOrAliasName( - org.openmetadata.service.jdbi3.KnowledgePageRepository - .KNOWLEDGE_PAGE_TERM_SEARCH_INDEX)) + KnowledgePageRepository.KNOWLEDGE_PAGE_TERM_SEARCH_INDEX)) .size(0) .aggregations( "children_by_parent", a -> a.filters(f -> f.filters(fs -> fs.keyed(filters))))); - es.co.elastic.clients.elasticsearch.core.SearchResponse - aggregationResponse = - newClient.search(aggregationRequest, es.co.elastic.clients.json.JsonData.class); + SearchResponse aggregationResponse = + newClient.search(aggregationRequest, JsonData.class); if (aggregationResponse == null || aggregationResponse.aggregations() == null @@ -1411,54 +1341,43 @@ private void populateChildrenCounts( return; } - java.util.Map - buckets = - aggregationResponse - .aggregations() - .get("children_by_parent") - .filters() - .buckets() - .keyed(); + Map buckets = + aggregationResponse.aggregations().get("children_by_parent").filters().buckets().keyed(); - for (org.openmetadata.schema.entity.data.PageHierarchy page : pageHierarchies) { + for (PageHierarchy page : pageHierarchies) { if (page.getId() == null) { continue; } - es.co.elastic.clients.elasticsearch._types.aggregations.FiltersBucket bucket = - buckets.get(page.getId().toString()); + FiltersBucket bucket = buckets.get(page.getId().toString()); if (bucket != null) { page.setChildrenCount((int) bucket.docCount()); } } } - private java.util.List - buildPageNestedSearchHierarchy( - java.util.List pageHierarchyList) { - java.util.Map - pageHierarchyMap = - pageHierarchyList.stream() - // Skip hits that lost their id during parsing (SearchUtils returns a - // null id for malformed/missing UUID strings) so Collectors.toMap - // does not throw on the null key. - .filter(p -> p.getId() != null) - .collect( - java.util.stream.Collectors.toMap( - org.openmetadata.schema.entity.data.PageHierarchy::getId, - page -> { - page.setChildren(new java.util.ArrayList<>()); - return page; - }, - (existing, replacement) -> existing, - java.util.LinkedHashMap::new)); - - java.util.List rootPages = - new java.util.ArrayList<>(); - - for (org.openmetadata.schema.entity.data.PageHierarchy page : pageHierarchyMap.values()) { - java.util.UUID parentId = page.getParent() != null ? page.getParent().getId() : null; - org.openmetadata.schema.entity.data.PageHierarchy parentPage = - parentId != null ? pageHierarchyMap.get(parentId) : null; + private List buildPageNestedSearchHierarchy( + List pageHierarchyList) { + Map pageHierarchyMap = + pageHierarchyList.stream() + // Skip hits that lost their id during parsing (SearchUtils returns a + // null id for malformed/missing UUID strings) so Collectors.toMap + // does not throw on the null key. + .filter(p -> p.getId() != null) + .collect( + Collectors.toMap( + PageHierarchy::getId, + page -> { + page.setChildren(new ArrayList<>()); + return page; + }, + (existing, replacement) -> existing, + LinkedHashMap::new)); + + List rootPages = new ArrayList<>(); + + for (PageHierarchy page : pageHierarchyMap.values()) { + UUID parentId = page.getParent() != null ? page.getParent().getId() : null; + PageHierarchy parentPage = parentId != null ? pageHierarchyMap.get(parentId) : null; if (parentPage != null) { parentPage.getChildren().add(page); } else { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchIndexManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchIndexManager.java index e352fd683f64..2c6491fb5f91 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchIndexManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchIndexManager.java @@ -136,6 +136,7 @@ public void deleteIndex(IndexMapping indexMapping) { public void createAliases(IndexMapping indexMapping) { try { Set aliases = new HashSet<>(indexMapping.getParentAliases(clusterAlias)); + aliases.addAll(indexMapping.getDataInsightAliases(clusterAlias)); aliases.add(indexMapping.getAlias(clusterAlias)); addIndexAlias(indexMapping, aliases.toArray(new String[0])); } catch (Exception e) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchSourceBuilderFactory.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchSourceBuilderFactory.java index 0af9d81409c7..3a176a9e6146 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchSourceBuilderFactory.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchSourceBuilderFactory.java @@ -13,8 +13,13 @@ import static org.openmetadata.service.search.SearchUtils.isServiceIndex; import static org.openmetadata.service.search.SearchUtils.isTimeSeriesIndex; +import es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier; +import es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode; import es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore; +import es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode; +import es.co.elastic.clients.elasticsearch._types.query_dsl.Operator; import es.co.elastic.clients.elasticsearch._types.query_dsl.Query; +import es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType; import es.co.elastic.clients.elasticsearch.core.search.Highlight; import java.util.ArrayList; import java.util.HashMap; @@ -26,10 +31,13 @@ import org.openmetadata.schema.api.search.AssetTypeConfiguration; import org.openmetadata.schema.api.search.FieldBoost; import org.openmetadata.schema.api.search.FieldValueBoost; +import org.openmetadata.schema.api.search.RankingConfiguration; +import org.openmetadata.schema.api.search.RankingStage; import org.openmetadata.schema.api.search.SearchSettings; import org.openmetadata.schema.api.search.TermBoost; import org.openmetadata.service.Entity; import org.openmetadata.service.search.CustomPropertySearchFields; +import org.openmetadata.service.search.SearchRankingHelper; import org.openmetadata.service.search.SearchSourceBuilderFactory; import org.openmetadata.service.search.indexes.ColumnSearchIndex; import org.openmetadata.service.search.indexes.ContextMemoryIndex; @@ -59,6 +67,7 @@ public class ElasticSearchSourceBuilderFactory private static final float DEFAULT_TIE_BREAKER = 0.3f; private static final float DEFAULT_BOOST = 1.0f; private static final float FUNCTION_BOOST_FACTOR = 0.3f; + private static final String RANKING_QUERY_PREFIX = "ranking:"; private final SearchSettings searchSettings; @@ -207,8 +216,7 @@ private Map extractAllFields(AssetTypeConfiguration assetConfig) return allFields; } - public es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildSearchQueryBuilderV2( - String query, Map fields) { + public Query buildSearchQueryBuilderV2(String query, Map fields) { Map fuzzyFields = fields.entrySet().stream() .filter(entry -> isFuzzyField(entry.getKey())) @@ -219,23 +227,23 @@ public es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildSearchQue .filter(entry -> isNonFuzzyField(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query fuzzyQuery = + Query fuzzyQuery = ElasticQueryBuilder.queryStringQuery( query, fuzzyFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.And, + Operator.And, "1", 10, 3, DEFAULT_TIE_BREAKER, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.MostFields); + TextQueryType.MostFields); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query nonFuzzyQuery = + Query nonFuzzyQuery = ElasticQueryBuilder.multiMatchQuery( query, nonFuzzyFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.MostFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.And, + TextQueryType.MostFields, + Operator.And, String.valueOf(DEFAULT_TIE_BREAKER), "0"); @@ -247,10 +255,7 @@ public es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildSearchQue } public ElasticSearchRequestBuilder searchBuilderV2( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query query, - es.co.elastic.clients.elasticsearch.core.search.Highlight highlightBuilder, - int fromOffset, - int size) { + Query query, Highlight highlightBuilder, int fromOffset, int size) { ElasticSearchRequestBuilder builder = new ElasticSearchRequestBuilder(); builder.query(query); if (highlightBuilder != null) { @@ -263,8 +268,7 @@ public ElasticSearchRequestBuilder searchBuilderV2( public ElasticSearchRequestBuilder buildUserOrTeamSearchBuilderV2( String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder = - buildSearchQueryBuilderV2(query, UserIndex.getFields()); + Query queryBuilder = buildSearchQueryBuilderV2(query, UserIndex.getFields()); return searchBuilderV2(queryBuilder, null, from, size); } @@ -292,8 +296,7 @@ private ElasticSearchRequestBuilder addAggregationV2( return searchRequestBuilder; } - public es.co.elastic.clients.elasticsearch.core.search.Highlight buildHighlightsV2( - List fields) { + public Highlight buildHighlightsV2(List fields) { ElasticHighlightBuilder hb = new ElasticHighlightBuilder(); hb.preTags(PRE_TAG); hb.postTags(POST_TAG); @@ -373,40 +376,34 @@ public ElasticSearchRequestBuilder buildTimeSeriesSearchBuilderV2( } public ElasticSearchRequestBuilder buildColumnSearchBuilderV2(String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder; + Query queryBuilder; if (nullOrEmpty(query) || "*".equals(query.trim())) { - queryBuilder = - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of(q -> q.matchAll(m -> m)); + queryBuilder = Query.of(q -> q.matchAll(m -> m)); } else { Map fields = ColumnSearchIndex.getFields(); queryBuilder = ElasticQueryBuilder.multiMatchQuery( query, fields, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.BestFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.Or, + TextQueryType.BestFields, + Operator.Or, String.valueOf(DEFAULT_TIE_BREAKER), "0"); } - es.co.elastic.clients.elasticsearch.core.search.Highlight hb = - buildHighlightsV2(List.of("name", "displayName", "description")); + Highlight hb = buildHighlightsV2(List.of("name", "displayName", "description")); return searchBuilderV2(queryBuilder, hb, from, size); } public ElasticSearchRequestBuilder buildServiceSearchBuilderV2(String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder = - buildSearchQueryBuilderV2(query, SearchIndex.getDefaultFields()); - es.co.elastic.clients.elasticsearch.core.search.Highlight hb = - buildHighlightsV2(new ArrayList<>()); + Query queryBuilder = buildSearchQueryBuilderV2(query, SearchIndex.getDefaultFields()); + Highlight hb = buildHighlightsV2(new ArrayList<>()); return searchBuilderV2(queryBuilder, hb, from, size); } public ElasticSearchRequestBuilder buildContextMemorySearchBuilderV2( String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder = - buildSearchQueryBuilderV2(query, ContextMemoryIndex.getFields()); - es.co.elastic.clients.elasticsearch.core.search.Highlight hb = - buildHighlightsV2(List.of("title", "summary", "question", "answer")); + Query queryBuilder = buildSearchQueryBuilderV2(query, ContextMemoryIndex.getFields()); + Highlight hb = buildHighlightsV2(List.of("title", "summary", "question", "answer")); return searchBuilderV2(queryBuilder, hb, from, size); } @@ -429,12 +426,9 @@ public ElasticSearchRequestBuilder buildDataAssetSearchBuilderV2( boolean explain, boolean includeAggregations) { AssetTypeConfiguration assetConfig = getAssetConfiguration(indexName); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query baseQuery = - buildBaseQueryV2(query, assetConfig); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query finalQuery = - applyFunctionScoringV2(baseQuery, assetConfig); - es.co.elastic.clients.elasticsearch.core.search.Highlight highlightBuilder = - buildHighlightingIfNeededV2(query, assetConfig); + Query baseQuery = buildBaseQueryV2(query, assetConfig); + Query finalQuery = applyFunctionScoringV2(baseQuery, assetConfig); + Highlight highlightBuilder = buildHighlightingIfNeededV2(query, assetConfig); ElasticSearchRequestBuilder searchRequestBuilder = createSearchSourceBuilderV2(finalQuery, from, size); @@ -459,10 +453,8 @@ public ElasticSearchRequestBuilder buildAggregateSearchBuilderV2( public ElasticSearchRequestBuilder buildAggregateSearchBuilderV2( String query, int from, int size, boolean includeAggregations) { AssetTypeConfiguration compositeConfig = buildCompositeAssetConfig(searchSettings); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query baseQuery = - buildQueryWithMatchTypesV2(query, compositeConfig); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query finalQuery = - applyFunctionScoringV2(baseQuery, compositeConfig); + Query baseQuery = buildQueryWithMatchTypesV2(query, compositeConfig); + Query finalQuery = applyFunctionScoringV2(baseQuery, compositeConfig); ElasticSearchRequestBuilder searchRequestBuilder = searchBuilderV2(finalQuery, null, from, size); @@ -484,34 +476,28 @@ public ElasticSearchRequestBuilder buildDataQualitySearchBuilderV2( } public ElasticSearchRequestBuilder buildTestCaseSearchV2(String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder = - buildSearchQueryBuilderV2(query, TestCaseIndex.getFields()); - es.co.elastic.clients.elasticsearch.core.search.Highlight hb = - buildHighlightsV2(List.of("testSuite.name", "testSuite.description")); + Query queryBuilder = buildSearchQueryBuilderV2(query, TestCaseIndex.getFields()); + Highlight hb = buildHighlightsV2(List.of("testSuite.name", "testSuite.description")); return searchBuilderV2(queryBuilder, hb, from, size); } public ElasticSearchRequestBuilder buildTestCaseResultSearchV2(String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder = - buildSearchQueryBuilderV2(query, TestCaseResultIndex.getFields()); - es.co.elastic.clients.elasticsearch.core.search.Highlight hb = - buildHighlightsV2(new ArrayList<>()); + Query queryBuilder = buildSearchQueryBuilderV2(query, TestCaseResultIndex.getFields()); + Highlight hb = buildHighlightsV2(new ArrayList<>()); return searchBuilderV2(queryBuilder, hb, from, size); } public ElasticSearchRequestBuilder buildTestCaseResolutionStatusSearchV2( String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder = + Query queryBuilder = buildSearchQueryBuilderV2(query, TestCaseResolutionStatusIndex.getFields()); - es.co.elastic.clients.elasticsearch.core.search.Highlight hb = - buildHighlightsV2(new ArrayList<>()); + Highlight hb = buildHighlightsV2(new ArrayList<>()); return searchBuilderV2(queryBuilder, hb, from, size); } public ElasticSearchRequestBuilder buildCostAnalysisReportDataSearchV2( String query, int from, int size) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryBuilder = - ElasticQueryBuilder.queryStringQuery(query); + Query queryBuilder = ElasticQueryBuilder.queryStringQuery(query); return searchBuilderV2(queryBuilder, null, from, size); } @@ -522,10 +508,8 @@ public ElasticSearchRequestBuilder buildCommonSearchBuilderV2(String query, int query, defaultConfig.getAssetType()); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query baseQuery = - buildQueryWithMatchTypesV2(query, defaultConfig); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query finalQuery = - applyGlobalBoostsV2(baseQuery); + Query baseQuery = buildQueryWithMatchTypesV2(query, defaultConfig); + Query finalQuery = applyGlobalBoostsV2(baseQuery); ElasticSearchRequestBuilder searchRequestBuilder = createCommonSearchSourceBuilderV2(finalQuery, from, size); @@ -538,21 +522,17 @@ public ElasticSearchRequestBuilder buildCommonSearchBuilderV2(String query, int public ElasticSearchRequestBuilder buildEntitySpecificAggregateSearchBuilderV2( String query, int from, int size) { AssetTypeConfiguration compositeConfig = buildCompositeAssetConfig(searchSettings); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query baseQuery = - buildQueryWithMatchTypesV2(query, compositeConfig); + Query baseQuery = buildQueryWithMatchTypesV2(query, compositeConfig); - List functions = - collectAllBoostFunctionsV2(); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query finalQuery = - applyBoostFunctionsV2(baseQuery, functions); + List functions = collectAllBoostFunctionsV2(); + Query finalQuery = applyBoostFunctionsV2(baseQuery, functions); ElasticSearchRequestBuilder searchRequestBuilder = searchBuilderV2(finalQuery, null, from, size); return addAggregationV2(searchRequestBuilder); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildBaseQueryV2( - String query, AssetTypeConfiguration assetConfig) { + private Query buildBaseQueryV2(String query, AssetTypeConfiguration assetConfig) { if (query == null || query.trim().isEmpty() || query.trim().equals("*")) { return ElasticQueryBuilder.boolQuery().must(ElasticQueryBuilder.matchAllQuery()).build(); } else if (containsQuerySyntax(query)) { @@ -562,30 +542,29 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildBaseQuer } } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildComplexSyntaxQueryV2( - String query, AssetTypeConfiguration assetConfig) { + private Query buildComplexSyntaxQueryV2(String query, AssetTypeConfiguration assetConfig) { Map fuzzyFields = new HashMap<>(); Map nonFuzzyFields = new HashMap<>(); classifyFields(assetConfig, fuzzyFields, nonFuzzyFields); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query fuzzyQuery = + Query fuzzyQuery = ElasticQueryBuilder.queryStringQuery( query, fuzzyFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.And, + Operator.And, "1", 10, 3, DEFAULT_TIE_BREAKER, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.MostFields); + TextQueryType.MostFields); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query nonFuzzyQuery = + Query nonFuzzyQuery = ElasticQueryBuilder.multiMatchQuery( query, nonFuzzyFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.MostFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.And, + TextQueryType.MostFields, + Operator.And, String.valueOf(DEFAULT_TIE_BREAKER), "0"); @@ -597,8 +576,60 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildComplexS .build(); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildSimpleQueryV2( - String query, AssetTypeConfiguration assetConfig) { + private Query buildSimpleQueryV2(String query, AssetTypeConfiguration assetConfig) { + RankingConfiguration ranking = SearchRankingHelper.resolveRanking(searchSettings, assetConfig); + if (ranking != null) { + return buildRankedSimpleQueryV2(query, assetConfig, ranking); + } + + ElasticQueryBuilder.BoolQueryBuilder combinedQuery = ElasticQueryBuilder.boolQuery(); + MatchTypeMultipliers multipliers = getMatchTypeMultipliers(assetConfig); + Map> fieldsByMatchType = groupFieldsByMatchType(assetConfig); + + addExactMatchQueriesV2( + combinedQuery, query, fieldsByMatchType.get(MATCH_TYPE_EXACT), multipliers.exactMatch); + addPhraseMatchQueriesV2( + combinedQuery, query, fieldsByMatchType.get(MATCH_TYPE_PHRASE), multipliers.phraseMatch); + addFuzzyMatchQueriesV2( + combinedQuery, query, fieldsByMatchType.get(MATCH_TYPE_FUZZY), multipliers.fuzzyMatch); + addStandardMatchQueriesV2(combinedQuery, query, fieldsByMatchType.get(MATCH_TYPE_STANDARD)); + addCustomPropertyMatchQueriesV2(combinedQuery, query, assetConfig); + + combinedQuery.minimumShouldMatch(1); + return ElasticQueryBuilder.boolQuery().must(combinedQuery.build()).build(); + } + + private Query buildRankedSimpleQueryV2( + String query, AssetTypeConfiguration assetConfig, RankingConfiguration ranking) { + List stageQueries = new ArrayList<>(); + String significantQuery = SearchRankingHelper.significantQueryText(query, ranking); + String exactSignificantQuery = + SearchRankingHelper.significantQueryTextPreservingCase(query, ranking); + + for (RankingStage stage : listOrEmpty(ranking.getStages())) { + Query stageQuery = + buildRankingStageQueryV2(query, significantQuery, exactSignificantQuery, stage); + if (stageQuery != null) { + stageQueries.add(stageQuery); + } + } + + if (stageQueries.isEmpty()) { + return buildLegacySimpleQueryV2(query, assetConfig); + } + + ElasticQueryBuilder.BoolQueryBuilder combinedQuery = ElasticQueryBuilder.boolQuery(); + combinedQuery.should( + stageQueries.size() == 1 + ? stageQueries.getFirst() + : ElasticQueryBuilder.disMaxQuery( + stageQueries, SearchRankingHelper.disMaxTieBreaker(ranking))); + addCustomPropertyMatchQueriesV2(combinedQuery, query, assetConfig); + combinedQuery.minimumShouldMatch(1); + return ElasticQueryBuilder.boolQuery().must(combinedQuery.build()).build(); + } + + private Query buildLegacySimpleQueryV2(String query, AssetTypeConfiguration assetConfig) { ElasticQueryBuilder.BoolQueryBuilder combinedQuery = ElasticQueryBuilder.boolQuery(); MatchTypeMultipliers multipliers = getMatchTypeMultipliers(assetConfig); Map> fieldsByMatchType = groupFieldsByMatchType(assetConfig); @@ -616,6 +647,84 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildSimpleQu return ElasticQueryBuilder.boolQuery().must(combinedQuery.build()).build(); } + private Query buildRankingStageQueryV2( + String originalQuery, + String significantQuery, + String exactSignificantQuery, + RankingStage stage) { + if (stage.getFields() == null || stage.getFields().isEmpty()) { + return null; + } + + RankingStage.MatchType matchType = + stage.getMatchType() == null ? RankingStage.MatchType.STANDARD : stage.getMatchType(); + return switch (matchType) { + case EXACT -> buildExactRankingStageQueryV2(exactSignificantQuery, stage); + case PHRASE -> buildPhraseRankingStageQueryV2(originalQuery, stage); + case FUZZY -> buildTextRankingStageQueryV2( + significantQuery, stage, getFuzziness(significantQuery)); + case TOKEN_COVERAGE, STANDARD -> buildTextRankingStageQueryV2(significantQuery, stage, "0"); + }; + } + + private Query buildExactRankingStageQueryV2(String query, RankingStage stage) { + List exactTexts = SearchRankingHelper.exactMatchTexts(query); + if (exactTexts.isEmpty()) { + return null; + } + + ElasticQueryBuilder.BoolQueryBuilder exactQuery = ElasticQueryBuilder.boolQuery(); + float weight = SearchRankingHelper.stageWeight(stage); + for (String field : stage.getFields()) { + for (int index = 0; index < exactTexts.size(); index++) { + exactQuery.should( + ElasticQueryBuilder.termQuery( + field, + exactTexts.get(index), + weight, + rankingQueryName(stage, field, String.valueOf(index)))); + } + } + exactQuery.minimumShouldMatch(1); + return exactQuery.build(); + } + + private Query buildPhraseRankingStageQueryV2(String query, RankingStage stage) { + ElasticQueryBuilder.BoolQueryBuilder phraseQuery = ElasticQueryBuilder.boolQuery(); + float weight = SearchRankingHelper.stageWeight(stage); + for (String field : stage.getFields()) { + phraseQuery.should( + ElasticQueryBuilder.matchPhraseQuery( + field, query, weight, rankingQueryName(stage, field))); + } + phraseQuery.minimumShouldMatch(1); + return phraseQuery.build(); + } + + private Query buildTextRankingStageQueryV2(String query, RankingStage stage, String fuzziness) { + Map fields = new LinkedHashMap<>(); + stage.getFields().forEach(field -> fields.put(field, DEFAULT_BOOST)); + return ElasticQueryBuilder.multiMatchQuery( + query, + fields, + TextQueryType.BestFields, + Operator.Or, + String.valueOf(DEFAULT_TIE_BREAKER), + fuzziness, + SearchRankingHelper.minimumShouldMatch(stage), + SearchRankingHelper.stageWeight(stage), + rankingQueryName(stage, "text"), + SearchRankingHelper.stageSearchAnalyzer(stage)); + } + + private String rankingQueryName(RankingStage stage, String field) { + return RANKING_QUERY_PREFIX + stage.getName() + ":" + field; + } + + private String rankingQueryName(RankingStage stage, String field, String suffix) { + return rankingQueryName(stage, field) + ":" + suffix; + } + /** * Adds a nested {@code customPropertiesTyped} clause for each admin-configured {@code * extension.} search field. The raw {@code extension} field is {@code enabled:false} so an @@ -631,9 +740,8 @@ private void addCustomPropertyMatchQueriesV2( } } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query customPropertyNestedQueryV2( - String query, CustomPropertySearchFields.Spec spec) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query inner = + private Query customPropertyNestedQueryV2(String query, CustomPropertySearchFields.Spec spec) { + Query inner = ElasticQueryBuilder.boolQuery() .must(customPropertyTermV2(CustomPropertySearchFields.NAME_FIELD, spec.propertyName())) .must(customPropertyValueQueryV2(query, spec)) @@ -642,12 +750,11 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query customPropert CustomPropertySearchFields.CUSTOM_PROPERTIES_TYPED, inner); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query customPropertyValueQueryV2( - String query, CustomPropertySearchFields.Spec spec) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query result; + private Query customPropertyValueQueryV2(String query, CustomPropertySearchFields.Spec spec) { + Query result; if (spec.exact()) { result = - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query.of( q -> q.term( t -> @@ -656,7 +763,7 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query customPropert .boost(spec.boost()))); } else { result = - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query.of( q -> q.match( m -> @@ -667,10 +774,8 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query customPropert return result; } - private static es.co.elastic.clients.elasticsearch._types.query_dsl.Query customPropertyTermV2( - String field, String value) { - return es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( - q -> q.term(t -> t.field(field).value(value))); + private static Query customPropertyTermV2(String field, String value) { + return Query.of(q -> q.term(t -> t.field(field).value(value))); } private void addExactMatchQueriesV2( @@ -683,7 +788,7 @@ private void addExactMatchQueriesV2( fields.forEach( (field, boost) -> exactMatchQuery.should( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query.of( q -> q.term( t -> @@ -706,7 +811,7 @@ private void addPhraseMatchQueriesV2( fields.forEach( (field, boost) -> phraseMatchQuery.should( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query.of( q -> q.matchPhrase( m -> m.field(field).query(query).boost(boost * multiplier))))); @@ -735,21 +840,18 @@ private void addFuzzyMatchQueriesV2( String fuzziness = getFuzziness(query); int maxExpansions = getMaxExpansions(query); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query fuzzyQuery = - es.co.elastic.clients.elasticsearch._types.query_dsl.Query.of( + Query fuzzyQuery = + Query.of( q -> q.multiMatch( m -> m.query(query) .fields(fieldList) - .type( - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType - .MostFields) + .type(TextQueryType.MostFields) .fuzziness(fuzziness) .maxExpansions(maxExpansions) .prefixLength(1) - .operator( - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.Or) + .operator(Operator.Or) .minimumShouldMatch(MINIMUM_SHOULD_MATCH) .tieBreaker((double) DEFAULT_TIE_BREAKER) .boost(multiplier))); @@ -773,55 +875,46 @@ private void addStandardMatchQueriesV2( .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (!fuzzyFields.isEmpty()) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query fuzzyQueryBuilder = - createStandardFuzzyQueryV2(query, fuzzyFields); + Query fuzzyQueryBuilder = createStandardFuzzyQueryV2(query, fuzzyFields); combinedQuery.should(fuzzyQueryBuilder); } if (!nonFuzzyFields.isEmpty()) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query nonFuzzyQueryBuilder = - createStandardNonFuzzyQueryV2(query, nonFuzzyFields); + Query nonFuzzyQueryBuilder = createStandardNonFuzzyQueryV2(query, nonFuzzyFields); combinedQuery.should(nonFuzzyQueryBuilder); } } } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query createStandardFuzzyQueryV2( - String query, Map fields) { + private Query createStandardFuzzyQueryV2(String query, Map fields) { return ElasticQueryBuilder.multiMatchQuery( query, fields, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.MostFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.Or, + TextQueryType.MostFields, + Operator.Or, String.valueOf(DEFAULT_TIE_BREAKER), getFuzziness(query)); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query createStandardNonFuzzyQueryV2( - String query, Map fields) { + private Query createStandardNonFuzzyQueryV2(String query, Map fields) { return ElasticQueryBuilder.multiMatchQuery( query, fields, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.MostFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.And, + TextQueryType.MostFields, + Operator.And, String.valueOf(DEFAULT_TIE_BREAKER), "0"); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore - buildTermBoostFunctionV2(TermBoost tb) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query filter = - ElasticQueryBuilder.termQuery(tb.getField(), tb.getValue()); + private FunctionScore buildTermBoostFunctionV2(TermBoost tb) { + Query filter = ElasticQueryBuilder.termQuery(tb.getField(), tb.getValue()); return ElasticQueryBuilder.weightFunction(filter, tb.getBoost()); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore - buildFieldValueBoostFunctionV2(FieldValueBoost fvb) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query condition = - buildConditionQueryV2(fvb); + private FunctionScore buildFieldValueBoostFunctionV2(FieldValueBoost fvb) { + Query condition = buildConditionQueryV2(fvb); - es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier modifier = - toFieldValueFactorModifierV2(fvb.getModifier()); + FieldValueFactorModifier modifier = toFieldValueFactorModifierV2(fvb.getModifier()); return ElasticQueryBuilder.fieldValueFactorFunction( condition, @@ -831,8 +924,7 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query createStandar modifier); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildConditionQueryV2( - FieldValueBoost fvb) { + private Query buildConditionQueryV2(FieldValueBoost fvb) { if (fvb.getCondition() == null || fvb.getCondition().getRange() == null) { return ElasticQueryBuilder.matchAllQuery(); } @@ -848,62 +940,48 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildConditio return ElasticQueryBuilder.rangeQuery(field, gte, lte, gt, lt); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier - toFieldValueFactorModifierV2(FieldValueBoost.Modifier modifier) { + private FieldValueFactorModifier toFieldValueFactorModifierV2(FieldValueBoost.Modifier modifier) { if (modifier == null) { return null; } return switch (modifier.value()) { - case "log" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier - .Log; - case "log1p" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier - .Log1p; - case "sqrt" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier - .Sqrt; - case "square" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier - .Square; - case "ln" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier.Ln; - case "ln1p" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier - .Ln1p; - case "ln2p" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier - .Ln2p; - case "reciprocal" -> es.co.elastic.clients.elasticsearch._types.query_dsl - .FieldValueFactorModifier.Reciprocal; + case "log" -> FieldValueFactorModifier.Log; + case "log1p" -> FieldValueFactorModifier.Log1p; + case "sqrt" -> FieldValueFactorModifier.Sqrt; + case "square" -> FieldValueFactorModifier.Square; + case "ln" -> FieldValueFactorModifier.Ln; + case "ln1p" -> FieldValueFactorModifier.Ln1p; + case "ln2p" -> FieldValueFactorModifier.Ln2p; + case "reciprocal" -> FieldValueFactorModifier.Reciprocal; default -> null; }; } - private es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode toScoreModeV2( - String mode) { + private FunctionScoreMode toScoreModeV2(String mode) { return switch (mode.toLowerCase()) { - case "avg" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.Avg; - case "max" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.Max; - case "min" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.Min; - case "multiply" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode - .Multiply; - case "first" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.First; - default -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.Sum; + case "avg" -> FunctionScoreMode.Avg; + case "max" -> FunctionScoreMode.Max; + case "min" -> FunctionScoreMode.Min; + case "multiply" -> FunctionScoreMode.Multiply; + case "first" -> FunctionScoreMode.First; + default -> FunctionScoreMode.Sum; }; } - private es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode toBoostModeV2( - String mode) { + private FunctionBoostMode toBoostModeV2(String mode) { return switch (mode.toLowerCase()) { - case "sum" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Sum; - case "avg" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Avg; - case "max" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Max; - case "min" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Min; - case "replace" -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode - .Replace; - default -> es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Multiply; + case "sum" -> FunctionBoostMode.Sum; + case "avg" -> FunctionBoostMode.Avg; + case "max" -> FunctionBoostMode.Max; + case "min" -> FunctionBoostMode.Min; + case "replace" -> FunctionBoostMode.Replace; + default -> FunctionBoostMode.Multiply; }; } - private List - collectBoostFunctionsV2(AssetTypeConfiguration assetConfig) { - List functions = - new ArrayList<>(); + private List collectBoostFunctionsV2(AssetTypeConfiguration assetConfig) { + List functions = new ArrayList<>(); // Add baseline weight of 1.0 so that assets with no tier/usage retain their text score // when boostMode is multiply. Without this, function_score could be 0 and zero out the @@ -934,36 +1012,33 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode t return functions; } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query applyFunctionScoringV2( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query baseQuery, - AssetTypeConfiguration assetConfig) { - List functions = - collectBoostFunctionsV2(assetConfig); + private Query applyFunctionScoringV2(Query baseQuery, AssetTypeConfiguration assetConfig) { + List functions = collectBoostFunctionsV2(assetConfig); if (functions.isEmpty()) { return baseQuery; } - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode scoreMode; - if (assetConfig.getScoreMode() != null) { - scoreMode = toScoreModeV2(assetConfig.getScoreMode().value()); - } else { - scoreMode = es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.Sum; - } - - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode boostMode; - if (assetConfig.getBoostMode() != null) { - boostMode = toBoostModeV2(assetConfig.getBoostMode().value()); - } else { - boostMode = es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Sum; - } + RankingConfiguration ranking = SearchRankingHelper.resolveRanking(searchSettings, assetConfig); + String scoreModeValue = + assetConfig.getScoreMode() != null ? assetConfig.getScoreMode().value() : "sum"; + String boostModeValue = + assetConfig.getBoostMode() != null ? assetConfig.getBoostMode().value() : "sum"; + FunctionScoreMode scoreMode = + toScoreModeV2(SearchRankingHelper.signalScoreMode(ranking, scoreModeValue)); + FunctionBoostMode boostMode = + toBoostModeV2(SearchRankingHelper.signalBoostMode(ranking, boostModeValue)); return ElasticQueryBuilder.functionScoreQuery( - baseQuery, functions, scoreMode, boostMode, FUNCTION_BOOST_FACTOR); + baseQuery, + functions, + scoreMode, + boostMode, + FUNCTION_BOOST_FACTOR, + SearchRankingHelper.signalMaxBoost(ranking)); } - private es.co.elastic.clients.elasticsearch.core.search.Highlight buildHighlightingIfNeededV2( - String query, AssetTypeConfiguration assetConfig) { + private Highlight buildHighlightingIfNeededV2(String query, AssetTypeConfiguration assetConfig) { if (query == null || query.trim().isEmpty()) { return null; } @@ -977,8 +1052,7 @@ private es.co.elastic.clients.elasticsearch.core.search.Highlight buildHighlight return null; } - private ElasticSearchRequestBuilder createSearchSourceBuilderV2( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query query, int from, int size) { + private ElasticSearchRequestBuilder createSearchSourceBuilderV2(Query query, int from, int size) { int maxHits = searchSettings.getGlobalSettings().getMaxResultHits(); ElasticSearchRequestBuilder builder = new ElasticSearchRequestBuilder(); builder.query(query); @@ -1016,8 +1090,7 @@ protected void addConfiguredAggregationsV2( } } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildQueryWithMatchTypesV2( - String query, AssetTypeConfiguration assetConfig) { + private Query buildQueryWithMatchTypesV2(String query, AssetTypeConfiguration assetConfig) { if (query == null || query.trim().isEmpty() || query.trim().equals("*")) { return ElasticQueryBuilder.boolQuery().must(ElasticQueryBuilder.matchAllQuery()).build(); } @@ -1029,26 +1102,22 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildQueryWit return buildSimpleQueryWithTypesV2(query, assetConfig); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildComplexQueryV2( - String query, AssetTypeConfiguration assetConfig) { + private Query buildComplexQueryV2(String query, AssetTypeConfiguration assetConfig) { Map allFields = extractAllFields(assetConfig); - es.co.elastic.clients.elasticsearch._types.query_dsl.Query queryStringBuilder = + Query queryStringBuilder = ElasticQueryBuilder.queryStringQuery( - query, - allFields, - es.co.elastic.clients.elasticsearch._types.query_dsl.Operator.And, - null, - 50, - 0, - 0.5, - es.co.elastic.clients.elasticsearch._types.query_dsl.TextQueryType.MostFields); + query, allFields, Operator.And, null, 50, 0, 0.5, TextQueryType.MostFields); return ElasticQueryBuilder.boolQuery().must(queryStringBuilder).build(); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildSimpleQueryWithTypesV2( - String query, AssetTypeConfiguration assetConfig) { + private Query buildSimpleQueryWithTypesV2(String query, AssetTypeConfiguration assetConfig) { + RankingConfiguration ranking = SearchRankingHelper.resolveRanking(searchSettings, assetConfig); + if (ranking != null) { + return buildRankedSimpleQueryV2(query, assetConfig, ranking); + } + ElasticQueryBuilder.BoolQueryBuilder combinedQuery = ElasticQueryBuilder.boolQuery(); MatchTypeMultipliers multipliers = getMatchTypeMultipliers(assetConfig); Map> fieldsByType = groupFieldsByMatchType(assetConfig); @@ -1075,10 +1144,8 @@ private void addMatchTypeQueriesV2( addStandardMatchQueriesV2(combinedQuery, query, fieldsByType.get(MATCH_TYPE_STANDARD)); } - private List - collectGlobalBoostFunctionsV2() { - List functions = - new ArrayList<>(); + private List collectGlobalBoostFunctionsV2() { + List functions = new ArrayList<>(); if (searchSettings.getGlobalSettings().getTermBoosts() != null) { searchSettings.getGlobalSettings().getTermBoosts().stream() @@ -1095,25 +1162,19 @@ private void addMatchTypeQueriesV2( return functions; } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query applyGlobalBoostsV2( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query baseQuery) { - List functions = - collectGlobalBoostFunctionsV2(); + private Query applyGlobalBoostsV2(Query baseQuery) { + List functions = collectGlobalBoostFunctionsV2(); if (functions.isEmpty()) { return baseQuery; } return ElasticQueryBuilder.functionScoreQuery( - baseQuery, - functions, - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.Sum, - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Sum, - FUNCTION_BOOST_FACTOR); + baseQuery, functions, FunctionScoreMode.Sum, FunctionBoostMode.Sum, FUNCTION_BOOST_FACTOR); } private ElasticSearchRequestBuilder createCommonSearchSourceBuilderV2( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query query, int from, int size) { + Query query, int from, int size) { return createSearchSourceBuilderV2(query, from, size); } @@ -1124,9 +1185,8 @@ private void addHighlightsIfConfiguredV2(ElasticSearchRequestBuilder searchReque } } - private es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore - buildEntitySpecificTermBoostV2(String assetType, TermBoost tb) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query filter = + private FunctionScore buildEntitySpecificTermBoostV2(String assetType, TermBoost tb) { + Query filter = ElasticQueryBuilder.boolQuery() .must(ElasticQueryBuilder.termQuery("entityType", assetType)) .must(ElasticQueryBuilder.termQuery(tb.getField(), tb.getValue())) @@ -1135,29 +1195,26 @@ private void addHighlightsIfConfiguredV2(ElasticSearchRequestBuilder searchReque return ElasticQueryBuilder.weightFunction(filter, tb.getBoost()); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScore - buildEntitySpecificFieldValueBoostV2(String assetType, FieldValueBoost fvb) { + private FunctionScore buildEntitySpecificFieldValueBoostV2( + String assetType, FieldValueBoost fvb) { ElasticQueryBuilder.BoolQueryBuilder conditionBuilder = ElasticQueryBuilder.boolQuery() .must(ElasticQueryBuilder.termQuery("entityType", assetType)); if (fvb.getCondition() != null && fvb.getCondition().getRange() != null) { - es.co.elastic.clients.elasticsearch._types.query_dsl.Query rangeQuery = - buildRangeQueryV2(fvb); + Query rangeQuery = buildRangeQueryV2(fvb); conditionBuilder.must(rangeQuery); } - es.co.elastic.clients.elasticsearch._types.query_dsl.Query condition = conditionBuilder.build(); + Query condition = conditionBuilder.build(); - es.co.elastic.clients.elasticsearch._types.query_dsl.FieldValueFactorModifier modifier = - toFieldValueFactorModifierV2(fvb.getModifier()); + FieldValueFactorModifier modifier = toFieldValueFactorModifierV2(fvb.getModifier()); return ElasticQueryBuilder.fieldValueFactorFunction( condition, fvb.getField(), fvb.getFactor(), fvb.getMissing(), modifier); } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildRangeQueryV2( - FieldValueBoost fvb) { + private Query buildRangeQueryV2(FieldValueBoost fvb) { var range = fvb.getCondition().getRange(); String field = fvb.getField(); @@ -1170,9 +1227,7 @@ private es.co.elastic.clients.elasticsearch._types.query_dsl.Query buildRangeQue } private void addAssetTypeBoostsV2( - List functions, - String assetType, - AssetTypeConfiguration assetConfig) { + List functions, String assetType, AssetTypeConfiguration assetConfig) { if (assetConfig.getTermBoosts() != null) { assetConfig.getTermBoosts().stream() @@ -1187,8 +1242,7 @@ private void addAssetTypeBoostsV2( } } - private void addEntitySpecificBoostsV2( - List functions) { + private void addEntitySpecificBoostsV2(List functions) { List dataAssetTypes = List.of( "table", @@ -1217,12 +1271,10 @@ private AssetTypeConfiguration findAssetTypeConfig(String assetType) { .orElse(null); } - private List - collectAllBoostFunctionsV2() { + private List collectAllBoostFunctionsV2() { // Add global boosts - List functions = - new ArrayList<>(collectGlobalBoostFunctionsV2()); + List functions = new ArrayList<>(collectGlobalBoostFunctionsV2()); // Add entity-specific boosts addEntitySpecificBoostsV2(functions); @@ -1230,18 +1282,12 @@ private AssetTypeConfiguration findAssetTypeConfig(String assetType) { return functions; } - private es.co.elastic.clients.elasticsearch._types.query_dsl.Query applyBoostFunctionsV2( - es.co.elastic.clients.elasticsearch._types.query_dsl.Query baseQuery, - List functions) { + private Query applyBoostFunctionsV2(Query baseQuery, List functions) { if (functions.isEmpty()) { return baseQuery; } return ElasticQueryBuilder.functionScoreQuery( - baseQuery, - functions, - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionScoreMode.Sum, - es.co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode.Sum, - FUNCTION_BOOST_FACTOR); + baseQuery, functions, FunctionScoreMode.Sum, FunctionBoostMode.Sum, FUNCTION_BOOST_FACTOR); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/dataInsightAggregators/ElasticSearchDynamicChartAggregatorInterface.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/dataInsightAggregators/ElasticSearchDynamicChartAggregatorInterface.java index 6f7855401e3c..f0db798c6f08 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/dataInsightAggregators/ElasticSearchDynamicChartAggregatorInterface.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/dataInsightAggregators/ElasticSearchDynamicChartAggregatorInterface.java @@ -194,6 +194,10 @@ default void populateDateHistogram( Map aggregationsMap, String parentAggName, List formulas) { + if (function == null && formula == null) { + throw new IllegalArgumentException( + "Data Insight chart metric must define either a function or a formula"); + } if (formula != null) { if (filter != null && !filter.equals("{}")) { try { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/ContextMemoryIndex.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/ContextMemoryIndex.java index 509ed939a164..100f190b1c3e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/ContextMemoryIndex.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/ContextMemoryIndex.java @@ -100,7 +100,6 @@ private void applyEntityReferences(Map doc) { doc.put("relatedEntities", related); doc.put("rootMemory", getEntityWithDisplayName(memory.getRootMemory())); doc.put("parentMemory", getEntityWithDisplayName(memory.getParentMemory())); - doc.put("sourceFile", getEntityWithDisplayName(memory.getSourceFile())); } public static Map getFields() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java index b8902ced2678..ea06b20762c7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java @@ -1,7 +1,9 @@ package org.openmetadata.service.search.indexes; import java.util.List; +import java.util.Optional; import org.openmetadata.schema.api.lineage.EsLineageData; +import org.openmetadata.schema.entity.type.Style; /** * Optional pre-fetched data threaded into {@link SearchIndex#buildSearchIndexDoc(DocBuildContext)} @@ -18,18 +20,57 @@ *
  • non-empty list — prefetched edges to apply directly. * * + *

    {@code serviceStylePrefetch} semantics: + * + *

      + *
    • {@link ServiceStylePrefetch#notPrefetched()} — no style prefetch was attempted for this + * entity; callers should fall back to per-entity lookups. + *
    • {@link ServiceStylePrefetch#prefetched(Optional)} with {@link Optional#empty()} — prefetch + * ran and this service has no style. + *
    • {@link ServiceStylePrefetch#prefetched(Optional)} with a value — prefetched style to apply. + *
    + * * The context is passed by value down the doc-build call chain; nothing is stored in thread-local * state, so callers and mixins see the dependency in their method signatures. */ -public record DocBuildContext(List prefetchedUpstreamLineage) { +public record DocBuildContext( + List prefetchedUpstreamLineage, ServiceStylePrefetch serviceStylePrefetch) { - private static final DocBuildContext EMPTY = new DocBuildContext(null); + private static final DocBuildContext EMPTY = + new DocBuildContext(null, ServiceStylePrefetch.notPrefetched()); + + public DocBuildContext { + serviceStylePrefetch = + serviceStylePrefetch == null ? ServiceStylePrefetch.notPrefetched() : serviceStylePrefetch; + } public static DocBuildContext empty() { return EMPTY; } public static DocBuildContext withUpstreamLineage(List upstreamLineage) { - return new DocBuildContext(upstreamLineage); + return new DocBuildContext(upstreamLineage, ServiceStylePrefetch.notPrefetched()); + } + + public static DocBuildContext of( + List upstreamLineage, ServiceStylePrefetch serviceStylePrefetch) { + return new DocBuildContext(upstreamLineage, serviceStylePrefetch); + } + + public record ServiceStylePrefetch(boolean prefetched, Optional