Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Semantic search (#61036)

Noah Moss1a61eb257cec
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index b98ffb07188..0461c41103f 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -408,6 +408,7 @@
clojure.test.check.clojure-test/defspec clojure.test/deftest
clojure.test.check.properties/for-all clojure.core/let
clojurewerkz.quartzite.jobs/defjob clojure.core/defn
+ com.climate.claypoole/with-shutdown! clojure.core/let
instaparse.core/defparser clojure.core/def
metabase-enterprise.action-v2.test-util/with-test-tables! clojure.core/let
metabase-enterprise.serialization.test-util/with-dbs clojure.core/fn
@@ -512,6 +513,7 @@
metabase-enterprise.advanced-permissions.models.permissions.application-permissions-test/with-new-group-and-current-graph hooks.common/with-two-top-level-bindings
metabase-enterprise.audit-app.pages-test/with-temp-objects hooks.common/with-one-binding
metabase-enterprise.cache.config-test/with-temp-persist-models hooks.common/with-seven-bindings
+ metabase-enterprise.semantic-search.db.connection/with-migrate-tx hooks.common/let-one-with-optional-value
metabase-enterprise.serialization.test-util/with-temp-dpc hooks.toucan2.tools.with-temp/with-temp
metabase.api.common.internal-test/with-jetty-server hooks.common/with-one-binding
metabase.api.macros/defendpoint hooks.metabase.api.macros/defendpoint
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 59846122c30..d8c41b28cb4 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1033,9 +1033,11 @@
metabase.search.appdb.scoring
metabase.search.config
metabase.search.core
+ metabase.search.engine
metabase.search.in-place.scoring
metabase.search.ingestion
metabase.search.init
+ metabase.search.scoring
metabase.search.spec}
:uses #{analytics
api
@@ -1524,6 +1526,7 @@
premium-features
enterprise/advanced-config
enterprise/scim
+ enterprise/semantic-search
enterprise/sso}}
enterprise/api
@@ -1691,7 +1694,8 @@
enterprise/llm
{:team "Metabot"
:api #{metabase-enterprise.llm.api
- metabase-enterprise.llm.init}
+ metabase-enterprise.llm.init
+ metabase-enterprise.llm.settings}
:uses #{analytics
analyze
api
@@ -1703,6 +1707,7 @@
enterprise/metabot-v3
{:team "Metabot"
:api #{metabase-enterprise.metabot-v3.api
+ metabase-enterprise.metabot-v3.client
metabase-enterprise.metabot-v3.core
metabase-enterprise.metabot-v3.init
metabase-enterprise.metabot-v3.tools.api}
@@ -1790,6 +1795,24 @@
:uses #{premium-features
search}}
+ enterprise/semantic-search
+ {:team "Metabot"
+ :api #{metabase-enterprise.semantic-search.api
+ metabase-enterprise.semantic-search.core
+ metabase-enterprise.semantic-search.init}
+ :uses #{analytics
+ api
+ connection-pool
+ models
+ permissions
+ premium-features
+ search
+ settings
+ task
+ util
+ enterprise/llm
+ enterprise/metabot-v3}}
+
enterprise/serialization
{:team "Workflows"
:api #{metabase-enterprise.serialization.api
diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml
index 25ac9f695c7..0026a637fc4 100644
--- a/.github/workflows/run-tests.yml
+++ b/.github/workflows/run-tests.yml
@@ -83,6 +83,13 @@ jobs:
with:
skip: ${{ needs.files-changed.outputs.backend_all != 'true' && needs.static-viz-files-changed.outputs.static_viz != 'true' }}
+ semantic-search-tests:
+ needs: files-changed
+ uses: ./.github/workflows/semantic-search.yml
+ secrets: inherit
+ with:
+ skip: ${{ needs.files-changed.outputs.backend_all != 'true' }}
+
app-db-tests:
needs: files-changed
uses: ./.github/workflows/app-db.yml
diff --git a/.github/workflows/semantic-search.yml b/.github/workflows/semantic-search.yml
new file mode 100644
index 00000000000..f63e2575380
--- /dev/null
+++ b/.github/workflows/semantic-search.yml
@@ -0,0 +1,145 @@
+name: Semantic Search Tests
+
+on:
+ workflow_call:
+ inputs:
+ skip:
+ type: boolean
+ default: false
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-semantic-search
+ cancel-in-progress: true
+
+jobs:
+ semantic-search-tests-pgvector:
+ if: ${{ !inputs.skip }}
+ runs-on: ubuntu-22.04
+ timeout-minutes: 60
+ strategy:
+ fail-fast: false
+ matrix:
+ version:
+ - name: pgvector pg16
+ junit-name: semantic-search-tests-pgvector-16
+ image: pgvector/pgvector:pg16
+ env:
+ enable-ssl-tests: 'false'
+ job:
+ - name: Semantic Search Tests
+ build-static-viz: false
+ test-args: >-
+ :only '"enterprise/backend/test/metabase_enterprise/semantic_search"'
+ exclude-tag: ':mb/driver-tests'
+
+ services:
+ pgvector:
+ image: ${{ matrix.version.image }}
+ ports:
+ - "5432:5432"
+ env:
+ POSTGRES_DB: mb_semantic_search
+ POSTGRES_USER: postgres
+ POSTGRES_PASSWORD: postgres
+ env:
+ # Only run old migrations tests on pushes to master or release branches. All other branches should skip tests
+ # with the tag `mb/old-migrations-test`. `__ADDITIONAL_EXCLUDED_TAG__` is not used anywhere outside of splicing
+ # it in to the command below.
+ __ADDITIONAL_EXCLUDED_TAG__: >-
+ ${{
+ (
+ github.event_name == 'push' &&
+ (
+ github.ref == 'master' ||
+ startsWith(github.ref, 'release-')
+ ) &&
+ ''
+ ) ||
+ ':mb/old-migrations-test'
+ }}
+ MB_PGVECTOR_DB_URL: 'jdbc:postgres://localhost:5432/mb_semantic_search?user=postgres&password=postgres'
+ CI: 'true'
+ name: "${{ matrix.version.name }} ${{ matrix.job.name }}"
+ steps:
+ - uses: actions/checkout@v4
+ - name: Test ${{ matrix.version.name }}
+ uses: ./.github/actions/test-driver
+ with:
+ build-static-viz: ${{ matrix.job.build-static-viz }}
+ junit-name: ${{ matrix.version.junit-name }}
+ test-args: >-
+ ${{ matrix.job.test-args }}
+ :exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
+ - name: Upload Test Results
+ uses: ./.github/actions/upload-test-results
+ if: always()
+ with:
+ input-path: ./target/junit/
+ output-name: ${{ github.job }}
+ bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
+ aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
+ aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
+ aws-region: ${{ vars.AWS_REGION }}
+ trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
+
+ semantic-search-tests-result:
+ needs:
+ - semantic-search-tests-pgvector
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ name: semantic-search-tests-result
+ if: always() && !cancelled()
+ steps:
+ - name: Check job status
+ uses: actions/github-script@v7
+ env:
+ needs: ${{ toJson(needs) }}
+ with:
+ script: | # js
+ const needs = JSON.parse(process.env.needs);
+
+ const jobs = Object.entries(needs).map(
+ ([jobName, jobValues]) => ({
+ name: jobName,
+ result: jobValues.result
+ }));
+
+ // are all jobs skipped or successful?
+ if (jobs.every(job => (job.result === 'skipped' || job.result === 'success'))) {
+ console.log("");
+ console.log(" _------. ");
+ console.log(" / , \_ ");
+ console.log(" / / /{}\ |o\_ ");
+ console.log(" / \ `--' /-' \ ");
+ console.log(" | \ \ | ");
+ console.log(" | |`-, | ");
+ console.log(" / /__/)/ ");
+ console.log(" | | ");
+ console.log("");
+ console.log("All semantic search tests have passed (or have been skipped). Cam is very proud of you.");
+ process.exit(0);
+ }
+
+ // otherwise, something failed
+ console.log("");
+ console.log(" .::::::::::. .::::::::::. ");
+ console.log(" .::::''''''::::. .::::''''''::::. ");
+ console.log(" .:::' `::::.... ....::::' `:::. ");
+ console.log(" .::' `:::::::| |:::::::' `::. ");
+ console.log(" .::| |::::::|_ ___ __|::::::| |::. ");
+ console.log(" `--' |::::::|_()__()_|::::::| `--' ");
+ console.log(" ::: |::-o::| |::o-::| ::: ");
+ console.log(" `::. .|::::::| |::::::|. .::' ");
+ console.log(" `:::. .::\-----' `-----/::. .:::' ");
+ console.log(" `::::......::::' `::::......::::' ");
+ console.log(" `::::::::::' `::::::::::' ");
+ console.log("");
+ console.log("Semantic search tests have failed. You have been sentenced to MetaJail.");
+
+ jobs.forEach((job) => {
+ if (job.result !== 'success') {
+ console.log(`${job.name} - ${job.result}`);
+ }
+ });
+
+ process.exit(1);
diff --git a/.github/workflows/uberjar.yml b/.github/workflows/uberjar.yml
index ed19225a4c8..3ebb8fb1640 100644
--- a/.github/workflows/uberjar.yml
+++ b/.github/workflows/uberjar.yml
@@ -11,8 +11,9 @@ on:
push:
branches:
- master
- - metabot-v3-main
+ - feature-visualizer
- internal-tools
+ - nm-semantic-search-in-metabase
paths-ignore:
# config files
- ".**"
diff --git a/deps.edn b/deps.edn
index 38b445cbdde..d28f45fe9ba 100644
--- a/deps.edn
+++ b/deps.edn
@@ -56,6 +56,7 @@
com.h2database/h2 ^:antq/exclude ; https://metaboat.slack.com/archives/CKZEMT1MJ/p1727191010259979
{:mvn/version "2.1.214"} ; embedded SQL database
com.ibm.icu/icu4j {:mvn/version "77.1"} ; Used to transliterate Unicode characters into Latin characters
+ com.knuddels/jtokkit {:mvn/version "1.1.0"} ; Java tokenizer library for OpenAI models, used for token counting in semantic search
com.mchange/c3p0 {:mvn/version "0.10.1"} ; DB connection pool
com.snowplowanalytics/snowplow-java-tracker ^:antq/exclude ; 2+ depend on apache httpclient 5.x, but saml and clj-http depend on 4.x
{:mvn/version "1.0.1"} ; Snowplow analytics
diff --git a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
index f9dadf69e21..833b5723ae4 100644
--- a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
+++ b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
@@ -2,6 +2,7 @@
(:require
[metabase-enterprise.advanced-config.settings :as advanced-config.settings]
[metabase-enterprise.scim.core :as scim]
+ [metabase-enterprise.semantic-search.core :as semantic-search]
[metabase-enterprise.sso.settings :as sso-settings]
[metabase.driver :as driver]
[metabase.premium-features.core :as premium-features :refer [defenterprise]]
@@ -27,4 +28,7 @@
:enabled (t2/exists? :model/GroupTableAccessPolicy)}
{:name :email-allow-list
:available (premium-features/enable-email-allow-list?)
- :enabled (boolean (some? (advanced-config.settings/subscription-allowed-domains)))}])
+ :enabled (boolean (some? (advanced-config.settings/subscription-allowed-domains)))}
+ {:name :semantic-search
+ :available (premium-features/enable-semantic-search?)
+ :enabled (semantic-search/supported?)}])
diff --git a/enterprise/backend/src/metabase_enterprise/api/routes.clj b/enterprise/backend/src/metabase_enterprise/api/routes.clj
index 3b043b8c46c..b47f81f5c81 100644
--- a/enterprise/backend/src/metabase_enterprise/api/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api/routes.clj
@@ -26,6 +26,7 @@
[metabase-enterprise.permission-debug.api]
[metabase-enterprise.sandbox.api.routes]
[metabase-enterprise.scim.routes]
+ [metabase-enterprise.semantic-search.api]
[metabase-enterprise.serialization.api]
[metabase-enterprise.stale.api]
[metabase-enterprise.upload-management.api]
@@ -50,6 +51,7 @@
:llm-autodescription (deferred-tru "LLM Auto-description")
:metabot-v3 (deferred-tru "MetaBot")
:scim (deferred-tru "SCIM configuration")
+ :semantic-search (deferred-tru "Semantic Search")
:serialization (deferred-tru "Serialization")
:table-data-editing (deferred-tru "Table Data Editing")
:upload-management (deferred-tru "Upload Management")
@@ -99,6 +101,7 @@
"/metabot-v3" (premium-handler metabase-enterprise.metabot-v3.api/routes :metabot-v3)
"/permission_debug" (premium-handler metabase-enterprise.permission-debug.api/routes :advanced-permissions)
"/scim" (premium-handler metabase-enterprise.scim.routes/routes :scim)
+ "/semantic-search" (premium-handler metabase-enterprise.semantic-search.api/routes :semantic-search)
"/serialization" (premium-handler metabase-enterprise.serialization.api/routes :serialization)
"/stale" (premium-handler metabase-enterprise.stale.api/routes :collection-cleanup)
"/upload-management" (premium-handler metabase-enterprise.upload-management.api/routes :upload-management)})
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index fc7bc16f320..20c9acadde8 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -15,5 +15,6 @@
[metabase-enterprise.llm.init]
[metabase-enterprise.metabot-v3.init]
[metabase-enterprise.scim.init]
+ [metabase-enterprise.semantic-search.init]
[metabase-enterprise.sso.init]
[metabase-enterprise.stale.init]))
diff --git a/enterprise/backend/src/metabase_enterprise/llm/settings.clj b/enterprise/backend/src/metabase_enterprise/llm/settings.clj
index c4e3850afd9..a8274f39301 100644
--- a/enterprise/backend/src/metabase_enterprise/llm/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/llm/settings.clj
@@ -11,6 +11,14 @@
:export? false
:doc "This feature is experimental.")
+(defsetting ee-openai-api-base-url
+ (deferred-tru "The OpenAI embeddings base URL used in Metabase Enterprise.")
+ :encryption :no
+ :visibility :settings-manager
+ :default "https://api.openai.com"
+ :export? false
+ :doc "This feature is experimental.")
+
(defsetting ee-openai-api-key
(deferred-tru "The OpenAI API Key used in Metabase Enterprise.")
:encryption :no
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
index efd3b44baf4..175f9ac304c 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
@@ -91,6 +91,9 @@
(defn- example-question-generation-endpoint []
(str (metabot-v3.settings/ai-service-base-url) "/v1/example-question-generation/batch"))
+(defn- generate-embeddings-endpoint []
+ (str (metabot-v3.settings/ai-service-base-url) "/v1/embeddings"))
+
(mu/defn request :- ::metabot-v3.client.schema/ai-service.response
"Make a V2 request to the AI Service."
[{:keys [context messages profile-id conversation-id session-id state]}
@@ -370,3 +373,19 @@
(:status response) (:reason-phrase response))
{:request (assoc options :body payload)
:response response})))))
+
+(defn generate-embeddings
+ "Generate vector embeddings for a batch of inputs questions for the given models and metrics."
+ [model-name texts]
+ (let [url (generate-embeddings-endpoint)
+ body {:model model-name
+ :input texts
+ :encoding_format "base64"}
+ options (build-request-options body)
+ response (post! url options)]
+ (if (= (:status response) 200)
+ (:body response)
+ (throw (ex-info (format "Error in generate-embeddings request to AI service: unexpected status: %d %s"
+ (:status response) (:reason-phrase response))
+ {:request (assoc options :body body)
+ :response response})))))
diff --git a/enterprise/backend/src/metabase_enterprise/search/scoring.clj b/enterprise/backend/src/metabase_enterprise/search/scoring.clj
index 5722e0bf4d6..59a0bfd394a 100644
--- a/enterprise/backend/src/metabase_enterprise/search/scoring.clj
+++ b/enterprise/backend/src/metabase_enterprise/search/scoring.clj
@@ -3,12 +3,13 @@
[metabase.premium-features.core :as premium-features :refer [defenterprise]]
[metabase.search.appdb.scoring :as appdb.scoring]
[metabase.search.config :as search.config]
- [metabase.search.in-place.scoring :as scoring]))
+ [metabase.search.in-place.scoring :as scoring]
+ [metabase.search.scoring :as search.scoring]))
(def ^:private enterprise-scorers
- {:official-collection {:expr (appdb.scoring/truthy :official_collection)
+ {:official-collection {:expr (search.scoring/truthy :official_collection)
:pred #(premium-features/has-feature? :official-collections)}
- :verified {:expr (appdb.scoring/truthy :verified)
+ :verified {:expr (search.scoring/truthy :verified)
:pred #(premium-features/has-feature? :content-verification)}})
(defn- additional-scorers
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/api.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/api.clj
new file mode 100644
index 00000000000..3217c35598b
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/api.clj
@@ -0,0 +1,46 @@
+(ns metabase-enterprise.semantic-search.api
+ "/api/ee/semantic-search endpoints"
+ (:require
+ [clojure.core.memoize :as memoize]
+ [metabase-enterprise.semantic-search.env :as semantic.env]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.permissions.core :as perms]
+ [metabase.search.ingestion :as search.ingestion]))
+
+(def ^:private indexible-items-count
+ (memoize/ttl search.ingestion/search-items-count
+ :ttl/threshold (* 5 60 1000))) ; 5 minutes
+
+(defn- active-index-document-count
+ [pgvector index-metadata]
+ (when-let [table-name (-> index-metadata :index :table-name)]
+ (semantic.index/index-size pgvector table-name)))
+
+(api.macros/defendpoint :get "/status"
+ "Fetch the indexing status of the currently active semantic search index table.
+
+ Returns a map with keys:
+ :indexed_count <number of indexed items>
+ :total_est <estimated total number of items to index>
+
+ If no index is active, returns an empty map."
+ []
+ (perms/check-has-application-permission :setting)
+ (let [pgvector (semantic.env/get-pgvector-datasource!)
+ index-metadata (semantic.env/get-index-metadata)
+ active-index (when (and pgvector index-metadata)
+ (semantic.index-metadata/get-active-index-state pgvector index-metadata))]
+ (try
+ (if active-index
+ {:indexed_count (active-index-document-count pgvector active-index)
+ :total_est (indexible-items-count)}
+ {})
+ (catch Exception e
+ (throw (ex-info "Error fetching semantic search index status" {:cause e}))))))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/semantic-search` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/core.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/core.clj
new file mode 100644
index 00000000000..47412321073
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/core.clj
@@ -0,0 +1,143 @@
+(ns metabase-enterprise.semantic-search.core
+ "Enterprise implementations of semantic search core functions using defenterprise."
+ (:require
+ [medley.core :as m]
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase-enterprise.semantic-search.env :as semantic.env]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.pgvector-api :as semantic.pgvector-api]
+ [metabase-enterprise.semantic-search.settings :as semantic.settings]
+ [metabase.analytics.core :as analytics]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [metabase.search.engine :as search.engine]
+ [metabase.util.log :as log]))
+
+(defn- fallback-engine
+ "Find the highest priority search engine available for fallback."
+ []
+ (first (filter search.engine/supported-engine?
+ search.engine/fallback-engine-priority)))
+
+(defn- index-active? [pgvector index-metadata]
+ (boolean (semantic.index-metadata/get-active-index-state pgvector index-metadata)))
+
+;; TODO: url should likely reside in settings
+(defenterprise supported?
+ "Enterprise implementation of semantic search engine support check."
+ :feature :semantic-search
+ []
+ (and
+ (some? semantic.db.datasource/db-url)
+ (semantic.settings/semantic-search-enabled)))
+
+(defenterprise results
+ "Enterprise implementation of semantic search results with improved fallback logic. Falls back to appdb search only
+ when semantic search returns too few results and some results were filtered out (e.g. due to permission checks)."
+ :feature :semantic-search
+ [search-ctx]
+ (try
+ (let [{:keys [results raw-count]}
+ (semantic.pgvector-api/query (semantic.env/get-pgvector-datasource!)
+ (semantic.env/get-index-metadata)
+ search-ctx)
+ final-count (count results)
+ threshold (semantic.settings/semantic-search-min-results-threshold)]
+ (if (or (>= final-count threshold)
+ (zero? raw-count))
+ results
+ ;; Fallback: semantic search found results but some were filtered out (e.g. due to permission checks), so try to
+ ;; supplement with appdb search.
+ (let [fallback (fallback-engine)]
+ (log/debugf "Semantic search returned %d final results (< %d) from %d raw results, supplementing with %s search"
+ final-count threshold raw-count fallback)
+ (analytics/inc! :metabase-search/semantic-fallback-triggered {:fallback-engine fallback})
+ (analytics/observe! :metabase-search/semantic-results-before-fallback final-count)
+ (let [fallback-results (search.engine/results (assoc search-ctx :search-engine fallback))
+ combined-results (concat results fallback-results)
+ deduped-results (m/distinct-by (juxt :model :id) combined-results)]
+ (take (semantic.settings/semantic-search-results-limit) deduped-results)))))
+ (catch Exception e
+ (log/error e "Error executing semantic search")
+ (throw (ex-info "Error executing semantic search" {:type :semantic-search-error} e)))))
+
+;; TODO: tx-write
+(defenterprise update-index!
+ "Enterprise implementation of semantic index updating."
+ :feature :semantic-search
+ [document-reducible]
+ (let [pgvector (semantic.env/get-pgvector-datasource!)
+ index-metadata (semantic.env/get-index-metadata)]
+ (if-not (index-active? pgvector index-metadata)
+ (log/warn "update-index! called prior to init!")
+ (semantic.pgvector-api/gate-updates!
+ pgvector
+ index-metadata
+ document-reducible))))
+
+(defenterprise delete-from-index!
+ "Enterprise implementation of semantic index deletion."
+ :feature :semantic-search
+ [model ids]
+ (let [pgvector (semantic.env/get-pgvector-datasource!)
+ index-metadata (semantic.env/get-index-metadata)]
+ (if-not (index-active? pgvector index-metadata)
+ (log/warn "delete-from-index! called prior to init!")
+ (semantic.pgvector-api/gate-deletes!
+ pgvector
+ index-metadata
+ model
+ ids))))
+
+;; NOTE:
+;; we're currently not returning stats from `init!` and `reindex!` as the async nature means
+;; we'd report skewed values for the `metabase-search` metrics.
+
+;; TODO: add reindexing/table-swapping logic when index is detected as stale
+(defenterprise init!
+ "Initialize the semantic search table and populate it with initial data."
+ :feature :semantic-search
+ [searchable-documents _opts]
+ (let [pgvector (semantic.env/get-pgvector-datasource!)
+ index-metadata (semantic.env/get-index-metadata)
+ embedding-model (semantic.env/get-configured-embedding-model)]
+ (semantic.pgvector-api/init-semantic-search! pgvector index-metadata embedding-model)
+ (semantic.pgvector-api/gate-updates! pgvector index-metadata searchable-documents)
+ nil))
+
+(defenterprise reindex!
+ "Reindex the semantic search index."
+ :feature :semantic-search
+ [searchable-documents _opts]
+ (let [pgvector (semantic.env/get-pgvector-datasource!)
+ index-metadata (semantic.env/get-index-metadata)
+ embedding-model (semantic.env/get-configured-embedding-model)]
+ ;; todo force a new index
+ (semantic.pgvector-api/init-semantic-search! pgvector index-metadata embedding-model)
+ (semantic.pgvector-api/gate-updates! pgvector index-metadata searchable-documents)
+ nil))
+
+;; TODO: implement
+(defenterprise reset-tracking!
+ "Enterprise implementation of semantic search tracking reset."
+ :feature :semantic-search
+ []
+ nil)
+
+(comment
+ (update-index! [{:model "card"
+ :id "1"
+ :searchable_text "This is a test card"}
+ {:model "card"
+ :id "2"
+ :searchable_text "This is a test card too"}
+ {:model "dashboard"
+ :id "3"
+ :searchable_text "This is a test dashboard"}])
+ (delete-from-index! "card" ["1" "2"])
+
+ ;; reindex! testing
+ (require '[metabase.search.ingestion :as search.ingestion])
+ (def all-docs (search.ingestion/searchable-documents))
+ (def subset-docs (eduction (take 2000) all-docs))
+ (reindex! subset-docs {})
+ (reindex! all-docs {}))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/connection.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/connection.clj
new file mode 100644
index 00000000000..e70bcb86dfe
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/connection.clj
@@ -0,0 +1,18 @@
+(ns metabase-enterprise.semantic-search.db.connection
+ (:require
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase-enterprise.semantic-search.db.locking :as semantic.db.locking]
+ [next.jdbc :as jdbc]))
+
+(defn do-with-migrate-tx
+ "Impl. for [[with-migrate-tx]]."
+ [conn-or-ds thunk]
+ (jdbc/with-transaction [tx (or conn-or-ds
+ (semantic.db.datasource/ensure-initialized-data-source!))]
+ (semantic.db.locking/acquire-migration-lock! tx)
+ (thunk tx)))
+
+(defmacro with-migrate-tx
+ "Provide connection with migration advisory lock. Blocking."
+ [[conn-sym & [conn-expr]] & body]
+ `(do-with-migrate-tx ~conn-expr (fn [~conn-sym] ~@body)))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/datasource.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/datasource.clj
new file mode 100644
index 00000000000..27408da1dd8
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/datasource.clj
@@ -0,0 +1,75 @@
+(ns metabase-enterprise.semantic-search.db.datasource
+ (:require
+ [environ.core :refer [env]]
+ [metabase.connection-pool :as connection-pool]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc])
+ (:import
+ (com.mchange.v2.c3p0 DataSources)))
+
+(set! *warn-on-reflection* true)
+
+(def data-source
+ "Atom to hold the pooled JDBC data source for the semantic search database."
+ (atom nil))
+
+(def db-url
+ "The database URL used to connect to pgvector"
+ (env :mb-pgvector-db-url))
+
+;; See metabase.app-db.connection-pool-setup for more details on these properties
+;; TODO: not sure if we need the MetabaseConnectionCustomizer like in the app DB connection pool seutp
+(def ^:private semantic-search-connection-pool-props
+ "Connection pool properties for semantic search database using c3p0."
+ {"idleConnectionTestPeriod" 60
+ "maxIdleTimeExcessConnections" (* 10 60) ; 5 minutes
+ "maxConnectionAge" (* 30 60) ; 30 minutes
+ "maxPoolSize" 5 ; Small pool to start
+ "minPoolSize" 1
+ "initialPoolSize" 1
+ "dataSourceName" "metabase-semantic-search-db"})
+
+(defn- build-db-config
+ "Build database configuration from environment variables"
+ []
+ (if db-url
+ {:jdbcUrl db-url}
+ (throw (ex-info "MB_PGVECTOR_DB_URL environment variable is required for semantic search" {}))))
+
+(defn init-db!
+ "Initialize c3p0 connection pool for semantic search database.
+ Requires MB_PGVECTOR_DB_URL environment variable."
+ []
+ (locking data-source
+ (or @data-source
+ (let [db-config (build-db-config)
+ unpooled-ds (jdbc/get-datasource db-config)
+ pooled-ds (DataSources/pooledDataSource
+ ^javax.sql.DataSource unpooled-ds
+ (connection-pool/map->properties semantic-search-connection-pool-props))]
+ (log/info "Initializing semantic search connection pool with properties:" semantic-search-connection-pool-props)
+ (reset! data-source pooled-ds)))))
+
+(defn test-connection!
+ "Test database connectivity"
+ []
+ (if @data-source
+ (try
+ (let [result (jdbc/execute-one! @data-source ["SELECT 1 as test"])]
+ (log/info "Semantic search database connection successful:" result)
+ result)
+ (catch Exception e
+ (log/error "Semantic search database connection failed:" (.getMessage e))
+ (throw e)))
+ (throw (ex-info "Semantic search connection pool is not initialized. Call init-db! first." {}))))
+
+(comment
+ ;; docker-compose.yml
+ (.doReset #'db-url "jdbc:postgres://localhost:55432/mb_semantic_search?user=postgres&password=postgres")
+ (init-db!)
+ (test-connection!))
+
+(defn ensure-initialized-data-source!
+ "Return datasource. Initialize if necessary."
+ []
+ (or @data-source (init-db!)))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/locking.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/locking.clj
new file mode 100644
index 00000000000..6d14ecfb21a
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/locking.clj
@@ -0,0 +1,62 @@
+(ns metabase-enterprise.semantic-search.db.locking
+ (:require
+ [honey.sql :as sql]
+ [honey.sql.helpers :as sql.helpers]
+ [metabase-enterprise.semantic-search.db.util :as semantic.db.util]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc])
+ (:import
+ (java.sql SQLException)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private supported-lock-types
+ #{;; blocking exclusive transaction lock
+ :pg_advisory_xact_lock
+ ;; non-blocking exclusive transaction lock
+ :pg_try_advisory_xact_lock
+ ;; non-blocking shared transaction lock
+ :pg_try_advisory_xact_lock_shared})
+
+(defn- lock-not-avail-ex?
+ "SQL locking exceptino?"
+ [e]
+ (boolean
+ (when (instance? SQLException e)
+ (= "55P03" (.getSQLState ^SQLException e)))))
+
+(defn lock-or-throw!
+ "Acquire advisory lock. Throw if not possible. Blocks with blocking locks."
+ [conn lock-type lock-id]
+ (log/debugf "Attempting to acquire %s %d lock." lock-type lock-id)
+ (assert (supported-lock-types lock-type))
+ (assert (integer? lock-id))
+ (semantic.db.util/tx-or-throw! conn)
+ (let [sql (sql/format (sql.helpers/select [[lock-type [:raw lock-id]] :acquired]))
+ acquired? (:acquired (try (jdbc/execute-one! conn sql)
+ (catch SQLException e
+ (if (lock-not-avail-ex? e)
+ (throw (ex-info "Lock could not be acquired"
+ {:lock-type lock-type
+ :lock-id lock-id}
+ e))
+ (throw e)))))]
+ ;; For non-blocking write locks. Now not in use as we attempt migrating without shared write locks.
+ (when-not acquired?
+ (throw (ex-info "Lock could not be acquired"
+ {:lock-type lock-type
+ :lock-id lock-id})))
+ (log/debugf "Lock %s %d acquired." lock-type lock-id)
+ nil))
+
+(def ^:private migration-lock 19991)
+
+;; Unused atm as yolo-write by other nodes during migration should be safe
+#_(defn acquire-write-lock!
+ [conn]
+ (lock-or-throw! conn :pg_try_advisory_xact_lock_shared migration-lock))
+
+(defn acquire-migration-lock!
+ "Acquire migration advisory lock. Blocks until acquired or timeout (if conn lock_timeout is 0 then conn timeout)."
+ [conn]
+ (lock-or-throw! conn :pg_advisory_xact_lock migration-lock))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration.clj
new file mode 100644
index 00000000000..5a8769b04ac
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration.clj
@@ -0,0 +1,119 @@
+(ns metabase-enterprise.semantic-search.db.migration
+ (:require
+ [honey.sql :as sql]
+ [honey.sql.helpers :as sql.helpers]
+ [metabase-enterprise.semantic-search.db.migration.impl :as semantic.db.migration.impl]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc])
+ (:import
+ [java.sql SQLException]))
+
+(def ^:private columns
+ ;; No serial -- ids are chosen by migration authors
+ [[:version :bigint [:primary-key]]
+ [:migrated_at :timestamp [:default [:NOW]]]
+ [:status [:varchar 32]]])
+
+(def ^:private migration-table-hsql
+ (-> (sql.helpers/create-table :migration :if-not-exists)
+ (sql.helpers/with-columns columns)))
+
+(defn- migration-table-sql
+ []
+ (sql/format migration-table-hsql))
+
+(defn- ensure-migration-table!
+ [tx]
+ (let [sql (migration-table-sql)]
+ (try
+ (jdbc/execute! tx sql)
+ (catch SQLException e
+ (throw (ex-info "Failed to create migration table."
+ {:type ::migration-table-creation-failed}
+ e))))
+ nil))
+
+(defn- db-version
+ "Get database version of schema from migration table."
+ [tx]
+ (or (:max_version
+ (jdbc/execute-one! tx
+ (sql/format {:select [[[:max :version] :max_version]]
+ :from [:migration]})))
+ -1))
+
+(defn- write-successful-migration!
+ [tx]
+ (jdbc/execute-one! tx (sql/format (-> (sql.helpers/insert-into :migration)
+ (sql.helpers/values [{:version semantic.db.migration.impl/schema-version
+ :status "success"}])))))
+
+(defn maybe-migrate-schema!
+ "Execute schema migration (control, meta, gate, ...) if appropriate."
+ [tx opts]
+ (let [db-version (db-version tx)]
+ (cond
+ (= db-version semantic.db.migration.impl/schema-version)
+ (log/info "Migration already performed, skipping.")
+
+ (< db-version semantic.db.migration.impl/schema-version)
+ (do
+ (log/infof "Starting migration from version %d to %d."
+ db-version semantic.db.migration.impl/schema-version)
+ (semantic.db.migration.impl/migrate-schema! tx opts)
+ (write-successful-migration! tx))
+
+ :else
+ (log/infof "Database schema version (%d) is newer than code version (%d). Not performing migration."
+ db-version semantic.db.migration.impl/schema-version)))
+ nil)
+
+(defn- index-metadata-table-exists?
+ [tx]
+ (jdbc/execute-one! tx
+ (sql/format {:select [[[:raw 1] :exists]]
+ :from [:information_schema.tables]
+ :where [[:= :information_schema.tables.table_name [:inline "index_metadata"]]]
+ :limit 1})))
+
+(defn- lowest-dynamic-db-version
+ "Lowest index version. If there is lower than defined in code dynamic schema migration will be attempted."
+ [tx]
+ (or (when (index-metadata-table-exists? tx)
+ (:min_index
+ (jdbc/execute-one! tx
+ (sql/format {:select [[[:min :index_version] :min_index]]
+ :from [:index_metadata]}))))
+ 0))
+
+(defn maybe-migrate-dynamic-schema!
+ "Migration for dynamic tables (index_table_xyzs) if appropriate."
+ [tx opts]
+ (let [db-version (lowest-dynamic-db-version tx)]
+ (cond
+ (= db-version semantic.db.migration.impl/dynamic-schema-version)
+ (log/info "Dynamic tables migration already performed, skipping.")
+
+ (< db-version semantic.db.migration.impl/dynamic-schema-version)
+ (do
+ (log/infof "Starting dynamic tables migration from version %d to %d."
+ db-version semantic.db.migration.impl/dynamic-schema-version)
+ (semantic.db.migration.impl/migrate-dynamic-schema! tx opts))
+
+ :else
+ (log/infof "Dynamic tables database schema version (%d) is newer than code version (%d). Not performing migration."
+ db-version semantic.db.migration.impl/dynamic-schema-version)))
+ nil)
+
+(defn maybe-migrate!
+ "Execute schema and dynamic schema migrations."
+ [tx opts]
+ (ensure-migration-table! tx)
+ (maybe-migrate-schema! tx opts)
+ (maybe-migrate-dynamic-schema! tx opts)
+ nil)
+
+(defn drop-migration-table!
+ "Drop migration table."
+ [connectable]
+ (jdbc/execute! connectable (sql/format (sql.helpers/drop-table :if-exists :migration))))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
new file mode 100644
index 00000000000..78629fd8b27
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
@@ -0,0 +1,47 @@
+(ns metabase-enterprise.semantic-search.db.migration.impl
+ (:require
+ [honey.sql :as sql]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [next.jdbc :as jdbc]))
+
+(def schema-version
+ "Version to compare the [[metabase-enterprise.semantic-search.db.migration/db-version]] with. If this is higher,
+ schema migration will be performed."
+ 1)
+
+(defn- drop-all-but-migration-table
+ [tx]
+ (let [table-names (map (comp first vals)
+ (jdbc/execute! tx
+ (sql/format
+ {:select [[:tablename :xi]]
+ :from [:pg_tables]
+ :where [:and
+ [:<> :schemaname [:inline "information_schema"]]
+ [:<> :schemaname [:inline "pg_catalog"]]
+ [:<> :tablename [:inline "migration"]]]})))]
+ (doseq [table table-names]
+ (jdbc/execute! tx
+ (sql/format
+ {:drop-table [[[:raw table]]]})))))
+
+(defn migrate-schema!
+ "Migrate schema (control, metadata, gate, ...). Migration author is responsible for removing leftovers if necessary
+ and in general leaving schema in desired state."
+ [tx {:keys [index-metadata] :as _opts}]
+ ;; ideally index_table indexed are manipulated in dynamic schema part but for now it does not matter
+ (drop-all-but-migration-table tx)
+ (semantic.index-metadata/create-tables-if-not-exists! tx index-metadata)
+ (semantic.index-metadata/ensure-control-row-exists! tx index-metadata))
+
+(def dynamic-schema-version
+ "Code version of dynamic schema (index_table_xyzs). If higher than what's found in db dynamic schema migration will
+ be attempted."
+ 1)
+
+(defn migrate-dynamic-schema!
+ "Migrate runtime-managed schema, ie. schema of `index_table_...` tables. Migration author is responsible for removing
+ leftovers if necessary."
+ [_tx {_index-metadata :index-metadata _embedding-model :embedding-model :as _opts}]
+ ;; migration 1: all tables dropped in schema migration in single function call
+ )
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/util.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/util.clj
new file mode 100644
index 00000000000..98a7247a8b8
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/util.clj
@@ -0,0 +1,17 @@
+(ns metabase-enterprise.semantic-search.db.util
+ (:require
+ [next.jdbc :as jdbc]))
+
+(set! *warn-on-reflection* true)
+
+(defn tx-or-throw!
+ "Throw if not in transaction."
+ [conn]
+ (when-not #_{:clj-kondo/ignore [:discouraged-var]} (jdbc/active-tx? (.unwrap ^java.sql.Connection conn java.sql.Connection))
+ (throw (Exception. "Not in transaction."))))
+
+;; Unused now, may be handy for with-write-tx, acquire-write-lock
+#_(defn not-tx-or-throw!
+ [conn]
+ (when (jdbc/active-tx? (.unwrap ^java.sql.Connection conn java.sql.Connection))
+ (throw (Exception. "In transaction."))))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/docker-compose.yml b/enterprise/backend/src/metabase_enterprise/semantic_search/docker-compose.yml
new file mode 100644
index 00000000000..75861160e10
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/docker-compose.yml
@@ -0,0 +1,34 @@
+version: '3.8'
+
+services:
+ postgres:
+ image: pgvector/pgvector:pg16
+ environment:
+ POSTGRES_DB: mb_semantic_search
+ POSTGRES_USER: postgres
+ POSTGRES_PASSWORD: postgres
+ ports:
+ - "55432:5432"
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U postgres"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+ ollama:
+ image: ollama/ollama:latest
+ ports:
+ - "11434:11434"
+ volumes:
+ - ollama_data:/root/.ollama
+ healthcheck:
+ test: ["CMD", "curl", "-f", "http://localhost:11434/api/version"]
+ interval: 30s
+ timeout: 10s
+ retries: 3
+
+volumes:
+ postgres_data:
+ ollama_data:
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/embedding.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/embedding.clj
new file mode 100644
index 00000000000..e49597c485f
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/embedding.clj
@@ -0,0 +1,309 @@
+(ns metabase-enterprise.semantic-search.embedding
+ (:require
+ [clj-http.client :as http]
+ [clojure.string :as str]
+ [metabase-enterprise.metabot-v3.client :as metabot-v3.client]
+ [metabase-enterprise.semantic-search.settings :as semantic-settings]
+ [metabase.analytics.core :as analytics]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log])
+ (:import
+ [com.knuddels.jtokkit Encodings]
+ [com.knuddels.jtokkit.api Encoding EncodingType]))
+
+(set! *warn-on-reflection* true)
+
+(defn ^:private clean-model-name
+ "Clean up a model name to make it friendly for use in index names."
+ [model-name]
+ (-> model-name
+ (str/split #"/")
+ last
+ (str/replace #"[-:.]" "_")))
+
+(def ^:private model-abbreviations {"small" "sm" "medium" "md" "large" "lg" "tiny" "tn"})
+
+(defn abbrev-model-name
+ "Abbreviate long model names for use in index names."
+ [model-name]
+ (-> model-name
+ clean-model-name
+ (str/replace #"embedding|embed" "")
+ ((fn [s] (reduce-kv str/replace s model-abbreviations)))
+ (str/replace #"_{2,}" "_")
+ (str/replace #"^_+|_+$" "")))
+
+(defn clean-provider-name
+ "Clean up a provider names for use in index names."
+ [provider-name]
+ (str/replace provider-name #"[-:.]" "_"))
+
+(defn abbrev-provider-name
+ "Abbreviate long provider names for use in index names."
+ [provider-name]
+ (if (= provider-name "ai-service")
+ "ais"
+ (clean-provider-name provider-name)))
+
+;;; Token Counting for OpenAI Models
+
+(def ^:private ^Encoding openai-encoding
+ "OpenAI tokenizer encoding for cl100k_base (used by text-embedding models)."
+ (delay (.getEncoding (Encodings/newDefaultEncodingRegistry) EncodingType/CL100K_BASE)))
+
+(defn- count-tokens
+ "Count the number of tokens in a text string using OpenAI's cl100k_base encoding."
+ [^String text]
+ (when text
+ (let [^Encoding encoding @openai-encoding]
+ (.size (.encode encoding text)))))
+
+(defn- count-tokens-batch
+ "Count the total number of tokens across multiple text strings."
+ [texts]
+ (reduce + 0 (map count-tokens texts)))
+
+;;; Decode OpenAI base64 response
+
+(defn- extract-base64-response-embeddings
+ "Decode and extract the base64 encoded embedding from an /v1/embeddings OpenAI response"
+ [response]
+ (->> response
+ :data
+ (map (comp vec
+ (fn [^String base64-str]
+ (let [bytes (.decode (java.util.Base64/getDecoder) base64-str)
+ buffer (java.nio.ByteBuffer/wrap bytes)
+ _ (.order buffer java.nio.ByteOrder/LITTLE_ENDIAN)
+ float-count (/ (count bytes) 4)]
+ (repeatedly float-count #(.getFloat buffer))))
+ :embedding))
+ vec))
+
+;;; Batching Logic
+
+(defn- create-batches
+ "Split texts into batches that don't exceed the threshold.
+ Returns a vector of batches, where each batch is a vector of texts.
+ - threshold: Maximum allowed measure per batch
+ - measure: Function to measure each text (e.g., count-tokens)
+ - texts: Collection of texts to batch"
+ [threshold measure texts]
+ (let [step (fn [{:keys [current-batch current-measure batches] :as acc} text]
+ (let [text-measure (measure text)]
+ (cond
+ ;; Single text exceeds the limit - skip it with warning
+ (> text-measure threshold)
+ (do
+ (log/warn
+ (format "Skipping text that exceeds maximum measure per batch: %s"
+ (str (subs text 0 10) "..."))
+ {:measure text-measure :threshold threshold})
+ acc)
+
+ ;; Adding this text would exceed the limit - start new batch
+ (> (+ current-measure text-measure) threshold)
+ (assoc acc
+ :current-batch [text]
+ :current-measure text-measure
+ :batches (conj batches current-batch))
+
+ ;; Add to current batch
+ :else
+ (assoc acc
+ :current-batch (conj current-batch text)
+ :current-measure (+ current-measure text-measure)))))
+ {:keys [batches current-batch]}
+ (reduce step
+ {:current-batch [] :current-measure 0 :batches []}
+ texts)]
+ (if (seq current-batch)
+ (conj batches current-batch)
+ batches)))
+
+;;;; Provider SPI
+
+(defn- dispatch-provider [embedding-model & _] (:provider embedding-model))
+
+(defmulti get-embedding
+ "Returns a single embedding vector for the given text"
+ {:arglists '([embedding-model text])} dispatch-provider)
+
+(defmulti get-embeddings-batch
+ "Returns a sequential collection of embedding vectors, in the same order as the input texts."
+ {:arglists '([embedding-model texts])} dispatch-provider)
+
+(defmulti pull-model
+ "If a model needs to be downloaded (which is the case for ollama), downloads it."
+ {:arglists '([embedding-model])} dispatch-provider)
+
+;;;; Ollama impl
+
+(defn- ollama-get-embedding [model-name text]
+ (try
+ ;; TODO count ollama tokens into :metabase-search/semantic-embedding-tokens?
+ (log/debug "Generating Ollama embedding for text of length:" (count text))
+ (-> (http/post "http://localhost:11434/api/embeddings" ;; TODO: we should make the host configurable
+ {:headers {"Content-Type" "application/json"}
+ :body (json/encode {:model model-name
+ :prompt text})})
+ :body
+ (json/decode true)
+ :embedding)
+ (catch Exception e
+ (log/error e "Failed to generate Ollama embedding for text of length:" (count text))
+ (throw e))))
+
+(defn- ollama-get-embeddings-batch [model-name texts]
+ ;; Ollama doesn't have a native batch API, so we fall back to individual calls
+ ;; No special batching needed for Ollama - just process all texts
+ (log/debug "Generating" (count texts) "Ollama embeddings (using individual calls)")
+ (mapv #(ollama-get-embedding model-name %) texts))
+
+(defn- ollama-pull-model [model-name]
+ (try
+ (log/debug "Pulling embedding model from Ollama...")
+ (http/post "http://localhost:11434/api/pull" ;; TODO: make the host configurable
+ {:headers {"Content-Type" "application/json"}
+ :body (json/encode {:model model-name})})
+ (catch Exception e
+ (log/error e "Failed to pull embedding model")
+ (throw e))))
+
+(defmethod get-embedding "ollama" [{:keys [model-name]} text] (ollama-get-embedding model-name text))
+(defmethod get-embeddings-batch "ollama" [{:keys [model-name]} texts] (ollama-get-embeddings-batch model-name texts))
+(defmethod pull-model "ollama" [{:keys [model-name]}] (ollama-pull-model model-name))
+
+;;;; AI Service impl
+
+(defn- ai-service-get-embeddings-batch [model-name texts]
+ (try
+ (log/debug "Calling AI Service embeddings API" {:documents (count texts) :tokens (count-tokens-batch texts)})
+ (let [response (metabot-v3.client/generate-embeddings model-name texts)]
+ (analytics/inc! :metabase-search/semantic-embedding-tokens
+ {:provider "ai-service", :model model-name}
+ (->> response :usage :total_tokens))
+ (extract-base64-response-embeddings response))
+ (catch Exception e
+ (log/error e "AI Service embeddings API call failed" {:documents (count texts) :tokens (count-tokens-batch texts)})
+ (throw e))))
+
+(defn- ai-service-get-embedding [model-name text]
+ (try
+ (log/debug "Generating AI Service embedding for text of length:" (count text))
+ (first (ai-service-get-embeddings-batch model-name [text]))
+ (catch Exception e
+ (log/error e "Failed to generate AI Service embedding for text of length:" (count text))
+ (throw e))))
+
+(defmethod get-embedding "ai-service" [{:keys [model-name]} text] (ai-service-get-embedding model-name text))
+(defmethod get-embeddings-batch "ai-service" [{:keys [model-name]} texts] (ai-service-get-embeddings-batch model-name texts))
+
+;;;; OpenAI impl
+
+(defn- supports-dimensions?
+ "Check whether the model's API supports dimensions in request's body. At the time of writing supported on OpenAI's
+ text-embedding-3-small and text-embedding-3-large. Should be supported also on newer models when those are out."
+ [{:keys [model-name] :as _embedding-model}]
+ (boolean
+ (when (string? model-name)
+ (str/starts-with? model-name "text-embedding-3"))))
+
+(defn- openai-get-embeddings-batch
+ [{:keys [model-name vector-dimensions] :as embedding-model} texts]
+ (let [api-key (semantic-settings/openai-api-key)
+ endpoint (str (semantic-settings/openai-api-base-url) "/v1/embeddings")]
+ (when-not api-key
+ (throw (ex-info "OpenAI API key not configured" {:setting "ee-openai-api-key"})))
+ (try
+ (log/debug "Calling OpenAI embeddings API" {:documents (count texts) :tokens (count-tokens-batch texts)})
+ (let [response (-> (http/post endpoint
+ {:headers {"Content-Type" "application/json"
+ "Authorization" (str "Bearer " api-key)}
+ :body (json/encode (merge {:model model-name
+ :input texts
+ :encoding_format "base64"}
+ (when (supports-dimensions? embedding-model)
+ {:dimensions vector-dimensions})))})
+ :body
+ (json/decode true))]
+ (analytics/inc! :metabase-search/semantic-embedding-tokens
+ {:provider "openai", :model model-name}
+ (->> response :usage :total_tokens))
+ (extract-base64-response-embeddings response))
+ (catch Exception e
+ (log/error e "OpenAI embeddings API call failed" {:documents (count texts) :tokens (count-tokens-batch texts)})
+ (throw e)))))
+
+(defn- openai-get-embedding [embedding-model text]
+ (try
+ (log/debug "Generating OpenAI embedding for text of length:" (count text))
+ (first (openai-get-embeddings-batch embedding-model [text]))
+ (catch Exception e
+ (log/error e "Failed to generate OpenAI embedding for text of length:" (count text))
+ (throw e))))
+
+(defmethod get-embedding "openai" [embedding-model text] (openai-get-embedding embedding-model text))
+(defmethod get-embeddings-batch "openai" [embedding-model texts] (openai-get-embeddings-batch embedding-model texts))
+(defmethod pull-model "openai" [_] (log/debug "OpenAI provider does not require pulling a model"))
+
+;;;; Global embedding model
+
+(defn get-configured-model
+ "Get the environments default embedding model according to the ee-embedding-provider / ee-embedding-model settings."
+ []
+ {:provider (semantic-settings/ee-embedding-provider)
+ :model-name (semantic-settings/ee-embedding-model)
+ :vector-dimensions (semantic-settings/ee-embedding-model-dimensions)})
+
+(defn- calc-token-metrics
+ [texts]
+ (let [counts (map count-tokens texts)
+ avg-raw (/ (reduce + counts) (count counts))]
+ {:n (count texts)
+ :min (apply min counts)
+ :max (apply max counts)
+ :sum (reduce + counts)
+ :avg (parse-double (format "%.2f" (double avg-raw)))}))
+
+(defn process-embeddings-streaming
+ "Process texts in provider-appropriate batches, calling process-fn for each batch. process-fn will be called with
+ a map from text to embedding for each batch."
+ [embedding-model texts process-fn]
+ (when (seq texts)
+ (let [{:keys [model-name provider vector-dimensions]} embedding-model]
+ (u/profile (str "Generating embeddings " {:model model-name
+ :dimenions vector-dimensions
+ :texts (calc-token-metrics texts)})
+ (if (= "openai" provider)
+ (let [max-tokens-per-batch (semantic-settings/openai-max-tokens-per-batch)
+ batches (create-batches max-tokens-per-batch count-tokens texts)
+
+ process-batch
+ (fn [batch-idx batch-texts]
+ (let [embeddings (u/profile (format "Embedding batch %d/%d %s"
+ (inc batch-idx) (count batches) (str (calc-token-metrics batch-texts)))
+ (openai-get-embeddings-batch embedding-model batch-texts))
+ text-embedding-map (zipmap batch-texts embeddings)]
+ (process-fn text-embedding-map)))]
+
+ (transduce (map-indexed process-batch) (partial merge-with +) batches))
+
+ (let [embeddings (get-embeddings-batch embedding-model texts)
+ text-embedding-map (zipmap texts embeddings)]
+ (process-fn text-embedding-map)))))))
+
+(comment
+ ;; Configuration:
+ ;; MB_EE_EMBEDDING_PROVIDER: "openai" or "ollama" (default)
+ ;; MB_EE_EMBEDDING_MODEL: optional override (leave empty for provider defaults)
+ ;; - OpenAI default: "text-embedding-3-small"
+ ;; - Ollama default: "mxbai-embed-large"
+ ;; MB_EE_OPENAI_API_KEY your OpenAI API key
+ ;; MB_EE_EMBEDDING_MODEL_DIMENSIONS: defaults to 1024.
+
+ (def embedding-model (get-configured-model))
+ embedding-model
+ (pull-model embedding-model)
+ (get-embedding embedding-model "hello"))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/env.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/env.clj
new file mode 100644
index 00000000000..ef08ffc6db7
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/env.clj
@@ -0,0 +1,27 @@
+(ns metabase-enterprise.semantic-search.env
+ (:require
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase-enterprise.semantic-search.embedding :as semantic.embedding]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]))
+
+;; global configuration / state containment facility
+;; only core and the task definitions (for which integration with metabase demands globals)
+;; should need these
+
+;; TODO: Probably remove completely, all occurrences should be using db.connection
+(defn get-pgvector-datasource!
+ "Returns the instances pgvector Datasource, initializing lazily if needed."
+ []
+ (semantic.db.datasource/ensure-initialized-data-source!))
+
+(defn get-configured-embedding-model
+ "Returns the currently configured embedding model from settings."
+ []
+ (semantic.embedding/get-configured-model))
+
+(defn get-index-metadata
+ "Returns this instances index metadata configuration.
+ Currently, an instance only has one metadata root, so this will always have the same value in production."
+ []
+ ;; still useful to indirect this for tests
+ semantic.index-metadata/default-index-metadata)
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/gate.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/gate.clj
new file mode 100644
index 00000000000..7c5211b458b
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/gate.clj
@@ -0,0 +1,297 @@
+(ns metabase-enterprise.semantic-search.gate
+ "The gate table (managed by index-metadata) decouples document ingestion from embedding computation and indexing.
+
+ By avoiding producer/consumer coupling in this instance we get some advantages:
+ - downstream consumers can take an unbounded amount of time without necessarily increasing memory usage or providing
+ blocking backpressure onto search ingestion
+ - downstream consumers can recover after transient indexing/embedding errors, or due to process loss during indexing.
+ - multiple downstream indexes (or intermediate structures) can be maintained on a single document source
+ without re-reading the data from the appdb.
+ - provides opportunities to avoid wasted work when reindexing
+ (which is ultimately still necessary as the search ingestion system itself can lose data).
+
+ This namespace provides the `gate-documents!` function for writing gate documents and enforcing ordering guarantees.
+ Additionally, polling support functions are defined for indexing (see the lib indexer).
+
+ IMPORTANT: The gating mechanism is still based on heuristics, it alone is not enough to guarantee index convergence.
+ It only allows you to converge on a consistent index more often than if it did not exist (i.e. Re-indexes can be less frequent, and less expensive).
+
+ NOTE: The 'immediate mode' indexing apis in the libs: (index, pgvector-api) are still available and work as document
+ but are not coordinated with any gated updates and therefore might race if gate indexers are also running."
+ (:require
+ [buddy.core.hash :as buddy-hash]
+ [honey.sql :as sql]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import (java.sql Timestamp)
+ (java.time Duration Instant OffsetDateTime)
+ (org.postgresql.util PGobject)))
+
+(set! *warn-on-reflection* true)
+
+;; multiple threads can hit the gating table, row states can be committed in any order,
+;; gated table provides a gated_at value which never decreases with new writes
+;; regardless of commit ordering (via clock_timestamp())
+
+;; ideal maximum write time (we can allow for some error in lag-tolerance).
+;; we should see tx timeout policies set accordingly e.g: SET LOCAL statement_timeout
+;; we should use one transaction per write to limit opportunity for error here.
+(def ^Duration gate-write-timeout
+ "The time in which gate-documents! transactions should commit.
+ Optimistically enforced by SET LOCAL statement_timeout.
+ This value is used to determine the lag-tolerance, and the degree to which we might
+ expect to see out of order commits (e.g. lag-tolerance = gate-write-timeout * 2)."
+ (Duration/ofSeconds 5))
+
+(def max-batch-size
+ "The maximum number of documents that can be sent to (gate-documents!) without causing an error"
+ 512)
+
+(defn deleted-search-doc->gate-doc
+ "Converts a deleted document reference into a gate table record.
+ Document and hash are set to nil to signal deletion."
+ [model id default-updated-at]
+ {:id (str model "_" id)
+ :model model
+ :model_id id
+ :document nil
+ :document_hash nil
+ :updated_at default-updated-at})
+
+(defn- document-hash [search-doc]
+ (u/encode-base64-bytes (buddy-hash/sha1 (json/encode (into (sorted-map) search-doc)))))
+
+(defn- ->instant
+ ^Instant [inst]
+ (cond
+ (instance? Instant inst) inst
+ (instance? OffsetDateTime inst) (.toInstant ^OffsetDateTime inst)
+ :else (Instant/ofEpochMilli (inst-ms inst))))
+
+(defn- ->timestamp
+ "By default, our TIMESTAMP WITH TIME ZONE columns will result in JDBC timestamps. Which should be interpreted as
+ Instants.
+ We remain sympathetic, to that for now, despite the fact it would normally represent a LocalDateTime. We might change that fact later."
+ ^Timestamp [inst]
+ (if (instance? Timestamp inst)
+ inst
+ (Timestamp/from (->instant inst))))
+
+(defn search-doc->gate-doc
+ "Converts a search document into a gate table record, requires the document can be encoded as json."
+ [search-doc default-updated-at]
+ (let [{:keys [model id]} search-doc]
+ {:id (str model "_" id)
+ :model model
+ :model_id id
+ :document (doto (PGobject.)
+ (.setType "jsonb")
+ (.setValue (json/encode search-doc)))
+ :document_hash (document-hash search-doc)
+ :updated_at (->timestamp (or (:updated_at search-doc) default-updated-at))}))
+
+(defn gate-doc->search-doc
+ "Converts a gate table record back to a search document."
+ [gate-doc]
+ (let [{:keys [^PGobject document]} gate-doc]
+ (json/decode (.getValue document) keyword)))
+
+(defn gate-documents!
+ "Writes document changes to the gate table which improves ordering guarantees for downstream consumption.
+ Will not update gate records if:
+ a. It is an earlier document value according to the search documents updated_at value
+ b. It is literally the same document and reindexing would be redundant
+ Returns a count of rows actually updated/inserted."
+ [pgvector index-metadata gate-document-batch]
+ {:pre [;; countable only
+ (seqable? gate-document-batch)
+ ;; too many documents and we might see buffer size limits get hit in the driver, TODO: bench/play with this - document expectations
+ (<= (bounded-count (inc max-batch-size) gate-document-batch) max-batch-size)]}
+ ;; We will fix the transaction policy here (rather than letting caller decide) to encapsulate timeout behaviour
+ ;; and to ensure the READ COMMITTED :isolation level is set.
+ ;; NOTE: we depend on the UPDATE behaviour described here: https://www.postgresql.org/docs/current/transaction-iso.html#XACT-READ-COMMITTED
+ ;; i.e (the WHERE must be re-evaluated against the UPDATED row if another transaction commits concurrently).
+ (jdbc/with-transaction [tx pgvector {:isolation :read-committed}]
+ (when-some [gate-document-batch (->> gate-document-batch
+ (sort-by :updated_at)
+ (group-by :id)
+ (map (fn [[id updates]]
+ (when (< 1 (count updates))
+ (log/warnf "More than one (%d) update issued for a gate entry: %s" (count updates) id))
+ (peek updates)))
+ seq)]
+ (let [{:keys [gate-table-name]} index-metadata
+ upsert-q {:insert-into (keyword gate-table-name)
+ ;; sort to ensure locks are acquired predictably
+ :values (sort-by :id gate-document-batch)
+ :on-conflict [:id]
+ :do-update-set {:fields {:updated_at :excluded.updated_at
+ :model :excluded.model
+ :model_id :excluded.model_id
+ :document :excluded.document
+ :document_hash :excluded.document_hash
+ :gated_at [:clock_timestamp]}
+ :where [:and
+ ;; in the case of an updated_at collision, simulate old behaviour, later transactions on the gate win.
+ [:<= (keyword gate-table-name "updated_at") :excluded.updated_at]
+ ;; content diff
+ [:case
+ ;; now deleted, delete if was not previously
+ [:= nil :excluded.document_hash]
+ [:!= nil (keyword gate-table-name "document_hash")]
+
+ ;; was deleted (now has a value) - update
+ [:= nil (keyword gate-table-name "document_hash")]
+ true
+
+ ;; update if new value is different
+ :else
+ [:!= (keyword gate-table-name "document_hash") :excluded.document_hash]]]}}
+ upsert-sql (sql/format upsert-q :quoted true)]
+ (jdbc/execute! tx [(format "SET LOCAL statement_timeout = %d" (.toMillis gate-write-timeout))]) ; note pg cannot accept a parameter here
+ (let [update-count (::jdbc/update-count (jdbc/execute-one! tx upsert-sql))]
+ (log/infof "Gated %d document updates" update-count)
+ update-count)))))
+
+(def ^:private epoch-timestamp (->timestamp Instant/EPOCH))
+
+(defn poll
+ "Find document (gate table) ids that are highly likely to have been updated. Due to commit lag, if called with a watermark
+ close to the current postgres clock value, you will see some records with timestamps <= your watermark.
+ Therefore, any downstream processing must be idempotent - duplicate delivery is expected and intended.
+
+ Expect to receive a map with:
+ - `:poll-time` the postgres clock value as-of this poll
+ - `:update-candidates` a vector of [{:id, :document_hash, :gated_at}] maps. Guaranteed to be ordered by (gated_at, id).
+
+ Options:
+ - :limit (1000)
+ - :lag-tolerance (Duration) (should be at least gate-write-timeout + some buffer for timeout variation)
+
+ Call (next-watermark) on the result to determine where to poll next."
+ [pgvector index-metadata watermark & {:keys [^Duration lag-tolerance
+ limit]
+ :or {lag-tolerance (.multipliedBy gate-write-timeout 2) ; heuristic: still depends on postgres enforcing timeouts. We might still need a slow-pass over everything occasionally in the future.
+ limit 1000}}]
+ {:pre [(pos? limit)]}
+ (let [;; IMPORTANT: these Instant conversion must only be used for heuristic / approximate conditions (such as confidence-time)
+ ;; as their precision does not match the actual SQL clock_timestamp() value.
+ ^Instant last-poll-inst (or (some-> watermark :last-poll ->instant) Instant/EPOCH)
+ ^Instant last-seen-inst (or (some-> watermark :last-seen :gated_at ->instant) Instant/EPOCH)
+ confidence-time (.minus last-poll-inst lag-tolerance)
+ gate-min (if (.isBefore confidence-time last-seen-inst)
+ {:gated_at confidence-time}
+ ;; We might not have seen everything with the last poll
+ ;; e.g. maybe there were more than :limit rows
+ ;; For this case - we would expect the last-seen to be behind the confidence window,
+ ;; and we should not skip ahead.
+ ;; IMPORTANT: preserve the java.sql.Timestamp to retain the required precision.
+ ;; otherwise pagination behaviour is incorrect and the indexer can stall.
+ (or (:last-seen watermark) {:gated_at epoch-timestamp}))
+ poll-q {:union-all
+ [{:select [[nil :id]
+ [nil :document_hash]
+ [[:clock_timestamp] :gated_at]]} ; return pgs clock value, to use as the :poll-time
+ {:select [:q.id :q.document_hash :q.gated_at]
+ :from
+ ;; subquery is important otherwise :limit is honey-ed into the outer union
+ [[{:select [:id, :document_hash, :gated_at]
+ :from [(keyword (:gate-table-name index-metadata))]
+ ;; the earliest timestamp where we might expect to find new documents
+ :where (if (:id gate-min) ; :id here means we are polling from an exact watermark
+ ;; we can do a proper paging scan, and can assume no later data will arrive out-of-order.
+ [:>= [:composite :gated_at :id] [:composite (:gated_at gate-min) (:id gate-min)]]
+ ;; if outside the confidence time we have to assume we will receive out of order writes
+ ;; until our last seen falls within the confidence time
+ ;; this means the indexer can stall here if the :limit is exceeded until
+ ;; the confidence time moves or our last seen moves to be within the threshold.
+ [:>= :gated_at (:gated_at gate-min)])
+ :order-by [[:gated_at] [:id]]
+ :limit limit}
+ :q]]}]}
+ poll-sql (sql/format poll-q :quoted true)
+ rs (jdbc/execute! pgvector poll-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ poll-time (some #(when (nil? (:id %)) (:gated_at %)) rs)
+ _ (assert poll-time "expected poll time record (nil id)")
+ update-candidates (filterv #(some? (:id %)) rs)]
+ {:poll-time poll-time
+ :update-candidates update-candidates}))
+
+(defn next-watermark
+ "Given a poll result and the previous watermark, return next watermark (to be applied to poll at some future time)"
+ [watermark {:keys [poll-time update-candidates]}]
+ {:last-poll poll-time
+ :last-seen (or (peek update-candidates) (:last-seen watermark))})
+
+(defn resume-watermark
+ "Extracts a watermark for resuming indexer processing - assuming the previous watermark was flushed
+ to the metadata table."
+ [metadata-row]
+ (let [{:keys [indexer_last_poll
+ indexer_last_seen
+ indexer_last_seen_id
+ indexer_last_seen_hash]} metadata-row]
+ {:last-poll indexer_last_poll
+ :last-seen (when indexer_last_seen_id
+ {:id indexer_last_seen_id
+ :document_hash indexer_last_seen_hash
+ :gated_at indexer_last_seen})}))
+
+(defn flush-watermark!
+ "Persists an indexer watermark to the corresponding row in the metadata table for resumption after restarts.
+ Note: Issues an UPDATE, so assumes the metadata row exists (it should if you are polling!)."
+ [pgvector index-metadata index watermark]
+ (let [{:keys [last-poll last-seen]} watermark
+ update-q {:update [(keyword (:metadata-table-name index-metadata))]
+ :set {:indexer_last_poll last-poll
+ :indexer_last_seen_id (:id last-seen)
+ :indexer_last_seen (:gated_at last-seen)
+ :indexer_last_seen_hash (:document_hash last-seen)}
+ :where [:= :table_name (:table-name index)]}]
+ (jdbc/execute! pgvector (sql/format update-q :quoted true))))
+
+(comment
+ (def pgvector ((requiring-resolve 'metabase-enterprise.semantic-search.env/get-pgvector-datasource!)))
+ (def index-metadata ((requiring-resolve 'metabase-enterprise.semantic-search.env/get-index-metadata)))
+ (def search-docs (vec ((requiring-resolve 'metabase.search.ingestion/searchable-documents))))
+
+ (def null-updated-at (filter #(nil? (:updated_at %)) search-docs))
+ (count null-updated-at)
+ (take 1 null-updated-at)
+
+ (count search-docs)
+
+ (jdbc/execute! pgvector ["delete from index_gate"])
+
+ (doseq [chunk (partition-all 512 search-docs)]
+ (gate-documents! pgvector
+ index-metadata
+ (for [search-doc chunk
+ :let [search-doc (if (< (rand) 0.5)
+ (assoc search-doc :updated_at (java.time.Instant/now))
+ search-doc)]]
+ (search-doc->gate-doc search-doc (Instant/now)))))
+
+ (jdbc/execute! pgvector ["select * from index_gate limit 100"])
+
+ (def watermark
+ {:last-poll java.time.Instant/EPOCH
+ :last-seen nil})
+
+ (def poll-result (poll pgvector index-metadata watermark))
+ poll-result
+ (reverse (sort (map :gated_at (:update-candidates poll-result))))
+
+ (next-watermark watermark poll-result)
+
+ (def active-index-state
+ ((requiring-resolve 'metabase-enterprise.semantic-search.index-metadata/get-active-index-state)
+ pgvector
+ index-metadata))
+
+ (def index (:index active-index-state))
+ (flush-watermark! pgvector index-metadata index (next-watermark watermark poll-result))
+ (jdbc/execute! pgvector ["select * from index_metadata where table_name = ?" (:table-name index)]))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
new file mode 100644
index 00000000000..c7b2ecf5475
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
@@ -0,0 +1,910 @@
+(ns metabase-enterprise.semantic-search.index
+ (:require
+ [clojure.string :as str]
+ [com.climate.claypoole :as cp]
+ [honey.sql :as sql]
+ [honey.sql.helpers :as sql.helpers]
+ ;; TODO: extract schema code to go under db.migration
+ [metabase-enterprise.semantic-search.embedding :as embedding]
+ [metabase-enterprise.semantic-search.scoring :as scoring]
+ [metabase-enterprise.semantic-search.settings :as semantic-settings]
+ [metabase.analytics.core :as analytics]
+ [metabase.models.interface :as mi]
+ [metabase.search.config :as search.config]
+ [metabase.search.core :as search]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [nano-id.core :as nano-id]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs]
+ [toucan2.core :as t2])
+ (:import
+ [java.time Instant LocalDate OffsetDateTime ZonedDateTime]
+ [java.util.concurrent ArrayBlockingQueue RejectedExecutionHandler RejectedExecutionException TimeUnit ThreadPoolExecutor]
+ [org.postgresql.util PGobject]))
+
+(set! *warn-on-reflection* true)
+
+(comment
+ ((requiring-resolve 'metabase-enterprise.semantic-search.db.datasource/init-db!))
+ (def db @@(requiring-resolve 'metabase-enterprise.semantic-search.db.datasource/data-source)))
+
+(defn sql-format-quoted
+ "Call [[sql/format]] with {:quoted true}.
+
+ Ensures identifiers are quoted since the nano-ids used in temp table names when testing (and various other places)
+ might contain uppercase chars or hyphens which need to be quoted."
+ [honey-sql & {:as opts}]
+ (sql/format honey-sql (merge opts {:quoted true})))
+
+(def ^:dynamic *batch-size*
+ "The number of documents to process per batch when updating the index."
+ 150)
+
+(defn- index-table-schema
+ "Schema for the index table."
+ [vector-dimensions]
+ ;; Generate unique constraint name to avoid index name conflicts between multiple test tables
+ (let [unique-constraint-name (keyword (str "unique_constraint_" (nano-id/nano-id) "_model_model_id"))]
+ [[:id :bigint [:primary-key] [:raw "GENERATED BY DEFAULT AS IDENTITY"]]
+ [:model :text :not-null]
+ [:model_id :text :not-null]
+ [:collection_id :int]
+ [:creator_id :int]
+ [:database_id :int]
+ [:last_editor_id :int]
+ [:name :text :not-null]
+ [:content :text :not-null]
+ [:display_type :text]
+ [:archived :boolean [:default false]]
+ [:official_collection :boolean]
+ [:pinned :boolean]
+ [:verified :boolean]
+ [:dashboardcard_count :int]
+ [:view_count :int]
+ [:created_at :timestamp-with-time-zone [:default [:raw "CURRENT_TIMESTAMP"]] :not-null]
+ [:model_created_at :timestamp-with-time-zone]
+ [:model_updated_at :timestamp-with-time-zone]
+ [:last_viewed_at :timestamp-with-time-zone]
+ [:legacy_input :jsonb]
+ [:metadata :jsonb]
+ [:text_search_vector :tsvector :not-null]
+ [:text_search_with_native_query_vector :tsvector :not-null]
+ [:embedding [:raw (format "vector(%d)" vector-dimensions)] :not-null]
+ [[:constraint unique-constraint-name]
+ [:unique [:composite :model :model_id]]]]))
+
+(defn- format-embedding
+ "Formats and validates the embedding vector for SQL insertion."
+ [embedding]
+ ;; Validate all values are numeric as a safe-guard against malformed/malicious embeddings
+ (doseq [value embedding]
+ (when-not (number? value)
+ (throw (ex-info "Embedding contains non-numeric value"
+ {:invalid-value value
+ :embedding embedding}))))
+ (str "'[" (str/join ", " embedding) "]'::vector"))
+
+(defn- to-instant
+ [document-timestamp]
+ (cond
+ ;; loosey-goosey, but applies to json encoded instants from the gate table
+ ;; important: assumes all observable timestamps are encoded in an Instant friendly way (ISO8601)
+ (string? document-timestamp)
+ (Instant/parse document-timestamp)
+
+ (instance? OffsetDateTime document-timestamp)
+ (.toInstant ^OffsetDateTime document-timestamp)
+
+ (instance? ZonedDateTime document-timestamp)
+ (.toInstant ^ZonedDateTime document-timestamp)
+
+ :else (Instant/ofEpochMilli (inst-ms document-timestamp))))
+
+(defn- doc->db-record
+ "Convert a document to a database record with a provided embedding."
+ [embedding-vec {:keys [model id searchable_text created_at creator_id updated_at
+ last_editor_id archived verified official_collection database_id collection_id display_type legacy_input
+ pinned dashboardcard_count view_count last_viewed_at] :as doc}]
+ {:model model
+ :model_id id
+ :collection_id collection_id
+ :creator_id creator_id
+ :database_id database_id
+ :last_editor_id last_editor_id
+ :name (:name doc)
+ :content searchable_text
+ :display_type display_type
+ :archived archived
+ :official_collection official_collection
+ :pinned pinned
+ :verified verified
+ :dashboardcard_count dashboardcard_count
+ :view_count view_count
+ :model_created_at (some-> created_at to-instant)
+ :model_updated_at (some-> updated_at to-instant)
+ :last_viewed_at (some-> last_viewed_at to-instant)
+ :legacy_input [:cast (json/encode legacy_input) :jsonb]
+ :metadata [:cast (json/encode doc) :jsonb]
+ :embedding [:raw (format-embedding embedding-vec)]
+ :text_search_vector (if (:name doc)
+ [:||
+ (search/weighted-tsvector "A" (:name doc))
+ (search/weighted-tsvector "B" (:searchable_text doc ""))]
+ (search/weighted-tsvector "A" (:searchable_text doc "")))
+ :text_search_with_native_query_vector
+ (if (:name doc)
+ [:||
+ (search/weighted-tsvector "A" (:name doc))
+ (search/weighted-tsvector "B"
+ (str/join " " (remove str/blank? [(:searchable_text doc "")
+ (:native_query doc "")])))]
+ (search/weighted-tsvector "A"
+ (str/join " " (remove str/blank? [(:searchable_text doc "")
+ (:native_query doc "")]))))})
+
+(defn index-size
+ "Fetches the number of documents in the index table."
+ [connectable table-name]
+ (->> (jdbc/execute-one! connectable
+ (-> (sql.helpers/select [:%count.* :count])
+ (sql.helpers/from (keyword table-name))
+ (sql.helpers/limit 1)
+ sql-format-quoted))
+ :count))
+
+(defn- analytics-set-index-size!
+ "Set the semantic-index-size metric to the number of rows in the index table."
+ [connectable table-name]
+ (try
+ (->> (index-size connectable table-name)
+ (analytics/set! :metabase-search/semantic-index-size))
+ (catch Exception e
+ (log/warn e "Failed to set :metabase-search/semantic-index-size metric"))))
+
+(defn- batch-update!
+ [connectable table-name records->sql documents embeddings]
+ (when (seq documents)
+ (u/prog1 (->> documents (map :model) frequencies)
+ (u/profile (str "Semantic index database update of " (count documents) " documents " <>)
+ (doseq [batch (->> (map vector documents embeddings)
+ (map (fn [[doc embedding]] (doc->db-record embedding doc)))
+ (partition-all *batch-size*))]
+ (jdbc/execute! connectable (records->sql batch)))
+ (analytics-set-index-size! connectable table-name)))))
+
+(defn- execute-with-counts [connectable model ids sql]
+ (jdbc/execute! connectable sql)
+ (u/prog1 (count ids)
+ (log/debug "semantic search deleted a batch of" <>
+ "documents with model type" model)))
+
+(defn- batch-delete-ids!
+ [connectable table-name model ids->sql ids]
+ (let [deleted (transduce
+ (comp (partition-all *batch-size*)
+ (map (fn [ids]
+ (-> ids
+ (some->> ids->sql (execute-with-counts connectable model ids))
+ (or 0)))))
+ +
+ ids)]
+ (when (pos? deleted)
+ (log/info "semantic search deleted" deleted "total documents with model type" model)
+ (analytics-set-index-size! connectable table-name)
+ {model deleted})))
+
+(defn- db-records->update-set
+ [db-records]
+ (let [update-keys (-> db-records first (dissoc :id :model :model_id) keys)
+ excluded-kw (fn [column] (keyword (str "excluded." (name column))))]
+ (zipmap update-keys (map excluded-kw update-keys))))
+
+(defn- throw-if-max-pg-len
+ [resource-name msg]
+ (when (> (count resource-name) 63)
+ (throw (ex-info msg
+ {:table-name resource-name
+ :length (count resource-name)
+ :limit 63}))))
+
+(defn model-table-name
+ "Returns the table name for a model."
+ [embedding-model]
+ (let [{:keys [model-name provider vector-dimensions]} embedding-model
+ provider-name (embedding/abbrev-provider-name provider)
+ abbrev-model-name (embedding/abbrev-model-name model-name)
+ result (str "index_table_" provider-name "_" abbrev-model-name "_" vector-dimensions)]
+ (throw-if-max-pg-len result "Table name exceeds PostgreSQL limit")
+ result))
+
+(defn default-index
+ "Returns the default index spec for a model."
+ [embedding-model]
+ (let [table-name (model-table-name embedding-model)]
+ {:embedding-model embedding-model
+ :table-name table-name
+ :version 1}))
+
+(defn- upsert-embedding!-fn [connectable index text->docs]
+ (fn [text->embedding]
+ (let [batch-documents
+ (mapcat (fn [[text embedding]]
+ (if embedding
+ (map #(assoc % :embedding embedding) (get text->docs text))
+ (when-let [docs (get text->docs text)]
+ (log/warn "No embedding found for" (count docs) "documents with searchable text:"
+ {:searchable_text text
+ :document_count (count docs)}))))
+ text->embedding)]
+ (batch-update!
+ connectable
+ (:table-name index)
+ (fn [db-records]
+ (-> (sql.helpers/insert-into (keyword (:table-name index)))
+ (sql.helpers/values db-records)
+ (sql.helpers/on-conflict :model :model_id)
+ (sql.helpers/do-update-set (db-records->update-set db-records))
+ sql-format-quoted))
+ batch-documents
+ (map :embedding batch-documents)))))
+
+(defn- unwrap-pgobject
+ [^PGobject obj]
+ (.getValue ^PGobject obj))
+
+(defn- decode-pgobject
+ "Decode a PGObject (returned from a jsonb field) into a Clojure map."
+ [^PGobject obj]
+ (json/decode (unwrap-pgobject obj) true))
+
+(defn- existing-embedding-query [index texts]
+ (-> (sql.helpers/select-distinct-on [:content] :content :embedding)
+ (sql.helpers/from (keyword (:table-name index)))
+ (sql.helpers/where [:in :content texts])))
+
+(defn- partition-existing-embeddings [connectable index texts]
+ (let [found-embeddings
+ (->> (jdbc/execute! connectable
+ (sql-format-quoted (existing-embedding-query index texts))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ (into {} (map (fn [{:keys [content embedding]}]
+ [content (decode-pgobject embedding)]))))]
+ [(remove found-embeddings texts) found-embeddings]))
+
+(defn- upsert-index-batch!
+ [connectable index documents]
+ (when (seq documents)
+ (let [text->docs (group-by :searchable_text documents)
+ searchable-texts (keys text->docs)
+ upsert-embedding! (upsert-embedding!-fn connectable index text->docs)
+ [new-texts stats]
+ (u/profile (str "Semantic search embedding caching attempt for " {:docs (count documents) :texts (count searchable-texts)})
+ (let [[new-texts existing-embeddings] (partition-existing-embeddings connectable index searchable-texts)]
+ (if-not (seq existing-embeddings)
+ [searchable-texts nil]
+ (u/profile (str "Semantic search cached embedding db update for " {:texts (count existing-embeddings)})
+ [new-texts (upsert-embedding! existing-embeddings)]))))]
+ (->>
+ (when (seq new-texts)
+ (u/profile (str "Semantic search embedding generation and db update for " {:docs (count documents) :texts (count new-texts)})
+ (embedding/process-embeddings-streaming
+ (:embedding-model index)
+ new-texts
+ upsert-embedding!)))
+ (merge-with + stats)))))
+
+(def ^:private ^:dynamic *retrying* false)
+
+(defonce ^:private
+ ^{:doc "A shared thread pool for processing batched documents, including fetching embeddings. A custom retry handler
+ is used to block the caller thread until a thread is available, to prevent realizing documents until they can be
+ processed."}
+ index-update-executor
+ (delay
+ (let [n (long (semantic-settings/index-update-thread-count))
+ retry-handler (reify RejectedExecutionHandler
+ (^void rejectedExecution [_ ^Runnable task ^ThreadPoolExecutor executor]
+ (if *retrying*
+ (throw (RejectedExecutionException.))
+ (loop [attempt 0]
+ (let [op
+ (if (.isShutdown executor)
+ (.run task)
+ (try
+ (binding [*retrying* true]
+ (.execute executor task))
+ (catch RejectedExecutionException _ ::retry)))]
+ (case op
+ ::retry
+ (let [delay-ms (min 500 (* 10 (Math/pow 2 attempt)))]
+ (Thread/sleep (long delay-ms))
+ (recur (inc attempt)))
+ nil))))))]
+ (ThreadPoolExecutor. n n 0 TimeUnit/SECONDS
+ (ArrayBlockingQueue. n)
+ retry-handler))))
+
+(defn upsert-index-pooled!
+ "Returns a future which upserts the provided documents into the index table, executed using the provided thread pool."
+ [pool connectable index documents]
+ (cp/future pool (upsert-index-batch! connectable index documents)))
+
+(defn upsert-index!
+ "Inserts or updates documents in the index table. If a document with the same
+ model + model_id already exists, it will be replaced. Parallelizes batch insertion
+ using a shared thread pool with a configurable thread count (default: 2)."
+ ([connectable index documents-reducible & {:keys [serial?] :or {serial? false}}]
+ (not-empty
+ (let [pool @index-update-executor
+ results (transduce
+ (comp (partition-all *batch-size*)
+ (map (if serial?
+ #(upsert-index-batch! connectable index %)
+ #(upsert-index-pooled! pool connectable index %))))
+ conj
+ documents-reducible)]
+ (reduce (fn [update-counts result]
+ (let [value (if (future? result) @result result)]
+ (merge-with + update-counts (when value value))))
+ {}
+ results)))))
+
+(defn- drop-index-table-sql
+ [{:keys [table-name]}]
+ (-> (sql.helpers/drop-table :if-exists (keyword table-name))
+ sql-format-quoted))
+
+(defn drop-index-table!
+ "Drops the index table for the given embedding model if it exists."
+ [connectable index]
+ (jdbc/execute! connectable (drop-index-table-sql index)))
+
+;; We can't use full column names in the various index names, because otherwise we overflow postgres' max name length.
+;; NOTE If you add a new index, add it to index-embedding-name-length-test as well
+(defn- index-name
+ "Returns the name for an index for the given index configuration, column, and index type."
+ [index suffix]
+ (let [result (str (:table-name index) suffix)]
+ (throw-if-max-pg-len result "Index name exceeds PostgreSQL limit")
+ result))
+
+(defn hnsw-index-name
+ "Returns the name for a HNSW database index for the given semantic search index configuration."
+ [index]
+ ;; embedding => embed
+ (index-name index "_embed_hnsw_idx"))
+
+(defn fts-index-name
+ "Returns the name for a full-text database index for the given semantic search index configuration."
+ [index]
+ ;; text_search_vector => tsv
+ (index-name index "_tsv_gin_idx"))
+
+(defn fts-native-index-name
+ "Returns the name for a full-text database index with native queries for the given semantic search index configuration."
+ [index]
+ ;; text_search_with_native_query_vector => tswnqv
+ (index-name index "_tswnqv_gin_idx"))
+
+(defn- content-index-name
+ "Returns the name for a B-tree database index on `content` for the given semantic search index configuration.
+ Used for efficient `content IN ..` queries."
+ [index]
+ (index-name index "_content_idx"))
+
+(defn create-index-table-if-not-exists!
+ "Ensure that the index table exists and is ready to be populated. If
+ force-reset? is true, drops and recreates the table if it exists."
+ [connectable index & {:keys [force-reset?] :or {force-reset? false}}]
+ (try
+ (let [{:keys [embedding-model table-name]} index
+ _ (assert (not (re-find #"\s" table-name))
+ (format "whitespace in the table name (%s) is not currently supported" table-name))
+ {:keys [vector-dimensions]} embedding-model]
+ (log/info "Creating index table" table-name)
+ (jdbc/execute! connectable (sql/format (sql.helpers/create-extension :vector :if-not-exists)))
+ (when force-reset? (drop-index-table! connectable index))
+ (jdbc/execute!
+ connectable
+ (-> (sql.helpers/create-table (keyword table-name) :if-not-exists)
+ (sql.helpers/with-columns (index-table-schema vector-dimensions))
+ sql-format-quoted))
+ (jdbc/execute!
+ connectable
+ (-> (sql.helpers/create-index
+ [(keyword (hnsw-index-name index)) :if-not-exists]
+ [(keyword table-name) :using-hnsw [[:raw "embedding vector_cosine_ops"]]])
+ sql-format-quoted))
+ (jdbc/execute!
+ connectable
+ (-> (sql.helpers/create-index
+ [(keyword (fts-index-name index)) :if-not-exists]
+ [(keyword table-name) :using-gin :text_search_vector])
+ sql-format-quoted))
+ (jdbc/execute!
+ connectable
+ (-> (sql.helpers/create-index
+ [(keyword (fts-native-index-name index)) :if-not-exists]
+ [(keyword table-name) :using-gin :text_search_with_native_query_vector])
+ sql-format-quoted))
+ (jdbc/execute!
+ connectable
+ (-> (sql.helpers/create-index
+ [(keyword (content-index-name index)) :if-not-exists]
+ [(keyword table-name) :content])
+ sql-format-quoted)))
+ (catch Exception e
+ (throw (ex-info "Failed to create index table" {} e)))))
+
+(comment
+ (def embedding-model {:provider "ollama"
+ :model-name "mxbai-embed-large"
+ :vector-dimensions 1024})
+ (def index (default-index embedding-model))
+ (drop-index-table! db index)
+ (create-index-table-if-not-exists! db index)
+ (jdbc/execute! db ["select table_name from INFORMATION_SCHEMA.tables where table_name like 'index_table_%'"]))
+
+(defn- search-filters
+ "Generate WHERE conditions based on search context filters."
+ [{:keys [archived? verified models created-at created-by last-edited-at last-edited-by table-db-id ids display-type]}]
+ (let [conditions (filter some?
+ [(when (some? archived?)
+ [:= :archived archived?])
+ (when (some? verified)
+ [:= :verified verified])
+ (when (seq models)
+ [:in :model models])
+ (when (seq created-by)
+ [:in :creator_id created-by])
+ (when (seq last-edited-by)
+ [:in :last_editor_id last-edited-by])
+ (when table-db-id
+ [:= :database_id table-db-id])
+ (when (seq ids)
+ [:in :model_id (map str ids)])
+ (when (seq display-type)
+ [:in :display_type display-type])
+ (when (and created-at (:start created-at) (:end created-at))
+ [:between :model_created_at
+ (LocalDate/parse (:start created-at))
+ (LocalDate/parse (:end created-at))])
+ (when (and last-edited-at (:start last-edited-at) (:end last-edited-at))
+ [:between :model_updated_at
+ (LocalDate/parse (:start last-edited-at))
+ (LocalDate/parse (:end last-edited-at))])])]
+ (when (seq conditions)
+ (into [:and] conditions))))
+
+(def ^:private common-search-columns
+ [[:id :id]
+ [:model :model]
+ [:model_id :model_id]
+ [:collection_id :collection_id]
+ [:creator_id :creator_id]
+ [:database_id :database_id]
+ [:last_editor_id :last_editor_id]
+ [:name :name]
+ [:content :content]
+ [:display_type :display_type]
+ [:archived :archived]
+ [:official_collection :official_collection]
+ [:pinned :pinned]
+ [:verified :verified]
+ [:dashboardcard_count :dashboardcard_count]
+ [:view_count :view_count]
+ [:model_created_at :model_created_at]
+ [:model_updated_at :model_updated_at]
+ [:last_viewed_at :last_viewed_at]
+ [:metadata :metadata]])
+
+(defn- keyword-search-query [index search-context]
+ (let [filters (search-filters search-context)
+ ts-search-expr (search/to-tsquery-expr (:search-string search-context))
+ tsv-lang (search/tsv-language)
+ vector-column (if (:search-native-query search-context)
+ :text_search_with_native_query_vector
+ :text_search_vector)]
+ {:select (into common-search-columns
+ [[[:raw (format "row_number() OVER (ORDER BY ts_rank_cd(%s, query) DESC)" (name vector-column))]
+ :keyword_rank]])
+ :from [(keyword (:table-name index))]
+ ;; Using a join allows us to share the query expression between our SELECT and WHERE clauses.
+ ;; This follows the same secure pattern as metabase.search.appdb.specialization.postgres/base-query
+ :join [[[:raw "to_tsquery('" tsv-lang "', " [:lift ts-search-expr] ")"]
+ :query] [:= 1 1]]
+ :where (let [ts-query-filter [:raw (format "%s @@ query" (name vector-column))]]
+ (if (seq filters)
+ (into [:and ts-query-filter] [filters])
+ ts-query-filter))
+ :order-by [[:keyword_rank :asc]]
+ :limit (semantic-settings/semantic-search-results-limit)}))
+
+(defn- semantic-search-query
+ "Build a semantic search query using vector similarity with post-filtering to enable HNSW index usage."
+ [index embedding search-context]
+ (let [filters (search-filters search-context)
+ embedding-literal (format-embedding embedding)
+ max-cosine-distance 0.7
+ ;; Inner query: pure vector search to better trigger HNSW index vs. seqscan
+ ;; TODO: only pull in necessary extra columns from configured filters
+ hnsw-query {:select (into common-search-columns
+ [[[:raw (str "embedding <=> " embedding-literal)] :distance]])
+ :from [(keyword (:table-name index))]
+ :order-by [[[:raw (str "embedding <=> " embedding-literal)] :asc]]
+ :limit (semantic-settings/semantic-search-results-limit)}
+ base-query {:with [[:vector_candidates hnsw-query]]
+ :select (into common-search-columns
+ [[[:raw "row_number() OVER (ORDER BY distance ASC)"] :semantic_rank]
+ [:distance :semantic_score]])
+ :from [:vector_candidates]
+ :where [:<= :distance max-cosine-distance]
+ :order-by [[:semantic_rank :asc]]}]
+ (if filters
+ (update base-query :where #(into [:and] [% filters]))
+ base-query)))
+
+(defn- hybrid-search-query
+ "Build a hybrid search query using vector + keyword based searches and reranking with RRF"
+ [index embedding search-context]
+ (let [semantic-results (semantic-search-query index embedding search-context)
+ keyword-results (keyword-search-query index search-context)
+ full-query {:with [[:vector_results semantic-results]
+ [:text_results keyword-results]]
+ :select [[[:coalesce :v.id :t.id] :id]
+ [[:coalesce :v.model_id :t.model_id] :model_id]
+ [[:coalesce :v.model :t.model] :model]
+ [[:coalesce :v.content :t.content] :content]
+ [[:coalesce :v.verified :t.verified] :verified]
+ [[:coalesce :v.metadata :t.metadata] :metadata]
+ [[:coalesce :v.semantic_rank -1] :semantic_rank]
+ [[:coalesce :t.keyword_rank -1] :keyword_rank]]
+ :from [[:vector_results :v]]
+ :full-join [[:text_results :t] [:= :v.id :t.id]]
+ :limit (semantic-settings/semantic-search-results-limit)}]
+ full-query))
+
+(defn- legacy-input-with-score
+ "Fetches the legacy_input field from a result's metadata and attaches a score based on the
+ embedding distance."
+ [weights scorers row]
+ (-> (get-in row [:metadata :legacy_input])
+ (assoc
+ :score (:total_score row 1.0)
+ :all-scores (scoring/all-scores weights scorers row))))
+
+(defn- decode-metadata
+ "Decode `row`s `:metadata`."
+ [row]
+ (update row :metadata decode-pgobject))
+
+(defn- filter-can-read-indexed-entity
+ "Check permissions for indexed entities by resolving to their parent model / card"
+ [indexed-entity-docs]
+ (let [->model-index-id #(-> % :id search/indexed-entity-id->model-index-id)
+ model-index-ids (into #{} (map ->model-index-id indexed-entity-docs))
+ model-indexes (when (seq model-index-ids)
+ (t2/select :model/ModelIndex :id [:in model-index-ids]))
+ index-id->card (when (seq model-indexes)
+ (let [card-ids (map :model_id model-indexes)
+ cards (t2/select :model/Card :id [:in card-ids])
+ cards-by-id (u/index-by :id cards)]
+ (into {}
+ (map (fn [model-index]
+ [(:id model-index) (get cards-by-id (:model_id model-index))])
+ model-indexes))))]
+ (filterv (fn [doc]
+ (when-let [model-index-id (-> doc ->model-index-id)]
+ (when-let [parent-card (get index-id->card model-index-id)]
+ (mi/can-read? parent-card))))
+ indexed-entity-docs)))
+
+(defn- filter-read-permitted
+ "Returns only those documents in `docs` whose corresponding t2 instances pass an mi/can-read? check for the bound api user."
+ [docs]
+ (let [timer (u/start-timer)
+ doc->t2-model (fn [doc] (:model (search/spec (:model doc))))
+ {indexed-entities true regular-docs false} (group-by #(= "indexed-entity" (:model %)) docs)
+ other-docs (for [[t2-model docs] (group-by doc->t2-model regular-docs)
+ t2-instance (t2/select t2-model :id [:in (map :id docs)])]
+ t2-instance)
+ permitted-entities (filter-can-read-indexed-entity indexed-entities)
+ doc->t2 (comp (u/index-by (juxt :id t2/model) other-docs)
+ (juxt :id doc->t2-model))
+ result (into
+ (filterv (fn [doc] (some-> doc doc->t2 mi/can-read?)) regular-docs)
+ permitted-entities)
+ time-ms (u/since-ms timer)]
+
+ (log/debug "Permission filtering" {:before-count (count docs)
+ :after-count (count result)
+ :indexed-entities-count (count indexed-entities)
+ :regular-docs-count (count regular-docs)
+ :time-ms time-ms})
+
+ (analytics/inc! :metabase-search/permission-filtering-ms time-ms)
+
+ result))
+
+(defn- get-personal-collection-ids
+ "Get the set of personal collection IDs by extracting root collection IDs from locations."
+ [collections-map]
+ (let [root-collection-ids (->> collections-map
+ vals
+ (map :location)
+ (keep (fn [location]
+ (when-let [match (re-find #"^/(\d+)/" location)]
+ (parse-long (second match)))))
+ distinct)]
+ (when (seq root-collection-ids)
+ (->> (t2/select [:collection :id]
+ :id [:in root-collection-ids]
+ :personal_owner_id [:not= nil])
+ (map :id)
+ set))))
+
+(defn- filter-by-collection
+ "Filter documents based on personal collection preferences.
+ Equivalent to metabase.search.filter/personal-collections-where-clause but operates on docs in memory.
+
+ | Filter | Personal | Others' Personal | Shared Coll. | No Coll. |
+ |----------------|----------|------------------|--------------|----------|
+ | all | ✅ | ✅ | ✅ | ✅ |
+ | only-mine | ✅ | ❌ | ❌ | ❌ |
+ | only | ✅ | ✅ | ❌ | ❌ |
+ | exclude | ❌ | ❌ | ✅ | ✅ |
+ | exclude-others | ✅ | ❌ | ✅ | ✅ |
+ "
+ [docs {:keys [filter-items-in-personal-collection current-user-id]}]
+ (let [filter-type (or filter-items-in-personal-collection "all")]
+ (if (= filter-type "all")
+ docs
+ (let [collection-ids (keep :collection_id docs)
+ collections-map (when (seq collection-ids)
+ (->> (t2/select [:collection :id :location :personal_owner_id]
+ :id [:in collection-ids])
+ (into {} (map (juxt :id identity)))))
+ personal-collection-ids (when (not= filter-type "only-mine")
+ (get-personal-collection-ids collections-map))
+ user-personal-collection-id (t2/select-one-pk :model/Collection :personal_owner_id [:= current-user-id])
+ is-personal-collection? (fn [coll] (some? (:personal_owner_id coll)))
+ is-owned-by-user? (fn [coll] (= (:personal_owner_id coll) current-user-id))
+ is-in-user-personal-tree? (fn [coll] (str/starts-with? (:location coll) (str "/" user-personal-collection-id "/")))
+ is-in-any-personal-tree? (fn [coll]
+ (when-let [match (re-find #"^/(\d+)/" (:location coll))]
+ (contains? personal-collection-ids (parse-long (second match)))))]
+ (case filter-type
+ "only-mine"
+ (filterv (fn [doc]
+ (when-let [collection (get collections-map (:collection_id doc))]
+ (or (is-owned-by-user? collection)
+ (is-in-user-personal-tree? collection))))
+ docs)
+
+ "only"
+ (filterv (fn [doc]
+ (when-let [collection (get collections-map (:collection_id doc))]
+ (or (is-personal-collection? collection)
+ (is-in-any-personal-tree? collection))))
+ docs)
+
+ "exclude"
+ (filterv (fn [doc]
+ (let [collection-id (:collection_id doc)]
+ (or (nil? collection-id)
+ (when-let [collection (get collections-map collection-id)]
+ (and (not (is-personal-collection? collection))
+ (not (is-in-any-personal-tree? collection)))))))
+ docs)
+
+ "exclude-others"
+ (filterv (fn [doc]
+ (let [collection-id (:collection_id doc)]
+ (or (nil? collection-id)
+ (when-let [collection (get collections-map collection-id)]
+ (or (is-owned-by-user? collection)
+ (is-in-user-personal-tree? collection)
+ (and (not (is-personal-collection? collection))
+ (not (is-in-any-personal-tree? collection))))))))
+ docs)
+
+ docs)))))
+
+(defn- apply-collection-filter
+ "Apply personal collection filtering with logging."
+ [search-context docs]
+ (let [filter-type (:filter-items-in-personal-collection search-context)]
+ (if (or (nil? filter-type) (= filter-type "all"))
+ docs
+ (let [timer (u/start-timer)
+ filtered-docs (filter-by-collection docs search-context)]
+ (log/debug "Collection filter" {:filter filter-type
+ :before (count docs)
+ :after (count filtered-docs)
+ :dropped (- (count docs) (count filtered-docs))
+ :time_ms (u/since-ms timer)})
+ filtered-docs))))
+
+(defn query-index
+ "Query the index for documents similar to the search string.
+ Returns a map with :results and :raw-count."
+ [db index search-context]
+ (let [{:keys [embedding-model]} index
+ search-string (:search-string search-context)]
+ (if (str/blank? search-string)
+ {:results [] :raw-count 0}
+ (let [timer (u/start-timer)
+
+ embedding (embedding/get-embedding embedding-model search-string)
+ embedding-time-ms (u/since-ms timer)
+
+ db-timer (u/start-timer)
+ weights (search.config/weights (:context search-context))
+ scorers (scoring/semantic-scorers search-context)
+ query (->> (hybrid-search-query index embedding search-context)
+ (scoring/with-scores search-context scorers))
+ xform (comp (map decode-metadata)
+ (map (partial legacy-input-with-score weights (keys scorers))))
+ reducible (jdbc/plan db (sql-format-quoted query) {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ raw-results (into [] xform reducible)
+ db-query-time-ms (u/since-ms db-timer)
+
+ filtered-results (->> raw-results
+ filter-read-permitted
+ (apply-collection-filter search-context)
+ (mapv search/collapse-id))
+
+ total-time-ms (u/since-ms timer)]
+
+ (log/debug "Semantic search"
+ {:search-string-length (count search-string)
+ :embedding-time-ms embedding-time-ms
+ :db-query-time-ms db-query-time-ms
+ :raw-results-count (count raw-results)
+ :final-results-count (count filtered-results)
+ :total-time-ms total-time-ms})
+
+ (analytics/inc! :metabase-search/semantic-search-ms
+ {:embedding-model (:name embedding-model)}
+ total-time-ms)
+ (analytics/inc! :metabase-search/semantic-embedding-ms
+ {:embedding-model (:name embedding-model)}
+ embedding-time-ms)
+ (analytics/inc! :metabase-search/semantic-db-query-ms
+ {:embedding-model (:name embedding-model)}
+ db-query-time-ms)
+
+ (comment
+ (jdbc/execute! db (sql-format-quoted query)))
+
+ {:results filtered-results
+ :raw-count (count raw-results)}))))
+
+(comment
+ (def embedding-model (embedding/get-configured-model))
+ (def index (default-index embedding-model))
+ (def search-ctx {:search-string "pasta"})
+ (def embed (embedding/get-embedding embedding-model (:search-string search-ctx)))
+
+ (keyword-search-query index search-ctx)
+ (sql-format-quoted (keyword-search-query index search-ctx))
+ (jdbc/execute! db (sql-format-quoted (keyword-search-query index search-ctx)))
+
+ (semantic-search-query index embed search-ctx)
+ (sql/format (semantic-search-query index embed search-ctx))
+ (jdbc/execute! db (sql-format-quoted (semantic-search-query index embed search-ctx)))
+
+ (hybrid-search-query index embed search-ctx)
+ (sql-format-quoted (hybrid-search-query index embed search-ctx))
+ (jdbc/execute! db (sql-format-quoted (hybrid-search-query index embed search-ctx)))
+
+ (query-index db index search-ctx))
+
+(defn- delete-from-index-batch-sql
+ [model table-name batch-ids]
+ (when (seq batch-ids)
+ (-> (sql.helpers/delete-from table-name)
+ (sql.helpers/where [:and
+ [:= :model model]
+ [:in :model_id (map str batch-ids)]])
+ sql-format-quoted)))
+
+(defn delete-from-index!
+ "Deletes documents from the index table based on model and model_ids."
+ [db index model model-ids]
+ (batch-delete-ids!
+ db
+ (:table-name index)
+ model
+ (partial delete-from-index-batch-sql model (keyword (:table-name index)))
+ model-ids))
+
+(comment
+ (def pgvector ((requiring-resolve 'metabase-enterprise.semantic-search.env/get-pgvector-datasource!)))
+ (def embedding-model (embedding/get-configured-model))
+ (def index (default-index embedding-model))
+ (create-index-table-if-not-exists! pgvector index {:force-reset? true})
+ (upsert-index! db index [{:model "card"
+ :id "1"
+ :searchable_text "This is a test card"}])
+ (delete-from-index! db index "card" ["1"])
+ (delete-from-index! db index "dashboard" ["13"])
+ ;; no user
+ (query-index db index {:search-string "Copper knife"})
+
+ #_:clj-kondo/ignore
+ (require '[metabase.test :as mt])
+ (mt/with-test-user :crowberto
+ (doall (query-index db index {:search-string "Copper knife"}))))
+
+(comment
+ ;; Query performance analysis with EXPLAIN ANALYZE
+ ;; Run this to debug query performance and execution plans
+ (defn explain-analyze-query
+ [db sql-with-params]
+ (let [[sql & params] sql-with-params
+ explain-sql (str "EXPLAIN (ANALYZE true, BUFFERS true, FORMAT text) " sql)]
+ (jdbc/execute! db (into [explain-sql] params))))
+
+ ((requiring-resolve 'metabase-enterprise.semantic-search.db.datasource/init-db!))
+ (def db @@(requiring-resolve 'metabase-enterprise.semantic-search.db.datasource/data-source))
+ (jdbc/execute! db ["SHOW random_page_cost;"]) ; makes index scans appear cheaper
+ (jdbc/execute! db ["SHOW seq_page_cost;"]) ; default 1
+ (jdbc/execute! db ["SHOW hnsw.ef_search;"])
+ (jdbc/execute! db ["SET random_page_cost = 1.0;"]) ; Default 4, should set to seq_page_cost (default 1)
+ (jdbc/execute! db ["SET enable_seqscan = ON;"]) ; ON|OFF - Disable seq scan to force index scan
+
+ (def embedding-model (embedding/get-configured-model))
+ (def index (default-index embedding-model))
+ (def search-string "product orders")
+ (def search-context {:search-string search-string
+ :models ["card" "dashboard"]
+ :archived? false
+ :verified nil})
+ (def search-context {:search-string search-string})
+
+ (def embedding (embedding/get-embedding (:embedding-model index) search-string))
+
+ ;; Format queries for execution
+ (def semantic-sql (sql-format-quoted (semantic-search-query index embedding search-context)))
+ (def keyword-sql (sql-format-quoted (keyword-search-query index search-context)))
+ (def hybrid-sql (sql-format-quoted (hybrid-search-query index embedding search-context)))
+
+ ;; do in repl ->
+ #_(explain-analyze-query db semantic-sql)
+ #_(explain-analyze-query db keyword-sql)
+ #_(explain-analyze-query db hybrid-sql)
+
+ (def existing-sql (sql-format-quoted (existing-embedding-query index ["Some Text"])))
+ #_(explain-analyze-query db existing-sql)
+
+ ;; Code to test the custom thread pool. The transduction should process batches in parallel and new batches should
+ ;; only be realized in memory once a thread is available.
+ (defn process-batch [batch]
+ #_:clj-kondo/ignore
+ (println "Processing batch starting with " (first batch))
+ (Thread/sleep 2000)
+ {:count (count batch)})
+
+ (defn logging-range [n]
+ #_:clj-kondo/ignore
+ (map #(do (println "Realizing item" %) %)
+ (range n)))
+
+ (defn reducible [n]
+ (u/rconcat (logging-range n) []))
+
+ (let [pool @index-update-executor
+ futures
+ (transduce
+ (comp
+ (partition-all 10)
+ (map #(cp/future pool (process-batch %))))
+ conj
+ (reducible 100))]
+ (reduce (fn [acc fut]
+ (merge-with + acc @fut))
+ {}
+ futures)))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
new file mode 100644
index 00000000000..b13ba2206f9
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
@@ -0,0 +1,344 @@
+(ns metabase-enterprise.semantic-search.index-metadata
+ "Multi-index management for pgvector semantic search.
+
+ Tracks multiple embedding model indexes through metadata tables, supporting model switching
+ without data loss. Each embedding model (provider/name/dimensions) gets its own index table,
+ with a control table managing which index is currently active."
+ (:require
+ [honey.sql :as sql]
+ [honey.sql.helpers :as sql.helpers]
+ ;; TODO: extract schema code to go under db.migration
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase.util :as u]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs]))
+
+;; metadata and control tables allow multiple indexes to coexist
+;; while maintaining a single active pointer.
+;; This enables model switching without data loss - old indexes remain available and can still be targeted with index functions.
+;; Garbage / pending / switchover policy beyond 'one is active' TBD, right now we want the active index to reflect the global
+;; embedding configuration in metabase settings / envars.
+(def ^:private schema-0
+ "The version 0 schema for an index metadata system. This acts as a 'root' for indexes, and assumes a single set of documents
+ that will be indexed into multiple indexes (for different embedding models and so on)."
+ {:metadata
+ [[:id :bigint [:primary-key] [:raw "GENERATED BY DEFAULT AS IDENTITY"]]
+ [:provider :text :not-null]
+ [:model_name :text :not-null]
+ [:vector_dimensions :int :not-null]
+ [:table_name :text :not-null :unique]
+ [:index_version :int :not-null]
+ [:index_created_at :timestamp-with-time-zone :not-null]
+ [:indexer_last_poll :timestamp-with-time-zone :null]
+ [:indexer_last_seen :timestamp-with-time-zone :null]
+ [:indexer_last_seen_id :text :null]
+ [:indexer_last_seen_hash :text :null]]
+
+ :control
+ [[:id :bigint [:primary-key]] ;; not auto-inc, only one row - still useful to ensure only one row when inserting.
+ [:version :text :not-null]
+ [:active_id :int :null]
+ [:active_updated_at :timestamp-with-time-zone :null]]
+
+ :gate
+ [[:id :text :not-null :primary-key]
+ [:model :text :not-null]
+ [:model_id :text :not-null]
+ [:updated_at :timestamp-with-time-zone :not-null]
+ [:gated_at :timestamp-with-time-zone :not-null :default [:clock_timestamp]]
+ ;; null signals a delete
+ [:document :jsonb :null]
+ ;; assumes some text encoding. 'TEXT' is just so convenient to get that sweet equality.
+ ;; the actual hash encoding is pretty much irrelevant as long as nodes agree on it most of the time.
+ ;; even if they do not, as a redundancy filtering optimisation - nothing too bad happens.
+ [:document_hash :text :null]]})
+
+(defn qualify-index
+ "Qualifies an index-map, returning a new index-map that might have additional disambiguating prefixes applied
+ to table names.
+
+ This ensures tables/constraints created as part of operating a meta index can be isolated within
+ the same database."
+ [index index-metadata]
+ ;; if created databases for namespacing in tests we could probably remove this whole idea.
+ (let [{:keys [index-table-qualifier]} index-metadata
+ qualify (partial format index-table-qualifier)]
+ (-> index
+ (update :table-name qualify))))
+
+(def default-index-metadata
+ "The default index metadata configuration that will be used for the search engine integration."
+ {:version "1"
+ :metadata-table-name "index_metadata"
+ :control-table-name "index_control"
+ :gate-table-name "index_gate"
+ :index-table-qualifier "%s"})
+
+(defn- create-index-metadata-table-if-not-exists-sql [index-metadata]
+ (let [{:keys [metadata-table-name]} index-metadata
+ schema (:metadata schema-0)]
+ (-> (sql.helpers/create-table (keyword metadata-table-name) :if-not-exists)
+ (sql.helpers/with-columns schema)
+ (sql/format :quoted true))))
+
+(defn- create-control-table-if-not-exists-sql [index-metadata]
+ (let [{:keys [control-table-name]} index-metadata
+ schema (:control schema-0)]
+ (-> (sql.helpers/create-table (keyword control-table-name) :if-not-exists)
+ (sql.helpers/with-columns schema)
+ (sql/format :quoted true))))
+
+(defn- create-gate-table-if-not-exists-sql [index-metadata]
+ (let [{:keys [gate-table-name]} index-metadata
+ schema (:gate schema-0)]
+ (-> (sql.helpers/create-table (keyword gate-table-name) :if-not-exists)
+ (sql.helpers/with-columns schema)
+ (sql/format :quoted true))))
+
+(comment
+ (create-index-metadata-table-if-not-exists-sql default-index-metadata)
+ (create-control-table-if-not-exists-sql default-index-metadata)
+ (create-gate-table-if-not-exists-sql default-index-metadata))
+
+(defn ensure-control-row-exists!
+ "Ensures the singleton control row exists in the control table.
+ Idempotent - uses ON CONFLICT DO NOTHING to avoid duplicate key errors."
+ [pgvector index-metadata]
+ (let [{:keys [control-table-name version]} index-metadata]
+ (jdbc/execute!
+ pgvector
+ (-> (sql.helpers/insert-into (keyword control-table-name))
+ ;; Control table uses hardcoded id=0 to enforce a singleton row.
+ ;; This ensures exactly one control row exists, simplifying active index lookups
+ ;; and avoiding race conditions when multiple nodes initialize simultaneously.
+ (sql.helpers/values [{:id 0
+ :version version
+ :active_id nil
+ :active_updated_at nil}])
+ (sql.helpers/on-conflict :id)
+ (sql.helpers/do-nothing)
+ (sql/format :quoted true)))
+ nil))
+
+(defn create-tables-if-not-exists!
+ "Creates the metadata and control tables if they do not already exist"
+ [pgvector index-metadata]
+ (let [{:keys [metadata-table-name control-table-name gate-table-name version]} index-metadata]
+ ;; **note** we do not currently deal with version mismatches as there is only one version.
+ ;; metadata
+ (log/infof "Creating metadata table if not exists %s (%s)" metadata-table-name version)
+ (jdbc/execute!
+ pgvector
+ (create-index-metadata-table-if-not-exists-sql index-metadata))
+ ;; control
+ (log/infof "Creating control table if not exists %s (%s)" control-table-name version)
+ (jdbc/execute!
+ pgvector
+ (create-control-table-if-not-exists-sql index-metadata))
+ ;; gate
+ (log/infof "Creating gate table if not exists %s (%s)" gate-table-name version)
+ (jdbc/execute!
+ pgvector
+ (create-gate-table-if-not-exists-sql index-metadata))
+ (log/info "Creating gate table gated_at index if not exists")
+ (jdbc/execute!
+ pgvector
+ (sql/format
+ (sql.helpers/create-index
+ [(keyword (str (:gate-table-name index-metadata) "_gated_at")) :if-not-exists]
+ [(keyword (:gate-table-name index-metadata)) :gated_at :id])
+ :quoted true))
+ nil))
+
+(defn drop-tables-if-exists!
+ "Drops both metadata and control tables if they exist.
+ Used for cleanup in tests and development - destructive operation."
+ [pgvector index-metadata]
+ ;; we could move this to test.util as it is currently redundant in prod. I like it being here for locality and later
+ ;; we will probably use it trigger 'start fresh', even on deployed nodes.
+ (let [{:keys [metadata-table-name
+ control-table-name
+ gate-table-name]}
+ index-metadata]
+ (jdbc/execute!
+ pgvector
+ (-> (sql.helpers/drop-table :if-exists (keyword metadata-table-name))
+ (sql/format :quoted true)))
+ (jdbc/execute!
+ pgvector
+ (-> (sql.helpers/drop-table :if-exists (keyword control-table-name))
+ (sql/format :quoted true)))
+ (jdbc/execute!
+ pgvector
+ (-> (sql.helpers/drop-table :if-exists (keyword gate-table-name))
+ (sql/format :quoted true)))
+ nil))
+
+(defn- row->index [{:keys [provider
+ model_name
+ vector_dimensions
+ table_name
+ index_version]}]
+ {:embedding-model {:provider provider
+ :model-name model_name
+ :vector-dimensions vector_dimensions}
+ :table-name table_name
+ :version index_version})
+
+(defn- table-exists? [pgvector table-name]
+ (-> (jdbc/execute-one! pgvector
+ ["SELECT exists (select 1 FROM information_schema.tables WHERE table_name = ?) table_exists"
+ table-name]
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ (:table_exists false)))
+
+(defn- index-table-exists? [pgvector index]
+ (table-exists? pgvector (:table-name index)))
+
+(defn- control-and-metadata-tables-exist?
+ [pgvector index-metadata]
+ (and (table-exists? pgvector (:metadata-table-name index-metadata))
+ (table-exists? pgvector (:control-table-name index-metadata))))
+
+(defn get-active-index-state
+ "Returns the currently active index configuration, or nil if none active.
+
+ Expect a map with:
+ - :index
+ The indexes parameters, table-name, model etc, that you can use with functions taking `index` in the semantic search package)
+ - :metadata-row
+ The metadata record for this index, as returned by next.jdbc. Keys are unqualified."
+ [pgvector index-metadata]
+ (when (control-and-metadata-tables-exist? pgvector index-metadata)
+ (let [{:keys [metadata-table-name
+ control-table-name]}
+ index-metadata
+ ;; Returns nil if no active index is set (active_id is null).
+ active-row-sql (-> {:select [:m.*]
+ :from [[(keyword control-table-name) :c]]
+ :join [[(keyword metadata-table-name) :m] [:= :m.id :c.active_id]]}
+ (sql/format :quoted true))
+ active-row (jdbc/execute-one! pgvector active-row-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})]
+ (when active-row
+ {:index (row->index active-row)
+ :metadata-row active-row}))))
+
+(defn activate-index!
+ "Sets the specified index as active by updating the control table. The index-id is the `id` column value for
+ the indexes metadata row."
+ [pgvector index-metadata index-id]
+ (assert index-id)
+ (assert (nat-int? index-id) (format "expected an integer id (hint do not pass the index map!)"))
+ (let [{:keys [control-table-name]} index-metadata
+ ;; only one row, no traditional WHERE for now
+ activation-sql (-> {:update (keyword control-table-name)
+ :set {:active_id index-id
+ :active_updated_at [:now]}}
+ (sql/format :quoted true))]
+ (jdbc/execute! pgvector activation-sql)
+ nil))
+
+(defn find-best-index!
+ "Locates the optimal index to be used for the given embedding model.
+
+ Returns information that helps you decide what to do next in order to start using the index.
+
+ Returns map with
+ - :index the index parameters, table name, version etc.
+ - :metadata-row the unqualified next.jdbc row, nil if it is a new index or if the metadata row has somehow been deleted
+ - :index-table-exists whether the table named by the `:index` actually exists in the database"
+ [pgvector index-metadata embedding-model]
+ (let [{:keys [metadata-table-name
+ control-table-name]}
+ index-metadata
+
+ {:keys [provider
+ model-name
+ vector-dimensions]}
+ embedding-model
+
+ model-rows-sql (-> {:select [:m.* [[:coalesce [:= :c.active_id :m.id] false] :is_active]]
+ :from [[(keyword control-table-name) :c]
+ [(keyword metadata-table-name) :m]]
+ :where [:and
+ [:= :provider provider]
+ [:= :model_name model-name]
+ [:= :vector_dimensions vector-dimensions]]}
+ (sql/format :quoted true))
+ model-rows (jdbc/execute! pgvector model-rows-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+
+ {[active] true
+ inactive false}
+ (u/group-by :is_active #(dissoc % :is_active) model-rows)]
+ ;; Priority order: active matching index > inactive matching index > new
+ ;; This preserves existing data when possible and avoids unnecessary index creation.
+ (cond
+ ;; already active index matching model, return it.
+ active
+ (let [index (row->index active)]
+ {:index index
+ :index-table-exists (index-table-exists? pgvector index)
+ :metadata-row active
+ :active true})
+
+ ;; has an inactive index
+ (seq inactive)
+ (let [best-index-row (first inactive) ; 'best' is undefined right now, not sure if it matters
+ best-index (row->index best-index-row)]
+ {:index best-index
+ :index-table-exists (index-table-exists? pgvector best-index)
+ :metadata-row best-index-row
+ :active false})
+
+ ;; new or untracked index
+ :else
+ (let [index (qualify-index (semantic.index/default-index embedding-model) index-metadata)]
+ {:index index
+ :index-table-exists (index-table-exists? pgvector index)
+ :active false}))))
+
+(defn record-new-index-table!
+ "Records an index in the metadata table and returns its assigned ID.
+ The indexes :table-name must be unique, or you will receive a constraint violation."
+ [pgvector index-metadata index]
+ (let [{:keys [metadata-table-name]}
+ index-metadata
+
+ {index-table-name :table-name
+ index-version :version
+ :keys [embedding-model]}
+ index
+
+ {:keys [provider
+ model-name
+ vector-dimensions]}
+ embedding-model
+
+ insert-sql (-> (sql.helpers/insert-into (keyword metadata-table-name))
+ (sql.helpers/values [{:provider provider
+ :model_name model-name
+ :vector_dimensions vector-dimensions
+ :table_name index-table-name
+ :index_version index-version
+ :index_created_at [:now]}])
+ (sql.helpers/returning :id)
+ (sql/format :quoted true))
+ {:keys [id]} (jdbc/execute-one! pgvector insert-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})]
+ id))
+
+(comment
+ (def pgvector ((requiring-resolve 'metabase-enterprise.semantic-search.env/get-pgvector-datasource!)))
+ (def index-metadata ((requiring-resolve 'metabase-enterprise.semantic-search.env/get-index-metadata)))
+ (def embedding-model ((requiring-resolve 'metabase-enterprise.semantic-search.env/get-configured-embedding-model)))
+ (create-tables-if-not-exists! pgvector index-metadata)
+ (ensure-control-row-exists! pgvector index-metadata)
+ (drop-tables-if-exists! pgvector index-metadata)
+ (get-active-index-state pgvector index-metadata)
+ (-> (get-active-index-state pgvector index-metadata)
+ :metadata-row
+ :indexer_last_poll
+ class)
+ (find-best-index! pgvector index-metadata embedding-model)
+ (record-new-index-table! pgvector index-metadata (:index (find-best-index! pgvector index-metadata embedding-model)))
+ (activate-index! pgvector index-metadata (:id (:metadata-row (find-best-index! pgvector index-metadata embedding-model)))))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/indexer.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/indexer.clj
new file mode 100644
index 00000000000..69ded2afe3c
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/indexer.clj
@@ -0,0 +1,216 @@
+(ns metabase-enterprise.semantic-search.indexer
+ "Companion to the gate lib defining an indexing loop to be invoked as a singleton Quartz job.
+
+ - A (cluster singleton) interruptible quartz job should invoke (quartz-job-run!) (see task/indexer.clj).
+ - The job will poll the gate table in a loop and index anything new it finds (inserts, updates & deletes)
+ - Saves watermark state back to index metadata for each batch of documents indexed
+ (if interrupted / crashes / process dies, polling can continue from its watermark position).
+ - The job can run the indexing-loop for a time, eventually yielding back to quartz
+ - we do not poll once per job invocation, indexing-loop can poll and index data many, many times before yielding.
+ - it will exit if it has run for default-max-run-duration
+ - it will exit if it has not seen any new data in default-exit-early-cold-duration
+ - it will exit if it is interrupted (e.g. node shutdown)
+ - Polling behaviour respects the limitations of gate.clj (there is a 2x gate-write-timeout lag tolerance)
+ - if there is a lot of new write activity you might see the indexer stall for a short time
+ to wait for commit-races to become very unlikely.
+ - when reindexing cold gate entries the loop is free to index using straightforward key-set pagination, no stalls.
+ - Any kind of exception will immediately exit the loop (quartz is free to reschedule)."
+ (:require
+ [honey.sql :as sql]
+ [metabase-enterprise.semantic-search.gate :as semantic.gate]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import (java.time Duration Instant)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private poll-limit 1000)
+
+(def ^:private lag-tolerance (.multipliedBy semantic.gate/gate-write-timeout 2))
+
+(defn indexing-step
+ "Runs a single blocking step of the indexing loop."
+ [pgvector index-metadata index indexing-state]
+ (letfn [(poll []
+ (let [{:keys [watermark]} @indexing-state]
+ (semantic.gate/poll pgvector index-metadata watermark
+ :limit poll-limit
+ :lag-tolerance lag-tolerance)))
+ ;; when polling within the lag-tolerance window we need to expect
+ ;; to see the same gate entries when polling.
+ ;; We keep a :last-seen-candidates set so if we saw them last time we can filter them out
+ (remove-redundant-candidates [update-candidates]
+ (let [{:keys [last-seen-candidates]} @indexing-state]
+ (not-empty (if (seq last-seen-candidates)
+ (into [] (remove last-seen-candidates) update-candidates)
+ update-candidates))))
+
+ ;; currently we expect to flush the watermark each time we poll
+ (move-to-next-watermark [poll-result]
+ (let [{:keys [watermark]} @indexing-state
+ next-watermark (semantic.gate/next-watermark watermark poll-result)]
+ (vswap! indexing-state assoc :watermark next-watermark)
+ (semantic.gate/flush-watermark! pgvector index-metadata index next-watermark)))]
+ (let [{:keys [update-candidates] :as poll-result} (poll)]
+ (if-some [novel-candidates (remove-redundant-candidates update-candidates)]
+ (let [documents-query {:select [:model :model_id :document]
+ :from [(keyword (:gate-table-name index-metadata))]
+ :where [:in :id (sort (map :id novel-candidates))]}
+ documents-sql (sql/format documents-query :quoted true)
+ gate-docs (jdbc/execute! pgvector documents-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ updates (filter :document gate-docs)
+ deletes (remove :document gate-docs)
+ updated-documents (map semantic.gate/gate-doc->search-doc updates)]
+ (log/infof "Found gate updates: %d updates, %d deletes" (count updates) (count deletes))
+ (when (seq updated-documents)
+ (semantic.index/upsert-index! pgvector index updated-documents))
+ (doseq [[model deletes] (group-by :model deletes)]
+ (semantic.index/delete-from-index! pgvector index model (map :model_id deletes)))
+ (vswap! indexing-state assoc
+ :last-seen-change (Instant/now)
+ :last-indexed-count (count novel-candidates)
+ :last-poll-count (count update-candidates))
+ (move-to-next-watermark poll-result))
+ (do
+ (vswap! indexing-state assoc
+ :last-indexed-count 0
+ :last-poll-count (count update-candidates))
+ (move-to-next-watermark poll-result)))
+
+ ;; we use this to filter redundant entries from the last poll (duplicate delivery is expected and intended when
+ ;; at the tail of the gate index).
+ (vswap! indexing-state assoc :last-seen-candidates (set update-candidates)))))
+
+;; having a var is handy for tests
+(defn- sleep [ms]
+ (Thread/sleep (long ms)))
+
+(defn on-indexing-idle
+ "Runs any loop idle behaviour (such as waiting), called after each step."
+ [indexing-state]
+ (let [{:keys [last-poll-count last-indexed-count]} @indexing-state
+ novelty-ratio (if (zero? last-poll-count) 0 (/ last-indexed-count last-poll-count))]
+ (cond
+ ;; more than 25% the results are new, immediately get more
+ (< 0.25 novelty-ratio)
+ nil
+
+ ;; more than 10% the results are new, small backoff.
+ (< 0.1 novelty-ratio)
+ (sleep 250)
+
+ ;; more than 1% the results are new, medium backoff.
+ (< 0.01 novelty-ratio)
+ (sleep 1500)
+
+ ;; not a lot of new stuff, big back off.
+ :else
+ (sleep 3000))))
+
+(defn- on-indexing-interrupted []
+ (log/info "Indexing loop interrupted, exited gracefully"))
+
+(defn- max-run-time-elapsed?
+ "Returns true if :max-run-duration has been exceeded. We should yield back to quartz, to give other nodes a shot."
+ [{:keys [^Instant start-time
+ ^Duration max-run-duration]}
+ ^Instant now]
+ (and start-time (.isAfter now (.plus start-time max-run-duration))))
+
+(defn- exit-early-due-to-cold-data?
+ "Returns true if :exit-early-cold-duration has elapsed since we last saw any change.
+ We should yield back to quartz and release resources until rescheduled."
+ [{:keys [^Instant start-time
+ ^Instant last-seen-change
+ ^Duration exit-early-cold-duration]}
+ ^Instant now]
+ (and start-time
+ last-seen-change
+ (.isAfter now (.plus last-seen-change exit-early-cold-duration))))
+
+(defn indexing-loop
+ "Runs the indexing loop on the current thread, blocks until exit or interrupted.
+ See (max-run-time-elapsed?) and (exit-early-due-to-cold-data?) for automatic
+ exit conditions."
+ [pgvector
+ index-metadata
+ index
+ indexing-state]
+ (vswap! indexing-state assoc :start-time (Instant/now))
+ (loop []
+ (cond
+ (.isInterrupted (Thread/currentThread))
+ (on-indexing-interrupted)
+
+ (max-run-time-elapsed? @indexing-state (Instant/now))
+ (log/debug "Indexer run time elapsed. Indexer exiting, quartz will reschedule.")
+
+ (exit-early-due-to-cold-data? @indexing-state (Instant/now))
+ (log/debug "Indexer not seen any recent change, Indexer exiting, quartz will reschedule.")
+
+ :else
+ (let [interrupted (or (try
+ (indexing-step pgvector index-metadata index indexing-state)
+ false
+ (catch InterruptedException _
+ (log/info "Indexing thread interrupted while processing")
+ true))
+ (try
+ (on-indexing-idle indexing-state)
+ false
+ (catch InterruptedException _
+ (log/info "Indexing thread interrupted while idling")
+ true)))]
+ (if interrupted
+ (on-indexing-interrupted)
+ (recur))))))
+
+(def default-max-run-duration
+ "The default amount of time we expect to run the loop for before yielding to quartz."
+ (Duration/ofMinutes 60))
+
+(def default-exit-early-cold-duration
+ "The default time we should wait to see new data before yielding back to quartz."
+ (Duration/ofSeconds 30))
+
+(defn init-indexing-state
+ "Initialises the indexing state variable, contains the watermark position, statistics on
+ what has been seen, and parameters for policy such as the :max-run-duration."
+ [metadata-row]
+ (let [watermark (semantic.gate/resume-watermark metadata-row)
+ {:keys [last-seen]} watermark]
+ (volatile! {:watermark watermark
+ ;; The last-seen-candidates filters the expected redundant entries when
+ ;; polling beyond the confidence threshold. It is overwritten each time we poll.
+ ;; Seeding this value with the watermark solves a problem where the very last document
+ ;; will be re-indexed every time the indexer is rescheduled
+ :last-seen-candidates (if last-seen #{last-seen} #{})
+ :last-indexed-count 0
+ :last-poll-count 0
+ :max-run-duration default-max-run-duration
+ :exit-early-cold-duration default-exit-early-cold-duration})))
+
+(defn quartz-job-run!
+ "Quartz job (execute) implementation. Determines the active index before running
+ a (indexing-loop) with the default parameters.
+
+ Blocks until exit or interrupt if an active index exists."
+ [pgvector
+ index-metadata]
+ (let [{:keys [index metadata-row]} (semantic.index-metadata/get-active-index-state pgvector index-metadata)]
+ (when-not index (log/debug "No active semantic search index"))
+ (when index
+ (let [indexing-state (init-indexing-state metadata-row)]
+ (try
+ (indexing-loop
+ pgvector
+ index-metadata
+ index
+ indexing-state)
+ (catch InterruptedException ie (throw ie))
+ (catch Throwable t
+ (log/error t "An exception was caught during the indexing loop")
+ (throw t)))))))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/init.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/init.clj
new file mode 100644
index 00000000000..8ee268413c0
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/init.clj
@@ -0,0 +1,4 @@
+(ns metabase-enterprise.semantic-search.init
+ (:require
+ [metabase-enterprise.semantic-search.settings]
+ [metabase-enterprise.semantic-search.task.indexer]))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
new file mode 100644
index 00000000000..e416a3cdfa2
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
@@ -0,0 +1,154 @@
+(ns metabase-enterprise.semantic-search.pgvector-api
+ "High-level API for pgvector based semantic search over metabase.search documents.
+
+ Provides the primary interface for search, indexing, and document management.
+
+ Determines which index to target in the database using the index-metadata lib.
+
+ Important: The pgvector database must be setup for metadata by calling (init-semantic-search!)
+ After this, the document management and query functions will work as long as you pass the same index-metadata configuration."
+ (:require
+ [metabase-enterprise.semantic-search.db.connection :as semantic.db.connection]
+ [metabase-enterprise.semantic-search.db.migration :as semantic.db.migration]
+ [metabase-enterprise.semantic-search.gate :as semantic.gate]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase.util :as u]
+ [metabase.util.log :as log])
+ (:import (java.time Instant)))
+
+(set! *warn-on-reflection* true)
+
+#_{:clj-kondo/ignore [unresolved-require]}
+(comment
+ (require '[metabase-enterprise.semantic-search.db.datasource :as semantic.db])
+ (def pgvector (or @semantic.db/data-source (semantic.db/init-db!)))
+ (def index-metadata semantic.index-metadata/default-index-metadata)
+
+ (require '[metabase-enterprise.semantic-search.embedding :as semantic.embedding])
+ (def embedding-model (semantic.embedding/get-configured-model)))
+
+(defn- initialize-index!
+ [tx index-metadata embedding-model]
+ (let [active-index-state (semantic.index-metadata/get-active-index-state tx index-metadata)
+ active-index (:index active-index-state)
+ active-model (:embedding-model active-index)
+ ;; Model switching: compare configured embedding-model vs currently active model.
+ ;; If different, find/create appropriate index and activate it. This handles
+ ;; environment changes (model config updates) without losing existing indexes.
+ ;; nil active-model (no active index) is treated as model change so that a new index is created and made active
+ model-changed (not= embedding-model active-model)
+ model-switching (and active-model model-changed)]
+ (when model-switching
+ (log/infof "Configured model does not match active index, switching. Previous active: %s" (u/pprint-to-str active-index)))
+ (if model-changed
+ (let [{:keys [index metadata-row]}
+ (semantic.index-metadata/find-best-index! tx index-metadata embedding-model)]
+ ;; Metadata might exist without table (deleted manually) or table without metadata
+ ;; (created outside this system). Both cases are handled gracefully.
+ ;; We might delete some of this fancyness later once schema / setup etc solidifies
+ (semantic.index/create-index-table-if-not-exists! tx index)
+ (let [index-id (or (:id metadata-row) (semantic.index-metadata/record-new-index-table! tx index-metadata index))]
+ (semantic.index-metadata/activate-index! tx index-metadata index-id)
+ index))
+ active-index)))
+
+(defn init-semantic-search!
+ "Initialises a pgvector database for semantic search if it does not exist and creates an index for the provided
+ embedding model (if it does not exist).
+
+ Returns the index that you can use with semantic.search.index functions to operate on the index.
+
+ Designed to be called once at application startup (or in tests)."
+ [pgvector index-metadata embedding-model]
+ (semantic.db.connection/with-migrate-tx [tx pgvector]
+ (semantic.db.migration/maybe-migrate! tx {:index-metadata index-metadata
+ :embedding-model embedding-model})
+ (initialize-index! tx index-metadata embedding-model)))
+
+;; query/index-mgmt require an active index to be established first.
+;; init-semantic-search! must be called on startup
+(defn- ensure-active-index-state [pgvector index-metadata]
+ (or (semantic.index-metadata/get-active-index-state pgvector index-metadata)
+ (throw (ex-info "No active semantic search index found" {:index-metadata index-metadata}))))
+
+(defn query
+ "Executes a semantic search query against the active index. Returns results and metadata about filtering.
+ Requires init-semantic-search! to have been called first to establish active index, otherwise an exception will be thrown."
+ [pgvector index-metadata search-context]
+ (let [{:keys [index]} (ensure-active-index-state pgvector index-metadata)]
+ (semantic.index/query-index pgvector index search-context)))
+
+(defn index-documents!
+ "Indexes documents into the active semantic search index.
+ Documents are upserted - existing documents with same id are replaced.
+
+ This is the 'immediate mode' API for inserting documents, the expected production behaviour
+ is to instead (gate-updates!) the documents and allow the indexer task to pick them up.
+
+ `documents` is a logical collection, but can be reducible to save memory usage."
+ [pgvector index-metadata documents]
+ (let [{:keys [index]} (ensure-active-index-state pgvector index-metadata)]
+ (semantic.index/upsert-index! pgvector index documents)))
+
+(defn gate-updates!
+ "Stages document updates through the gate table to enable async indexing. See gate.clj.
+
+ NOTE: Returns a frequency map of input {model id-count} for compatibility with existing caller expectations -
+ but it is redundant and should otherwise be ignored."
+ [pgvector index-metadata documents]
+ (let [now (Instant/now)]
+ (transduce
+ (partition-all (min 512 semantic.gate/max-batch-size))
+ (completing
+ (fn [acc documents]
+ (->> documents
+ (mapv #(semantic.gate/search-doc->gate-doc % now))
+ (semantic.gate/gate-documents! pgvector index-metadata))
+ (merge-with + acc (frequencies (map :model documents)))))
+ {}
+ documents)))
+
+(defn gate-deletes!
+ "Stages document deletes through the gate table for async indexing. See gate.clj.
+
+ NOTE: Returns a frequency map of input {model id-count} for compatibility with existing caller expectations -
+ but it is redundant and should otherwise be ignored."
+ [pgvector index-metadata model ids]
+ (let [now (Instant/now)]
+ (transduce
+ (partition-all (min 512 semantic.gate/max-batch-size))
+ (completing
+ (fn [acc ids]
+ (->> ids
+ (mapv #(semantic.gate/deleted-search-doc->gate-doc model % now))
+ (semantic.gate/gate-documents! pgvector index-metadata))
+ (merge-with + acc {model (count ids)})))
+ {}
+ ids)))
+
+(defn delete-documents!
+ "Removes documents from the active index by model (search.spec model string) and ids.
+ `ids` is a logical collection, but can be reducible to save memory usage."
+ [pgvector index-metadata model ids]
+ (let [{:keys [index]} (ensure-active-index-state pgvector index-metadata)]
+ (semantic.index/delete-from-index! pgvector index model ids)))
+
+#_{:clj-kondo/ignore [:unresolved-require :metabase/modules]}
+(comment
+ (init-semantic-search! pgvector index-metadata embedding-model)
+ (index-documents! pgvector index-metadata [{:model "card"
+ :id "1"
+ :searchable_text "This is a test card"}])
+ (require '[metabase.test :as mt])
+ (mt/as-admin (query pgvector index-metadata {:search-string "test card"}))
+
+ (def index-state (ensure-active-index-state pgvector index-metadata))
+ (def index (:index index-state))
+
+ ;; warning: deletes everything
+ (require 'next.jdbc)
+ (next.jdbc/execute! pgvector ((requiring-resolve 'honey.sql/format) {:delete-from (keyword (:table-name index))} :quoted true))
+ (def searchable-documents (vec ((requiring-resolve 'metabase.search.ingestion/searchable-documents))))
+ (index-documents! pgvector index-metadata searchable-documents)
+ (mt/as-admin (query pgvector index-metadata {:search-string "sharp objects"})))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
new file mode 100644
index 00000000000..6323bdd057d
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
@@ -0,0 +1,95 @@
+(ns metabase-enterprise.semantic-search.scoring
+ (:require
+ [honey.sql.helpers :as sql.helpers]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.search.config :as search.config]
+ [metabase.search.scoring :as search.scoring]
+ [toucan2.util :as u]))
+
+(defn- ->col-expr
+ "For a given `col-name` return a :coalesce expression to reference it from the outer hybrid search query.
+
+ (->col-expr :model_id) -> [:coalesce :v.model_id :t.model_id]"
+ [col-name]
+ (let [prefix #(keyword (str %1 (name %2)))]
+ [:coalesce (prefix "v." col-name) (prefix "t." col-name)]))
+
+(defn- model-rank-exp [{:keys [context]}]
+ (let [search-order search.config/models-search-order
+ n (double (count search-order))
+ cases (map-indexed (fn [i sm]
+ [[:= (->col-expr :model) sm]
+ (or (search.config/scorer-param context :model sm)
+ [:inline (/ (- n i) n)])])
+ search-order)]
+ (-> (into [:case] cat (concat cases))
+ ;; if you're not listed, get a very poor score
+ (into [:else [:inline 0.01]]))))
+
+(def ^:private rrf-rank-exp
+ (let [k 60
+ keyword-weight 0.51
+ semantic-weight 0.49]
+ [:+
+ [:* [:cast semantic-weight :float]
+ [:coalesce [:/ 1.0 [:+ k [:. :v :semantic_rank]]] 0]]
+ [:* [:cast keyword-weight :float]
+ [:coalesce [:/ 1.0 [:+ k [:. :t :keyword_rank]]] 0]]]))
+
+(defn base-scorers
+ "The default constituents of the search ranking scores."
+ [{:keys [search-string limit-int] :as search-ctx}]
+ (if (and limit-int (zero? limit-int))
+ {:model [:inline 1]}
+ ;; NOTE: we calculate scores even if the weight is zero, so that it's easy to consider how we could affect any
+ ;; given set of results. At some point, we should optimize away the irrelevant scores for any given context.
+ {:rrf rrf-rank-exp
+ :pinned (search.scoring/truthy (->col-expr :pinned))
+ :recency (search.scoring/inverse-duration [:coalesce
+ (->col-expr :last_viewed_at)
+ (->col-expr :model_updated_at)]
+ [:now]
+ search.config/stale-time-in-days)
+ :dashboard (search.scoring/size (->col-expr :dashboardcard_count) search.config/dashboard-count-ceiling)
+ :model (model-rank-exp search-ctx)
+ :mine (search.scoring/equal (->col-expr :creator_id) (:current-user-id search-ctx))
+ :exact (if search-string
+ ;; perform the lower casing within the database, in case it behaves differently to our helper
+ (search.scoring/equal [:lower (->col-expr :name)] [:lower search-string])
+ [:inline 0])
+ :prefix (if search-string
+ ;; in this case, we need to transform the string into a pattern in code, so forced to use helper
+ (search.scoring/prefix [:lower (->col-expr :name)] (u/lower-case-en search-string))
+ [:inline 0])}))
+
+(def ^:private enterprise-scorers
+ {:official-collection {:expr (search.scoring/truthy (->col-expr :official_collection))
+ :pred #(premium-features/has-feature? :official-collections)}
+ :verified {:expr (search.scoring/truthy (->col-expr :verified))
+ :pred #(premium-features/has-feature? :content-verification)}})
+
+(defn- additional-scorers
+ "Which additional scorers are active?"
+ []
+ (into {}
+ (keep (fn [[k {:keys [expr pred]}]]
+ (when (pred)
+ [k expr])))
+ enterprise-scorers))
+
+(defn semantic-scorers
+ "Return the select-item expressions used to calculate the score for semantic search results."
+ [search-ctx]
+ (merge (base-scorers search-ctx)
+ (additional-scorers)))
+
+(defn with-scores
+ "Add a bunch of SELECT columns for the individual and total scores, and a corresponding ORDER BY."
+ [search-ctx scorers qry]
+ (-> (search.scoring/with-scores search-ctx scorers qry)
+ (sql.helpers/order-by [:total_score :desc])))
+
+(defn all-scores
+ "Score stats for each scorer"
+ [weights scorers index-row]
+ (search.scoring/all-scores weights scorers index-row))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj
new file mode 100644
index 00000000000..ba043df8d16
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj
@@ -0,0 +1,89 @@
+(ns metabase-enterprise.semantic-search.settings
+ (:require
+ [metabase-enterprise.llm.settings :as llm-settings]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.settings.core :as setting :refer [defsetting]]
+ [metabase.util.i18n :refer [deferred-tru]]))
+
+(defsetting ee-embedding-provider
+ (deferred-tru "The embedding provider to use (:openai, :ollama, or :ai-service)")
+ :encryption :no
+ :visibility :settings-manager
+ :default "ai-service"
+ :type :string
+ :export? false
+ :doc "This feature is experimental.")
+
+(defsetting ee-embedding-model
+ (deferred-tru "Set the embedding model for the selected provider")
+ :encryption :no
+ :visibility :settings-manager
+ :default "Snowflake/snowflake-arctic-embed-l-v2.0"
+ :export? false
+ :doc "This feature is experimental.")
+
+(defsetting ee-embedding-model-dimensions
+ (deferred-tru "Set the dimension size for the selected embedding model")
+ :encryption :no
+ :visibility :settings-manager
+ :default 1024
+ :type :positive-integer
+ :export? false
+ :doc "This feature is experimental.")
+
+(defn openai-api-base-url
+ "Get the OpenAI API base url from the existing LLM settings."
+ []
+ (llm-settings/ee-openai-api-base-url))
+
+(defn openai-api-key
+ "Get the OpenAI API key from the existing LLM settings."
+ []
+ (llm-settings/ee-openai-api-key))
+
+(defsetting semantic-search-enabled
+ (deferred-tru "Enable the semantic search engine? Intended as a kill switch for the semantic search feature while dogfooding.")
+ :visibility :internal
+ :export? false
+ :encryption :no
+ :default true
+ :getter (fn []
+ (and (setting/get-value-of-type :boolean :semantic-search-enabled)
+ (premium-features/enable-semantic-search?)))
+ :type :boolean)
+
+(defsetting openai-max-tokens-per-batch
+ (deferred-tru "The maximum number of tokens sent in a single embedding API call.")
+ :type :integer
+ :default 4000
+ :encryption :no
+ :export? false
+ :visibility :internal
+ :doc "The maximum number of tokens sent in a single embedding API call.")
+
+(defsetting semantic-search-results-limit
+ (deferred-tru "Maximum number of results to return from a single semantic search query.")
+ :type :integer
+ :default 1000
+ :encryption :no
+ :export? false
+ :visibility :internal
+ :doc "Maximum number of results to return from a single semantic search query.")
+
+(defsetting semantic-search-min-results-threshold
+ (deferred-tru "Minimum number of semantic search results required before falling back to other engines.")
+ :type :integer
+ :default 100
+ :encryption :no
+ :export? false
+ :visibility :internal
+ :doc "Minimum number of semantic search results required before falling back to other engines.")
+
+(defsetting index-update-thread-count
+ (deferred-tru "Number of threads to use for batched index updates, including embedding requests")
+ :type :integer
+ :default 2
+ :encryption :no
+ :export? false
+ :visibility :internal
+ :doc "Number of threads to use for batched index updates, including embedding requests")
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/task/indexer.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/task/indexer.clj
new file mode 100644
index 00000000000..4bca5d6d90f
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/task/indexer.clj
@@ -0,0 +1,73 @@
+(ns metabase-enterprise.semantic-search.task.indexer
+ (:require
+ #_[metabase-enterprise.semantic-search.db.connection :as semantic.db.connection]
+ [clojurewerkz.quartzite.jobs :as jobs]
+ [clojurewerkz.quartzite.schedule.simple :as simple]
+ [clojurewerkz.quartzite.triggers :as triggers]
+ [metabase-enterprise.semantic-search.env :as semantic.env]
+ [metabase-enterprise.semantic-search.indexer :as semantic-search.indexer]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.search.engine :as search.engine]
+ [metabase.task.core :as task]
+ [metabase.util.log :as log])
+ (:import (java.time Duration Instant)
+ (java.util Date)
+ (org.quartz DisallowConcurrentExecution)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private indexer-stem
+ (jobs/key "metabase-enterprise.semantic-search.indexer"))
+
+(def indexer-job-key
+ "Key used to define and trigger a job that maintains semantic search indexes."
+ (jobs/key (str indexer-stem ".job")))
+
+;; would prefer a job member, as quartz suggests in its InterruptableJob docs
+;; but if I do that quartz cannot initialize the job - there is probably a way around this.
+(defonce ^:private execution-thread-ref (volatile! nil))
+
+(deftype ^{DisallowConcurrentExecution true
+ :doc "Runs an indexer process for a time, expects to be rescheduled to continue"}
+ SemanticSearchIndexer []
+ org.quartz.Job
+ (execute [_ _]
+ (log/with-context {:quartz-job-type 'SemanticSearchIndexer}
+ (when (search.engine/supported-engine? :search.engine/semantic)
+ (try
+ (vreset! execution-thread-ref (Thread/currentThread))
+ (semantic-search.indexer/quartz-job-run! (semantic.env/get-pgvector-datasource!) (semantic.env/get-index-metadata))
+ ;; TODO: w-tx should be nogo here, move lower or add wrapper on exe
+ #_(semantic.db.connection/with-write-tx
+ [tx]
+ (semantic-search.indexer/quartz-job-run! tx (semantic.env/get-index-metadata)))
+ (finally
+ (locking execution-thread-ref
+ (vreset! execution-thread-ref nil)))))))
+ org.quartz.InterruptableJob
+ (interrupt [_]
+ ;; locking required here to avoid racing with the unset in the finally
+ ;; and interrupting some other unintended task/work
+ (locking execution-thread-ref
+ (when-some [^Thread execution-thread @execution-thread-ref]
+ (.interrupt execution-thread)))))
+
+(def ^:private ^Duration startup-delay (Duration/parse "PT10S"))
+(def ^:private ^Duration run-frequency (Duration/parse "PT10S"))
+
+(defmethod task/init! ::SemanticSearchIndexer [_]
+ (when (premium-features/has-feature? :semantic-search)
+ (let [job (jobs/build
+ (jobs/of-type SemanticSearchIndexer)
+ (jobs/store-durably)
+ (jobs/with-identity indexer-job-key))
+ trigger-key (triggers/key (str indexer-stem ".trigger"))
+ trigger (triggers/build
+ (triggers/with-identity trigger-key)
+ (triggers/for-job indexer-job-key)
+ (triggers/start-at (Date/from (.plus (Instant/now) startup-delay)))
+ (triggers/with-schedule
+ (simple/schedule
+ (simple/with-interval-in-milliseconds (.toMillis run-frequency))
+ (simple/repeat-forever))))]
+ (task/schedule-task! job trigger))))
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index 666dbf173ee..da494c01ed1 100644
--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
@@ -35,6 +35,7 @@
:query-reference-validation
:sandboxes
:scim
+ :semantic-search
:serialization
:session-timeout-config
:snippet-collections
@@ -74,6 +75,7 @@
:query_reference_validation true
:sandboxes true
:scim true
+ :semantic_search true
:serialization true
:session_timeout_config true
:snippet_collections true
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
new file mode 100644
index 00000000000..496263a2438
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
@@ -0,0 +1,67 @@
+(ns metabase-enterprise.semantic-search.api-test
+ (:require
+ [clojure.core.memoize :as memoize]
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.api :as semantic.api]
+ [metabase-enterprise.semantic-search.embedding :as semantic.embedding]
+ [metabase-enterprise.semantic-search.env :as semantic.env]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (compose-fixtures
+ (fixtures/initialize :db)
+ #'semantic.tu/once-fixture))
+
+(defmacro with-mock-index-metadata!
+ [& body]
+ `(with-redefs [semantic.env/get-pgvector-datasource! (constantly semantic.tu/db)
+ semantic.embedding/get-configured-model (constantly semantic.tu/mock-embedding-model)
+ semantic.env/get-index-metadata (constantly semantic.tu/mock-index-metadata)]
+ ~@body))
+
+(deftest status-endpoint-test
+ (testing "GET /api/ee/semantic-search/status"
+ (mt/with-premium-features #{:semantic-search}
+ (with-mock-index-metadata!
+ (with-open [index-ref (semantic.tu/open-temp-index!)]
+ (with-redefs [semantic.index-metadata/get-active-index-state (fn [_ _]
+ {:index @index-ref
+ :status :active})]
+ (let [expected-search-items-count (search.ingestion/search-items-count)]
+ (memoize/memo-clear! @#'semantic.api/indexible-items-count)
+ (testing "Correctly reports empty index status"
+ (let [{:keys [indexed_count total_est]} (mt/user-http-request :crowberto :get 200 "ee/semantic-search/status")]
+ (is (= 0 indexed_count))
+ (is (= expected-search-items-count total_est))))
+
+ (testing "Correctly reports size of index after inserting documents"
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents))
+ (let [{:keys [indexed_count total_est]} (mt/user-http-request :crowberto :get 200 "ee/semantic-search/status")]
+ (is (= 2 indexed_count))
+ (is (= expected-search-items-count total_est)))))))))
+
+ (testing "with semantic search disabled"
+ (mt/with-premium-features #{}
+ (let [response (mt/user-http-request :crowberto :get 402 "ee/semantic-search/status")]
+ (testing "returns 402 when semantic search feature is not available"
+ (is (= 402 (get-in response [:data :status-code])))))))
+
+ (testing "with no active index"
+ (mt/with-premium-features #{:semantic-search}
+ (with-redefs [semantic.env/get-pgvector-datasource! (constantly nil)
+ semantic.env/get-index-metadata (constantly nil)]
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/semantic-search/status")]
+ (testing "returns empty map when no index is active"
+ (is (= {} response)))))))))
+
+(deftest status-endpoint-permissions-test
+ (testing "GET /api/ee/semantic-search/status permissions"
+ (mt/with-premium-features #{:semantic-search}
+ (testing "admin users can access status endpoint"
+ (mt/user-http-request :crowberto :get 200 "ee/semantic-search/status"))
+
+ (testing "regular users cannot access status endpoint"
+ (mt/user-http-request :rasta :get 403 "ee/semantic-search/status")))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/core_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/core_test.clj
new file mode 100644
index 00000000000..de661d72e13
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/core_test.clj
@@ -0,0 +1,147 @@
+(ns metabase-enterprise.semantic-search.core-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.core :as semantic.core]
+ [metabase-enterprise.semantic-search.pgvector-api :as semantic.pgvector-api]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.search.appdb.core :as appdb]
+ [metabase.search.engine :as search.engine]
+ [metabase.search.settings :as search.settings]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (compose-fixtures
+ (fixtures/initialize :db)
+ #'semantic.tu/once-fixture))
+
+(deftest appdb-available-with-semantic
+ (mt/with-premium-features #{:semantic-search}
+ (mt/with-temporary-setting-values [search.settings/search-engine "semantic"]
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (semantic.tu/cleanup-index-metadata! semantic.tu/db semantic.tu/mock-index-metadata)
+ (semantic.tu/with-index!
+ (is (search.engine/supported-engine? :search.engine/appdb)))))))
+
+(deftest api-engine-switching-test
+ (mt/with-premium-features #{:semantic-search}
+ (mt/with-temporary-setting-values [search.settings/search-engine "semantic"]
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ ;; Disable falling back to appdb search engine when not enough semantic results are returned
+ (mt/with-temporary-setting-values [semantic-search-min-results-threshold 0]
+ (testing "API defaults to semantic engine when configured"
+ (let [semantic-called? (atom false)
+ appdb-called? (atom false)]
+ (with-redefs [semantic.pgvector-api/query
+ (fn [& _]
+ (reset! semantic-called? true)
+ {:results [{:id 1 :name "semantic-result" :model "card" :collection_id 1 :score 0}]
+ :raw-count 0})
+ appdb/results
+ (fn [_]
+ (reset! appdb-called? true)
+ [{:id 2 :name "appdb-result" :model "card" :collection_id 1 :score 0.9}])]
+
+ (let [response (mt/user-http-request :crowberto :get 200 "search" :q "test")]
+ (is @semantic-called? "Semantic search should be called by default")
+ (is (not @appdb-called?) "AppDB search should not be called by default")
+ (is (= "search.engine/semantic" (:engine response)))))))
+
+ (testing "API can override engine with search_engine=appdb parameter"
+ (let [semantic-called? (atom false)
+ appdb-called? (atom false)]
+ (with-redefs [semantic.pgvector-api/query
+ (fn [& _]
+ (reset! semantic-called? true)
+ {:results [{:id 1 :name "semantic-result" :model "card" :collection_id 1 :score 0.8}]
+ :raw-count 0})
+ appdb/results
+ (fn [_]
+ (reset! appdb-called? true)
+ [{:id 2 :name "appdb-result" :model "card" :collection_id 1 :score 0.9}])]
+
+ (let [response (mt/user-http-request :crowberto :get 200 "search" :q "test" :search_engine "appdb")]
+ (is (not @semantic-called?) "Semantic search should not be called when overridden")
+ (is @appdb-called? "AppDB search should be called when specified")
+ (is (= "search.engine/appdb" (:engine response))))))))))))
+
+(def ^:private search-context
+ {:query "test" :search-engine :search.engine/semantic})
+
+(defn- with-search-engine-mocks!
+ "Sets up search engine mocks for the semantic & appdb backends for testing fallback behavior.
+ appdb-fn can be a collection of results or a function that takes a context."
+ [semantic-results appdb-results thunk]
+ (with-redefs [semantic.pgvector-api/query (fn [_pgvector _index-metadata _search-ctx]
+ {:results semantic-results
+ ;; Set raw-count to a non-zero value to ensure fallback logic is
+ ;; triggered
+ :raw-count 1})
+ search.engine/results (fn [ctx]
+ (case (:search-engine ctx)
+ :search.engine/appdb (if (fn? appdb-results)
+ (appdb-results ctx)
+ appdb-results)
+ :search.engine/semantic (semantic.core/results ctx)))]
+ (thunk)))
+
+(defn- make-card-result
+ "Creates a card result with the given id and name."
+ [id name & {:keys [model score] :or {model "card"}}]
+ (cond-> {:id id :name name :model model}
+ score (assoc :score score)))
+
+(deftest test-semantic-search-fallback-supplementation
+ (testing "semantic search results below threshold are supplemented with appdb results"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/with-temporary-setting-values [semantic-search-min-results-threshold 3]
+ (let [semantic-result (make-card-result 1 "semantic-card" :score 0.9)
+ appdb-results [(make-card-result 1 "appdb-card-1")
+ (make-card-result 2 "appdb-card-2")
+ (make-card-result 3 "appdb-card-3")
+ (make-card-result 4 "appdb-dashboard" :model "dashboard")]
+ search-ctx search-context]
+ (with-search-engine-mocks! [semantic-result] appdb-results
+ (fn []
+ (let [results (semantic.core/results search-ctx)]
+ (testing "semantic result comes first"
+ (is (= semantic-result (first results))))
+
+ (testing "appdb results are appended, and duplicate model/id pairs are removed"
+ (is (= (rest appdb-results)
+ (rest results))))))))))))
+
+(deftest test-semantic-search-above-threshold-no-fallback
+ (testing "semantic search results above threshold are not supplemented"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/with-temporary-setting-values [semantic-search-min-results-threshold 3]
+ (let [semantic-results [(make-card-result 1 "semantic-card-1" :score 0.9)
+ (make-card-result 2 "semantic-card-2" :score 0.8)
+ (make-card-result 3 "semantic-card-3" :score 0.7)
+ (make-card-result 4 "semantic-card-4" :score 0.6)]
+ search-ctx search-context
+ fallback-fn (fn [ctx] (throw (ex-info "Should not call fallback engine" {:engine (:search-engine ctx)})))]
+ (with-search-engine-mocks! semantic-results fallback-fn
+ (fn []
+ (let [results (semantic.core/results search-ctx)]
+ (testing "returns only semantic results without fallback"
+ (is (= semantic-results results))
+ (is (= 4 (count results))))))))))))
+
+(deftest test-semantic-search-max-combined-results-limit
+ (testing "combined results are limited by semantic-search-results-limit"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/with-temporary-setting-values [semantic-search-min-results-threshold 3
+ semantic-search-results-limit 5]
+ (let [semantic-result (make-card-result 1 "semantic-card" :score 0.9)
+ appdb-results (for [i (range 2 10)]
+ (make-card-result i (str "appdb-card-" i)))
+ search-ctx search-context]
+ (with-search-engine-mocks! [semantic-result] appdb-results
+ (fn []
+ (let [results (semantic.core/results search-ctx)]
+ (testing "semantic result is included first"
+ (is (= semantic-result (first results))))
+ (testing "remaining slots filled with appdb results"
+ (let [remaining (rest results)]
+ (is (= 4 (count remaining)))
+ (is (every? #(contains? (set appdb-results) %) remaining))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/db_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/db_test.clj
new file mode 100644
index 00000000000..f6b239e03d5
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/db_test.clj
@@ -0,0 +1,54 @@
+(ns metabase-enterprise.semantic-search.db-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource])
+ (:import
+ (com.mchange.v2.c3p0 PoolBackedDataSource)))
+
+(set! *warn-on-reflection* true)
+
+(deftest connection-pool-initialization-test
+ (testing "Connection pool can be initialized and tested"
+ (when semantic.db.datasource/db-url
+ ;; Reset the data source to ensure clean test
+ (reset! semantic.db.datasource/data-source nil)
+
+ (testing "Data source is nil before initialization"
+ (is (nil? @semantic.db.datasource/data-source)))
+
+ (testing "init-db! creates a pooled data source"
+ (semantic.db.datasource/init-db!)
+ (is (some? @semantic.db.datasource/data-source))
+ (is (instance? PoolBackedDataSource @semantic.db.datasource/data-source)))
+
+ (testing "test-connection! works with pooled connection"
+ (let [result (semantic.db.datasource/test-connection!)]
+ (is (= {:test 1} result))))
+
+ (testing "Connection pool properties are configured correctly"
+ (when (instance? PoolBackedDataSource @semantic.db.datasource/data-source)
+ (let [pool ^PoolBackedDataSource @semantic.db.datasource/data-source]
+ ;; Test that pool is properly configured
+ (is (<= (.getNumConnections pool) 5))
+ (is (>= (.getNumConnections pool) 0))))))))
+
+(deftest db-url-validation-test
+ (testing "init-db! throws exception when DB URL is missing"
+ (with-redefs [semantic.db.datasource/db-url nil
+ semantic.db.datasource/data-source (atom nil)]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"MB_PGVECTOR_DB_URL environment variable is required"
+ (semantic.db.datasource/init-db!))))))
+
+(deftest test-connection-before-init-test
+ (testing "test-connection! throws exception when pool not initialized"
+ (let [orig-data-source @semantic.db.datasource/data-source]
+ (try
+ (reset! semantic.db.datasource/data-source nil)
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Semantic search connection pool is not initialized"
+ (semantic.db.datasource/test-connection!)))
+ (finally
+ (reset! semantic.db.datasource/data-source orig-data-source))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj
new file mode 100644
index 00000000000..26b2d7fcf9f
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj
@@ -0,0 +1,232 @@
+(ns metabase-enterprise.semantic-search.embedding-test
+ (:require
+ [clj-http.client :as http]
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.embedding :as embedding]
+ [metabase.analytics.core :as analytics]
+ [metabase.test :as mt]
+ [metabase.util.json :as json])
+ (:import
+ [java.nio ByteBuffer ByteOrder]
+ [java.util Base64]))
+
+(set! *warn-on-reflection* true)
+
+(deftest test-get-provider
+ (testing "get-active-model returns based on setting"
+ (mt/with-temporary-setting-values [ee-embedding-provider "ai-service"
+ ee-embedding-model "mxbai-embed-large"
+ ee-embedding-model-dimensions 1024]
+ (is (= {:provider "ai-service"
+ :model-name "mxbai-embed-large"
+ :vector-dimensions 1024}
+ (embedding/get-configured-model))))
+
+ (mt/with-temporary-setting-values [ee-embedding-provider "ollama"
+ ee-embedding-model "mxbai-embed-large"
+ ee-embedding-model-dimensions 1024]
+ (is (= {:provider "ollama"
+ :model-name "mxbai-embed-large"
+ :vector-dimensions 1024}
+ (embedding/get-configured-model))))
+
+ (mt/with-temporary-setting-values [ee-embedding-provider "openai"
+ ee-embedding-model "text-embedding-3-small"
+ ee-embedding-model-dimensions 1536]
+ (is (= {:provider "openai"
+ :model-name "text-embedding-3-small"
+ :vector-dimensions 1536}
+ (embedding/get-configured-model))))))
+
+(deftest test-model-dimensions-with-settings
+ (testing "model-dimensions uses setting defaults when override is nil"
+ (mt/with-temporary-setting-values [ee-embedding-model-dimensions nil]
+ (is (= 1024 (:vector-dimensions (embedding/get-configured-model))))))
+
+ (testing "model-dimensions uses override when specified"
+ (mt/with-temporary-setting-values [ee-embedding-model-dimensions 768]
+ (is (= 768 (:vector-dimensions (embedding/get-configured-model)))))))
+
+(deftest test-openai-provider-validation
+ (testing "OpenAIProvider throws when API key not configured"
+ (let [embedding-model {:provider "openai"
+ :model-name "text-embedding-3-small"
+ :vector-dimensions 1536}]
+ (mt/with-temporary-setting-values [ee-openai-api-key nil]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"OpenAI API key not configured"
+ (embedding/get-embedding embedding-model "test text")))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"OpenAI API key not configured"
+ (embedding/get-embeddings-batch embedding-model ["test text"])))))))
+
+(deftest test-token-counting
+ (testing "count-tokens returns reasonable counts for text"
+ (is (= 2 (#'embedding/count-tokens "Hello world")))
+ (is (= 9 (#'embedding/count-tokens "This is a longer sentence with more tokens.")))
+ (is (zero? (#'embedding/count-tokens "")))
+ (is (nil? (#'embedding/count-tokens nil)))))
+
+(deftest test-batching-logic
+ (testing "create-batches handles empty input"
+ (is (empty? (#'embedding/create-batches 10 count [])))
+ (is (empty? (#'embedding/create-batches 10 count nil))))
+
+ (testing "create-batches with single short text"
+ (let [texts ["Short text"]
+ batches (#'embedding/create-batches 10 count texts)]
+ (is (= 1 (count batches)))
+ (is (= texts (first batches)))))
+
+ (testing "create-batches splits texts appropriately with smaller token limit"
+ ;; Use a smaller token limit to make testing more predictable
+ (let [texts ["This is document 1" "This is document 2" "This is document 3"]
+ batches (#'embedding/create-batches 10 #'embedding/count-tokens texts)]
+ (is (= [["This is document 1" "This is document 2"] ["This is document 3"]]
+ batches))))
+
+ (testing "create-batches skips texts that exceed token limit"
+ (let [texts ["Short" "This is a much longer text that exceeds the limit" "Also short"]
+ batches (#'embedding/create-batches 5 #'embedding/count-tokens texts)]
+ ;; Should skip the long text and batch the short ones
+ (is (= [["Short" "Also short"]] batches)))))
+
+(defn- float-vectors-approx=
+ "Compare two vectors of floats for approximate equality within a given tolerance."
+ ([v1 v2]
+ (float-vectors-approx= v1 v2 0.0001))
+ ([v1 v2 tolerance]
+ (and (= (count v1) (count v2))
+ (every? #(< (Math/abs ^double %) tolerance)
+ (map - v1 v2)))))
+
+(defn- encode-floats-to-base64
+ "Helper function to base64 encode a vector of floats using little-endian byte order.
+ Inverse of [[metabase-enterprise.semantic-search.embedding/extract-base64-response-embeddings]] "
+ [float-vector]
+ (let [byte-count (* (count float-vector) 4)
+ buffer (doto (ByteBuffer/allocate byte-count)
+ (.order ByteOrder/LITTLE_ENDIAN))]
+ (doseq [f float-vector]
+ (.putFloat buffer (float f)))
+ (.encodeToString (Base64/getEncoder) (.array buffer))))
+
+(deftest test-extract-base64-response-embeddings
+ (testing "extracts single embedding correctly"
+ (let [test-embedding [1.0 2.5 -0.5 3.14159]
+ base64-str (encode-floats-to-base64 test-embedding)
+ response {:data [{:embedding base64-str}]}
+ result (#'embedding/extract-base64-response-embeddings response)]
+ (is (= 1 (count result)))
+ (is (= (count test-embedding) (count (first result))))
+ (is (float-vectors-approx= test-embedding (first result)))))
+
+ (testing "extracts multiple embeddings correctly"
+ (let [embedding1 [1.0 2.0 3.0]
+ embedding2 [-1.0 -2.0 -3.0]
+ embedding3 [0.0 0.5 -0.5]
+ base64-str1 (encode-floats-to-base64 embedding1)
+ base64-str2 (encode-floats-to-base64 embedding2)
+ base64-str3 (encode-floats-to-base64 embedding3)
+ response {:data [{:embedding base64-str1}
+ {:embedding base64-str2}
+ {:embedding base64-str3}]}
+ result (#'embedding/extract-base64-response-embeddings response)]
+ (is (= 3 (count result)))
+ (is (float-vectors-approx= embedding1 (nth result 0)))
+ (is (float-vectors-approx= embedding2 (nth result 1)))
+ (is (float-vectors-approx= embedding3 (nth result 2)))))
+
+ (testing "edge cases that return empty results"
+ (testing "handles empty data array"
+ (let [response {:data []}
+ result (#'embedding/extract-base64-response-embeddings response)]
+ (is (= [] result))))
+
+ (testing "handles missing :data key"
+ (let [response {}
+ result (#'embedding/extract-base64-response-embeddings response)]
+ (is (= [] result))))
+
+ (testing "handles zero-length embedding"
+ (let [base64-str (encode-floats-to-base64 [])
+ response {:data [{:embedding base64-str}]}
+ result (#'embedding/extract-base64-response-embeddings response)]
+ (is (= 1 (count result)))
+ (is (= [] (first result))))))
+
+ (testing "handles large embedding vectors"
+ (let [large-embedding (vec (map float (range 1536)))
+ base64-str (encode-floats-to-base64 large-embedding)
+ response {:data [{:embedding base64-str}]}
+ result (#'embedding/extract-base64-response-embeddings response)]
+ (is (= 1 (count result)))
+ (is (= 1536 (count (first result))))
+ (is (float-vectors-approx= (take 5 large-embedding) (take 5 (first result))))
+ (is (float-vectors-approx= (take-last 5 large-embedding) (take-last 5 (first result))))))
+
+ (testing "error cases"
+ (testing "invalid base64 string throws exception"
+ (is (thrown? Exception
+ (#'embedding/extract-base64-response-embeddings
+ {:data [{:embedding "not-valid-base64!@#$"}]}))))
+
+ (testing "non-string embedding value throws exception"
+ (is (thrown? Exception
+ (#'embedding/extract-base64-response-embeddings
+ {:data [{:embedding 123}]}))))
+
+ (testing "base64 string with invalid byte count (not multiple of 4) throws exception"
+ ;; Create a base64 string that decodes to 3 bytes
+ (let [encoder (Base64/getEncoder)
+ invalid-base64 (.encodeToString encoder (byte-array [1 2 3]))]
+ (is (thrown? Exception
+ (#'embedding/extract-base64-response-embeddings
+ {:data [{:embedding invalid-base64}]})))))))
+
+(deftest test-get-embedding
+ (mt/with-temporary-setting-values [ee-openai-api-key "mock-openai-api-key"]
+ (let [mock-embedding [1.0 2.0 3.0 4.0]
+ openai-response {:data [{:object "embedding"
+ :embedding (encode-floats-to-base64 mock-embedding)
+ :index 0}]
+ :model "some-model"
+ :usage {:prompt_tokens 1
+ :total_tokens 1}}
+ analytics-calls (atom [])]
+ (doseq [{:keys [provider mock-response counts-tokens?]}
+ [{:provider "openai"
+ :mock-response openai-response
+ :counts-tokens? true}
+ {:provider "ai-service"
+ :mock-response openai-response
+ :counts-tokens? true}
+ {:provider "ollama"
+ :mock-response {:embedding mock-embedding}
+ :counts-tokens? false}]]
+ (mt/with-dynamic-fn-redefs [analytics/inc! (fn [metric & args]
+ (swap! analytics-calls conj [metric args]))
+ http/post (fn post-mock [_url & _options]
+ {:status 200
+ :headers {"Content-Type" "application/json"}
+ :body (json/encode mock-response)})]
+ (testing provider
+ (reset! analytics-calls [])
+ (is (= mock-embedding (#'embedding/get-embedding {:provider provider
+ :model-name "some-model"
+ :vector-dimensions 4}
+ "hello")))
+ (is (= [mock-embedding] (#'embedding/get-embeddings-batch {:provider provider
+ :model-name "some-model"
+ :vector-dimensions 4}
+ ["hello"])))
+ (when counts-tokens?
+ (let [tokens-calls (filter #(= :metabase-search/semantic-embedding-tokens (first %)) @analytics-calls)]
+ (is (= 2 (count tokens-calls)))
+ (is (= {:provider provider
+ :model "some-model"}
+ (-> tokens-calls first second first)))
+ (is (= (get-in mock-response [:usage :total_tokens])
+ (-> tokens-calls first second second)))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/gate_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/gate_test.clj
new file mode 100644
index 00000000000..4363fd4a61b
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/gate_test.clj
@@ -0,0 +1,328 @@
+(ns metabase-enterprise.semantic-search.gate-test
+ (:require
+ [buddy.core.hash :as buddy-hash]
+ [clojure.test :refer :all]
+ [clojure.walk :as walk]
+ [honey.sql :as sql]
+ [metabase-enterprise.semantic-search.gate :as semantic.gate]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import (java.io Closeable)
+ (java.sql Timestamp)
+ (java.time Duration Instant)
+ (org.postgresql.util PGobject)))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+(defn- open-tables! ^Closeable [pgvector index-metadata]
+ (semantic.tu/closeable
+ (semantic.index-metadata/create-tables-if-not-exists! pgvector index-metadata)
+ (fn [_] (semantic.tu/cleanup-index-metadata! pgvector index-metadata))))
+
+(defn- ts ^Timestamp [s] (Timestamp/from (Instant/parse s)))
+
+(deftest search-doc->gate-doc-test
+ (testing "converts search document to gate document format"
+ (let [t1 (ts "2025-01-01T12:00:00Z")
+ t2 (ts "2025-01-02T12:00:00Z")
+ search-doc {:model "card"
+ :id "123"
+ :searchable_text "Dog Training Guide"
+ :updated_at t1}
+ sut semantic.gate/search-doc->gate-doc]
+ (is (= {:id "card_123"
+ :model_id "123"
+ :model "card"
+ :document (doto (PGobject.)
+ (.setType "jsonb")
+ (.setValue (json/encode search-doc)))
+ :document_hash (u/encode-base64-bytes (buddy-hash/sha1 (json/encode (into (sorted-map) search-doc))))
+ :updated_at (:updated_at search-doc)}
+ (sut search-doc t2)))
+
+ (testing "uses default updated_at when search doc has none"
+ (is (= t2
+ (:updated_at (sut (dissoc search-doc :updated_at) t2))
+ (:updated_at (sut (assoc search-doc :updated_at nil) t2))))))))
+
+(deftest gate-doc->search-doc-test
+ (let [original-search-doc {:model "card" :id "123" :searchable_text "Dog Training Guide"}
+ gate-doc {:document (doto (PGobject.)
+ (.setType "jsonb")
+ (.setValue (json/encode original-search-doc)))}
+ recovered-doc (semantic.gate/gate-doc->search-doc gate-doc)]
+ (is (= original-search-doc recovered-doc))))
+
+(defn- get-gate-rows! [pgvector index-metadata]
+ (jdbc/execute! pgvector (sql/format {:select [:*]
+ :from [(keyword (:gate-table-name index-metadata))]
+ :order-by [[:id :asc]]}
+ :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+
+(defn- get-gate-row! [pgvector index-metadata id]
+ (jdbc/execute-one! pgvector (sql/format {:select [:*]
+ :from [(keyword (:gate-table-name index-metadata))]
+ :where [:= :id id]}
+ :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+
+(defn- comparable-gate-row [row]
+ (walk/postwalk
+ (fn [x]
+ (cond
+ (bytes? x) (u/encode-base64-bytes x)
+ (inst? x) (inst-ms x)
+ (instance? PGobject x) (json/decode (.getValue ^PGobject x))
+ :else x))
+ row))
+
+(defn- pg-clock-timestamp! [pgvector]
+ (:ts (jdbc/execute-one! pgvector ["select clock_timestamp() ts"])))
+
+(deftest gate-documents!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ t0 (ts "2025-01-01T00:00:00Z")
+ t1 (ts "2025-01-01T00:01:00Z")
+ t2 (ts "2025-01-02T00:03:10Z")
+ t3 (ts "2025-01-03T00:02:42Z")
+ c1 {:model "card" :id "123" :searchable_text "Dog Training Guide"}
+ c2 {:model "card" :id "123" :searchable_text "Dog Training Guide 2"}
+ c3 {:model "card" :id "123" :searchable_text "Dog Training Guide 3"}
+ d1 {:model "dashboard" :id "456" :searchable_text "Elephant Migration"}
+ version semantic.gate/search-doc->gate-doc
+ delete (fn [doc t] (semantic.gate/deleted-search-doc->gate-doc (:model doc) (:id doc) t))
+ sut semantic.gate/gate-documents!]
+
+ (with-open [_ (open-tables! pgvector index-metadata)]
+ (testing "brand new index, writes accepted"
+ (let [docs [(version c1 t1) (version d1 t1)]
+ existing-timestamp (pg-clock-timestamp! pgvector)
+ update-count (sut pgvector index-metadata docs)
+ gate-rows (map comparable-gate-row (get-gate-rows! pgvector index-metadata))
+ new-timestamp (pg-clock-timestamp! pgvector)]
+ (is (= 2 update-count))
+ (is (= (frequencies (map comparable-gate-row docs))
+ (frequencies (map #(dissoc % :gated_at) gate-rows))))
+ (testing "timestamps in range of expected pg clock value"
+ (doseq [{:keys [gated_at]} gate-rows]
+ (is (<= (inst-ms existing-timestamp)
+ gated_at
+ (inst-ms new-timestamp)))))))
+
+ (testing "same doc a second time is ignored"
+ (let [previous-state (get-gate-rows! pgvector index-metadata)]
+ (is (= 0 (sut pgvector index-metadata [(version c1 t1) (version d1 t1)])))
+ (is (= (map comparable-gate-row previous-state)
+ (map comparable-gate-row (get-gate-rows! pgvector index-metadata))))))
+
+ (testing "if document has a newer timestamp, but the same content - not updated"
+ (is (= 0 (sut pgvector index-metadata [(version c1 t2)]))))
+
+ (testing "if document has an older timestamp and new content, not updated"
+ (is (= 0 (sut pgvector index-metadata [(version c2 t0)]))))
+
+ (testing "if document has same timestamp and new content, updated"
+ (let [lower-bound (pg-clock-timestamp! pgvector)]
+ (is (= 1 (sut pgvector index-metadata [(version c2 t1)])))
+ (is (<= (inst-ms lower-bound)
+ (inst-ms (:gated_at (get-gate-row! pgvector index-metadata (:id (version c2 t1)))))))))
+
+ (testing "if document has newer timestamp and new content, updated"
+ (is (= 1 (sut pgvector index-metadata [(version c1 t2)]))))
+
+ (testing "documents are not deleted if older"
+ (let [previous-state (get-gate-rows! pgvector index-metadata)]
+ (is (= 0 (sut pgvector index-metadata [(delete d1 t0)])))
+ (is (= (map comparable-gate-row previous-state)
+ (map comparable-gate-row (get-gate-rows! pgvector index-metadata))))))
+
+ (testing "documents are deleted if they have the same or newer timestamp"
+ (is (= 1 (sut pgvector index-metadata [(delete d1 t1)])))
+ (is (= 1 (sut pgvector index-metadata [(delete c1 t3)]))))
+
+ (testing "documents are not deleted if already deleted, regardless of timestamp"
+ (is (= 0 (sut pgvector index-metadata [(delete d1 t2)]))))
+
+ (testing "documents are not undeleted if new write is older than the delete"
+ (is (= 0 (sut pgvector index-metadata [(version d1 t0)]))))
+
+ (testing "documents are undeleted if new write is newer than the delete"
+ (is (= 1 (sut pgvector index-metadata [(version d1 t3)]))))
+
+ (testing "last logical update is preferred if multiple submitted, regardless of order"
+ (is (= 1 (sut pgvector index-metadata [(version c1 t2)
+ (version c3 t3)
+ (delete c1 t2)
+ (version c1 t1)])))
+ (is (= (comparable-gate-row (version c3 t3))
+ (comparable-gate-row (dissoc (get-gate-row! pgvector index-metadata (:id (version c3 t3))) :gated_at))))))))
+
+(deftest poll-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ epoch-watermark {:last-poll Instant/EPOCH :last-seen Instant/EPOCH}
+ c1 {:model "card" :id "123" :searchable_text "a"}
+ c2 {:model "card" :id "234" :searchable_text "b"}
+ c3 {:model "card" :id "345" :searchable_text "c"}
+ t0 (ts "2025-01-01T00:00:00Z")
+ t1 (ts "2025-01-01T00:01:00Z")
+ t2 (ts "2025-01-02T00:03:10Z")
+ version semantic.gate/search-doc->gate-doc
+ delete (fn [doc t] (semantic.gate/deleted-search-doc->gate-doc (:model doc) (:id doc) t))
+ gate! semantic.gate/gate-documents!
+ sut semantic.gate/poll]
+
+ (with-open [_ (open-tables! pgvector index-metadata)]
+
+ (testing "empty gate table"
+ (let [clock-lower-bound (inst-ms (pg-clock-timestamp! pgvector))
+ poll-result (sut pgvector index-metadata epoch-watermark)
+ clock-upper-bound (inst-ms (pg-clock-timestamp! pgvector))]
+ (is (<= clock-lower-bound (inst-ms (:poll-time poll-result)) clock-upper-bound))
+ (is (= [] (:update-candidates poll-result)))
+ (let [next-poll-result (sut pgvector index-metadata (semantic.gate/next-watermark epoch-watermark poll-result))]
+ (is (not= epoch-watermark (semantic.gate/next-watermark epoch-watermark poll-result)))
+ (is (<= (inst-ms (:poll-time poll-result)) (inst-ms (:poll-time next-poll-result))))
+ (is (= [] (:update-candidates poll-result))))))
+
+ (testing "from epoch happy path"
+ (testing "add a doc, picked up"
+ (gate! pgvector index-metadata [(version c2 t0)])
+ (let [poll-result (sut pgvector index-metadata epoch-watermark)]
+ (is (= {(:id (version c2 t0)) 1} (frequencies (map :id (:update-candidates poll-result)))))))
+
+ (testing "add a new doc and delete, all 3 operations are picked up from epoch"
+ (gate! pgvector index-metadata [(version c1 t0) (delete c3 t1)])
+ (let [poll-result (sut pgvector index-metadata epoch-watermark)]
+ (is (= (frequencies (map :id [(version c2 t0) (version c1 t0) (delete c3 t1)]))
+ (frequencies (map :id (:update-candidates poll-result)))))))
+
+ (testing "limit works, will get the earlier record (c2 write)" ; note remains undefined within a timestamp
+ (let [poll-result (sut pgvector index-metadata epoch-watermark :limit 1)]
+ (is (= [(:id (version c2 t0))] (map :id (:update-candidates poll-result))))))
+
+ (testing "watermark test"
+
+ ;; assign unique gate timestamps to each record, so following assertions are deterministic
+ (doseq [[t {:keys [id]}] (map vector
+ [t0
+ t1
+ t2]
+ (get-gate-rows! pgvector index-metadata))]
+ (jdbc/execute-one!
+ pgvector
+ (sql/format {:update (keyword (:gate-table-name index-metadata))
+ :set {:gated_at t}
+ :where [:= :id id]}
+ :quoted true)))
+
+ (let [[g1 g2 g3] (sort (map :gated_at (get-gate-rows! pgvector index-metadata)))
+ lag-tolerance (Duration/ofSeconds 3)
+ poll-times #(sort (map :gated_at (:update-candidates (sut pgvector index-metadata % :lag-tolerance lag-tolerance))))
+ timestamp-plus #(.plus (.toInstant ^Timestamp %1) ^Duration %2)]
+ (is (= [g1 g2 g3] (poll-times epoch-watermark)))
+ (testing "seen everything, but still in lag tolerance window"
+ (is (= [g1 g2 g3] (poll-times {:last-poll g1 :last-seen {:gated_at g3}})))
+ (is (= [g1 g2 g3] (poll-times {:last-poll (timestamp-plus g1 lag-tolerance) :last-seen {:gated_at g3}}))))
+ (testing "entries drop once confidence window slides forwards"
+ (is (= [g2 g3] (poll-times {:last-poll (timestamp-plus g1 (.multipliedBy lag-tolerance 2))
+ :last-seen {:gated_at g3}}))))
+ (testing "if last seen is < confidence, we still pull those entries (no gaps)"
+ (is (= [g1 g2 g3] (poll-times {:last-poll (timestamp-plus g1 (.multipliedBy lag-tolerance 2))
+ :last-seen {:gated_at g1}})))
+ (testing "true even for big gaps"
+ (is (= [g2 g3] (poll-times {:last-poll (timestamp-plus g3 (.multipliedBy lag-tolerance 1000))
+ :last-seen {:gated_at g2}})))))))))))
+
+(deftest watermark-management-test
+ (testing "next-watermark updates watermark based on poll results"
+ (let [initial-watermark {:last-poll (ts "2025-01-01T12:00:00Z")
+ :last-seen {:id "card_1"
+ :document_hash "foo"
+ :gated_at (ts "2025-01-01T11:00:00Z")}}
+ poll-result {:poll-time (ts "2025-01-01T13:00:00Z")
+ :update-candidates [{:id "card_123" :documen_hash "foo" :gated_at (ts "2025-01-01T12:30:00Z")}
+ {:id "dashboard_456" :document_hash nil :gated_at (ts "2025-01-01T12:45:00Z")}]}
+ next-watermark (semantic.gate/next-watermark initial-watermark poll-result)]
+
+ (is (= (ts "2025-01-01T13:00:00Z") (:last-poll next-watermark)))
+ (is (= {:gated_at (ts "2025-01-01T12:45:00Z")
+ :document_hash nil
+ :id "dashboard_456"}
+ (:last-seen next-watermark)))))
+
+ (testing "resume-watermark extracts watermark from metadata row"
+ (let [metadata-row {:indexer_last_poll (ts "2025-01-01T12:00:00Z")
+ :indexer_last_seen (ts "2025-01-01T11:30:00Z")
+ :indexer_last_seen_id "card_1"
+ :indexer_last_seen_hash "foo"}
+ watermark (semantic.gate/resume-watermark metadata-row)]
+
+ (is (= (ts "2025-01-01T12:00:00Z") (:last-poll watermark)))
+ (is (= {:id "card_1"
+ :document_hash "foo"
+ :gated_at (ts "2025-01-01T11:30:00Z")}
+ (:last-seen watermark))))))
+
+(deftest flush-watermark!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model1 {:provider "foo" :model-name "m1" :vector-dimensions 42}
+ model2 {:provider "foo" :model-name "m2" :vector-dimensions 42}
+ index1 (semantic.index-metadata/qualify-index (semantic.index/default-index model1) index-metadata)
+ index2 (semantic.index-metadata/qualify-index (semantic.index/default-index model2) index-metadata)
+ watermark {:last-poll (ts "2025-01-01T13:00:00Z")
+ :last-seen {:id "card_1"
+ :document_hash "bar"
+ :gated_at (ts "2025-01-01T12:45:00Z")}}]
+
+ (with-open [_ (open-tables! pgvector index-metadata)]
+
+ (let [id1
+ (semantic.index-metadata/record-new-index-table!
+ pgvector
+ index-metadata
+ index1)
+
+ id2
+ (semantic.index-metadata/record-new-index-table!
+ pgvector
+ index-metadata
+ index2)]
+
+ (semantic.gate/flush-watermark! pgvector index-metadata index2 watermark)
+
+ (let [indexer-records
+ (->> (jdbc/execute! pgvector
+ (-> {:select [:id
+ :indexer_last_poll
+ :indexer_last_seen
+ :indexer_last_seen_hash
+ :indexer_last_seen_id]
+ :from [(keyword (:metadata-table-name index-metadata))]}
+ (sql/format :quoted true))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ (sort-by :id))
+ [index1-meta index2-meta] indexer-records]
+ (is (= 2 (count indexer-records)))
+ (is (= {:id id1
+ :indexer_last_seen_id nil
+ :indexer_last_seen_hash nil
+ :indexer_last_poll nil
+ :indexer_last_seen nil}
+ index1-meta))
+ (is (=? {:id id2
+ :indexer_last_poll (:last-poll watermark)
+ :indexer_last_seen_id "card_1"
+ :indexer_last_seen_hash "bar"
+ :indexer_last_seen (:gated_at (:last-seen watermark))}
+ index2-meta)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/index_embedding_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/index_embedding_test.clj
new file mode 100644
index 00000000000..32c0ce34e1d
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/index_embedding_test.clj
@@ -0,0 +1,55 @@
+(ns metabase-enterprise.semantic-search.index-embedding-test
+ "Tests for things at the intersection of the index and embedding namespaces."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase.test :as mt]))
+
+(def ^:private test-provider "ai-service")
+(def ^:private test-short-model-name "short-model")
+(def ^:private test-long-model-name "some-really-really-really-really-really-long-model-name-that-will-exceed-the-limit")
+(def ^:private test-vector-dimensions 1024)
+(def ^:private pg-limit-error-pattern #"exceeds PostgreSQL limit")
+
+;; Postgres truncates indentifier names to 63 bytes (+ 1 byte for a terminating NULL). Ensure that errors are thrown
+;; if a resource name would exceed the limit for any embedding provider + model combination.
+(deftest ^:parallel index-embedding-name-length-test
+ (mt/with-premium-features #{:semantic-search}
+ (testing "Throws if index name would be longer than the 63 byte Postgres limit"
+ (doseq [name-func [#'semantic.index/hnsw-index-name
+ #'semantic.index/fts-index-name
+ #'semantic.index/fts-native-index-name]]
+ (testing (str name-func)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ pg-limit-error-pattern
+ (-> {:provider test-provider
+ :model-name test-long-model-name
+ :vector-dimensions test-vector-dimensions}
+ semantic.index/default-index))))))
+ (testing "Succeeds if index name would be less than the 63 byte Postgres limit"
+ (let [index (-> {:provider test-provider
+ :model-name test-short-model-name
+ :vector-dimensions test-vector-dimensions}
+ semantic.index/default-index)]
+ (doseq [name-func [#'semantic.index/hnsw-index-name
+ #'semantic.index/fts-index-name
+ #'semantic.index/fts-native-index-name]]
+ (testing (str name-func)
+ (is (string? (name-func index)))
+ (is (< (count (name-func index)) 64))))))))
+
+(deftest ^:parallel table-name-length-test
+ (mt/with-premium-features #{:semantic-search}
+ (testing "Throws if table name exceeds 63 byte Postgres limit"
+ (let [embedding-model {:provider test-provider
+ :model-name test-long-model-name
+ :vector-dimensions test-vector-dimensions}]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Table name exceeds PostgreSQL limit"
+ (semantic.index/model-table-name embedding-model)))))
+ (testing "Succeeds if table name would be less than the 63 byte Postgres limit"
+ (let [embedding-model {:provider test-provider
+ :model-name test-short-model-name
+ :vector-dimensions test-vector-dimensions}]
+ (is (string? (semantic.index/model-table-name embedding-model)))
+ (is (< (count (semantic.index/model-table-name embedding-model)) 64))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/index_metadata_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/index_metadata_test.clj
new file mode 100644
index 00000000000..e179cd9ff9c
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/index_metadata_test.clj
@@ -0,0 +1,214 @@
+(ns metabase-enterprise.semantic-search.index-metadata-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.util :as u]))
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+;; NOTE: isolation tests are absent, in prod there is only one index-metadata
+
+(deftest qualify-index-test
+ (let [sut semantic.index-metadata/qualify-index]
+ (testing "default qualifier sanity"
+ (is (= "%s" (:index-table-qualifier semantic.index-metadata/default-index-metadata))))
+ (testing "qualify-index applies table qualifier to index map"
+ (is (= {:table-name "foo_bar_baz"} (sut {:table-name "bar"} {:index-table-qualifier "foo_%s_baz"})))
+ (is (= {:table-name "bar"} (sut {:table-name "bar"} {:index-table-qualifier "%s"})))
+ (testing "qualifier applies to derived index names"
+ (is (= "foo_bar_embed_hnsw_idx" (-> (sut {:table-name "bar"} {:index-table-qualifier "foo_%s"})
+ semantic.index/hnsw-index-name)))))))
+
+(deftest create-tables-if-not-exists!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ ;; could use open-tables here but I chose to be explicit
+ sut #(semantic.tu/closeable
+ (semantic.index-metadata/create-tables-if-not-exists! %1 %2)
+ (fn [_] (semantic.index-metadata/drop-tables-if-exists! %1 %2)))]
+ (testing "creates metadata and control tables when they don't exist"
+ (with-open [_ (sut pgvector index-metadata)]
+ (is (semantic.tu/table-exists-in-db? (:metadata-table-name index-metadata)))
+ (is (semantic.tu/table-exists-in-db? (:control-table-name index-metadata)))
+ (is (semantic.tu/table-exists-in-db? (:gate-table-name index-metadata)))))
+ (testing "is idempotent when tables already exist"
+ (with-open [_ (sut pgvector index-metadata)]
+ (let [table-names-snap (semantic.tu/get-table-names pgvector)
+ _ (sut pgvector index-metadata)]
+ (is (= table-names-snap (semantic.tu/get-table-names pgvector))))))))
+
+(defn- open-tables! [pgvector index-metadata]
+ (semantic.tu/closeable
+ (semantic.index-metadata/create-tables-if-not-exists! pgvector index-metadata)
+ (fn [_] (semantic.tu/cleanup-index-metadata! pgvector index-metadata))))
+
+(deftest drop-tables-if-exists!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ sut semantic.index-metadata/drop-tables-if-exists!]
+ (with-open [_ (open-tables! pgvector index-metadata)]
+ (let [table-names-snap (semantic.tu/get-table-names pgvector)
+ _ (sut pgvector index-metadata)
+ now-expected (remove (hash-set (:control-table-name index-metadata)
+ (:metadata-table-name index-metadata)
+ (:gate-table-name index-metadata))
+ table-names-snap)]
+ (is (= now-expected (semantic.tu/get-table-names pgvector)))))))
+
+(deftest ensure-control-row-exists!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ sut semantic.index-metadata/ensure-control-row-exists!]
+ (with-open [_ (open-tables! pgvector index-metadata)]
+ (testing "creates singleton control row with id=0"
+ (is (= [] (semantic.tu/get-control-rows pgvector index-metadata)) "should be empty at start")
+ (sut pgvector index-metadata)
+ (is (= [{:id 0, :version (:version index-metadata), :active_id nil, :active_updated_at nil}]
+ (semantic.tu/get-control-rows pgvector index-metadata))))
+ (testing "is idempotent - doesn't create duplicate rows"
+ (let [control-snap (semantic.tu/get-control-rows pgvector index-metadata)]
+ (sut pgvector index-metadata)
+ (is (= control-snap (semantic.tu/get-control-rows pgvector index-metadata))))))))
+
+(deftest activate-index!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ un-index (semantic.index/default-index semantic.tu/mock-embedding-model)
+ index1 (semantic.index-metadata/qualify-index (assoc un-index :table-name "i1") index-metadata)
+ index2 (semantic.index-metadata/qualify-index (assoc un-index :table-name "i2") index-metadata)
+ sut semantic.index-metadata/activate-index!]
+ (with-open [_ (open-tables! pgvector index-metadata)]
+ (let [index-id1 (semantic.index-metadata/record-new-index-table! pgvector index-metadata index1)
+ index-id2 (semantic.index-metadata/record-new-index-table! pgvector index-metadata index2)]
+ (testing "does nothing if no control row"
+ ;; note: I might recommend this to throw if no control row, this behaviour is ok for now
+ (sut pgvector index-metadata index-id1)
+ (is (= [] (semantic.tu/get-control-rows pgvector index-metadata))))
+
+ (semantic.index-metadata/ensure-control-row-exists! pgvector index-metadata)
+
+ (testing "sets specified index as active"
+ (sut pgvector index-metadata index-id1)
+ (is (=? [{:active_id index-id1}] (semantic.tu/get-control-rows pgvector index-metadata)))
+ (testing "switch again"
+ (sut pgvector index-metadata index-id2)
+ (is (=? [{:active_id index-id2}] (semantic.tu/get-control-rows pgvector index-metadata)))))))))
+
+(deftest get-active-index-state-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ un-index (semantic.index/default-index semantic.tu/mock-embedding-model)
+ index (semantic.index-metadata/qualify-index un-index index-metadata)
+ sut semantic.index-metadata/get-active-index-state]
+ (with-open [_ (open-tables! pgvector index-metadata)]
+ (semantic.index-metadata/ensure-control-row-exists! pgvector index-metadata)
+ (testing "by default there is no active index"
+ (is (nil? (sut pgvector index-metadata))))
+ (testing "returns active index configuration when one is set"
+ (let [index-id (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)]
+ (semantic.index-metadata/activate-index! pgvector index-metadata index-id)
+ (is (=? [{:active_id index-id}] (semantic.tu/get-control-rows pgvector index-metadata)))
+ (is (=? {:index index
+ :metadata-row (first (semantic.tu/get-metadata-rows pgvector index-metadata))}
+ (sut pgvector index-metadata))))))))
+
+(defn- default-index [embedding-model index-metadata]
+ (-> (semantic.index/default-index embedding-model)
+ (semantic.index-metadata/qualify-index index-metadata)))
+
+(defn- add-index! [pgvector index-metadata embedding-model]
+ (let [index (default-index embedding-model index-metadata)]
+ (semantic.index/create-index-table-if-not-exists! pgvector index)
+ {:index index
+ :index-id (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)}))
+
+(defn- setup-scenario! [pgvector index-metadata {:keys [active inactive]}]
+ (semantic.index-metadata/ensure-control-row-exists! pgvector index-metadata)
+ (when active
+ (let [{:keys [index-id]} (add-index! pgvector index-metadata active)]
+ (semantic.index-metadata/activate-index! pgvector index-metadata index-id)))
+ (run! #(add-index! pgvector index-metadata %) inactive))
+
+(deftest find-best-index!-test
+ (let [pgvector semantic.tu/db
+ embedding-model1 semantic.tu/mock-embedding-model
+ embedding-model2 (assoc semantic.tu/mock-embedding-model
+ :model-name "mock2")
+ sut semantic.index-metadata/find-best-index!
+ ;; warning: the setup-scenario can currently only set up a happy path
+ ;; other variables include:
+ ;; - table not existing
+ ;; - metadata not existing
+ ;; - duplicate indexes with different table names
+ ;; in practice early on these are not likely to be major concerns, so letting them slide for now
+ scenarios [{:desc "no metadata"}
+ {:desc "single active model, happy path"
+ :active embedding-model1}
+ {:desc "single active model, happy path, model 2"
+ :active embedding-model2}
+ {:desc "active + inactive models"
+ :active embedding-model2
+ :inactive [embedding-model1]}
+ {:desc "multiple inactive models"
+ :inactive [embedding-model1
+ embedding-model2]}]
+ all-models [embedding-model1 embedding-model2]]
+ (doseq [{:keys [desc active inactive] :as scenario} scenarios
+ :let [index-metadata (semantic.tu/unique-index-metadata)
+ index' #(default-index % index-metadata)
+ sut' #(sut pgvector index-metadata %)]]
+ (testing (str "scenario: " desc)
+ (with-open [_ (open-tables! pgvector index-metadata)]
+ (setup-scenario! pgvector index-metadata scenario)
+ (let [metadata-rows (semantic.tu/get-metadata-rows pgvector index-metadata)
+ model-name->row (u/index-by :model_name metadata-rows)
+ model-row (comp model-name->row :model-name)]
+ (doseq [model all-models
+ :let [is-active (= model active)
+ is-inactive (some #{model} inactive)]]
+ (cond
+ is-active
+ (testing "is already active"
+ (is (= {:index (index' model)
+ :index-table-exists true
+ :metadata-row (model-row model)
+ :active true}
+ (sut' model))))
+ is-inactive
+ (testing "is inactive"
+ (is (= {:index (index' model)
+ :index-table-exists true
+ :metadata-row (model-row model)
+ :active false}
+ (sut' model))))
+ :else
+ (testing "no metadata"
+ (is (= {:index (index' model)
+ :index-table-exists false
+ :active false}
+ (sut' model))))))))))))
+
+(deftest record-new-index-table!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ embedding-model semantic.tu/mock-embedding-model
+ index (default-index embedding-model index-metadata)
+ sut semantic.index-metadata/record-new-index-table!]
+ (with-open [_ (open-tables! pgvector index-metadata)]
+ (testing "empty to start"
+ (is (= [] (semantic.tu/get-metadata-rows pgvector index-metadata))))
+ (testing "records index metadata and returns assigned ID"
+ (let [index-id (sut pgvector index-metadata index)]
+ (is (int? index-id))
+ (is (=? [{:id index-id
+ :provider (:provider embedding-model)
+ :model_name (:model-name embedding-model)
+ :vector_dimensions (:vector-dimensions embedding-model)
+ :table_name (:table-name index)
+ :index_version (:version index)}]
+ (semantic.tu/get-metadata-rows pgvector index-metadata)))))
+
+ (testing "enforces unique table-name constraint"
+ (is (thrown-with-msg? Exception #"duplicate key" (sut pgvector index-metadata index)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj
new file mode 100644
index 00000000000..5dc94bf6564
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj
@@ -0,0 +1,561 @@
+(ns metabase-enterprise.semantic-search.index-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.embedding :as semantic.embedding]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.analytics.core :as analytics]
+ [metabase.api.common :as api]
+ [metabase.collections.models.collection :as collection]
+ [metabase.models.interface :as mi]
+ [metabase.test :as mt]
+ [metabase.util :as u]))
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+(deftest create-index-table!-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [index-ref (semantic.tu/open-temp-index!)]
+ ;; open-temp-index-table! creates the temp table, so drop it in order to test create!.
+ (semantic.index/drop-index-table! semantic.tu/db semantic.tu/mock-index)
+ (testing "index table is not present before create!"
+ (is (not (semantic.tu/table-exists-in-db? (:table-name @index-ref))))
+ (is (not (semantic.tu/table-has-index? (:table-name @index-ref) (semantic.index/hnsw-index-name @index-ref))))
+ (is (not (semantic.tu/table-has-index? (:table-name @index-ref) (semantic.index/fts-index-name @index-ref))))
+ (is (not (semantic.tu/table-has-index? (:table-name @index-ref) (semantic.index/fts-native-index-name @index-ref)))))
+ (testing "index table is present after create!"
+ (semantic.index/create-index-table-if-not-exists! semantic.tu/db semantic.tu/mock-index {:force-reset? false})
+ (is (semantic.tu/table-exists-in-db? (:table-name @index-ref)))
+ (is (semantic.tu/table-has-index? (:table-name @index-ref) (semantic.index/hnsw-index-name @index-ref)))
+ (is (semantic.tu/table-has-index? (:table-name @index-ref) (semantic.index/fts-index-name @index-ref)))
+ (is (semantic.tu/table-has-index? (:table-name @index-ref) (semantic.index/fts-native-index-name @index-ref)))))))
+
+(deftest drop-index-table!-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [index-ref (semantic.tu/open-temp-index!)]
+ (testing "index table is present before drop!"
+ (is (semantic.tu/table-exists-in-db? (:table-name @index-ref))))
+ (testing "index table is not present after drop!"
+ (semantic.index/drop-index-table! semantic.tu/db semantic.tu/mock-index)
+ (is (not (semantic.tu/table-exists-in-db? (:table-name @index-ref))))))))
+
+(deftest upsert-index!-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (semantic.tu/check-index-has-no-mock-docs)
+ (testing "upsert-index! returns nil if you pass it an empty collection"
+ (is (nil? (semantic.tu/upsert-index! [])))
+ (semantic.tu/check-index-has-no-mock-docs))
+ (testing "upsert-index! works on a fresh index"
+ (is (= {"card" 1, "dashboard" 1}
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents))))
+ (semantic.tu/check-index-has-mock-docs))
+ (testing "upsert-index! works with duplicate documents"
+ (is (= {"card" 1, "dashboard" 1}
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents))))
+ (semantic.tu/check-index-has-mock-docs)))))
+
+(deftest upsert-index!-tsvectors-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (semantic.tu/check-index-has-no-mock-docs)
+ (testing "upsert-index! works on a fresh index"
+ (is (= {"card" 1, "dashboard" 1}
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents)))))
+ (testing "indexed cards have text search vectors populated"
+ (is (=? [{:model "card"
+ :model_id "123"
+ :creator_id 1
+ :content "Dog Training Guide"
+ :text_search_vector #(and (str/includes? % "dog")
+ (str/includes? % "train"))
+ :text_search_with_native_query_vector #(and (str/includes? % "dog")
+ (str/includes? % "train")
+ (str/includes? % "select")
+ (str/includes? % "breed")
+ (str/includes? % "trick"))}]
+ (semantic.tu/query-tsvectors {:model "card", :model_id "123"}))))
+ (let [result (semantic.tu/query-tsvectors {:model "dashboard", :model_id "456"})
+ valid-tsvector? (every-pred string? seq)]
+ (testing "indexed dashboards have text search vectors populated"
+ (is (=? [{:model "dashboard"
+ :model_id "456"
+ :creator_id 2
+ :content "Elephant Migration"
+ :text_search_vector valid-tsvector?
+ :text_search_with_native_query_vector valid-tsvector?}]
+ result)))
+ (testing "both tsvectors are equal for models with no native query"
+ (is (= (:text_search_vector result)
+ (:text_search_with_native_query_vector result))))))))
+
+(deftest delete-from-index!-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (semantic.tu/check-index-has-no-mock-docs)
+ (testing "upsert-index! before delete!"
+ (is (= {"card" 1, "dashboard" 1}
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents))))
+ (semantic.tu/check-index-has-mock-docs))
+ (testing "delete-from-index! returns nil if you pass it an empty collection"
+ (is (nil? (semantic.tu/delete-from-index! "card" [])))
+ (semantic.tu/check-index-has-mock-docs))
+ (testing "delete-from-index! works for cards"
+ (is (= {"card" 1}
+ (semantic.tu/delete-from-index! "card" ["123"])))
+ (semantic.tu/check-index-has-no-mock-card)
+ (semantic.tu/check-index-has-mock-dashboard))
+ (testing "delete-from-index! works for dashboards"
+ (is (= {"dashboard" 1}
+ (semantic.tu/delete-from-index! "dashboard" ["456"])))
+ (semantic.tu/check-index-has-no-mock-docs))
+ (testing "delete-from-index! doesn't complain if you delete a document that doesn't exist"
+ (is (= {"card" 1}
+ (semantic.tu/delete-from-index! "card" ["123"])))
+ (semantic.tu/check-index-has-no-mock-docs)))))
+
+(deftest batch-process-mock-docs!-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (binding [semantic.index/*batch-size* 1]
+ (let [extra-ids (->> (range 1337 1347) (map str))
+ extra-docs (map (fn [id doc]
+ (assoc doc :id id))
+ extra-ids
+ (flatten (repeat (semantic.tu/mock-documents))))
+ mock-docs (into (semantic.tu/mock-documents) extra-docs)]
+ (testing "ensure upsert! and delete! work when batch size is exceeded"
+ (semantic.tu/check-index-has-no-mock-docs)
+ (testing "upsert-index! with batch processing"
+ (is (= {"card" 6, "dashboard" 6}
+ (semantic.tu/upsert-index! mock-docs)))
+ (semantic.tu/check-index-has-mock-docs))
+ (testing "delete-from-index! with batch processing"
+ (testing "delete just the card"
+ (is (= {"card" 11}
+ (semantic.tu/delete-from-index! "card" (into ["123"] extra-ids))))
+ (semantic.tu/check-index-has-no-mock-card)
+ (semantic.tu/check-index-has-mock-dashboard)))
+ (testing "delete the dashboard"
+ (is (= {"dashboard" 11}
+ (semantic.tu/delete-from-index! "dashboard" (into ["456"] extra-ids))))
+ (semantic.tu/check-index-has-no-mock-docs))))))))
+
+(defn- only-first-call [r f]
+ (let [is-first (atom true)]
+ (fn [& args]
+ (when @is-first
+ (is (= @r semantic.index/*batch-size*))
+ (reset! is-first false)
+ (apply f args)))))
+
+(deftest reducible-is-respected-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (binding [semantic.index/*batch-size* 2]
+ (let [docs (semantic.tu/mock-documents)
+ realized (atom 0)
+ mock-docs (eduction (comp (map str)
+ (map (fn [id]
+ (swap! realized inc)
+ (assoc (first docs) :id id))))
+ (range 123 500))]
+
+ (testing "ensure upsert! and delete! don't realize the full reducible at once"
+ (semantic.tu/check-index-has-no-mock-docs)
+
+ (testing "upsert-index!"
+ (with-redefs [semantic.index/upsert-index-pooled! (only-first-call realized @#'semantic.index/upsert-index-pooled!)]
+ (is (= {"card" 2} (semantic.tu/upsert-index! mock-docs))))
+ (semantic.tu/check-index-has-mock-card))
+
+ (reset! realized 0)
+ (testing "delete-from-index!"
+ (with-redefs [semantic.index/delete-from-index-batch-sql (only-first-call realized @#'semantic.index/delete-from-index-batch-sql)]
+ (is (= {"card" 2} (semantic.tu/delete-from-index! "card" (eduction (map :id) mock-docs)))))
+ (semantic.tu/check-index-has-no-mock-docs))))))))
+
+(defn- track-concurrency
+ [max-concurrent f]
+ (let [current-concurrent (atom 0)]
+ (fn [& args]
+ (swap! current-concurrent inc)
+ (swap! max-concurrent (fn [m] (max m @current-concurrent)))
+ (try
+ (apply f args)
+ (finally
+ (swap! current-concurrent dec))))))
+
+(deftest upsert-index-concurrent-batch-processing-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (testing "ensure upsert! batch processing is concurrent update to index-update-thread-count"
+ (binding [semantic.index/*batch-size* 2]
+ (let [max-concurrent (atom 0)
+ update-fn @#'semantic.index/upsert-index-batch!
+ docs (take 100 (map-indexed (fn [i doc] (assoc doc :id (str i)))
+ (cycle (semantic.tu/mock-documents))))]
+ (with-redefs [semantic.index/upsert-index-batch! (track-concurrency
+ max-concurrent
+ (fn [& args] (apply update-fn args)))]
+ (semantic.tu/check-index-has-no-mock-docs)
+ (is (= {"card" 50, "dashboard" 50}
+ (semantic.tu/upsert-index! docs)))
+ (is (= 2 @max-concurrent) "Expected up to 2 concurrent batches"))))))))
+
+(deftest upsert-index-batched-embeddings-pairing-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (testing "Documents with different searchable texts get associated with their correct embeddings"
+ (let [test-documents [{:model "card"
+ :id "1"
+ :name "Dog Training Guide"
+ :searchable_text "Dog Training Guide"
+ :creator_id 1
+ :legacy_input {:model "card" :id "1"}
+ :metadata {}}
+ {:model "card"
+ :id "2"
+ :name "Elephant Migration"
+ :searchable_text "Elephant Migration"
+ :creator_id 2
+ :legacy_input {:model "card" :id "2"}
+ :metadata {}}
+ {:model "card"
+ :id "3"
+ :name "Tiger Conservation"
+ :searchable_text "Tiger Conservation"
+ :creator_id 3
+ :legacy_input {:model "card" :id "3"}
+ :metadata {}}]]
+ ;; Each embedding should be processed separately
+ (mt/with-temporary-setting-values [openai-max-tokens-per-batch 3]
+ (binding [semantic.index/*batch-size* 1]
+ (semantic.tu/upsert-index! test-documents)
+ ;; Verify each document has its own correct embedding
+ (is (= [{:model "card" :model_id "1" :creator_id 1
+ :content "Dog Training Guide"
+ :embedding (semantic.tu/get-mock-embedding "Dog Training Guide")}]
+ (semantic.tu/query-embeddings {:model "card" :model_id "1"})))
+
+ (is (= [{:model "card" :model_id "2" :creator_id 2
+ :content "Elephant Migration"
+ :embedding (semantic.tu/get-mock-embedding "Elephant Migration")}]
+ (semantic.tu/query-embeddings {:model "card" :model_id "2"})))
+
+ (is (= [{:model "card" :model_id "3" :creator_id 3
+ :content "Tiger Conservation"
+ :embedding (semantic.tu/get-mock-embedding "Tiger Conservation")}]
+ (semantic.tu/query-embeddings {:model "card" :model_id "3"}))))))))))
+
+(defn- embedding-reuse-with-batch-size! [batch-size & {:keys [inter-batch? serial?]}]
+ (let [test-documents [{:model "card"
+ :id "1"
+ :name "Dog Training Guide"
+ :searchable_text "Dog Training Guide"
+ :creator_id 1
+ :legacy_input {:model "card" :id "1"}
+ :metadata {}}
+ {:model "card"
+ :id "2"
+ :name "Elephant Migration"
+ :searchable_text "Elephant Migration"
+ :creator_id 2
+ :legacy_input {:model "card" :id "2"}
+ :metadata {}}
+ {:model "card"
+ :id "3"
+ :name "Dog Training Guide"
+ :searchable_text "Dog Training Guide"
+ :creator_id 3
+ :legacy_input {:model "card" :id "3"}
+ :metadata {}}]]
+ (binding [semantic.index/*batch-size* batch-size]
+ (let [{:keys [calls proxy]} (semantic.tu/spy semantic.embedding/process-embeddings-streaming)
+ inter-batch-cache-hit? (atom false)]
+ (with-redefs [semantic.embedding/process-embeddings-streaming proxy
+ semantic.index/partition-existing-embeddings
+ (let [orig @#'semantic.index/partition-existing-embeddings]
+ (fn [& args]
+ (let [ret (apply orig args)]
+ (when (seq (second ret))
+ (reset! inter-batch-cache-hit? true))
+ ret)))]
+ (semantic.tu/upsert-index! test-documents :serial? serial?))
+ (is (= inter-batch? @inter-batch-cache-hit?))
+ (is (= 1 (count @calls)))
+ (is (= ["Dog Training Guide" "Elephant Migration"]
+ (second (:args (first @calls))))))
+ (is (= [{:model "card" :model_id "1" :creator_id 1
+ :content "Dog Training Guide"
+ :embedding (semantic.tu/get-mock-embedding "Dog Training Guide")}]
+ (semantic.tu/query-embeddings {:model "card" :model_id "1"})))
+
+ (is (= [{:model "card" :model_id "2" :creator_id 2
+ :content "Elephant Migration"
+ :embedding (semantic.tu/get-mock-embedding "Elephant Migration")}]
+ (semantic.tu/query-embeddings {:model "card" :model_id "2"})))
+
+ (is (= [{:model "card" :model_id "3" :creator_id 3
+ :content "Dog Training Guide"
+ :embedding (semantic.tu/get-mock-embedding "Dog Training Guide")}]
+ (semantic.tu/query-embeddings {:model "card" :model_id "3"}))))))
+
+(deftest upsert-index-embeddings-caching-test
+ (mt/with-premium-features #{:semantic-search}
+ (testing "Documents with identical searchable texts lead to cached embedding"
+ (testing "via intra-batch deduping"
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (embedding-reuse-with-batch-size! 3 :inter-batch? false)))
+ (testing "via inter-batch caching"
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ ;; Ensure batches are processed serially -- concurrent batches don't support inter-batch caching.
+ (embedding-reuse-with-batch-size! 2 :inter-batch? true :serial? true))))))
+
+(deftest prometheus-metrics-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (mt/with-prometheus-system! [_ system]
+ (testing "semantic-index-size starts at zero"
+ (is (= 0.0 (mt/metric-value system :metabase-search/semantic-index-size))))
+ (testing "semantic-index-size is updated after upsert-index! on empty db"
+ (is (= {"card" 1, "dashboard" 1}
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents))))
+ (is (= 2.0 (mt/metric-value system :metabase-search/semantic-index-size))))
+ (testing "semantic-index-size is updated after delete-from-index!"
+ (is (= {"card" 1}
+ (semantic.tu/delete-from-index! "card" ["123"])))
+ (is (= 1.0 (mt/metric-value system :metabase-search/semantic-index-size))))
+ (testing "semantic-index-size is updated after upsert-index! on populated db"
+ (is (= {"card" 1, "dashboard" 1}
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents))))
+ (is (= 2.0 (mt/metric-value system :metabase-search/semantic-index-size))))))))
+
+(deftest ^:syncronized semantic-search-analytics-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (semantic.tu/upsert-index! (semantic.tu/mock-documents))
+ (testing "Analytics metrics are recorded for semantic search operations"
+ (let [analytics-calls (atom [])]
+ (mt/with-dynamic-fn-redefs [analytics/inc! (fn [metric & args]
+ (swap! analytics-calls conj [metric args]))]
+ (testing "Permission filtering metrics"
+ (reset! analytics-calls [])
+ (mt/with-test-user :crowberto
+ (semantic.index/query-index semantic.tu/db semantic.tu/mock-index
+ {:search-string "dog training"}))
+
+ (let [permission-calls (filter #(= :metabase-search/permission-filtering-ms (first %)) @analytics-calls)]
+ (is (= 1 (count permission-calls)))
+ (let [time-ms (first (second (first permission-calls)))]
+ (is (number? time-ms))
+ (is (< time-ms 1000) "Permission filtering should complete within 1000ms"))))
+
+ (testing "Semantic search timing metrics"
+ (reset! analytics-calls [])
+ (mt/with-test-user :crowberto
+ (semantic.index/query-index semantic.tu/db semantic.tu/mock-index
+ {:search-string "elephant migration"}))
+
+ (let [metric-names (set (map first @analytics-calls))]
+ (is (contains? metric-names :metabase-search/semantic-search-ms))
+ (is (contains? metric-names :metabase-search/semantic-embedding-ms))
+ (is (contains? metric-names :metabase-search/semantic-db-query-ms))
+ (is (contains? metric-names :metabase-search/permission-filtering-ms)))
+
+ (testing "timing values are reasonable"
+ (doseq [[metric args] @analytics-calls
+ :when (#{:metabase-search/semantic-search-ms
+ :metabase-search/semantic-embedding-ms
+ :metabase-search/semantic-db-query-ms
+ :metabase-search/permission-filtering-ms} metric)]
+ (let [time-ms (if (= metric :metabase-search/permission-filtering-ms)
+ (first args)
+ (second args))]
+ (is (number? time-ms) (str "Time for " metric " should be numeric"))
+ (is (>= time-ms 0) (str "Time for " metric " should be non-negative"))
+ (is (< time-ms 1000) (str "Time for " metric " should be under 1000ms")))))
+
+ (let [embedding-metrics (filter #(#{:metabase-search/semantic-search-ms
+ :metabase-search/semantic-embedding-ms
+ :metabase-search/semantic-db-query-ms} (first %)) @analytics-calls)]
+ (doseq [[_ args] embedding-metrics]
+ (let [labels (first args)]
+ (is (map? labels) "Should have labels map")
+ (is (contains? labels :embedding-model) "Should include embedding-model label")))))))))))
+
+(deftest filter-by-collection-test
+ (testing "filter-by-collection function filters documents based on personal collection preferences"
+ (let [user1-id (mt/user->id :rasta)
+ user2-id (mt/user->id :crowberto)
+ user1-personal-coll-id (u/the-id (collection/user->personal-collection user1-id))
+ user2-personal-coll-id (u/the-id (collection/user->personal-collection user2-id))]
+ (mt/with-temp
+ [:model/Collection {shared-coll-id :id} {:name "Shared Collection"}
+ :model/Collection {user1-sub-coll-id :id} {:location (str "/" user1-personal-coll-id "/") :name "User1 Sub"}
+ :model/Collection {user2-sub-coll-id :id} {:location (str "/" user2-personal-coll-id "/") :name "User2 Sub"}]
+
+ (let [docs [{:id "doc1" :model "card" :collection_id user1-personal-coll-id}
+ {:id "doc2" :model "card" :collection_id user2-personal-coll-id}
+ {:id "doc3" :model "card" :collection_id shared-coll-id}
+ {:id "doc4" :model "card" :collection_id nil}
+ {:id "doc5" :model "card" :collection_id user1-sub-coll-id}
+ {:id "doc6" :model "card" :collection_id user2-sub-coll-id}]]
+
+ (testing "filter-type 'all' returns all documents unchanged"
+ (let [context {:filter-items-in-personal-collection "all" :current-user-id user1-id}
+ result (#'semantic.index/filter-by-collection docs context)]
+ (is (= 6 (count result)))
+ (is (= (set (map :id docs)) (set (map :id result))))))
+
+ (testing "filter-type nil defaults to 'all' behavior"
+ (let [context {:filter-items-in-personal-collection nil :current-user-id user1-id}
+ result (#'semantic.index/filter-by-collection docs context)]
+ (is (= 6 (count result)))
+ (is (= (set (map :id docs)) (set (map :id result))))))
+
+ (testing "filter-type 'only-mine' returns only current user's personal collection items"
+ (let [context {:filter-items-in-personal-collection "only-mine" :current-user-id user1-id}
+ result (#'semantic.index/filter-by-collection docs context)
+ result-ids (set (map :id result))]
+ (is (= #{"doc1" "doc5"} result-ids))))
+
+ (testing "filter-type 'only' returns all personal collection items (any user)"
+ (let [context {:filter-items-in-personal-collection "only" :current-user-id user1-id}
+ result (#'semantic.index/filter-by-collection docs context)
+ result-ids (set (map :id result))]
+ (is (= #{"doc1" "doc2" "doc5" "doc6"} result-ids))))
+
+ (testing "filter-type 'exclude' returns only shared and uncollected items"
+ (let [context {:filter-items-in-personal-collection "exclude" :current-user-id user1-id}
+ result (#'semantic.index/filter-by-collection docs context)
+ result-ids (set (map :id result))]
+ (is (= #{"doc3" "doc4"} result-ids))))
+
+ (testing "filter-type 'exclude-others' returns user's personal items plus shared/uncollected items"
+ (let [context {:filter-items-in-personal-collection "exclude-others" :current-user-id user1-id}
+ result (#'semantic.index/filter-by-collection docs context)
+ result-ids (set (map :id result))]
+ (is (= #{"doc1" "doc3" "doc4" "doc5"} result-ids)))))))))
+
+(deftest filter-can-read-indexed-entity-test
+ (mt/with-premium-features #{:semantic-search}
+ (testing "filter-can-read-indexed-entity function"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card model-1 (assoc (mt/card-with-source-metadata-for-query
+ (mt/mbql-query products {:fields [$id $title]
+ :limit 1}))
+ :type "model"
+ :name "Readable Model"
+ :database_id (mt/id)
+ :collection_id coll-id)
+ :model/Card model-2 (assoc (mt/card-with-source-metadata-for-query
+ (mt/mbql-query products {:fields [$id $title]
+ :limit 1}))
+ :type "model"
+ :name "Unreadable Model"
+ :database_id (mt/id)
+ :collection_id coll-id)
+ :model/ModelIndex model-index-1 {:model_id (:id model-1)
+ :pk_ref (mt/$ids :products $id)
+ :value_ref (mt/$ids :products $title)
+ :schedule "0 0 0 * * *"
+ :state "initial"
+ :creator_id (mt/user->id :rasta)}
+ :model/ModelIndex model-index-2 {:model_id (:id model-2)
+ :pk_ref (mt/$ids :products $id)
+ :value_ref (mt/$ids :products $title)
+ :schedule "0 0 0 * * *"
+ :state "initial"
+ :creator_id (mt/user->id :rasta)}]
+ (let [indexed-entity-docs [{:id (str (:id model-index-1) ":123")
+ :model "indexed-entity"
+ :content "Test Entity 1"}
+ {:id (str (:id model-index-2) ":456")
+ :model "indexed-entity"
+ :content "Test Entity 2"}
+ {:id "invalid:789"
+ :model "indexed-entity"
+ :content "Invalid Entity"}]]
+
+ (testing "returns all entities when user can read all parent cards"
+ (binding [api/*current-user-permissions-set* (atom #{"/"})]
+ (let [result (#'semantic.index/filter-can-read-indexed-entity indexed-entity-docs)]
+ (is (= 2 (count result)))
+ (is (= #{(str (:id model-index-1) ":123") (str (:id model-index-2) ":456")}
+ (set (map :id result)))))))
+
+ (testing "returns no entities when user cannot read any parent cards"
+ (binding [api/*current-user-permissions-set* (atom #{})]
+ (let [result (#'semantic.index/filter-can-read-indexed-entity indexed-entity-docs)]
+ (is (= 0 (count result))))))
+
+ (testing "returns subset when user can read some parent cards"
+ (with-redefs [mi/can-read? (fn [card] (= (:id card) (:id model-1)))]
+ (let [result (#'semantic.index/filter-can-read-indexed-entity indexed-entity-docs)]
+ (is (= 1 (count result)))
+ (is (= (str (:id model-index-1) ":123") (:id (first result)))))))
+
+ (testing "handles empty input"
+ (is (= [] (#'semantic.index/filter-can-read-indexed-entity []))))
+
+ (testing "handles invalid entity IDs"
+ (let [invalid-only-docs [{:id "invalid:789" :model "indexed-entity" :content "Invalid"}]]
+ (is (= [] (#'semantic.index/filter-can-read-indexed-entity invalid-only-docs)))))
+
+ (testing "handles non-existent model indexes"
+ (let [non-existent-docs [{:id "99999:123" :model "indexed-entity" :content "Non-existent"}]]
+ (is (= [] (#'semantic.index/filter-can-read-indexed-entity non-existent-docs))))))))))
+
+(deftest indexed-entity-collapse-id-test
+ (mt/with-premium-features #{:semantic-search}
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card model-1 (assoc (mt/card-with-source-metadata-for-query
+ (mt/mbql-query products {:fields [$id $title]
+ :limit 1}))
+ :type "model"
+ :name "Fish Tank Setup"
+ :database_id (mt/id)
+ :collection_id coll-id)
+ :model/ModelIndex model-index-1 {:model_id (:id model-1)
+ :pk_ref (mt/$ids :products $id)
+ :value_ref (mt/$ids :products $title)
+ :schedule "0 0 0 * * *"
+ :state "initial"
+ :creator_id (mt/user->id :rasta)}]
+ (let [docs [{:model "dataset"
+ :id (:id model-1)
+ :name (:name model-1)
+ :searchable_text (:name model-1)
+ :created_at #t "2025-01-01T12:00:00Z"
+ :creator_id (mt/user->id :crowberto)
+ :archived false
+ :collection_id coll-id
+ :legacy_input {:id (:id model-1)
+ :model "dataset"
+ :dataset_query (:dataset_query model-1)}
+ :metadata {:title (:name model-1)}}
+ {:id (str (:id model-index-1) ":1234")
+ :name "Antarctic wildlife"
+ :model "indexed-entity"
+ :archived false
+ :collection_id coll-id
+ :searchable_text "Antarctic wildlife"
+ :legacy_input {:id (str (:id model-index-1) ":1234")
+ :name "Antarctic wildlife"
+ :model "indexed-entity"}
+ :metadata {:title "Antarctic wildlife"}}]]
+ (with-open [_ (semantic.tu/open-temp-index!)]
+ (testing "indexed-entity can be inserted into index"
+ (is (=
+ {"indexed-entity" 1, "dataset" 1}
+ (semantic.tu/upsert-index! docs))))
+ (testing "indexed-entity has id collapsed"
+ (is (= {:id 1234
+ :name "Antarctic wildlife"
+ :model "indexed-entity"}
+ (mt/as-admin
+ (-> (semantic.tu/query-index {:search-string "Antarctic wildlife"})
+ first
+ (select-keys [:id :name :model])))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
new file mode 100644
index 00000000000..ddedf4a79c7
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
@@ -0,0 +1,425 @@
+(ns metabase-enterprise.semantic-search.indexer-test
+ (:require
+ [clojure.test :refer :all]
+ [honey.sql :as sql]
+ [metabase-enterprise.semantic-search.gate :as semantic.gate]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.indexer :as semantic.indexer]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.util :as u]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import (java.io Closeable)
+ (java.sql Timestamp)
+ (java.time Duration Instant)))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+(defn- open-metadata! ^Closeable [pgvector index-metadata]
+ (semantic.tu/closeable
+ (semantic.index-metadata/create-tables-if-not-exists! pgvector index-metadata)
+ (fn [_] (semantic.tu/cleanup-index-metadata! pgvector index-metadata))))
+
+(defn- open-index! ^Closeable [pgvector index]
+ (semantic.tu/closeable
+ (semantic.index/create-index-table-if-not-exists! pgvector index)
+ (fn [_] (semantic.index/drop-index-table! pgvector index))))
+
+(defn- get-metadata-row! [pgvector index-metadata index]
+ (jdbc/execute-one! pgvector
+ (sql/format {:select [:*]
+ :from [(keyword (:metadata-table-name index-metadata))]
+ :where [:= :table_name (:table-name index)]}
+ :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+
+(defn- ts ^Timestamp [s]
+ (Timestamp/from (Instant/parse s)))
+
+(deftest indexing-step-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ t1 (ts "2025-01-01T00:01:00Z")
+ t2 (ts "2025-01-02T00:03:10Z")
+ t3 (ts "2025-01-03T00:02:42Z")
+ c1 {:model "card" :id "1" :name "Poodle" :searchable_text "Dog Training Guide"}
+ c2 {:model "card" :id "2" :name "Pug" :searchable_text "Dog Training Guide 2"}
+ c3 {:model "card" :id "3" :name "Collie" :searchable_text "Dog Training Guide 3"}
+ version semantic.gate/search-doc->gate-doc
+ delete (fn [doc t] (semantic.gate/deleted-search-doc->gate-doc (:model doc) (:id doc) t))]
+ (with-open [_ (open-metadata! pgvector index-metadata)
+ _ (open-index! pgvector index)]
+ (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)
+
+ (let [metadata-row (get-metadata-row! pgvector index-metadata index)
+ initial-watermark (semantic.gate/resume-watermark metadata-row)
+ indexing-state (semantic.indexer/init-indexing-state metadata-row)
+ {poll-proxy :proxy poll-calls :calls} (semantic.tu/spy semantic.gate/poll)
+ {upsert-proxy :proxy upsert-calls :calls} (semantic.tu/spy semantic.index/upsert-index!)
+ {delete-proxy :proxy delete-calls :calls} (semantic.tu/spy semantic.index/delete-from-index!)
+ clear-spies (fn []
+ (reset! poll-calls [])
+ (reset! upsert-calls [])
+ (reset! delete-calls []))]
+
+ (is (= initial-watermark (:watermark @indexing-state)))
+
+ (testing "gate is empty, poll counts should be zero - and upsert/delete should not be called"
+ (with-redefs [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+ (is (= [] @upsert-calls))
+ (is (= [] @delete-calls))
+ (is (= 1 (count @poll-calls)))
+ (is (= 0 (:last-poll-count @indexing-state)))
+ (is (= 0 (:last-indexed-count @indexing-state)))
+
+ (testing "watermark has been updated"
+ (let [[{poll-result :ret}] @poll-calls]
+ (is (= (semantic.gate/next-watermark initial-watermark poll-result) (:watermark @indexing-state)))
+ (testing "watermark has been flushed to the metadata table"
+ (is (= (:watermark @indexing-state)
+ (semantic.gate/resume-watermark (get-metadata-row! pgvector index-metadata index)))))))))
+
+ (testing "add some data to the gate we should see upsert / delete be called"
+ (clear-spies)
+ (semantic.gate/gate-documents! pgvector index-metadata [(version c1 t1) (delete c2 t2)])
+ (with-redefs [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+ (is (= 1 (count @upsert-calls)))
+ (is (= 1 (count @delete-calls)))
+ (is (= 1 (count @poll-calls)))
+ (is (= 2 (:last-poll-count @indexing-state)))
+ (is (= 2 (:last-indexed-count @indexing-state)))
+
+ (testing "watermark has been updated"
+ (let [[{poll-result :ret}] @poll-calls]
+ (is (= (semantic.gate/next-watermark initial-watermark poll-result) (:watermark @indexing-state)))
+ (testing "watermark has been flushed to the metadata table"
+ (is (= (:watermark @indexing-state)
+ (semantic.gate/resume-watermark (get-metadata-row! pgvector index-metadata index)))))))))
+
+ (testing "stepping again with no new data does nothing"
+ (clear-spies)
+ (with-redefs [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+ (is (= 0 (count @upsert-calls)))
+ (is (= 0 (count @delete-calls)))
+ (is (= 1 (count @poll-calls)))
+ (is (= 2 (:last-poll-count @indexing-state)))
+ (is (= 0 (:last-indexed-count @indexing-state)))))
+
+ (testing "add some more data, picked up"
+ (clear-spies)
+ (semantic.gate/gate-documents! pgvector index-metadata [(version c2 t3)])
+ (with-redefs [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+ (is (= 1 (count @upsert-calls)))
+ (is (= 0 (count @delete-calls)))
+ (is (= 1 (count @poll-calls)))
+ (is (= 1 (:last-indexed-count @indexing-state)))))
+
+ (testing "exceptions during indexing are bubbled, and the watermark position is preserved"
+ (clear-spies)
+ (semantic.gate/gate-documents! pgvector index-metadata [(version c3 t3)])
+ (let [previous-state @indexing-state]
+ (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (Exception. "Boom")))
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
+ (is (thrown-with-msg? Exception #"Boom" (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)))
+ (is (= 0 (count @delete-calls)))
+ (is (= 1 (count @poll-calls)))
+ (testing "state/watermark was not updated"
+ (is (= previous-state @indexing-state)))))
+
+ (testing "exceptions are recovered from"
+ (clear-spies)
+ (with-redefs [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
+ (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
+ (is (= 1 (count @upsert-calls)))
+ (is (= 0 (count @delete-calls)))
+ (is (= 1 (count @poll-calls))))))))))
+
+;; todo not sure I like this cuteness
+(deftest on-indexing-idle-test
+ (testing "idle behavior based on novelty ratio"
+ (let [indexing-state (volatile! {:last-poll-count 100 :last-indexed-count 30})]
+
+ (testing "high novelty ratio (>25%) - no sleep"
+ (with-redefs [semantic.indexer/sleep (fn [ms] (throw (ex-info "Should not sleep" {:ms ms})))]
+ (is (nil? (semantic.indexer/on-indexing-idle indexing-state)))))
+
+ (testing "medium novelty ratio (10-25%) - small backoff"
+ (vswap! indexing-state assoc :last-indexed-count 15) ; 15% novelty
+ (let [sleep-called (atom nil)]
+ (with-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
+ (semantic.indexer/on-indexing-idle indexing-state)
+ (is (= 250 @sleep-called)))))
+
+ (testing "low novelty ratio (1-10%) - medium backoff"
+ (vswap! indexing-state assoc :last-indexed-count 5) ; 5% novelty
+ (let [sleep-called (atom nil)]
+ (with-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
+ (semantic.indexer/on-indexing-idle indexing-state)
+ (is (= 1500 @sleep-called)))))
+
+ (testing "very low novelty ratio (<1%) - big backoff"
+ (vswap! indexing-state assoc :last-indexed-count 0) ; 0% novelty
+ (let [sleep-called (atom nil)]
+ (with-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
+ (semantic.indexer/on-indexing-idle indexing-state)
+ (is (= 3000 @sleep-called))))))))
+
+(defn- open-loop-thread! ^Closeable [& loop-args]
+ (let [caught-ex (volatile! nil)]
+ (semantic.tu/closeable
+ {:caught-ex caught-ex
+ :thread
+ (doto (Thread.
+ ^Runnable
+ (bound-fn*
+ (fn []
+ (try
+ (apply semantic.indexer/indexing-loop loop-args)
+ (catch Throwable t
+ (vreset! caught-ex t))))))
+ (.setDaemon true)
+ (.start))}
+ (fn [{:keys [^Thread thread]}]
+ (when (.isAlive thread)
+ (.interrupt thread)
+ (when-not (.join thread (Duration/ofSeconds 30))
+ (log/fatal "Indexing loop thread not exiting during test!")))))))
+
+(deftest indexing-loop-thread-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ index semantic.tu/mock-index
+ metadata-row {:indexer_last_poll Instant/EPOCH
+ :indexer_last_seen Instant/EPOCH}
+ step-ex (volatile! nil) ; holds an exception to be thrown during the step function
+ indexing-state (semantic.indexer/init-indexing-state metadata-row)
+ call-counter (atom {:idle 0 :step 0})
+ wait-for-calls (fn []
+ (let [ocalls @call-counter
+ max-wait (+ (System/currentTimeMillis) 100)]
+ (loop []
+ (cond
+ (not= ocalls @call-counter) true
+ (< max-wait (System/currentTimeMillis)) false
+ :else (recur)))))
+ step-called (promise)
+ idle-called (promise)]
+
+ (with-redefs [semantic.indexer/on-indexing-idle (fn [_]
+ (deliver idle-called true)
+ (swap! call-counter update :idle inc)
+ (when (.isInterrupted (Thread/currentThread))
+ (throw (InterruptedException.))))
+ semantic.indexer/indexing-step (fn [& _]
+ (deliver step-called true)
+ (swap! call-counter update :step inc)
+ (when-some [ex @step-ex] (throw ex))
+ (when (.isInterrupted (Thread/currentThread))
+ (throw (InterruptedException.))))]
+
+ (with-open [loop-thread
+ (open-loop-thread! pgvector
+ index-metadata
+ index
+ indexing-state)]
+ (let [{:keys [caught-ex ^Thread thread]} @loop-thread]
+ (is (not= :timeout (deref idle-called 100 :timeout)))
+ (is (not= :timeout (deref step-called 100 :timeout)))
+
+ (testing "start time set"
+ (is (inst? (:start-time @indexing-state))))
+
+ (testing "called repeatedly"
+ (is (wait-for-calls)))
+
+ (testing "called 1 to 1"
+ (let [{:keys [idle step]} @call-counter
+ lower (dec idle)
+ upper (inc idle)]
+ (is (<= lower step upper))))
+
+ (testing "exceptions are bubbled out of loop, will not loop forever"
+ (let [ex (Exception. (str "Error: " (u/generate-nano-id)))]
+ (vreset! step-ex ex)
+ (is (.join thread (Duration/ofSeconds 1)) "loop exits")
+ (is (= (ex-message ex) (ex-message @caught-ex)))))))
+
+ (testing "loop interruptible"
+ (with-open [loop-thread
+ (open-loop-thread! pgvector
+ index-metadata
+ index
+ indexing-state)]
+ (let [{:keys [^Thread thread]} @loop-thread]
+ (.interrupt thread)
+ (is (.join thread (Duration/ofSeconds 1)))))))))
+
+(deftest indexing-loop-exit-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model semantic.tu/mock-embedding-model
+ index (semantic.index-metadata/qualify-index (semantic.index/default-index model) index-metadata)
+ t1 (ts "2025-01-01T00:01:00Z")
+ c1 {:model "card" :id "1" :name "Dog" :searchable_text "Dog Training Guide"}
+ version semantic.gate/search-doc->gate-doc]
+ (with-open [_ (open-metadata! pgvector index-metadata)
+ _ (open-index! pgvector index)]
+ (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)
+
+ (testing "exits immediately after max run duration elapses"
+ (let [run-time (u/start-timer)
+ indexing-state (semantic.indexer/init-indexing-state (get-metadata-row! pgvector index-metadata index))]
+ (vswap! indexing-state assoc :max-run-duration (Duration/ofMillis 1))
+ (with-redefs [semantic.indexer/sleep (fn [_])]
+ (with-open [loop-thread (open-loop-thread! pgvector
+ index-metadata
+ index
+ indexing-state)]
+ (let [{:keys [^Thread thread caught-ex]} @loop-thread
+ max-wait 1000
+ wait-time (u/start-timer)]
+ (testing "exits"
+ (is
+ (loop []
+ (cond
+ (not (.isAlive thread)) true
+ (< max-wait (u/since-ms wait-time)) false
+ :else (recur))))
+ (testing "did not wait too long"
+ (is (<= (u/since-ms run-time) 500)))
+ (testing "did not crash"
+ (is (nil? @caught-ex)))))))))
+
+ (testing "exists early if no new records after a time"
+ (let [run-time (u/start-timer)
+ indexing-state (semantic.indexer/init-indexing-state (get-metadata-row! pgvector index-metadata index))
+ upsert-index! semantic.index/upsert-index!
+ indexed (atom [])]
+ (vswap! indexing-state assoc :exit-early-cold-duration (Duration/ofMillis 1))
+ (with-redefs [semantic.indexer/sleep (fn [_])
+ semantic.index/upsert-index! (fn [pgvector index docs]
+ (let [docs (vec docs)]
+ (swap! indexed into docs)
+ (upsert-index! pgvector index docs)))]
+ ;; need some data first for early exit, or it does nothing
+ (semantic.gate/gate-documents! pgvector index-metadata [(version c1 t1)])
+ (with-open [loop-thread (open-loop-thread! pgvector
+ index-metadata
+ index
+ indexing-state)]
+ (let [{:keys [^Thread thread caught-ex]} @loop-thread
+ wait-time (u/start-timer)
+ max-wait 1000]
+ (testing "exits"
+ (is
+ (loop []
+ (cond
+ (not (.isAlive thread)) true
+ (< max-wait (u/since-ms wait-time)) false
+ :else (recur))))
+ (testing "has seen our row before exiting"
+ (is (= 1 (count @indexed))))
+ (testing "did not wait too long"
+ (is (<= (u/since-ms run-time) 500)))
+ (testing "did not crash"
+ (is (nil? @caught-ex))))))))))))
+
+(deftest init-indexing-state-test
+ (testing "initializes indexing state from metadata row"
+ (let [metadata-row {:indexer_last_poll (ts "2025-01-01T12:00:00Z")
+ :indexer_last_seen (ts "2025-01-01T11:30:00Z")
+ :indexer_last_seen_id "foo"
+ :indexer_last_seen_hash "bar"}
+ state (semantic.indexer/init-indexing-state metadata-row)
+ state-value @state
+ expected-last-seen {:id "foo" :document_hash "bar" :gated_at (ts "2025-01-01T11:30:00Z")}]
+ (is (= (ts "2025-01-01T12:00:00Z") (get-in state-value [:watermark :last-poll])))
+ (is (= expected-last-seen (get-in state-value [:watermark :last-seen])))
+ (is (= #{expected-last-seen} (:last-seen-candidates state-value)))
+ (is (zero? (:last-indexed-count state-value)))
+ (is (zero? (:last-poll-count state-value))))))
+
+(deftest quartz-job-run!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ open-job-thread (fn [& args]
+ (let [caught-ex (volatile! nil)]
+ (semantic.tu/closeable
+ {:caught-ex caught-ex
+ :thread
+ (doto (Thread.
+ ^Runnable
+ (bound-fn*
+ (fn []
+ (try
+ (apply semantic.indexer/quartz-job-run! args)
+ (catch Throwable t
+ (vreset! caught-ex t))))))
+ (.setDaemon true)
+ (.start))}
+ (fn [{:keys [^Thread thread]}]
+ (when (.isAlive thread)
+ (.interrupt thread)
+ (when-not (.join thread (Duration/ofSeconds 30))
+ (log/fatal "Indexing loop thread not exiting during test!")))))))]
+
+ (testing "exit immediately: no active index / index tables"
+ (with-open [job-thread ^Closeable (open-job-thread pgvector index-metadata)]
+ (let [{:keys [caught-ex ^Thread thread]} @job-thread]
+ (testing "thread exited"
+ (is (.join thread (Duration/ofSeconds 5))))
+ (testing "did not crash"
+ (is (nil? @caught-ex))))))
+
+ (testing "runs loop on active index then exits"
+ (let [loop-args (atom [])
+ metadata-row {:indexer_last_poll (ts "2025-01-01T12:00:00Z")
+ :indexer_last_seen (ts "2025-01-01T11:30:00Z")}
+ index {:table-name "foo"}]
+ (with-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index index :metadata-row metadata-row})
+ semantic.indexer/indexing-loop (fn [& args] (swap! loop-args conj args) nil)]
+ (with-open [job-thread ^Closeable (open-job-thread pgvector index-metadata)]
+ (let [{:keys [caught-ex ^Thread thread]} @job-thread]
+ (testing "thread exited (loop returned)"
+ (is (.join thread (Duration/ofSeconds 5))))
+ (testing "args as expected"
+ (is (= 1 (count @loop-args)))
+ (let [[[_ _ passed-index indexing-state]] @loop-args]
+ (is (= index passed-index))
+ (is (= @(semantic.indexer/init-indexing-state metadata-row) @indexing-state))))
+ (testing "did not crash"
+ (is (nil? @caught-ex))))))))
+
+ (doseq [ex [(Exception. "Boom")
+ (AssertionError. "Assert")
+ (InterruptedException. "Interrupt")]]
+ (testing "exit on exception/error during loop"
+ (with-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index {} :metadata-row {}})
+ semantic.indexer/indexing-loop (fn [& _] (throw ex))]
+ (with-open [job-thread ^Closeable (open-job-thread pgvector index-metadata)]
+ (let [{:keys [caught-ex ^Thread thread]} @job-thread]
+ (testing "thread exited"
+ (is (.join thread (Duration/ofSeconds 5))))
+ (testing "crashed with expected msg"
+ (is (= (ex-message ex) (ex-message @caught-ex)))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/migration_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/migration_test.clj
new file mode 100644
index 00000000000..dce18a83bd8
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/migration_test.clj
@@ -0,0 +1,254 @@
+(ns metabase-enterprise.semantic-search.migration-test
+ (:require
+ [clojure.test :refer [deftest is testing use-fixtures]]
+ [honey.sql :as sql]
+ [java-time.api :as t]
+ [medley.core :as m]
+ [metabase-enterprise.semantic-search.core :as semantic.core]
+ [metabase-enterprise.semantic-search.db.connection :as semantic.db.connection]
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase-enterprise.semantic-search.db.migration :as semantic.db.migration]
+ [metabase-enterprise.semantic-search.db.migration.impl :as semantic.db.migration.impl]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.pgvector-api :as semantic.pgvector-api]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [metabase.util.log :as log]
+ [metabase.util.log.capture :as log.capture]
+ [next.jdbc :as jdbc]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+(use-fixtures :each #'semantic.tu/ensure-no-migration-table-fixture)
+
+(deftest migration-table-versions-test
+ (mt/with-premium-features #{:semantic-search}
+ (semantic.tu/with-test-db! semantic.tu/default-test-db
+ (letfn [(migrate-and-get-db-version
+ [attempted-version]
+ (with-redefs [semantic.db.migration.impl/schema-version attempted-version
+ semantic.db.migration.impl/migrate-schema! (constantly nil)]
+ (log.capture/with-log-messages-for-level [messages [metabase-enterprise.semantic-search.db.migration :info]]
+ (semantic.db.connection/with-migrate-tx [tx]
+ (semantic.db.migration/maybe-migrate! tx nil)
+ {:messages (messages)
+ :db-version (@#'semantic.db.migration/db-version tx)}))))]
+ (testing "Migration up works"
+ (u/prog1 (migrate-and-get-db-version 130)
+ (is (= 130 (:db-version <>)))
+ (is (m/find-first (comp #{"Starting migration from version -1 to 130."} :message)
+ (:messages <>)))))
+ (testing "Migration down is noop"
+ (u/prog1 (migrate-and-get-db-version 1)
+ (is (= 130 (:db-version <>)))
+ (is (m/find-first
+ (comp #{(str "Database schema version (130) is newer than "
+ "code version (1). Not performing migration.")}
+ :message)
+ (:messages <>)))))
+ (testing "Migration to the same version is noop"
+ (u/prog1 (migrate-and-get-db-version 130)
+ (is (= 130 (:db-version <>)))
+ (is (m/find-first (comp #{"Migration already performed, skipping."} :message)
+ (:messages <>)))))))))
+
+(deftest migration-lock-coordination-test
+ (mt/with-premium-features #{:semantic-search}
+ (semantic.tu/with-test-db! semantic.tu/default-test-db
+ (testing "Migration of simultaneous init attempt is blocked"
+ (let [original-write-fn @#'semantic.db.migration/write-successful-migration!
+ original-migrate-fn @#'semantic.db.connection/do-with-migrate-tx
+ results (atom {:executed-migrations 0
+ :log []})]
+ (with-redefs-fn {;; TODO: why in ci init index won't succeed -- http on embedding
+ #'semantic.pgvector-api/index-documents! (constantly nil)
+ #'semantic.db.connection/do-with-migrate-tx
+ (fn [& args]
+ (let [tid (.getId (Thread/currentThread))]
+ ;; leaving in the timestamp for repl purposes
+ (swap! results update :log conj [tid :started (t/local-date-time)])
+ (apply original-migrate-fn args)
+ (swap! results update :log conj [tid :ended (t/local-date-time)]))
+ nil)
+ #'semantic.db.migration/write-successful-migration!
+ (fn [& args]
+ (Thread/sleep 2000)
+ (apply original-write-fn args)
+ (swap! results update :executed-migrations inc)
+ nil)}
+ (fn []
+ (let [;; thread 1 attempts migration on clean db
+ f1 (future
+ (swap! results assoc :tid-first (.getId (Thread/currentThread)))
+ (semantic.core/init! (semantic.tu/mock-documents) nil))
+ ;; thread 2 attempts migration
+ f2 (future
+ (swap! results assoc :tid-second (.getId (Thread/currentThread)))
+ (Thread/sleep 100)
+ (semantic.core/init! (semantic.tu/mock-documents) nil))]
+ ;; wait for completion
+ @f1
+ @f2
+ (testing "Single migration performed"
+ (= 1 (:executed-migrations @results)))
+ (testing "Database locks acquired in expected order"
+ (let [{:keys [tid-first tid-second]} @results]
+ (is (=? [[tid-first :started any?]
+ [tid-second :started any?]
+ [tid-first :ended any?]
+ [tid-second :ended any?]]
+ (:log @results)))))))))))))
+
+(defn- map-contains-keys?
+ [m kseq]
+ (reduce #(and %1 (contains? m %2)) true kseq))
+
+(defn- qualify
+ [q xs]
+ (into []
+ (map (fn [x] (keyword (name q) (name x))))
+ xs))
+
+(deftest expected-db-schema-after-migration-test
+ (try
+ (mt/with-premium-features #{:semantic-search}
+ (semantic.tu/with-test-db! semantic.tu/default-test-db
+ (with-redefs [semantic.pgvector-api/index-documents! (constantly nil)]
+ (semantic.core/init! (semantic.tu/mock-documents) nil)
+ (testing "migration table has expected columns"
+ (is (map-contains-keys?
+ (jdbc/execute-one! (semantic.db.datasource/ensure-initialized-data-source!)
+ (sql/format {:select [:*]
+ :from [:migration]}))
+ (qualify :migration [:migrated_at
+ :status
+ :version]))))
+ (testing "control table has expected columns"
+ (is (map-contains-keys?
+ (jdbc/execute-one! (semantic.db.datasource/ensure-initialized-data-source!)
+ (sql/format {:select [:*]
+ :from [:index_control]}))
+ (qualify :index_control [:active_id
+ :active_updated_at
+ :id
+ :version]))))
+ (testing "metadata table has expected columns"
+ (is (map-contains-keys?
+ (jdbc/execute-one! semantic.tu/db
+ (sql/format {:select [:*]
+ :from [:index_metadata]}))
+ (qualify :index_metadata [:id
+ :index_created_at
+ :index_version
+ :indexer_last_poll
+ :indexer_last_seen
+ :indexer_last_seen_hash
+ :indexer_last_seen_id
+ :model_name
+ :provider
+ :table_name
+ :vector_dimensions]))))
+ (testing "index table has expected columns"
+ (let [index-table (->
+ (jdbc/execute-one! (semantic.db.datasource/ensure-initialized-data-source!)
+ (sql/format {:select [[:im.table_name]]
+ :from [[:index_control :ic]]
+ :join [[:index_metadata :im]
+ [:= :ic.active_id :im.id]]}))
+ :index_metadata/table_name)]
+ (is (=? #{"archived"
+ "collection_id"
+ "content"
+ "created_at"
+ "creator_id"
+ "dashboardcard_count"
+ "database_id"
+ "display_type"
+ "embedding"
+ "id"
+ "last_editor_id"
+ "last_viewed_at"
+ "legacy_input"
+ "metadata"
+ "model"
+ "model_created_at"
+ "model_id"
+ "model_updated_at"
+ "name"
+ "official_collection"
+ "pinned"
+ "text_search_vector"
+ "text_search_with_native_query_vector"
+ "verified"
+ "view_count"}
+ (->> (jdbc/execute! semantic.tu/db
+ (sql/format {:select [:column_name]
+ :from [:information_schema.columns]
+ :where [[:= :table_name [:inline index-table]]]}))
+ (map :columns/column_name)
+ set)))))
+ (testing "index table has expected columns"
+ (is (= ["document" "document_hash" "gated_at" "id" "model" "model_id" "updated_at"]
+ (->> (jdbc/execute! semantic.tu/db
+ (sql/format {:select [:column_name]
+ :from [:information_schema.columns]
+ :where [[:= :table_name [:inline "index_gate"]]]}))
+ (map :columns/column_name)
+ sort
+ vec)))))))
+ (catch Throwable e
+ (log/fatal e)
+ (throw e))))
+
+(defn- has-column?!
+ [tx table-name column-name]
+ (seq (jdbc/execute-one! tx (sql/format {:select [[[:raw 1] :contains]]
+ :from [:information_schema.columns]
+ :where [:and
+ [:= :table_name [:inline table-name]]
+ [:= :column_name [:inline column-name]]]}))))
+
+(deftest dynamic-schema-migration-test
+ (mt/with-premium-features #{:semantic-search}
+ (semantic.tu/with-test-db! semantic.tu/default-test-db
+ (with-redefs [semantic.pgvector-api/index-documents! (constantly nil)]
+ (semantic.core/init! (semantic.tu/mock-documents) nil)
+ ;; add column to index table
+ (let [original-dynamic-schema semantic.db.migration.impl/dynamic-schema-version]
+ (with-redefs-fn {#'semantic.db.migration.impl/migrate-dynamic-schema!
+ (fn [tx _opts]
+ (let [table_names (->> (jdbc/execute! tx
+ (sql/format {:select [:table_name]
+ :from [:index_metadata]
+ :where [[:< :index_version semantic.db.migration.impl/dynamic-schema-version]]
+ :group-by [:table_name]}))
+ (map :index_metadata/table_name)
+ set)]
+ (doseq [table_name table_names]
+ (when-not (has-column?! tx table_name "new_col")
+ (jdbc/execute! tx (sql/format {:alter-table [table_name] :add-column [[:new_col :int]]}))))
+ (jdbc/execute! tx (sql/format {:update :index_metadata
+ :set {:index_version semantic.db.migration.impl/dynamic-schema-version}
+ :where [[:in :table_name table_names]]}))))
+ #'semantic.db.migration.impl/dynamic-schema-version (inc original-dynamic-schema)}
+ (fn []
+ ;; Trigger migration by next initialization attempt
+ (semantic.core/init! (semantic.tu/mock-documents) nil)
+ (let [#:index_metadata{:keys [index_version table_name]}
+ (jdbc/execute-one! (semantic.db.datasource/ensure-initialized-data-source!)
+ (sql/format
+ {:select [:*]
+ :from [:index_metadata]}))]
+ (testing "Index metadata table ids were updated"
+ (is (= index_version semantic.db.migration.impl/dynamic-schema-version)))
+ (testing "Index table contains new column"
+ (is (has-column?! (semantic.db.datasource/ensure-initialized-data-source!)
+ table_name "new_col")))))))))))
+
+(deftest schema-version-match-default-version-test
+ (testing "Default schema should match dynamic schema version"
+ (is (= semantic.db.migration.impl/dynamic-schema-version
+ (-> (semantic.index/default-index semantic.tu/mock-embedding-model)
+ :version)))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
new file mode 100644
index 00000000000..68e86b26530
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
@@ -0,0 +1,253 @@
+(ns metabase-enterprise.semantic-search.pgvector-api-test
+ (:require
+ [clojure.test :refer :all]
+ [honey.sql :as sql]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.indexer :as semantic.indexer]
+ [metabase-enterprise.semantic-search.pgvector-api :as semantic.pgvector-api]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import (java.io Closeable)
+ (java.time Duration)))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+(use-fixtures :each #'semantic.tu/ensure-no-migration-table-fixture)
+
+;; NOTE: isolation tests are absent, in prod there is only one index-metadata
+
+(deftest init-semantic-search!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model1 semantic.tu/mock-embedding-model
+ model2 (assoc semantic.tu/mock-embedding-model :model-name "embed-harder")
+ sut* semantic.pgvector-api/init-semantic-search!
+ cleanup (fn [_] (semantic.tu/cleanup-index-metadata! pgvector index-metadata))
+ sut #(semantic.tu/closeable (apply sut* %&) cleanup)]
+ (with-open [index-ref ^Closeable (sut pgvector index-metadata model1)]
+ (testing "sets up active index for model1"
+ (let [active-state (semantic.index-metadata/get-active-index-state pgvector index-metadata)]
+ (is (= @index-ref (:index active-state)))
+ (is (= model1 (:embedding-model (:index active-state))))
+ (is (= (:model-name model1) (:model_name (:metadata-row active-state))))
+ (testing "idempotent"
+ (let [new-index @(sut pgvector index-metadata model1)]
+ (is (= @index-ref new-index))
+ (is (= active-state (semantic.index-metadata/get-active-index-state pgvector index-metadata)))))))
+ (testing "switch to model1"
+ (let [new-index @(sut pgvector index-metadata model2)
+ active-state (semantic.index-metadata/get-active-index-state pgvector index-metadata)]
+ (is (= model2 (:embedding-model new-index)))
+ (is (= new-index (:index active-state))))
+ (testing "model1 index still exists"
+ (is (=? {:index {:embedding-model model1}
+ :active false
+ :index-table-exists true}
+ (semantic.index-metadata/find-best-index! pgvector index-metadata model1))))
+ (testing "switch back!"
+ (let [new-index @(sut pgvector index-metadata model1)
+ active-state (semantic.index-metadata/get-active-index-state pgvector index-metadata)]
+ (is (= model1 (:embedding-model new-index)))
+ (is (= new-index (:index active-state)))
+ (testing "model2 index still exists"
+ (is (=? {:index {:embedding-model model2}
+ :active false
+ :index-table-exists true}
+ (semantic.index-metadata/find-best-index! pgvector index-metadata model2))))))))))
+
+(defn- open-semantic-search! ^Closeable [pgvector index-metadata embedding-model]
+ (semantic.tu/closeable
+ (semantic.pgvector-api/init-semantic-search! pgvector index-metadata embedding-model)
+ (fn [_]
+ (semantic.tu/cleanup-index-metadata! pgvector index-metadata))))
+
+(defn- test-not-initialized [sut & args]
+ (testing "throws if not initialized"
+ ;; not defined specific exception behaviour here yet, but best not to return empty or something silly like that
+ (is (thrown? Exception (apply sut args)))))
+
+(deftest index-documents!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model1 semantic.tu/mock-embedding-model
+ model2 (assoc semantic.tu/mock-embedding-model :model-name "embedagain")
+ sut semantic.pgvector-api/index-documents!]
+ (test-not-initialized sut pgvector index-metadata model1)
+ (with-open [index-ref (open-semantic-search! pgvector index-metadata model1)]
+ ;; no specific behaviour, only proxies the active index to the index search
+ (testing "is only a proxy for the active index call"
+ (let [{:keys [proxy calls]} (semantic.tu/spy semantic.index/upsert-index!)
+ documents (semantic.tu/mock-documents)]
+ (with-redefs [semantic.index/upsert-index! proxy]
+ (testing "check proxies correct args and ret is untouched"
+ (let [ret (sut pgvector index-metadata documents)]
+ (is (= [{:args [pgvector @index-ref documents]
+ :ret ret}]
+ @calls))))
+
+ (testing "check proxies after switch"
+ (reset! calls [])
+ (let [new-index (semantic.pgvector-api/init-semantic-search! pgvector index-metadata model2)
+ ret (sut pgvector index-metadata documents)]
+ (is (= [{:args [pgvector new-index documents]
+ :ret ret}]
+ @calls))))))))))
+
+(deftest delete-documents!-test
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ dash "dashboard"
+ card "card"
+ model1 semantic.tu/mock-embedding-model
+ model2 (assoc semantic.tu/mock-embedding-model :model-name "embedagain")
+ sut semantic.pgvector-api/delete-documents!
+ documents (semantic.tu/mock-documents)
+ {card-ids "card", dash-ids "dashboard"} (u/group-by :model :id documents)]
+ (test-not-initialized sut pgvector index-metadata model1)
+ (with-open [index-ref (open-semantic-search! pgvector index-metadata model1)]
+ ;; no specific behaviour, only proxies the active index to the index search
+ (testing "is only a proxy for the active index call"
+ (semantic.pgvector-api/index-documents! pgvector index-metadata documents)
+ (let [{:keys [calls proxy]} (semantic.tu/spy semantic.index/delete-from-index!)]
+ (with-redefs [semantic.index/delete-from-index! proxy]
+ (testing "check proxies correct args and ret is untouched"
+ (let [ret1 (sut pgvector index-metadata dash dash-ids)
+ ret2 (sut pgvector index-metadata card card-ids)
+ ret3 (sut pgvector index-metadata card dash-ids)
+ ret4 (sut pgvector index-metadata card [])]
+ (is (= [{:args [pgvector @index-ref dash dash-ids]
+ :ret ret1}
+ {:args [pgvector @index-ref card card-ids]
+ :ret ret2}
+ {:args [pgvector @index-ref card dash-ids]
+ :ret ret3}
+ {:args [pgvector @index-ref card []]
+ :ret ret4}]
+ @calls))))
+ (testing "check proxies after switch"
+ (reset! calls [])
+ (let [new-index (semantic.pgvector-api/init-semantic-search! pgvector index-metadata model2)
+ ret (sut pgvector index-metadata dash dash-ids)]
+ (is (= [{:args [pgvector new-index dash dash-ids]
+ :ret ret}]
+ @calls))))))))))
+
+(deftest query-test
+ (semantic.tu/with-indexable-documents!
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ model1 semantic.tu/mock-embedding-model
+ model2 (assoc semantic.tu/mock-embedding-model :model-name "judge-embedd")
+ remove-scores (fn [rows] (mapv #(dissoc % :score :all-scores) rows)) ; scores have time-sensitives components
+ sut* semantic.pgvector-api/query
+ sut #(remove-scores (:results (mt/as-admin (apply sut* %&)))) ; see notes below about perms
+ search-string "insect patterns" ; specifics of search will be handled under index tests
+ _ (assert (semantic.tu/mock-embeddings search-string)
+ "search string should have test embedding")
+ search {:search-string search-string}]
+ (test-not-initialized sut pgvector index-metadata search)
+ (with-open [index-ref (open-semantic-search! pgvector index-metadata model1)]
+ (semantic.pgvector-api/index-documents! pgvector index-metadata (vec (search.ingestion/searchable-documents)))
+ (testing "search results are the same as direct index query"
+ (let [index-results (remove-scores (:results (mt/as-admin (semantic.index/query-index pgvector @index-ref search))))
+ api-results (sut pgvector index-metadata search)]
+ (testing "sanity check the test is setup correctly" (is (seq api-results)))
+ (is (= api-results index-results))))
+ ;; it would be better to test permissions at a higher level than we currently do, but for now to save time...
+ (testing "assumption: permissions are applied at the index query level, check the expected fn is called"
+ (let [query-index semantic.index/query-index
+ called (atom false)]
+ (with-redefs [semantic.index/query-index (fn [& args] (reset! called true) (apply query-index args))]
+ (sut pgvector index-metadata search)
+ (is @called))))
+ (testing "same results after reinit"
+ (let [current-results (sut pgvector index-metadata search)]
+ (semantic.pgvector-api/init-semantic-search! pgvector index-metadata model1)
+ (is (= current-results (sut pgvector index-metadata search)))))
+ (testing "switching to an empty index"
+ (let [current-results (sut pgvector index-metadata search)]
+ (semantic.pgvector-api/init-semantic-search! pgvector index-metadata model2)
+ ;; sanity
+ (is (not= @index-ref (:index (semantic.index-metadata/get-active-index-state pgvector index-metadata))))
+ (testing "empty to start but works"
+ (is (= [] (sut pgvector index-metadata search))))
+ (testing "after indexing returns again"
+ (semantic.pgvector-api/index-documents! pgvector index-metadata (vec (search.ingestion/searchable-documents)))
+ ;; todo test the results with different mock embeddings to show the embeddings
+ ;; can actually change
+ (is (seq (sut pgvector index-metadata search))))
+ (testing "querying previous index directly still works"
+ (is (= current-results (remove-scores (:results (mt/as-admin (semantic.index/query-index pgvector @index-ref search)))))))))
+ (testing "throws exception when no active index exists"
+ ;; corrupt the control table
+ (jdbc/execute! pgvector (sql/format {:delete-from (keyword (:control-table-name index-metadata))}
+ :quoted true))
+ (is (thrown-with-msg? Exception #"No active semantic search index" (sut pgvector index-metadata search))))))))
+
+(deftest e2e-index-a-sample-db-with-gate-test
+ (let [docs (mt/dataset test-data (vec (search.ingestion/searchable-documents)))
+ pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ embedding-model semantic.tu/mock-embedding-model
+ open-job-thread (fn [& args]
+ (let [caught-ex (volatile! nil)]
+ (semantic.tu/closeable
+ {:caught-ex caught-ex
+ :thread
+ (doto (Thread.
+ ^Runnable
+ (bound-fn*
+ (fn []
+ (try
+ (apply semantic.indexer/quartz-job-run! args)
+ (catch InterruptedException _)
+ (catch Throwable t
+ (vreset! caught-ex t))))))
+ (.setDaemon true)
+ (.start))}
+ (fn [{:keys [^Thread thread]}]
+ (when (.isAlive thread)
+ (.interrupt thread)
+ (when-not (.join thread (Duration/ofSeconds 30))
+ (log/fatal "Indexing loop thread not exiting during test!")))))))]
+ (with-redefs [semantic.indexer/sleep (fn [_]) ; do not slow down
+ semantic.indexer/poll-limit 4 ; important to test poll / paging (not many docs in test-data)
+ semantic.indexer/lag-tolerance Duration/ZERO] ; if too high will slow the test down significantly
+
+ (with-open [index-ref (open-semantic-search! pgvector index-metadata embedding-model)
+ job-thread ^Closeable (open-job-thread pgvector index-metadata)]
+ (let [index @index-ref
+ {:keys [caught-ex ^Thread thread]} @job-thread]
+
+ (is (= (frequencies (map :model docs)) (semantic.pgvector-api/gate-updates! pgvector index-metadata docs)))
+
+ (let [max-wait (+ (System/currentTimeMillis) 1000)
+ get-indexed-q {:select [:model [:model_id :id]] :from [(keyword (:table-name index))]}
+ get-indexed (fn [] (frequencies
+ (jdbc/execute! pgvector
+ (sql/format get-indexed-q :quoted true)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})))
+ expected-indexed (frequencies (distinct (map (fn [{:keys [model id]}]
+ {:model model
+ :id (str id)})
+ docs)))
+ indexed-in-time (loop [indexed {}]
+ (cond
+ (< max-wait (System/currentTimeMillis)) indexed
+ (= indexed expected-indexed) indexed
+ :else (recur (get-indexed))))]
+
+ (testing "we indexed all the expected documents"
+ (is (= expected-indexed indexed-in-time))))
+
+ (testing "interrupt"
+ (.interrupt thread)
+ (is (.join thread (Duration/ofSeconds 10)))
+ (is (nil? @caught-ex))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/query_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/query_test.clj
new file mode 100644
index 00000000000..3c86450f617
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/query_test.clj
@@ -0,0 +1,266 @@
+(ns metabase-enterprise.semantic-search.query-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.permissions.models.permissions :as perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+(deftest database-initialised-test
+ (is (some? @semantic.db.datasource/data-source))
+ (is (= {:test 1} (semantic.db.datasource/test-connection!))))
+
+(deftest basic-query-test
+ (testing "Simple queries with no filters"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-index!
+ (testing "Dog-related query finds dog content"
+ (let [results (semantic.tu/query-index {:search-string "puppy"})]
+ (is (= "Dog Training Guide" (-> results first :name)))))
+
+ (testing "Bird-related query finds bird content"
+ (let [results (semantic.tu/query-index {:search-string "avian"})]
+ (is (= "Bird Watching Tips" (-> results first :name))))))))))
+
+(defn- index-of-name
+ "Return the index of the item with :name `name` in `coll`"
+ [coll name]
+ (first (keep-indexed (fn [idx item]
+ (when (= name (:name item))
+ idx))
+ coll)))
+
+(deftest native-query-test
+ (testing "Tests for :search-native-query"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-index!
+ (let [not-top-10? #(or (nil? %) (< 10 %))
+ top-three? #(< % 3)]
+ (doseq [{:keys [name desc search-string search-native-query? expected-index?]}
+ [{:name "Dog Training Guide"
+ :desc "contains"
+ :search-string "AVG(tricks)"
+ :search-native-query? false
+ :expected-index? not-top-10?}
+ {:name "Dog Training Guide"
+ :desc "contains"
+ :search-string "AVG(tricks)"
+ :search-native-query? true
+ :expected-index? top-three?}
+ {:name "Dog Training Guide"
+ :desc "contains"
+ :search-string "GROUP BY breed"
+ :search-native-query? false
+ :expected-index? not-top-10?}
+ {:name "Dog Training Guide"
+ :desc "contains"
+ :search-string "GROUP BY breed"
+ :search-native-query? true
+ :expected-index? top-three?}
+ {:name "Dog Training Guide"
+ :desc "does not contain"
+ :search-string "SUM(tricks)"
+ :search-native-query? false
+ :expected-index? not-top-10?}
+ {:name "Dog Training Guide"
+ :desc "does not contain"
+ :search-string "SUM(tricks)"
+ :search-native-query? true
+ :expected-index? not-top-10?}
+ {:name "Bird Watching Tips"
+ :desc "does not contain (no native query)"
+ :search-string "AVG(tricks)"
+ :search-native-query? true
+ :expected-index? not-top-10?}
+ {:name "Dog Training Guide"
+ :desc "semantic search"
+ :search-string "puppy"
+ :search-native-query? true
+ :expected-index? top-three?}
+ {:name "Bird Watching Tips"
+ :desc "semantic search"
+ :search-string "avian"
+ :search-native-query? true
+ :expected-index? top-three?}
+ {:name "Dog Training Guide"
+ :desc "non-native keyword query"
+ :search-string "Training"
+ :search-native-query? true
+ :expected-index? top-three?}
+ {:name "Bird Watching Tips"
+ :desc "non-native keyword query"
+ :search-string "Watching"
+ :search-native-query? true
+ :expected-index? top-three?}]]
+ (testing (format "\n%s %s %s %s" name desc search-string search-native-query?)
+ (is (-> (semantic.tu/query-index {:search-string search-string
+ :search-native-query search-native-query?})
+ (index-of-name name)
+ expected-index?))))))))))
+
+(deftest model-filtering-test
+ (testing "Filter results by model type"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-index!
+ (testing "Filter for cards only"
+ (let [card-results (semantic.tu/query-index {:search-string "avian" :models ["card"]})
+ filtered-results (semantic.tu/filter-for-mock-embeddings card-results)]
+ (is (pos? (count filtered-results)))
+ (is (every? #(= "card" (:model %)) card-results))))
+
+ (testing "Filter for dashboards only"
+ (let [dashboard-results (semantic.tu/query-index {:search-string "marine mammal" :models ["dashboard"]})
+ filtered-results (semantic.tu/filter-for-mock-embeddings dashboard-results)]
+ (is (pos? (count filtered-results)))
+ (is (every? #(= "dashboard" (:model %)) dashboard-results))))
+
+ (testing "Filter for multiple model types"
+ (let [mixed-results (semantic.tu/query-index {:search-string "predator" :models ["card" "dashboard"]})
+ filtered-results (semantic.tu/filter-for-mock-embeddings mixed-results)]
+ (is (pos? (count filtered-results)))
+ (is (every? #(contains? #{"card" "dashboard"} (:model %)) mixed-results)))))))))
+
+(deftest archived-filtering-test
+ (testing "Filter results by archived status"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-index!
+ (testing "Include only non-archived items"
+ (let [active-results (semantic.tu/query-index {:search-string "feline" :archived? false})]
+ (is (every? #(not (:archived %)) active-results))))
+
+ (testing "Include only archived items"
+ (let [archived-results (semantic.tu/query-index {:search-string "feline" :archived? true})
+ filtered-results (semantic.tu/filter-for-mock-embeddings archived-results)]
+ (is (pos? (count filtered-results)))
+ (is (every? :archived archived-results))))
+
+ (testing "Include all items regardless of archived status"
+ (let [all-results (semantic.tu/query-index {:search-string "feline"})
+ filtered-results (semantic.tu/filter-for-mock-embeddings all-results)]
+ (is (pos? (count filtered-results))))))))))
+
+(deftest creator-filtering-test
+ (testing "Filter results by creator"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-index!
+ (testing "Filter by single creator"
+ (let [crowberto-results (semantic.tu/query-index {:search-string "aquatic" :created-by [(mt/user->id :crowberto)]})
+ filtered-results (semantic.tu/filter-for-mock-embeddings crowberto-results)]
+ (is (pos? (count filtered-results)))
+ (is (every? #(= (mt/user->id :crowberto) (:creator_id %)) crowberto-results))))
+
+ (testing "Filter by multiple creators"
+ (let [multi-creator-results (semantic.tu/query-index {:search-string "endangered species"
+ :created-by [(mt/user->id :crowberto) (mt/user->id :rasta)]})]
+ (is (pos? (count multi-creator-results)))
+ (is (every? #(contains? #{(mt/user->id :crowberto) (mt/user->id :rasta)} (:creator_id %)) multi-creator-results)))))))))
+
+(deftest verified-filtering-test
+ (testing "Filter results by verified status"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-index!
+ (testing "Include only verified items"
+ (let [verified-results (semantic.tu/query-index {:search-string "puppy" :verified true})
+ filtered-results (semantic.tu/filter-for-mock-embeddings verified-results)]
+ (is (pos? (count filtered-results)))
+ (is (every? :verified verified-results))))
+
+ (testing "Include all items regardless of verified status when filter not specified"
+ (let [all-results (semantic.tu/query-index {:search-string "puppy"})
+ filtered-results (semantic.tu/filter-for-mock-embeddings all-results)]
+ (is (pos? (count filtered-results))))))))))
+
+(deftest complex-filtering-test
+ (testing "Complex filters with multiple criteria"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-index!
+ (testing "Non-archived cards by specific creator"
+ (let [results (semantic.tu/query-index {:search-string "equine"
+ :models ["card"]
+ :archived? false
+ :created-by [(mt/user->id :rasta)]})
+ filtered-results (semantic.tu/filter-for-mock-embeddings results)]
+ (is (pos? (count filtered-results)))
+ (is (every? #(and (= "card" (:model %))
+ (not (:archived %))
+ (= (mt/user->id :rasta) (:creator_id %))) results))))
+
+ (testing "Archived dashboards by multiple creators"
+ (let [results (semantic.tu/query-index {:search-string "Antarctic wildlife"
+ :models ["dashboard"]
+ :archived? true
+ :created-by [(mt/user->id :crowberto) (mt/user->id :rasta)]})
+ filtered-results (semantic.tu/filter-for-mock-embeddings results)]
+ (is (pos? (count filtered-results)))
+ (is (every? #(and (= "dashboard" (:model %))
+ (:archived %)
+ (contains? #{(mt/user->id :crowberto) (mt/user->id :rasta)} (:creator_id %))) results))))
+
+ (testing "Verified items with additional filters"
+ (let [results (semantic.tu/query-index {:search-string "marine mammal"
+ :models ["dashboard"]
+ :verified true
+ :archived? false})]
+ (is (every? #(and (= "dashboard" (:model %))
+ (:verified %)
+ (not (:archived %))) results)))))))))
+
+(deftest permissions-test
+ (mt/with-premium-features #{:semantic-search}
+ (semantic.tu/with-index!
+ (let [monsters-table (t2/select-one-pk :model/Table :name "Monsters Table")
+ q (fn [model s] (map :name (semantic.tu/query-index {:search-string s, :models [model]})))
+ all-users (perms-group/all-users)
+ unrestrict-table (fn [table-id]
+ (data-perms/set-table-permission! all-users table-id :perms/create-queries :query-builder)
+ (data-perms/set-table-permission! all-users table-id :perms/view-data :unrestricted))
+ restrict-table (fn [table-id]
+ (data-perms/set-table-permission! all-users table-id :perms/create-queries :no)
+ (data-perms/set-table-permission! all-users table-id :perms/view-data :blocked))]
+ (perms/revoke-collection-permissions! (perms-group/all-users) (t2/select-one :model/Collection :name "Cryptozoology"))
+ (restrict-table monsters-table)
+ (testing "admin"
+ (mt/with-test-user :crowberto
+ (testing "collection permissions"
+ (is (some #{"Loch Ness Stuff"} (q "dashboard" "prehistoric monsters")))
+ (is (some #{"Bigfoot Sightings"} (q "card" "spooky video evidence"))))
+ (testing "data permissions"
+ (is (some #{"Monsters Table"} (q "table" "monster facts"))))))
+ (testing "all-users"
+ (mt/with-test-user :rasta
+ (testing "collection permissions"
+ (is (not-any? #{"Loch Ness Stuff"} (q "dashboard" "prehistoric monsters")))
+ (is (not-any? #{"Bigfoot Sightings"} (q "card" "spooky video evidence"))))
+ (testing "data permissions"
+ (is (not-any? #{"Monsters Table"} (q "table" "monster facts"))))
+ (testing "give data permissions"
+ (unrestrict-table monsters-table)
+ (data-perms/disable-perms-cache
+ (is (some #{"Monsters Table"} (q "table" "monster facts")))))))))))
+
+(deftest basic-batched-query-test
+ (testing "Small-batch reindexing"
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (binding [semantic.index/*batch-size* 1]
+ (semantic.tu/with-index!
+ (testing "Horse-related query finds horse content"
+ (let [results (semantic.tu/query-index {:search-string "marine mammal"})]
+ (is (= "Whale Communication" (-> results first :name)))))
+
+ (testing "Tiger-related query finds tiger content"
+ (let [results (semantic.tu/query-index {:search-string "endangered species"})]
+ (is (= "Tiger Conservation" (-> results first :name)))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj
new file mode 100644
index 00000000000..7cf35e1a023
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj
@@ -0,0 +1,177 @@
+(ns metabase-enterprise.semantic-search.scoring-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.search.appdb.scoring-test :refer [with-weights]]
+ [metabase.test :as mt])
+ (:import
+ (java.time Instant)
+ (java.time.temporal ChronoUnit)))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+(defn- add-doc-defaults
+ [doc]
+ (merge {:id 123
+ :searchable_text (:name doc)
+ :created_at #t "2025-01-01T12:00:00Z"
+ :creator_id (mt/user->id :rasta)
+ :archived false
+ :legacy_input {:id (or (:id doc) 123)
+ :model (:model doc)
+ :name (:name doc)}
+ :metadata {:title (:name doc)}}
+ doc))
+
+(defmacro with-index-contents!
+ "Populate the index with the given documents."
+ {:style/indent :defn}
+ [documents & body]
+ `(with-open [_# (semantic.tu/open-temp-index!)]
+ (semantic.tu/upsert-index! (map add-doc-defaults ~documents))
+ ~@body))
+
+(defn search-results*
+ [search-string & {:as raw-ctx}]
+ (mapv (juxt :model :id :name)
+ ;; side-step permissions for these tests
+ (mt/with-dynamic-fn-redefs [semantic.index/filter-read-permitted identity]
+ (semantic.tu/query-index (merge {:search-string search-string
+ :search-engine "semantic"
+ :current-user-id (mt/user->id :rasta)}
+ raw-ctx)))))
+
+(defn search-results
+ "Like search-results* but with a sanity check that search without weights returns a different result."
+ [ranker-key search-string & {:as raw-ctx}]
+ (let [result (with-weights {ranker-key 1} (search-results* search-string raw-ctx))
+ inverted (with-weights {ranker-key -1} (search-results* search-string raw-ctx))]
+ ;; note that this may not be a strict reversal, due to ties.
+ (is (not= inverted result)
+ "sanity check: search-no-weights should be different")
+ result))
+
+(deftest rrf-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-index-contents!
+ [{:model "card" :id 1 :name "orders"}
+ {:model "card" :id 2 :name "unrelated"}
+ {:model "card" :id 3 :name "classified" :searchable_text "available only by court order"}
+ {:model "card" :id 4 :name "order"}
+ {:model "card" :id 5 :name "orders, invoices, other stuff", :searchable_text "a verbose description"}
+ {:model "card" :id 6 :name "ordering"}]
+ (with-redefs [semantic.tu/mock-embeddings {"order" [0.11 -0.33 0.56 -0.77]
+ "orders" [0.12 -0.34 0.57 -0.78]
+ "ordering" [0.13 -0.35 0.58 -0.79]
+ "unrelated" [-0.1 -0.2 -0.3 -0.4]
+ "classified" [0.11 0.22 0.33 0.44]
+ "orders, invoices, other stuff" [0.17 -0.39 0.62 -0.83]
+ "available only by court order" [-0.11 -0.22 -0.33 -0.44]}]
+ (testing "Preferences according to textual matches"
+ ;; Note that, ceteris paribus, the ordering in the database is currently stable - this might change!
+ ;; Due to stemming, we do not distinguish between exact matches and those that differ slightly.
+ (is (= [["card" 1 "orders"]
+ ["card" 4 "order"]
+ ["card" 6 "ordering"]
+ ["card" 5 "orders, invoices, other stuff"]
+ ;; If the match is only in a secondary field, it is less preferred.
+ ["card" 3 "classified"]]
+ (search-results :rrf "order"))))))))
+
+(deftest exact-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-index-contents!
+ [{:model "card" :id 1 :name "the any most of stop words very"}
+ {:model "card" :id 2 :name "stop words"}]
+ (testing "Preferences according to exact name matches, including stop words"
+ (is (= [["card" 1 "the any most of stop words very"]
+ ["card" 2 "stop words"]]
+ (search-results :exact "the any most of stop words very")))))))
+
+(deftest prefix-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-index-contents!
+ [{:model "card" :id 1 :name "this is a prefix of something longer"}
+ {:model "card" :id 2 :name "a prefix this is not, unfortunately"}]
+ (testing "We can boost exact prefix matches"
+ (is (= [["card" 1 "this is a prefix of something longer"]
+ ["card" 2 "a prefix this is not, unfortunately"]]
+ (search-results :prefix "this is a prefix")))))))
+
+(deftest pinned-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-index-contents!
+ [{:model "card" :id 1 :name "not pinned" :pinned false}
+ {:model "card" :id 2 :name "yes pinned" :pinned true}]
+ (is (= [["card" 2 "yes pinned"]
+ ["card" 1 "not pinned"]]
+ (search-results :pinned "pinned"))))))
+
+(deftest mine-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-index-contents!
+ [{:model "card" :id 1 :name "crowberto" :creator_id (mt/user->id :crowberto)}
+ {:model "card" :id 2 :name "rasta" :creator_id (mt/user->id :rasta)}]
+ (is (= [["card" 2 "rasta"]
+ ["card" 1 "crowberto"]]
+ (search-results :mine "mine" {:current-user-id (mt/user->id :rasta)}))))))
+
+(deftest model-test
+ (mt/with-premium-features #{:semantic-search}
+ (with-index-contents!
+ [{:model "dataset" :id 1 :name "card ancient"}
+ {:model "card" :id 2 :name "card recent"}
+ {:model "metric" :id 3 :name "card old"}]
+ (testing "There is a preferred ordering in which different models are returned"
+ (is (= [["metric" 3 "card old"]
+ ["card" 2 "card recent"]
+ ["dataset" 1 "card ancient"]]
+ (search-results :model "card"))))
+ (testing "We can override this order with weights"
+ (is (= [["dataset" 1 "card ancient"]
+ ["metric" 3 "card old"]
+ ["card" 2 "card recent"]]
+ (with-weights {:model 1.0 :model/dataset 1.0}
+ (search-results* "card"))))))))
+
+(deftest recency-test
+ (mt/with-premium-features #{:semantic-search}
+ (let [right-now (Instant/now)
+ long-ago (.minus right-now 1 ChronoUnit/DAYS)
+ forever-ago (.minus right-now 10 ChronoUnit/DAYS)]
+ (with-index-contents!
+ [{:model "card" :id 1 :name "card ancient" :last_viewed_at forever-ago}
+ {:model "card" :id 2 :name "card recent" :last_viewed_at right-now}
+ {:model "card" :id 3 :name "card old" :last_viewed_at long-ago}]
+ (testing "More recently viewed results are preferred"
+ (is (= [["card" 2 "card recent"]
+ ["card" 3 "card old"]
+ ["card" 1 "card ancient"]]
+ (search-results :recency "card"))))))))
+
+(deftest dashboard-count-test
+ (mt/with-premium-features #{:semantic-search}
+ (testing "cards used in dashboard have higher rank"
+ (with-index-contents!
+ [{:model "card" :id 1 :name "card no used" :dashboardcard_count 2}
+ {:model "card" :id 2 :name "card used" :dashboardcard_count 3}]
+ (is (= [["card" 2 "card used"]
+ ["card" 1 "card no used"]]
+ (search-results :dashboard "card")))))))
+
+(defn indifferent?
+ "Check that the results and their order do not depend on the given ranker."
+ [ranker-key search-string & {:as raw-ctx}]
+ (= (with-weights {ranker-key 1} (search-results* search-string raw-ctx))
+ (with-weights {ranker-key -1} (search-results* search-string raw-ctx))))
+
+(deftest dashboard-count-test-2
+ (mt/with-premium-features #{:semantic-search}
+ (testing "it has a ceiling, more than the ceiling is considered to be equal"
+ (with-index-contents!
+ [{:model "card" :id 1 :name "card popular" :dashboardcard_count 200}
+ {:model "card" :id 2 :name "card" :dashboardcard_count 201}]
+ (is (indifferent? :dashboard "card"))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/test_util.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/test_util.clj
new file mode 100644
index 00000000000..d04987ad3a9
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/test_util.clj
@@ -0,0 +1,475 @@
+(ns metabase-enterprise.semantic-search.test-util
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [environ.core :refer [env]]
+ [honey.sql :as sql]
+ [honey.sql.helpers :as sql.helpers]
+ [metabase-enterprise.semantic-search.core]
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase-enterprise.semantic-search.db.migration :as semantic.db.migration]
+ [metabase-enterprise.semantic-search.embedding :as semantic.embedding]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
+ [metabase-enterprise.semantic-search.indexer :as semantic.indexer]
+ [metabase.search.core :as search.core]
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [next.jdbc :as jdbc]
+ [next.jdbc.protocols :as jdbc.protocols]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import
+ (clojure.lang IDeref)
+ (com.mchange.v2.c3p0 PooledDataSource)
+ (java.io Closeable)
+ (java.time Instant)))
+
+(set! *warn-on-reflection* true)
+
+;; If I won't find any use for following muted code in follow-up tasks I'll delete it -- lbrdnk
+
+(def default-test-db "my_test_db")
+
+(defn- alt-db-name-url
+ [url alt-name]
+ (when (string? url)
+ (u/prog1 (str/replace-first url
+ #"(^\S+//\S+/)([A-Za-z0-9_-]+)($|\?.*)"
+ (str "$1" alt-name "$3"))
+ (when (nil? <>) (throw (Exception. "Empty pgvector url."))))))
+
+(defn do-with-temp-datasource!
+ "Impl [[with-temp-datasource]]."
+ [db-name thunk]
+ (with-redefs [semantic.db.datasource/db-url (alt-db-name-url (:mb-pgvector-db-url env) db-name)
+ semantic.db.datasource/data-source (atom nil)]
+ (try
+ ;; ensure datasource was initialized so we can close it in finally.
+ (semantic.db.datasource/ensure-initialized-data-source!)
+ (thunk)
+ (finally
+ (.close ^PooledDataSource @semantic.db.datasource/data-source)))))
+
+(defmacro with-temp-datasource!
+ "Redefine datasource for testing, not thread-safe"
+ [db-name & body]
+ `(do-with-temp-datasource! ~db-name (fn [] ~@body)))
+
+(defn do-with-test-db!
+ "Impl [[with-test-db]]"
+ [db-name thunk]
+ (with-temp-datasource! "postgres"
+ (try
+ (jdbc/execute! (semantic.db.datasource/ensure-initialized-data-source!)
+ [(str "DROP DATABASE IF EXISTS " db-name " (FORCE)")])
+ (log/fatal "creating database")
+ (jdbc/execute! (semantic.db.datasource/ensure-initialized-data-source!)
+ [(str "CREATE DATABASE " db-name)])
+ (log/fatal "created database")
+ (catch java.sql.SQLException e
+ (log/fatal "creation failed")
+ (throw e))))
+ (with-temp-datasource! db-name
+ (thunk)))
+
+(defmacro with-test-db!
+ "Drop, create database dbname on pgvector and redefine datasource accordingly. Not thread safe."
+ [db-name & body]
+ `(do-with-test-db! ~db-name (fn [] ~@body)))
+
+(def ^:private init-delay
+ (delay
+ (when-not @semantic.db.datasource/data-source
+ (semantic.db.datasource/init-db!))))
+
+(defn once-fixture [f]
+ (when semantic.db.datasource/db-url
+ @init-delay
+ (f)))
+
+(declare db)
+
+#_{:clj-kondo/ignore [:metabase/test-helpers-use-non-thread-safe-functions]}
+(defn ensure-no-migration-table-fixture [f]
+ (semantic.db.migration/drop-migration-table! db)
+ (f)
+ (semantic.db.migration/drop-migration-table! db))
+
+(def db
+ "Proxies the semantic.db.datasource/data-source, avoids the deref and prettifies a little"
+ ;; proxy because semantic.db.datasource/data-source is not initialised until the fixture runs
+ (reify jdbc.protocols/Sourceable
+ (get-datasource [_] (jdbc.protocols/get-datasource @semantic.db.datasource/data-source))))
+
+(comment
+ (jdbc/execute! db ["select 1"]))
+
+(def mock-embeddings
+ "Static mapping from strings to (made-up) 4-dimensional embedding vectors for testing. Each pair of strings represents a
+ document and a search query that should be most semantically similar to it, according to the embeddings."
+ {"Dog Training Guide" [0.12 -0.34 0.56 -0.78]
+ "puppy" [0.13 -0.33 0.57 -0.77]
+ "Bird Watching Tips" [0.23 0.45 -0.67 0.89]
+ "avian" [0.24 0.46 -0.66 0.88]
+ "Cat Behavior Study" [0.11 -0.22 0.33 -0.44]
+ "feline" [0.12 -0.21 0.34 -0.43]
+ "Horse Racing Analysis" [0.55 0.66 -0.77 0.88]
+ "equine" [0.56 0.67 -0.76 0.87]
+ "Fish Tank Setup" [0.10 0.20 -0.30 0.40]
+ "aquatic" [0.11 0.21 -0.29 0.39]
+ "Elephant Migration" [0.15 -0.25 0.35 -0.45]
+ "pachyderm" [0.16 -0.24 0.36 -0.44]
+ "Lion Pride Dynamics" [0.31 0.42 -0.53 0.64]
+ "predator" [0.32 0.43 -0.52 0.63]
+ "Penguin Colony Study" [0.75 -0.86 0.97 -0.18]
+ "Antarctic wildlife" [0.76 -0.85 0.96 -0.17]
+ "Whale Communication" [0.29 0.38 -0.47 0.56]
+ "marine mammal" [0.30 0.39 -0.46 0.55]
+ "Tiger Conservation" [0.65 -0.74 0.83 -0.92]
+ "endangered species" [0.66 -0.73 0.84 -0.91]
+ "Butterfly Migration" [0.17 0.28 -0.39 0.50]
+ "insect patterns" [0.18 0.29 -0.38 0.49]})
+
+(defn get-mock-embedding
+ "Lookup the embedding for `text` in [[mock-embeddings]]."
+ [text]
+ (get mock-embeddings text [0.01 0.02 0.03 0.04]))
+
+(defn get-mock-embeddings-batch
+ "Lookup embeddings for multiple texts in [[mock-embeddings]]."
+ [texts]
+ (mapv get-mock-embedding texts))
+
+;;;; mock provider
+
+(def mock-embedding-model
+ {:provider "mock"
+ :model-name "model"
+ :vector-dimensions 4})
+
+(def mock-index-metadata
+ "An index metadata to qualify and isolate mock indexes"
+ {:version "0"
+ :metadata-table-name "mock_index_metadata"
+ :control-table-name "mock_index_control"
+ :gate-table-name "mock_index_gate"
+ :index-table-qualifier "_%s"})
+
+(defn unique-index-metadata
+ []
+ (let [uniq-id (System/nanoTime)
+ fmt (str "mock_%s_" uniq-id)]
+ {:version "0"
+ :metadata-table-name (format fmt "metadata")
+ :control-table-name (format fmt "control")
+ :gate-table-name (format fmt "gate")
+ :index-table-qualifier fmt}))
+
+(def mock-index
+ "A mock index for testing low level indexing functions.
+ Coincides with what the index-metadata system would create for the mock-embedding-model."
+ (-> (semantic.index/default-index mock-embedding-model)
+ (semantic.index-metadata/qualify-index mock-index-metadata)))
+
+(defmethod semantic.embedding/get-embedding "mock" [_ text] (get-mock-embedding text))
+(defmethod semantic.embedding/get-embeddings-batch "mock" [_ texts] (get-mock-embeddings-batch texts))
+(defmethod semantic.embedding/pull-model "mock" [_])
+
+(defn query-index [search-context]
+ (:results (semantic.index/query-index db mock-index search-context)))
+
+(defn upsert-index! [documents & opts]
+ (apply semantic.index/upsert-index! db mock-index documents opts))
+
+(defn delete-from-index! [model ids]
+ (semantic.index/delete-from-index! db mock-index model ids))
+
+(defn dog-training-native-query []
+ (mt/native-query {:query "SELECT AVG(tricks) FROM dogs WHERE age > 7 GROUP BY breed"}))
+
+(defn mock-documents []
+ (let [native-query-json (-> (dog-training-native-query) json/encode)]
+ [{:model "card"
+ :id 123
+ :name "Dog Training Guide"
+ :searchable_text "Dog Training Guide"
+ :created_at #t "2025-01-01T12:00:00Z"
+ :creator_id 1
+ :archived false
+ :legacy_input {:id 123
+ :model "card"
+ :dataset_query native-query-json}
+ :native_query native-query-json
+ :metadata {:title "Dog Training Guide"
+ :description "How to teach an old dog new tricks"
+ :native-query native-query-json}}
+ {:model "dashboard"
+ :id 456
+ :name "Elephant Migration"
+ :searchable_text "Elephant Migration"
+ :created_at #t "2025-02-01T12:00:00Z"
+ :creator_id 2
+ :archived true
+ :legacy_input {:model "dashboard" :id 456}
+ :metadata {:title "Elephant Migration" :description "How do elephants deal with schema upgrades?"}}]))
+
+(defn filter-for-mock-embeddings
+ "Filter results to only include items whose names are keys in mock-embeddings map."
+ [results]
+ (filter #(contains? mock-embeddings (:name %)) results))
+
+(defn closeable [o close-fn]
+ (reify
+ IDeref
+ (deref [_] o)
+ Closeable
+ (close [_] (close-fn o))))
+
+(defn open-temp-index! ^Closeable []
+ (closeable
+ (do (semantic.index/create-index-table-if-not-exists! db mock-index {:force-reset? true})
+ mock-index)
+ (fn cleanup-temp-index-table! [{:keys [table-name]}]
+ (try
+ (semantic.index/drop-index-table! db mock-index)
+ (catch Exception e
+ (log/error e "Warning: failed to clean up test table" table-name))))))
+
+(defmacro with-indexable-documents!
+ "Add a collection of test documents to that can be indexed to the appdb."
+ [& body]
+ `(mt/dataset ~(symbol "test-data")
+ (mt/with-temp [:model/Collection {col1# :id} {:name "Wildlife Collection" :archived false}
+
+ :model/Collection {col2# :id} {:name "Archived Animals" :archived true}
+
+ :model/Collection {col3# :id} {:name "Cryptozoology", :archived false}
+
+ :model/Card {card1# :id} {:name "Dog Training Guide" :collection_id col1# :creator_id (mt/user->id :crowberto) :archived false
+ :query_type "native" :dataset_query (dog-training-native-query)}
+
+ :model/Card {} {:name "Bird Watching Tips" :collection_id col1# :creator_id (mt/user->id :rasta) :archived false}
+
+ :model/Card {} {:name "Cat Behavior Study" :collection_id col2# :creator_id (mt/user->id :crowberto) :archived true}
+
+ :model/Card {} {:name "Horse Racing Analysis" :collection_id col1# :creator_id (mt/user->id :rasta) :archived false}
+
+ :model/Card {} {:name "Fish Tank Setup" :collection_id col2# :creator_id (mt/user->id :crowberto) :archived true}
+
+ :model/Card {} {:name "Bigfoot Sightings" :collection_id col3# :creator_id (mt/user->id :crowberto), :archived false}
+
+ :model/ModerationReview {} {:moderated_item_type "card"
+ :moderated_item_id card1#
+ :moderator_id (mt/user->id :crowberto)
+ :status "verified"
+ :most_recent true}
+
+ :model/Dashboard {} {:name "Elephant Migration" :collection_id col1# :creator_id (mt/user->id :rasta) :archived false}
+
+ :model/Dashboard {} {:name "Lion Pride Dynamics" :collection_id col1# :creator_id (mt/user->id :crowberto) :archived false}
+
+ :model/Dashboard {} {:name "Penguin Colony Study" :collection_id col2# :creator_id (mt/user->id :rasta) :archived true}
+
+ :model/Dashboard {} {:name "Whale Communication" :collection_id col1# :creator_id (mt/user->id :crowberto) :archived false}
+
+ :model/Dashboard {} {:name "Tiger Conservation" :collection_id col2# :creator_id (mt/user->id :rasta) :archived true}
+
+ :model/Dashboard {} {:name "Loch Ness Stuff" :collection_id col3# :creator_id (mt/user->id :crowberto), :archived false}
+
+ :model/Database {db-id# :id} {:name "Animal Database"}
+
+ :model/Table {} {:name "Species Table", :db_id db-id#}
+
+ :model/Table {} {:name "Monsters Table", :db_id db-id#, :active true}]
+ ~@body)))
+
+(defn index-all!
+ "Run indexer synchonously until we've exhausted polling all documents"
+ []
+ (let [metadata-row {:indexer_last_poll Instant/EPOCH
+ :indexer_last_seen Instant/EPOCH}
+ indexing-state (semantic.indexer/init-indexing-state metadata-row)
+ step (fn [] (semantic.indexer/indexing-step db mock-index-metadata mock-index indexing-state))]
+ (while (do (step) (pos? (:last-indexed-count @indexing-state))))))
+
+(defmacro blocking-index!
+ "Execute body ensuring [[index-all!]] is invoked at the end"
+ [& body]
+ `(let [ret# (do ~@body)]
+ (index-all!)
+ ret#))
+
+(defmacro with-index!
+ "Ensure a clean, small index for testing populated with a few collections, cards, and dashboards."
+ [& body]
+ `(with-indexable-documents!
+ (with-redefs [semantic.embedding/get-configured-model (fn [] mock-embedding-model)
+ semantic.index-metadata/default-index-metadata mock-index-metadata]
+ (with-open [_# (open-temp-index!)]
+ (binding [search.ingestion/*force-sync* true]
+ (blocking-index!
+ (search.core/reindex! :search.engine/semantic {:force-reset true}))
+ ~@body)))))
+
+(defn table-exists-in-db?
+ "Check if a table actually exists in the database"
+ [table-name]
+ (when table-name
+ (try
+ (let [result (jdbc/execute! db
+ ["SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = ?)"
+ (name table-name)])]
+ (-> result first vals first))
+ (catch Exception _ false))))
+
+(defn table-has-index?
+ [table-name index-name]
+ (when table-name
+ (try
+ (let [result (jdbc/execute! db
+ ["SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?)"
+ (name table-name)
+ (name index-name)])]
+ (-> result first vals first))
+ (catch Exception _ false))))
+
+(defn get-metadata-rows [pgvector index-metadata]
+ (jdbc/execute! pgvector
+ (-> {:select [:*]
+ :from [(keyword (:metadata-table-name index-metadata))]}
+ (sql/format :quoted true))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+
+(defn get-control-rows [pgvector index-metadata]
+ (jdbc/execute! pgvector
+ (-> {:select [:*]
+ :from [(keyword (:control-table-name index-metadata))]}
+ (sql/format :quoted true))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+
+(defn cleanup-index-metadata!
+ "A-la-carte drop everything related to the index-metdata root (including index tables themselves)"
+ [pgvector index-metadata]
+ (doseq [{:keys [table_name]}
+ (when (table-exists-in-db? (:metadata-table-name index-metadata))
+ (get-metadata-rows pgvector index-metadata))]
+ (semantic.index/drop-index-table! pgvector {:table-name table_name}))
+ (semantic.index-metadata/drop-tables-if-exists! pgvector index-metadata)
+ (semantic.db.migration/drop-migration-table! pgvector))
+
+(defn get-table-names [pgvector]
+ (->> ["select table_name from information_schema.tables"]
+ (jdbc/execute! pgvector)
+ (mapv :tables/table_name)))
+
+(defn- decode-column
+ [row column]
+ (update row column #'semantic.index/decode-pgobject))
+
+(defn- unwrap-column
+ [row column]
+ (update row column #'semantic.index/unwrap-pgobject))
+
+(defn- decode-embedding
+ "Decode `row`'s `:embedding` column."
+ [row]
+ (decode-column row :embedding))
+
+(defn- unwrap-tsvectors
+ "Decode `row`'s `:text_search_vector` and `:text_search_with_native_query_vector` columns."
+ [row]
+ (-> row
+ (unwrap-column :text_search_vector)
+ (unwrap-column :text_search_with_native_query_vector)))
+
+#_:clj-kondo/ignore
+(defn full-index
+ "Query the full index table and return all documents with decoded embeddings.
+ Not used in tests, but useful for debugging."
+ []
+ (->> (jdbc/execute! db
+ (-> (sql.helpers/select :model :model_id :content :creator_id :embedding)
+ (sql.helpers/from (keyword (:table-name mock-index)))
+ semantic.index/sql-format-quoted)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ (mapv decode-embedding)))
+
+(defn query-embeddings
+ "Query the `mock-index` table and return the decoded `:embedding`s for the given `model`"
+ [{:keys [model model_id]}]
+ (->> (jdbc/execute! db
+ (-> (sql.helpers/select :model :model_id :content :creator_id :embedding)
+ (sql.helpers/from (keyword (:table-name mock-index)))
+ (sql.helpers/where :and
+ [:= :model model]
+ [:= :model_id model_id])
+ semantic.index/sql-format-quoted)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ (mapv decode-embedding)))
+
+(defn query-tsvectors
+ "Query the `mock-index` table and return the unwrapped tsvector columns for the given `model`"
+ [{:keys [model model_id]}]
+ (->> (jdbc/execute! db
+ (-> (sql.helpers/select :model :model_id :content :creator_id
+ :text_search_vector :text_search_with_native_query_vector)
+ (sql.helpers/from (keyword (:table-name mock-index)))
+ (sql.helpers/where :and
+ [:= :model model]
+ [:= :model_id model_id])
+ semantic.index/sql-format-quoted)
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ (mapv unwrap-tsvectors)))
+
+(defn check-index-has-no-mock-card []
+ (testing "no mock card present"
+ (is (= []
+ (query-embeddings {:model "card"
+ :model_id "123"})))))
+
+(defn check-index-has-no-mock-dashboard []
+ (testing "no mock dashboard present"
+ (is (= []
+ (query-embeddings {:model "dashboard"
+ :model_id "456"})))))
+
+(defn check-index-has-no-mock-docs []
+ (let [{:keys [table-name]} mock-index
+ table-exists-sql "select exists(select * from information_schema.tables where table_name = ?) table_exists"
+ [{:keys [table_exists]}] (jdbc/execute! db [table-exists-sql table-name])]
+ (when table_exists
+ (check-index-has-no-mock-card)
+ (check-index-has-no-mock-dashboard))))
+
+(defn check-index-has-mock-card []
+ (is (= [{:model "card"
+ :model_id "123"
+ :creator_id 1
+ :content "Dog Training Guide"
+ :embedding (get-mock-embedding "Dog Training Guide")}]
+ (query-embeddings {:model "card"
+ :model_id "123"}))))
+
+(defn check-index-has-mock-dashboard []
+ (is (= [{:model "dashboard"
+ :model_id "456"
+ :creator_id 2
+ :content "Elephant Migration"
+ :embedding (get-mock-embedding "Elephant Migration")}]
+ (query-embeddings {:model "dashboard"
+ :model_id "456"}))))
+
+(defn check-index-has-mock-docs []
+ (check-index-has-mock-card)
+ (check-index-has-mock-dashboard))
+
+(defn spy [f]
+ (let [calls (atom [])]
+ {:calls calls
+ :proxy (fn [& args]
+ (let [ret (apply f args)]
+ (swap! calls conj {:args args, :ret ret})
+ ret))}))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/without_init_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/without_init_test.clj
new file mode 100644
index 00000000000..28133cf9f69
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/without_init_test.clj
@@ -0,0 +1,44 @@
+(ns metabase-enterprise.semantic-search.without-init-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.core :as semantic]
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase-enterprise.semantic-search.env :as semantic.env]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.test :as mt]))
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+;; When booting a new install from a fresh app db, we can wind up getting calls into the search backend from things
+;; like loading the sample or audit db content before search has been initialized, and therefore before receiving an
+;; init! call. These tests ensure that we can handle such calls and don't throw if it does happen.
+
+(defn- without-init! [test-func]
+ (mt/with-premium-features #{:semantic-search}
+ (try
+ (semantic.tu/cleanup-index-metadata! semantic.tu/db semantic.tu/mock-index-metadata)
+ (with-redefs [semantic.db.datasource/data-source (atom nil)
+ semantic.env/get-index-metadata (constantly semantic.tu/mock-index-metadata)
+ semantic.env/get-configured-embedding-model (constantly semantic.tu/mock-embedding-model)]
+ (test-func))
+ (finally
+ (semantic.tu/cleanup-index-metadata! semantic.tu/db semantic.tu/mock-index-metadata)))))
+
+(deftest reindex!-without-init!-test
+ (without-init!
+ #(testing "reindex! works without init!"
+ (semantic.tu/blocking-index!
+ (semantic/reindex! (semantic.tu/mock-documents) {}))
+ (semantic.tu/check-index-has-mock-docs))))
+
+(deftest update-index!-without-init!-test
+ (without-init!
+ #(testing "update-index! is a no-op without init!"
+ (is (nil? (semantic/update-index! (semantic.tu/mock-documents))))
+ (is (not (semantic.tu/table-exists-in-db? (:table-name semantic.tu/mock-index)))))))
+
+(deftest delete-from-index!-without-init!-test
+ (without-init!
+ #(testing "delete-from-index! is a no-op without init!"
+ (is (nil? (semantic/delete-from-index! "card" ["123"])))
+ (is (not (semantic.tu/table-exists-in-db? (:table-name semantic.tu/mock-index)))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/api/search.ts b/enterprise/frontend/src/metabase-enterprise/api/search.ts
new file mode 100644
index 00000000000..02c402f2bae
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/api/search.ts
@@ -0,0 +1,17 @@
+import { EnterpriseApi } from "./api";
+
+export const searchApi = EnterpriseApi.injectEndpoints({
+ endpoints: (builder) => ({
+ getSemanticSearchStatus: builder.query<
+ { indexed_count: number; total_est: number },
+ void
+ >({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/semantic-search/status",
+ }),
+ }),
+ }),
+});
+
+export const { useGetSemanticSearchStatusQuery } = searchApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.js b/enterprise/frontend/src/metabase-enterprise/plugins.js
index 02c55793de7..1df336e3fa7 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.js
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.js
@@ -39,3 +39,4 @@ import "./user_provisioning";
import "./clean_up";
import "./metabot";
import "./database_replication";
+import "./semantic_search";
diff --git a/enterprise/frontend/src/metabase-enterprise/semantic_search/SearchSettingsWidget.tsx b/enterprise/frontend/src/metabase-enterprise/semantic_search/SearchSettingsWidget.tsx
new file mode 100644
index 00000000000..391ac0f0a35
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/semantic_search/SearchSettingsWidget.tsx
@@ -0,0 +1,123 @@
+import { useEffect, useState } from "react";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { SettingHeader } from "metabase/admin/settings/components/SettingHeader";
+import { BasicAdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";
+import { UpsellSemanticSearchPill } from "metabase/admin/upsells/UpsellSemanticSearch";
+import { getErrorMessage, useAdminSetting } from "metabase/api/utils";
+import { getPlan, isProPlan } from "metabase/common/utils/plan";
+import { useSelector } from "metabase/lib/redux";
+import { getSetting } from "metabase/selectors/settings";
+import { Box, Progress, Stack, Text, Tooltip } from "metabase/ui";
+import { useGetSemanticSearchStatusQuery } from "metabase-enterprise/api/search";
+
+function useLatch(bool: boolean) {
+ const [hasSeenTrue, setHasSeenTrue] = useState(bool);
+
+ useEffect(() => {
+ if (bool && !hasSeenTrue) {
+ setHasSeenTrue(true);
+ }
+ }, [hasSeenTrue, bool]);
+
+ return hasSeenTrue;
+}
+
+export function SearchSettingsWidget({
+ statusPollingInterval = 5000,
+}: {
+ statusPollingInterval?: number;
+}) {
+ const plan = useSelector((state) =>
+ getPlan(getSetting(state, "token-features")),
+ );
+ const shouldUpsell = !isProPlan(plan);
+
+ const { value } = useAdminSetting("search-engine");
+ const semanticSearchEnabled = value === "semantic";
+
+ const [hasFinishedIndexing, setHasFinishedIndexing] = useState(false);
+ const response = useGetSemanticSearchStatusQuery(undefined, {
+ pollingInterval: statusPollingInterval,
+ skip: !semanticSearchEnabled || hasFinishedIndexing,
+ });
+ const { indexed_count = 0, total_est = 1 } = response.data || {};
+
+ // total records is an estimate, assume we're done a bit early
+ // to avoid showing status when we shouldn't
+ const estimatedPercentComplete = Math.round(
+ (indexed_count / total_est) * 100,
+ );
+ const progress =
+ estimatedPercentComplete >= 95 ? 100 : estimatedPercentComplete;
+
+ useEffect(() => {
+ if (progress === 100) {
+ setHasFinishedIndexing(true);
+ }
+ }, [progress]);
+
+ const isIndexing = useLatch(response.data !== undefined && progress !== 100);
+
+ return (
+ <Stack data-testid="search-engine-setting">
+ <Stack gap="0">
+ <SettingHeader
+ id="search-engine"
+ title={t`Advanced semantic search`}
+ description={t`Provides more relevant search results.`}
+ />
+
+ {shouldUpsell && (
+ <div>
+ <UpsellSemanticSearchPill source="settings-general" />
+ </div>
+ )}
+ </Stack>
+
+ {!shouldUpsell && (
+ <>
+ <Box>
+ <Tooltip label={t`Contact support to change this setting.`}>
+ <Box display="inline-flex">
+ <BasicAdminSettingInput
+ name="search-engine"
+ inputType="boolean"
+ value={semanticSearchEnabled}
+ disabled
+ onChange={_.noop}
+ />
+ </Box>
+ </Tooltip>
+ </Box>
+
+ {response.error && (
+ <Text c="error">
+ {getErrorMessage(
+ response,
+ t`Unable to fetch health status of search index.`,
+ )}
+ </Text>
+ )}
+
+ {!response.error && isIndexing && (
+ <Stack gap="xs">
+ <Progress
+ size="md"
+ value={progress}
+ maw="25rem"
+ animated={progress < 100}
+ />
+ <Text c="text-light" size="md">
+ {progress === 100
+ ? t`Initialized search index`
+ : t`Initializing search index...`}
+ </Text>
+ </Stack>
+ )}
+ </>
+ )}
+ </Stack>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/semantic_search/SearchSettingsWidget.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/semantic_search/SearchSettingsWidget.unit.spec.tsx
new file mode 100644
index 00000000000..4ae359daa1a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/semantic_search/SearchSettingsWidget.unit.spec.tsx
@@ -0,0 +1,155 @@
+import fetchMock from "fetch-mock";
+import { match } from "ts-pattern";
+
+import {
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type {
+ SearchEngineSettingValue,
+ TokenFeatures,
+} from "metabase-types/api";
+import {
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import {
+ createMockSettingsState,
+ createMockState,
+} from "metabase-types/store/mocks";
+
+import { SearchSettingsWidget } from "./SearchSettingsWidget";
+
+const defaultMockSearchStatus = {
+ indexed_count: 50,
+ total_est: 100,
+};
+
+const setup = async (
+ searchEngine: SearchEngineSettingValue,
+ plan: "pro" | "starter",
+ searchStatusData = defaultMockSearchStatus,
+ statusPollingInterval?: number,
+) => {
+ const tokenFeatures: Partial<TokenFeatures> = match(plan)
+ .with("pro", () => ({
+ semantic_search: true,
+ hosting: true,
+ }))
+ .with("starter", () => ({
+ hosting: true,
+ }))
+ .exhaustive();
+
+ const settings = createMockSettings({
+ "search-engine": searchEngine,
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ });
+
+ setupPropertiesEndpoints(settings);
+ setupSettingsEndpoints([
+ {
+ key: "search-engine",
+ value: searchEngine,
+ is_env_setting: false,
+ description: "Search engine to use",
+ env_name: "METABASE_SEARCH_ENGINE",
+ },
+ ]);
+
+ // Mock the search status API
+ fetchMock.get("path:/api/ee/semantic-search/status", searchStatusData, {
+ name: "search-sync-status",
+ });
+
+ renderWithProviders(
+ <SearchSettingsWidget statusPollingInterval={statusPollingInterval} />,
+ {
+ storeInitialState: createMockState({
+ settings: createMockSettingsState(settings),
+ currentUser: createMockUser({ is_superuser: true }),
+ }),
+ },
+ );
+
+ expect(
+ await screen.findByTestId("search-engine-setting"),
+ ).toBeInTheDocument();
+};
+
+const progressBar = () => screen.findByRole("progressbar");
+const toggle = () => screen.findByRole("switch");
+
+describe("SearchSettingsWidget", () => {
+ it("should display upsell for non-pro plans", async () => {
+ await setup("semantic", "starter");
+ expect(
+ await screen.findByText(/Advanced semantic search/),
+ ).toBeInTheDocument();
+ expect(await screen.findByText(/Get this with Pro/)).toBeInTheDocument();
+ });
+
+ it("should display setting toggle as disabled for pro plans", async () => {
+ await setup("semantic", "pro");
+
+ expect(
+ await screen.findByText("Advanced semantic search"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("upsell-semantic-search"),
+ ).not.toBeInTheDocument();
+ expect(await toggle()).toBeDisabled();
+ expect(await toggle()).toBeChecked();
+ });
+
+ it("should show progress when indexing is in progress", async () => {
+ await setup("semantic", "pro", { indexed_count: 25, total_est: 100 });
+
+ expect(
+ await screen.findByText("Initializing search index..."),
+ ).toBeInTheDocument();
+ expect(await progressBar()).toHaveAttribute("aria-valuenow", "25");
+ });
+
+ it("should not show progress when once indexing is complete", async () => {
+ await setup("semantic", "pro", { indexed_count: 50, total_est: 100 }, 50);
+
+ expect(
+ await screen.findByText("Initializing search index..."),
+ ).toBeInTheDocument();
+ expect(await progressBar()).toHaveAttribute("aria-valuenow", "50");
+
+ fetchMock.modifyRoute("search-sync-status", {
+ response: () => ({
+ indexed_count: 100,
+ total_est: 100,
+ }),
+ });
+ expect(
+ await screen.findByText(/Initialized search index/),
+ ).toBeInTheDocument();
+ expect(await progressBar()).toHaveAttribute("aria-valuenow", "100");
+ });
+
+ it("should not show progress when indexing was already complete", async () => {
+ await setup("semantic", "pro", { indexed_count: 100, total_est: 100 });
+
+ await waitFor(() => {
+ expect(
+ screen.queryByText("Initializing search index..."),
+ ).not.toBeInTheDocument();
+ });
+ expect(screen.queryByRole("progressbar")).not.toBeInTheDocument();
+ });
+
+ it("should handle API errors", async () => {
+ fetchMock.get("path:/api/ee/semantic-search/status", 500);
+ await setup("semantic", "pro");
+
+ expect(
+ await screen.findByText("Unable to fetch health status of search index."),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/semantic_search/index.tsx b/enterprise/frontend/src/metabase-enterprise/semantic_search/index.tsx
new file mode 100644
index 00000000000..610115d163f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/semantic_search/index.tsx
@@ -0,0 +1,8 @@
+import { PLUGIN_SEMANTIC_SEARCH } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import { SearchSettingsWidget } from "./SearchSettingsWidget";
+
+if (hasPremiumFeature("semantic_search")) {
+ PLUGIN_SEMANTIC_SEARCH.SearchSettingsWidget = SearchSettingsWidget;
+}
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index fb2a545b456..6c59ac6b38f 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -134,6 +134,7 @@ export const createMockTokenFeatures = (
ai_sql_generation: false,
database_routing: false,
development_mode: false,
+ semantic_search: false,
...opts,
});
@@ -332,6 +333,7 @@ export const createMockSettings = (
"scim-enabled": false,
"scim-base-url": "http://localhost:3000/api/ee/scim/v2/",
"snowplow-url": "",
+ "search-engine": "appdb",
"search-typeahead-enabled": true,
"setup-token": null,
"session-cookies": null,
diff --git a/frontend/src/metabase-types/api/search.ts b/frontend/src/metabase-types/api/search.ts
index 88920ffc229..a3119095aae 100644
--- a/frontend/src/metabase-types/api/search.ts
+++ b/frontend/src/metabase-types/api/search.ts
@@ -133,7 +133,7 @@ export type SearchRequest = {
include_metadata?: boolean | null;
non_temporal_dim_ids?: string | null;
has_temporal_dim?: boolean | null;
- search_engine?: string | null;
+ search_engine?: "appdb" | "in-place" | "semantic" | null;
display_type?: string[] | null;
// this should be in ListCollectionItemsRequest but legacy code expects them here
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index fd244819e09..03dd3ea9894 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -286,6 +286,7 @@ export const tokenFeatures = [
"development_mode",
"etl_connections",
"etl_connections_pg",
+ "semantic_search",
] as const;
export type TokenFeature = (typeof tokenFeatures)[number];
@@ -577,6 +578,8 @@ export type ColorSettings = Record<string, string>;
export type IllustrationSettingValue = "default" | "none" | "custom";
export type TimeoutValue = { amount: number; unit: string };
+export type SearchEngineSettingValue = "semantic" | "appdb" | "in-place";
+
export type DatabaseReplicationConnections = Record<
DatabaseId,
{ connection_id: string }
@@ -598,6 +601,7 @@ export interface EnterpriseSettings extends Settings {
"ee-openai-api-key"?: string;
"ee-openai-model"?: string;
"session-timeout": TimeoutValue | null;
+ "search-engine": SearchEngineSettingValue | null;
"scim-enabled"?: boolean | null;
"scim-base-url"?: string;
"send-new-sso-user-admin-email?"?: boolean;
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx
index 7749323deed..db29109c892 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx
@@ -7,7 +7,7 @@ import {
import { UpsellDevInstances } from "metabase/admin/upsells";
import ExternalLink from "metabase/common/components/ExternalLink";
import { useDocsUrl } from "metabase/common/hooks";
-import { PLUGIN_LANDING_PAGE } from "metabase/plugins";
+import { PLUGIN_LANDING_PAGE, PLUGIN_SEMANTIC_SEARCH } from "metabase/plugins";
import { DevInstanceBanner } from "../GeneralSettings/DevInstanceBanner";
import { AdminSettingInput } from "../widgets/AdminSettingInput";
@@ -36,6 +36,8 @@ export function GeneralSettingsPage() {
<HttpsOnlyWidget />
+ <PLUGIN_SEMANTIC_SEARCH.SearchSettingsWidget />
+
<CustomHomepageDashboardSetting />
<PLUGIN_LANDING_PAGE.LandingPageWidget />
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx
index 6ec3cf7400d..6e3f25c69af 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx
@@ -32,6 +32,7 @@ const generalSettings = {
"humanization-strategy": "simple",
"enable-xrays": false,
"allowed-iframe-hosts": "https://cooldashboards.limo",
+ "search-engine": "appdb",
} as const;
const setup = async () => {
diff --git a/frontend/src/metabase/admin/upsells/UpsellSemanticSearch.tsx b/frontend/src/metabase/admin/upsells/UpsellSemanticSearch.tsx
new file mode 100644
index 00000000000..6c0406950f1
--- /dev/null
+++ b/frontend/src/metabase/admin/upsells/UpsellSemanticSearch.tsx
@@ -0,0 +1,12 @@
+import { t } from "ttag";
+
+import { UpsellPill } from "./components";
+import { UPGRADE_URL } from "./constants";
+
+export const UpsellSemanticSearchPill = ({ source }: { source: string }) => {
+ return (
+ <UpsellPill campaign="semantic-search" link={UPGRADE_URL} source={source}>
+ {t`Get this with Pro. Try for free.`}
+ </UpsellPill>
+ );
+};
diff --git a/frontend/src/metabase/common/utils/plan.ts b/frontend/src/metabase/common/utils/plan.ts
index cae30ddd5ec..cd314aa0e39 100644
--- a/frontend/src/metabase/common/utils/plan.ts
+++ b/frontend/src/metabase/common/utils/plan.ts
@@ -1,13 +1,12 @@
import type { TokenFeatures } from "metabase-types/api";
import { tokenFeatures } from "metabase-types/api";
-export type Plan =
- | "oss"
- | "starter"
- | "starter-with-dwh"
- | "pro-cloud"
- | "pro-cloud-with-dwh"
- | "pro-self-hosted";
+export type ProPlan = "pro-cloud" | "pro-cloud-with-dwh" | "pro-self-hosted";
+
+export type Plan = "oss" | "starter" | "starter-with-dwh" | ProPlan;
+
+export const isProPlan = (plan: Plan): plan is ProPlan =>
+ plan.startsWith("pro-");
export const getPlan = (features?: TokenFeatures | null): Plan => {
if (features) {
@@ -17,6 +16,7 @@ export const getPlan = (features?: TokenFeatures | null): Plan => {
feature !== "attached_dwh" &&
features[feature],
);
+
if (hasAnyProFeatures) {
if (features.hosting) {
return features.attached_dwh ? "pro-cloud-with-dwh" : "pro-cloud";
diff --git a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx
index 078936dcf6b..b335e1a4676 100644
--- a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx
@@ -328,7 +328,7 @@ describe("LinkedEntityPicker", () => {
await screen.findByPlaceholderText(/search/i),
typedText,
);
- await userEvent.click(screen.getByText("Everywhere"));
+ await userEvent.click(await screen.findByText("Everywhere"));
expect(
await screen.findByText(questionSearchResult.name),
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 66e57024a23..c30d938d2ad 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -804,3 +804,7 @@ export const PLUGIN_SMTP_OVERRIDE: {
CloudSMTPConnectionCard: PluginPlaceholder,
SMTPOverrideConnectionForm: PluginPlaceholder,
};
+
+export const PLUGIN_SEMANTIC_SEARCH = {
+ SearchSettingsWidget: PluginPlaceholder,
+};
diff --git a/src/metabase/analytics/core.clj b/src/metabase/analytics/core.clj
index ae7ff26384c..c27d1d6bfe3 100644
--- a/src/metabase/analytics/core.clj
+++ b/src/metabase/analytics/core.clj
@@ -24,6 +24,7 @@
clear!
connection-pool-info
inc!
+ observe!
set!
setup!
shutdown!]
diff --git a/src/metabase/analytics/prometheus.clj b/src/metabase/analytics/prometheus.clj
index e9f87d1ae82..2344e2fb754 100644
--- a/src/metabase/analytics/prometheus.clj
+++ b/src/metabase/analytics/prometheus.clj
@@ -276,7 +276,9 @@
;; 1ms -> 10minutes
:buckets [1 500 1000 5000 10000 30000 60000 120000 300000 600000]})
(prometheus/gauge :metabase-search/appdb-index-size
- {:description "Number of rows in the active index table."})
+ {:description "Number of rows in the active appdb index table."})
+ (prometheus/gauge :metabase-search/semantic-index-size
+ {:description "Number of rows in the active semantic index table."})
(prometheus/gauge :metabase-search/queue-size
{:description "Number of updates on the search indexing queue."})
(prometheus/counter :metabase-search/response-ok
@@ -289,7 +291,29 @@
(prometheus/gauge :metabase-search/engine-active
{:description "Whether a given engine is active. This does NOT mean that it is the default."
:labels [:engine]})
- ;; notification metrics
+ (prometheus/counter :metabase-search/semantic-embedding-tokens
+ {:description (str "Number of tokens consumed by the given embedding model and provider. "
+ "Not all providers track token use.")
+ :labels [:model :provider]})
+ (prometheus/counter :metabase-search/permission-filtering-ms
+ {:description "Total number of ms spent filtering readable docs"})
+ (prometheus/counter :metabase-search/semantic-search-ms
+ {:description "Total number of ms spent performing a semantic search"
+ :labels [:embedding-model]})
+ (prometheus/counter :metabase-search/semantic-embedding-ms
+ {:description "Total number of ms spent calculating the embedding of the search string"
+ :labels [:embedding-model]})
+ (prometheus/counter :metabase-search/semantic-db-query-ms
+ {:description "Total number of ms spent querying the search index"
+ :labels [:embedding-model]})
+ (prometheus/counter :metabase-search/semantic-fallback-triggered
+ {:description "Number of times semantic search triggered fallback to appdb search due to insufficient results"
+ :labels [:fallback-engine]})
+ (prometheus/histogram :metabase-search/semantic-results-before-fallback
+ {:description "Distribution of result counts from semantic search when fallback is triggered"
+ :buckets [0 1 5 10 20 50 100]})
+
+;; notification metrics
(prometheus/counter :metabase-notification/send-ok
{:description "Number of successful notification sends."
:labels [:payload-type]})
diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.clj
index c07f72ca3c8..4c0ea3e7bbf 100644
--- a/src/metabase/analytics/stats.clj
+++ b/src/metabase/analytics/stats.clj
@@ -736,7 +736,7 @@
(defn- ee-snowplow-features-data'
[]
- (let [features [:sso-jwt :sso-saml :scim :sandboxes :email-allow-list]]
+ (let [features [:sso-jwt :sso-saml :scim :sandboxes :email-allow-list :semantic-search]]
(map
(fn [feature]
{:name feature
diff --git a/src/metabase/permissions/models/collection/graph.clj b/src/metabase/permissions/models/collection/graph.clj
index 0e6433011f9..5b9f088e652 100644
--- a/src/metabase/permissions/models/collection/graph.clj
+++ b/src/metabase/permissions/models/collection/graph.clj
@@ -87,7 +87,6 @@
(defn- calculate-perm-groups [collection-namespace group-id->perms collection-ids]
(into {}
- #_:clj-kondo/ignore
(cp/with-shutdown! [pool (+ 2 (cp/ncpus))]
(doall (cp/upmap pool
(fn [group-id]
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index 71b7c4359df..5cdf1374e1b 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -61,6 +61,7 @@
enable-query-reference-validation?
enable-sandboxes?
enable-scim?
+ enable-semantic-search?
enable-serialization?
enable-session-timeout-config?
enable-snippet-collections?
diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.clj
index d704a94b951..afd6c0a394e 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -271,6 +271,10 @@
"Does the Metabase Cloud instance have ETL connections with PG?"
:etl-connections-pg)
+(define-premium-feature ^{:added "0.56.0"} enable-semantic-search?
+ "Should we enable the semantic search backend?"
+ :semantic-search)
+
(define-premium-feature ^{:added "0.57.0"} table-data-editing?
"Should we allow users to edit the data within tables?"
:table-data-editing)
@@ -308,6 +312,7 @@
:query_reference_validation (enable-query-reference-validation?)
:sandboxes (enable-sandboxes?)
:scim (enable-scim?)
+ :semantic_search (enable-semantic-search?)
:serialization (enable-serialization?)
:session_timeout_config (enable-session-timeout-config?)
:snippet_collections (enable-snippet-collections?)
diff --git a/src/metabase/search/appdb/core.clj b/src/metabase/search/appdb/core.clj
index 878c13befb4..d02f7a71593 100644
--- a/src/metabase/search/appdb/core.clj
+++ b/src/metabase/search/appdb/core.clj
@@ -1,6 +1,5 @@
(ns metabase.search.appdb.core
(:require
- [clojure.string :as str]
[environ.core :as env]
[honey.sql.helpers :as sql.helpers]
[java-time.api :as t]
@@ -16,6 +15,7 @@
[metabase.search.ingestion :as search.ingestion]
[metabase.search.permissions :as search.permissions]
[metabase.search.settings :as search.settings]
+ [metabase.search.util :as search.util]
[metabase.settings.core :as setting]
[metabase.util :as u]
[metabase.util.i18n :as i18n]
@@ -41,33 +41,24 @@
#{:postgres :h2})
(defmethod search.engine/supported-engine? :search.engine/appdb [_]
- (and (or (not config/is-prod?)
- (= "appdb" (some-> (search.settings/search-engine) name)))
+ (and (or config/is-dev?
+ ;; if the default engine is semantic we want appdb to be available,
+ ;; as we want to mix results
+ (#{"appdb" "semantic"} (some-> (search.settings/search-engine) name)))
(supported-db? (mdb/db-type))))
(defn- parse-datetime [s]
(when s (OffsetDateTime/parse s)))
-(defn- collapse-id [{:keys [id] :as row}]
- (assoc row :id (if (number? id) id (parse-long (last (str/split (:id row) #":"))))))
-
(defn- rehydrate [weights active-scorers index-row]
(-> (json/decode+kw (:legacy_input index-row))
- collapse-id
+ search.util/collapse-id
(assoc
;; this relies on the corresponding scorer, which is not great coupling.
;; ideally we would make per-user computed attributes part of the spec itself.
:bookmark (pos? (:bookmarked index-row 0))
:score (:total_score index-row 1)
- :all-scores (mapv (fn [k]
- ;; we shouldn't get null scores, but just in case (i.e., because there are bugs)
- (let [score (or (get index-row k) 0)
- weight (or (weights k) 0)]
- {:score score
- :name k
- :weight weight
- :contribution (* weight score)}))
- active-scorers))
+ :all-scores (search.scoring/all-scores weights active-scorers index-row))
(update :created_at parse-datetime)
(update :updated_at parse-datetime)
(update :last_edited_at parse-datetime)))
@@ -102,7 +93,7 @@
true (sql.helpers/where (or-null permitted-clause))
personal-clause (sql.helpers/where (or-null personal-clause)))))
-(defmethod search.engine/results :search.engine/appdb
+(defn- results
[{:keys [search-engine search-string] :as search-ctx}]
;; Check whether there is a query-able index.
(when-not (search.index/active-table)
@@ -153,6 +144,10 @@
(#'search.index/sync-tracking-atoms!)
(throw e))))
+(defmethod search.engine/results :search.engine/appdb
+ [search-ctx]
+ (results search-ctx))
+
(defmethod search.engine/model-set :search.engine/appdb
[search-ctx]
;; We ignore any current models filter
diff --git a/src/metabase/search/appdb/scoring.clj b/src/metabase/search/appdb/scoring.clj
index 4659eca7e2b..be55ab6eaa9 100644
--- a/src/metabase/search/appdb/scoring.clj
+++ b/src/metabase/search/appdb/scoring.clj
@@ -1,78 +1,20 @@
(ns metabase.search.appdb.scoring
(:require
[clojure.core.memoize :as memoize]
- [clojure.string :as str]
[honey.sql.helpers :as sql.helpers]
[metabase.config.core :as config]
[metabase.premium-features.core :refer [defenterprise]]
[metabase.search.appdb.index :as search.index]
[metabase.search.appdb.specialization.api :as specialization]
[metabase.search.config :as search.config]
+ [metabase.search.scoring :as search.scoring]
[metabase.util :as u]
[toucan2.core :as t2]))
-(def ^:private seconds-in-a-day 86400)
-
-(defn truthy
- "Prefer it when a (potentially nullable) boolean is true."
- [column]
- [:coalesce [:cast column :integer] [:inline 0]])
-
-(defn equal
- "Prefer it when it matches a specific (non-null) value"
- [column value]
- [:coalesce [:case [:= column value] [:inline 1] :else [:inline 0]] [:inline 0]])
-
-(defn prefix
- "Prefer it when the given value is a completion of a specific (non-null) value"
- [column value]
- [:coalesce [:case [:like column (str (str/replace value "%" "%%") "%")] [:inline 1] :else [:inline 0]] [:inline 0]])
-
-(defn size
- "Prefer items whose value is larger, up to some saturation point. Items beyond that point are equivalent."
- [column ceiling]
- [:least
- [:inline 1]
- [:/
- [:coalesce column [:inline 0]]
- ;; protect against div / 0
- [:greatest
- [:inline 1]
- (if (number? ceiling)
- [:inline (double ceiling)]
- [:cast ceiling :float])]]])
-
-(defn inverse-duration
- "Score at item based on the duration between two dates, where less is better."
- [from-column to-column ceiling-in-days]
- (let [ceiling [:inline ceiling-in-days]]
- [:/
- [:greatest
- [:- ceiling
- [:/
- ;; Use seconds for granularity in the fraction.
- ;; TODO will probably need to specialize this based on (mdb/db-type)
- [[:raw "EXTRACT(epoch FROM (" [:- to-column from-column] [:raw "))"]]]
- [:inline (double seconds-in-a-day)]]]
- [:inline 0]]
- ceiling]))
-
-(defn- sum-columns [column-names]
- (if (seq column-names)
- (reduce (fn [expr col] [:+ expr col])
- (first column-names)
- (rest column-names))
- [:inline 1]))
-
-(defn- weighted-score [context [column-alias expr]]
- [:* [:inline (search.config/weight context column-alias)] expr])
-
-(defn- select-items [context scorers]
- (concat
- (for [[column-alias expr] scorers]
- [expr column-alias])
- [[(sum-columns (map (partial weighted-score context) scorers))
- :total_score]]))
+(defn all-scores
+ "Score stats for each scorer"
+ [weights scorers index-row]
+ (search.scoring/all-scores weights scorers index-row))
;; TODO move these to the spec definitions
(def ^:private bookmarked-models [:card :collection :dashboard])
@@ -119,9 +61,9 @@
(let [views (view-count-percentiles percentile)
cases (for [[sm v] views]
[[:= :search_index.model [:inline (name sm)]] (max (or v 0) 1)])]
- (size :view_count (if (seq cases)
- (into [:case] cat cases)
- 1))))
+ (search.scoring/size :view_count (if (seq cases)
+ (into [:case] cat cases)
+ 1))))
(defn- model-rank-exp [{:keys [context]}]
(let [search-order search.config/models-search-order
@@ -144,20 +86,20 @@
;; given set of results. At some point, we should optimize away the irrelevant scores for any given context.
{:text (specialization/text-score)
:view-count (view-count-expr search.config/view-count-scaling-percentile)
- :pinned (truthy :pinned)
+ :pinned (search.scoring/truthy :pinned)
:bookmarked bookmark-score-expr
- :recency (inverse-duration [:coalesce :last_viewed_at :model_updated_at] [:now] search.config/stale-time-in-days)
- :user-recency (inverse-duration (user-recency-expr search-ctx) [:now] search.config/stale-time-in-days)
- :dashboard (size :dashboardcard_count search.config/dashboard-count-ceiling)
+ :recency (search.scoring/inverse-duration [:coalesce :last_viewed_at :model_updated_at] [:now] search.config/stale-time-in-days)
+ :user-recency (search.scoring/inverse-duration (user-recency-expr search-ctx) [:now] search.config/stale-time-in-days)
+ :dashboard (search.scoring/size :dashboardcard_count search.config/dashboard-count-ceiling)
:model (model-rank-exp search-ctx)
- :mine (equal :search_index.creator_id (:current-user-id search-ctx))
+ :mine (search.scoring/equal :search_index.creator_id (:current-user-id search-ctx))
:exact (if search-string
;; perform the lower casing within the database, in case it behaves differently to our helper
- (equal [:lower :search_index.name] [:lower search-string])
+ (search.scoring/equal [:lower :search_index.name] [:lower search-string])
[:inline 0])
:prefix (if search-string
;; in this case, we need to transform the string into a pattern in code, so forced to use helper
- (prefix [:lower :search_index.name] (u/lower-case-en search-string))
+ (search.scoring/prefix [:lower :search_index.name] (u/lower-case-en search-string))
[:inline 0])}))
(defenterprise scorers
@@ -166,8 +108,6 @@
[search-ctx]
(base-scorers search-ctx))
-(defn- scorer-select-items [search-ctx scorers] (select-items (:context search-ctx) scorers))
-
(defn- bookmark-join [model user-id]
(let [model-name (name model)
table-name (str model-name "_bookmark")]
@@ -185,6 +125,6 @@
(defn with-scores
"Add a bunch of SELECT columns for the individual and total scores, and a corresponding ORDER BY."
[{:keys [current-user-id] :as search-ctx} scorers qry]
- (-> (apply sql.helpers/select qry (scorer-select-items search-ctx scorers))
+ (-> (search.scoring/with-scores search-ctx scorers qry)
(join-bookmarks current-user-id)
(sql.helpers/order-by [:total_score :desc])))
diff --git a/src/metabase/search/appdb/specialization/postgres.clj b/src/metabase/search/appdb/specialization/postgres.clj
index 56e2d01184f..e0f55b38b77 100644
--- a/src/metabase/search/appdb/specialization/postgres.clj
+++ b/src/metabase/search/appdb/specialization/postgres.clj
@@ -1,52 +1,10 @@
(ns metabase.search.appdb.specialization.postgres
(:require
[clojure.string :as str]
- [metabase.app-db.core :as mdb]
[metabase.search.appdb.specialization.api :as specialization]
- [metabase.search.ingestion :as search.ingestion]
- [metabase.search.settings :as search.settings]
- [metabase.util :as u]
- [metabase.util.i18n :as i18n]
- [metabase.util.string :as u.str]
+ [metabase.search.util :as search.util]
[toucan2.core :as t2]))
-(def ^:private available-tsv-languages
- "Mapping of our available locals to the names of the postgres tsvector languages.
- Queries the pg_ts_config table to find out which languages are actually available."
- (if (= :postgres (mdb/db-type))
- (let [default-mapping {:ar :arabic
- :ar_SA :arabic
- :ca :catalan
- :da :danish
- :en :english
- :fi :finnish
- :fr :french
- :de :german
- :hu :hungarian
- :id :indonesian
- :it :italian
- :nb :norwegian
- :pt_BR :portuguese
- :ru :russian
- :sr :serbian
- :es :spanish
- :sv :swedish
- :tr :turkish}
- available-languages (->> (t2/query {:select [:cfgname]
- :from [:pg_ts_config]})
- (map :cfgname)
- (map keyword)
- set)]
- (into {} (filter (comp available-languages val) default-mapping)))
- {}))
-
-(defn- tsv-language []
- (if-let [custom-language (search.settings/search-language)]
- custom-language
- (if-let [lang ((keyword (i18n/site-locale-string)) available-tsv-languages)]
- (name lang)
- "simple")))
-
(defmethod specialization/table-schema :postgres [base-schema]
(into [[:id :bigint [:primary-key] [:raw "GENERATED BY DEFAULT AS IDENTITY"]]
[:search_vector :tsvector :not-null]
@@ -76,75 +34,14 @@
:on-conflict [:model :model_id]
:do-update-set (zipmap update-keys (map excluded-kw update-keys))}))))
-(defn- quote* [s]
- (str "'" (str/replace s "'" "''") "'"))
-
-(defn- process-phrase [word-or-phrase]
- ;; a phrase is quoted even if the closing quotation mark has not been typed yet
- (cond
- ;; trailing quotation mark
- (= word-or-phrase "\"") nil
- ;; quoted phrases must be matched sequentially
- (str/starts-with? word-or-phrase "\"")
- (as-> word-or-phrase <>
- ;; remove the quote mark(s)
- (str/replace <> #"^\"|\"$" "")
- (str/trim <>)
- (str/split <> #"\s+")
- (map quote* <>)
- (str/join " <-> " <>))
-
- ;; negation
- (re-find #"^-\w" word-or-phrase)
- (str "!" (quote* (subs word-or-phrase 1)))
-
- ;; just a regular word
- :else
- (quote* word-or-phrase)))
-
-(defn- split-preserving-quotes
- "Break up the words in the search input, preserving quoted and partially quoted segments."
- [s]
- (re-seq #"\"[^\"]*(?:\"|$)|[^\s\"]+|\s+" (u/lower-case-en s)))
-
-(defn- process-clause [words-and-phrases]
- (->> words-and-phrases
- (remove #{"and"})
- (map process-phrase)
- (remove str/blank?)
- (str/join " & ")))
-
-(defn- complete-last-word
- "Add wildcards at the end of the final word, so that we match ts completions."
- [expression]
- (str/replace expression #"(\S+)(?=\s*$)" "$1:*"))
-
-(defn- to-tsquery-expr
- "Given the user input, construct a query in the Postgres tsvector query language."
- [input]
- (str
- (when input
- (let [trimmed (str/trim input)
- complete? (not (str/ends-with? trimmed "\""))
- ;; TODO also only complete if the :context is appropriate
- maybe-complete (if complete? complete-last-word identity)]
- (->> (str/replace trimmed "\\" "\\\\")
- split-preserving-quotes
- (remove str/blank?)
- (partition-by #{"or"})
- (remove #(= (first %) "or"))
- (map process-clause)
- (str/join " | ")
- maybe-complete)))))
-
(defmethod specialization/base-query :postgres
[active-table search-term search-ctx select-items]
{:select select-items
:from [[active-table :search_index]]
;; Using a join allows us to share the query expression between our SELECT and WHERE clauses.
:join [[[:raw "to_tsquery('"
- (tsv-language) "', "
- [:lift (to-tsquery-expr search-term)] ")"]
+ (search.util/tsv-language) "', "
+ [:lift (search.util/to-tsquery-expr search-term)] ")"]
:query] [:= 1 1]]
:where (if (str/blank? search-term)
[:= [:inline 1] [:inline 1]]
@@ -155,20 +52,16 @@
"search_vector")
" @@ query")])})
-(defn- weighted-tsvector [weight text]
- ;; tsvector has a max value size of 1048575 bytes, limit to less than that because the multiple values get concatenated together
- [:setweight [:to_tsvector [:inline (tsv-language)] [:cast (u.str/limit-bytes text search.ingestion/max-searchable-value-length) :text]] [:inline weight]])
-
(defmethod specialization/extra-entry-fields :postgres [entity]
{:search_vector
[:||
- (weighted-tsvector "A" (:name entity))
- (weighted-tsvector "B" (:searchable_text entity ""))]
+ (search.util/weighted-tsvector "A" (:name entity))
+ (search.util/weighted-tsvector "B" (:searchable_text entity ""))]
:with_native_query_vector
[:||
- (weighted-tsvector "A" (:name entity))
- (weighted-tsvector "B" (str/join " " (keep entity [:searchable_text :native_query])))]})
+ (search.util/weighted-tsvector "A" (:name entity))
+ (search.util/weighted-tsvector "B" (str/join " " (keep entity [:searchable_text :native_query])))]})
;; See https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING
;; 0 (the default) ignores the document length
diff --git a/src/metabase/search/config.clj b/src/metabase/search/config.clj
index 47803d075a6..d368a508ec4 100644
--- a/src/metabase/search/config.clj
+++ b/src/metabase/search/config.clj
@@ -85,7 +85,9 @@
:text 5
:mine 1
:exact 5
- :prefix 0}
+ :prefix 0
+ ;; TODO figure out a better way to blend these scorers with wildly different scale.
+ :rrf 5000}
:command-palette
{:prefix 5
:model/collection 1
diff --git a/src/metabase/search/core.clj b/src/metabase/search/core.clj
index cc20d57efb6..e552867f36f 100644
--- a/src/metabase/search/core.clj
+++ b/src/metabase/search/core.clj
@@ -9,6 +9,7 @@
[metabase.search.impl :as search.impl]
[metabase.search.in-place.legacy :as search.legacy]
[metabase.search.ingestion :as search.ingestion]
+ [metabase.search.semantic.core :as search.engines.semantic]
[metabase.search.spec :as search.spec]
[metabase.search.util :as search.util]
[metabase.util :as u]
@@ -21,6 +22,7 @@
;; TODO -- maybe engine loading should be moved to [[metabase.search.init]] instead
search.engine/keep-me
search.engines.appdb/keep-me
+ search.engines.semantic/keep-me
search.legacy/keep-me
search.config/keep-me
@@ -43,7 +45,16 @@
searchable-value-trim-sql]
[search.spec
- define-spec])
+ spec
+ define-spec]
+
+ [search.util
+ collapse-id
+ indexed-entity-id->model-index-id
+ indexed-entity-id->model-pk
+ tsv-language
+ to-tsquery-expr
+ weighted-tsvector])
(defmethod analytics/known-labels :metabase-search/index-updates
[_]
diff --git a/src/metabase/search/engine.clj b/src/metabase/search/engine.clj
index 49660a0c328..ad9b98080f4 100644
--- a/src/metabase/search/engine.clj
+++ b/src/metabase/search/engine.clj
@@ -1,6 +1,11 @@
;; The interface encapsulating the various search engine backends.
(ns metabase.search.engine)
+(def fallback-engine-priority
+ "Search engines in order of preference for fallback scenarios."
+ [:search.engine/appdb
+ :search.engine/in-place])
+
(defmulti supported-engine?
"Does this instance support the given engine?"
{:arglists '([engine])}
@@ -44,7 +49,8 @@
search-engine))
(defmulti init!
- "Ensure that the search index exists, an is ready to take search queries."
+ "Ensure that the search index exists, and is ready to take search queries.
+ Returns a map of the number of documents indexed in each model"
{:arglists '([engine opts])}
(fn [engine _opts]
engine))
diff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.clj
index 428d116395b..ebea5407e8d 100644
--- a/src/metabase/search/impl.clj
+++ b/src/metabase/search/impl.clj
@@ -209,8 +209,7 @@
;; It would be good to have a warning on start up for this.
:search.engine/in-place))
(first (filter search.engine/supported-engine?
- [:search.engine/appdb
- :search.engine/in-place]))))
+ search.engine/fallback-engine-priority))))
(defn- parse-engine [value]
(or (when-not (str/blank? value)
@@ -393,17 +392,16 @@
;; We get to do this slicing and dicing with the result data because
;; the pagination of search is for UI improvement, not for performance.
;; We intend for the cardinality of the search results to be below the default max before this slicing occurs
- (cond->
- {:data (cond->> total-results
- (some? (:offset-int search-ctx)) (drop (:offset-int search-ctx))
- (some? (:limit-int search-ctx)) (take (:limit-int search-ctx))
- true (map add-perms-for-col))
- :limit (:limit-int search-ctx)
- :models (:models search-ctx)
- :offset (:offset-int search-ctx)
- :table_db_id (:table-db-id search-ctx)
- :engine (:search-engine search-ctx)
- :total (count total-results)}
+ (cond-> {:data (cond->> total-results
+ (some? (:offset-int search-ctx)) (drop (:offset-int search-ctx))
+ (some? (:limit-int search-ctx)) (take (:limit-int search-ctx))
+ true (map add-perms-for-col))
+ :limit (:limit-int search-ctx)
+ :models (:models search-ctx)
+ :offset (:offset-int search-ctx)
+ :table_db_id (:table-db-id search-ctx)
+ :engine (:search-engine search-ctx)
+ :total (count total-results)}
(:calculate-available-models? search-ctx)
(assoc :available_models (model-set-fn search-ctx)))))
diff --git a/src/metabase/search/ingestion.clj b/src/metabase/search/ingestion.clj
index 52243694109..71670266a72 100644
--- a/src/metabase/search/ingestion.clj
+++ b/src/metabase/search/ingestion.clj
@@ -143,7 +143,14 @@
(eduction (map #(assoc % :model search-model)))))
(defn- search-items-reducible []
- (reduce u/rconcat [] (map spec-index-reducible search.spec/search-models)))
+ (let [models search.spec/search-models
+ ;; we're pushing indexed entities last in the search items reducible
+ ;; so that more important models gets indexed first, making the partial
+ ;; index more usable earlier
+ sorted-models (cond-> models
+ (contains? models "indexed-entity")
+ (-> (disj "indexed-entity") (concat ["indexed-entity"])))]
+ (reduce u/rconcat [] (map spec-index-reducible sorted-models))))
(defn- query->documents [query-reducible]
(->> query-reducible
@@ -160,6 +167,18 @@
[]
(query->documents (search-items-reducible)))
+(defn search-items-count
+ "Returns a count of all searchable items in the database."
+ []
+ (->> (for [model search.spec/search-models]
+ (-> (spec-index-query-where model nil)
+ (assoc :select [[:%count.* :count]])
+ t2/query
+ first
+ :count))
+ (filter some?)
+ (reduce + 0)))
+
(def ^:dynamic *force-sync*
"Force ingestion to happen immediately, on the same thread."
false)
diff --git a/src/metabase/search/scoring.clj b/src/metabase/search/scoring.clj
new file mode 100644
index 00000000000..dbf2e788f84
--- /dev/null
+++ b/src/metabase/search/scoring.clj
@@ -0,0 +1,92 @@
+(ns metabase.search.scoring
+ (:require
+ [clojure.string :as str]
+ [honey.sql.helpers :as sql.helpers]
+ [metabase.search.config :as search.config]))
+
+(def ^:private seconds-in-a-day 86400)
+
+(defn truthy
+ "Prefer it when a (potentially nullable) boolean is true."
+ [column]
+ [:coalesce [:cast column :integer] [:inline 0]])
+
+(defn equal
+ "Prefer it when it matches a specific (non-null) value"
+ [column value]
+ [:coalesce [:case [:= column value] [:inline 1] :else [:inline 0]] [:inline 0]])
+
+(defn prefix
+ "Prefer it when the given value is a completion of a specific (non-null) value"
+ [column value]
+ [:coalesce [:case [:like column (str (str/replace value "%" "%%") "%")] [:inline 1] :else [:inline 0]] [:inline 0]])
+
+(defn size
+ "Prefer items whose value is larger, up to some saturation point. Items beyond that point are equivalent."
+ [column ceiling]
+ [:least
+ [:inline 1]
+ [:/
+ [:coalesce column [:inline 0]]
+ ;; protect against div / 0
+ [:greatest
+ [:inline 1]
+ (if (number? ceiling)
+ [:inline (double ceiling)]
+ [:cast ceiling :float])]]])
+
+(defn inverse-duration
+ "Score at item based on the duration between two dates, where less is better."
+ [from-column to-column ceiling-in-days]
+ (let [ceiling [:inline ceiling-in-days]]
+ [:/
+ [:greatest
+ [:- ceiling
+ [:/
+ ;; Use seconds for granularity in the fraction.
+ ;; TODO will probably need to specialize this based on (mdb/db-type)
+ [[:raw "EXTRACT(epoch FROM (" [:- to-column from-column] [:raw "))"]]]
+ [:inline (double seconds-in-a-day)]]]
+ [:inline 0]]
+ ceiling]))
+
+(defn sum-columns
+ "Sum the columns in `column-names`."
+ [column-names]
+ (if (seq column-names)
+ (reduce (fn [expr col] [:+ expr col])
+ (first column-names)
+ (rest column-names))
+ [:inline 1]))
+
+(defn weighted-score
+ "Multiply a score by its weight."
+ [context [column-alias expr]]
+ [:* [:inline (search.config/weight context column-alias)] expr])
+
+(defn select-items
+ "Select expressions for each scorer, plus a :total_score that is the weighted sum of the `scorers`."
+ [context scorers]
+ (concat
+ (for [[column-alias expr] scorers]
+ [expr column-alias])
+ [[(sum-columns (map (partial weighted-score context) scorers))
+ :total_score]]))
+
+(defn with-scores
+ "Add a bunch of SELECT columns for the individual and total scores."
+ [search-ctx scorers qry]
+ (apply sql.helpers/select qry (select-items (:context search-ctx) scorers)))
+
+(defn all-scores
+ "Scoring stats for each `index-row`."
+ [weights scorers index-row]
+ (mapv (fn [k]
+ ;; we shouldn't get null scores, but just in case (i.e., because there are bugs)
+ (let [score (or (get index-row k) 0)
+ weight (or (weights k) 0)]
+ {:score score
+ :name k
+ :weight weight
+ :contribution (* weight score)}))
+ scorers))
diff --git a/src/metabase/search/semantic/core.clj b/src/metabase/search/semantic/core.clj
new file mode 100644
index 00000000000..74aec49e55d
--- /dev/null
+++ b/src/metabase/search/semantic/core.clj
@@ -0,0 +1,121 @@
+(ns metabase.search.semantic.core
+ (:require
+ [metabase.premium-features.core :refer [defenterprise]]
+ [metabase.search.config :as search.config]
+ [metabase.search.engine :as search.engine]
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.util.log :as log]))
+
+(defn- oss-semantic-search-error
+ "Helper function to throw semantic search enterprise feature error."
+ []
+ (throw (ex-info "Semantic search is a premium feature and requires an enterprise license."
+ {:type :semantic-search-not-available})))
+
+;; defenterprise functions that map directly to search.engine methods
+
+(defenterprise supported?
+ "Check if semantic search is supported on this instance."
+ metabase-enterprise.semantic-search.core
+ []
+ false)
+
+(defenterprise results
+ "Execute a semantic search query and return results."
+ metabase-enterprise.semantic-search.core
+ [_search-ctx]
+ (oss-semantic-search-error))
+
+(defenterprise update-index!
+ "Update the semantic search index with the given documents."
+ metabase-enterprise.semantic-search.core
+ [_document-reducible]
+ (oss-semantic-search-error))
+
+(defenterprise delete-from-index!
+ "Delete documents from the semantic search index."
+ metabase-enterprise.semantic-search.core
+ [_model _ids]
+ (oss-semantic-search-error))
+
+(defenterprise init!
+ "Initialize the semantic search index."
+ metabase-enterprise.semantic-search.core
+ [_searchable-documents _opts]
+ (oss-semantic-search-error))
+
+(defenterprise reindex!
+ "Perform a full reindex of the semantic search engine."
+ metabase-enterprise.semantic-search.core
+ [_searchable-documents _opts]
+ (oss-semantic-search-error))
+
+(defenterprise reset-tracking!
+ "Reset tracking for the semantic search engine."
+ metabase-enterprise.semantic-search.core
+ []
+ (oss-semantic-search-error))
+
+;; Search engine method implementations
+
+(defmethod search.engine/supported-engine? :search.engine/semantic [_]
+ (try
+ (supported?)
+ (catch Exception e
+ (log/warn e "Semantic search engine not supported")
+ false)))
+
+(defmethod search.engine/results :search.engine/semantic
+ [search-ctx]
+ (results search-ctx))
+
+(defmethod search.engine/model-set :search.engine/semantic
+ [_search-ctx]
+ search.config/all-models)
+
+(defmethod search.engine/update! :search.engine/semantic
+ [_ document-reducible]
+ (try
+ (log/info "Updating semantic search engine")
+ (update-index! document-reducible)
+ (catch Exception e
+ (log/error e "Error updating semantic search engine")
+ {})))
+
+(defmethod search.engine/delete! :search.engine/semantic
+ [_ model ids]
+ (try
+ (log/info "Deleting from semantic search engine")
+ (delete-from-index! model ids)
+ (catch Exception e
+ (log/error e "Error deleting from semantic search engine")
+ {})))
+
+(defmethod search.engine/init! :search.engine/semantic
+ [_ opts]
+ (try
+ (log/info "Initializing semantic search engine")
+ (init! (search.ingestion/searchable-documents) opts)
+ (catch Exception e
+ (log/error e "Error initializing semantic search engine")
+ (throw e))))
+
+(defmethod search.engine/reindex! :search.engine/semantic
+ [_ opts]
+ (try
+ (log/info "Reindexing semantic search engine")
+ (reindex! (search.ingestion/searchable-documents) opts)
+ (catch Exception e
+ (log/error e "Error reindexing semantic search engine")
+ (throw e))))
+
+(comment
+ (def docs (vec (search.ingestion/searchable-documents)))
+ (init! docs {})
+ (reindex! docs {}))
+
+(defmethod search.engine/reset-tracking! :search.engine/semantic [_]
+ (try
+ (reset-tracking!)
+ (catch Exception e
+ (log/debug e "Error resetting tracking for semantic search engine"))))
diff --git a/src/metabase/search/settings.clj b/src/metabase/search/settings.clj
index a4cd2ddf723..a27e5971e7e 100644
--- a/src/metabase/search/settings.clj
+++ b/src/metabase/search/settings.clj
@@ -14,9 +14,10 @@
:audit :getter)
(defsetting search-engine
- (i18n/deferred-tru "Which engine to use when performing search. Supported values are :in-place and :appdb")
- :visibility :internal
+ (i18n/deferred-tru "Which engine to use by default when performing search. Supported values are :in-place, :appdb, and :semantic")
+ :visibility :authenticated
:export? false
+ :setter :none
:default :appdb
:type :keyword)
diff --git a/src/metabase/search/task/search_index.clj b/src/metabase/search/task/search_index.clj
index 964bff530a1..b4c53ed4e0f 100644
--- a/src/metabase/search/task/search_index.clj
+++ b/src/metabase/search/task/search_index.clj
@@ -65,4 +65,5 @@
(ingestion/start-listener!))
(comment
- (task/job-exists? reindex-job-key))
+ (task/job-exists? reindex-job-key)
+ (task/trigger-now! reindex-job-key))
diff --git a/src/metabase/search/util.clj b/src/metabase/search/util.clj
index 4e231297ff3..dd33c8f5f71 100644
--- a/src/metabase/search/util.clj
+++ b/src/metabase/search/util.clj
@@ -1,4 +1,13 @@
-(ns metabase.search.util)
+(ns metabase.search.util
+ (:require
+ [clojure.string :as str]
+ [metabase.app-db.core :as mdb]
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.search.settings :as search.settings]
+ [metabase.util :as u]
+ [metabase.util.i18n :as i18n]
+ [metabase.util.string :as u.str]
+ [toucan2.core :as t2]))
(defn impossible-condition?
"An (incomplete) check where queries will definitely return nothing, to help avoid spurious index update queries."
@@ -12,3 +21,137 @@
:and (boolean (some impossible-condition? (rest where)))
:or (every? impossible-condition? (rest where))
false)))
+
+(defn- explode-multipart-ids
+ "Split integer IDs from a `multi-part-id-string` like \"123:456\" => (\"123\" \"456\")"
+ [multi-part-id-string]
+ (str/split multi-part-id-string #":"))
+
+(defn indexed-entity-id->model-index-id
+ "Extract the model-index-id from a composite indexed-entity id like <model-index-id>:<model-pk>"
+ [indexed-entity-id]
+ (-> (explode-multipart-ids indexed-entity-id)
+ first
+ parse-long))
+
+(defn indexed-entity-id->model-pk
+ "Extract the model-pk from a composite indexed-entity id like <model-index-id>:<model-pk>"
+ [indexed-entity-id]
+ (-> (explode-multipart-ids indexed-entity-id)
+ last
+ parse-long))
+
+(defn collapse-id
+ "Collapse the id of search results that may contain multiple ids (like indexed-entities)."
+ [{:keys [id] :as row}]
+ (assoc row :id (if (number? id) id (indexed-entity-id->model-pk id))))
+
+;;; ============================================================================
+;;; Postgres-specific utilities
+;;; ============================================================================
+
+(def ^:private available-tsv-languages
+ "Mapping of our available locals to the names of the postgres tsvector languages.
+ Queries the pg_ts_config table to find out which languages are actually available."
+ (if (= :postgres (mdb/db-type))
+ (let [default-mapping {:ar :arabic
+ :ar_SA :arabic
+ :ca :catalan
+ :da :danish
+ :en :english
+ :fi :finnish
+ :fr :french
+ :de :german
+ :hu :hungarian
+ :id :indonesian
+ :it :italian
+ :nb :norwegian
+ :pt_BR :portuguese
+ :ru :russian
+ :sr :serbian
+ :es :spanish
+ :sv :swedish
+ :tr :turkish}
+ available-languages (->> (t2/query {:select [:cfgname]
+ :from [:pg_ts_config]})
+ (map :cfgname)
+ (map keyword)
+ set)]
+ (into {} (filter (comp available-languages val) default-mapping)))
+ {}))
+
+(defn tsv-language
+ "Get the appropriate text search configuration language for Postgres tsvector operations."
+ []
+ (if-let [custom-language (search.settings/search-language)]
+ custom-language
+ (if-let [lang ((keyword (i18n/site-locale-string)) available-tsv-languages)]
+ (name lang)
+ "simple")))
+
+(defn- quote* [s]
+ (str "'" (str/replace s "'" "''") "'"))
+
+(defn- process-phrase [word-or-phrase]
+ ;; a phrase is quoted even if the closing quotation mark has not been typed yet
+ (cond
+ ;; trailing quotation mark
+ (= word-or-phrase "\"") nil
+ ;; quoted phrases must be matched sequentially
+ (str/starts-with? word-or-phrase "\"")
+ (as-> word-or-phrase <>
+ ;; remove the quote mark(s)
+ (str/replace <> #"^\"|\"$" "")
+ (str/trim <>)
+ (str/split <> #"\s+")
+ (map quote* <>)
+ (str/join " <-> " <>))
+
+ ;; negation
+ (re-find #"^-\w" word-or-phrase)
+ (str "!" (quote* (subs word-or-phrase 1)))
+
+ ;; just a regular word
+ :else
+ (quote* word-or-phrase)))
+
+(defn- split-preserving-quotes
+ "Break up the words in the search input, preserving quoted and partially quoted segments."
+ [s]
+ (re-seq #"\"[^\"]*(?:\"|$)|[^\s\"]+|\s+" (u/lower-case-en s)))
+
+(defn- process-clause [words-and-phrases]
+ (->> words-and-phrases
+ (remove #{"and"})
+ (map process-phrase)
+ (remove str/blank?)
+ (str/join " & ")))
+
+(defn- complete-last-word
+ "Add wildcards at the end of the final word, so that we match ts completions."
+ [expression]
+ (str/replace expression #"(\S+)(?=\s*$)" "$1:*"))
+
+(defn to-tsquery-expr
+ "Given the user input, construct a query in the Postgres tsvector query language."
+ [input]
+ (str
+ (when input
+ (let [trimmed (str/trim input)
+ complete? (not (str/ends-with? trimmed "\""))
+ ;; TODO also only complete if the :context is appropriate
+ maybe-complete (if complete? complete-last-word identity)]
+ (->> (str/replace trimmed "\\" "\\\\")
+ split-preserving-quotes
+ (remove str/blank?)
+ (partition-by #{"or"})
+ (remove #(= (first %) "or"))
+ (map process-clause)
+ (str/join " | ")
+ maybe-complete)))))
+
+(defn weighted-tsvector
+ "Create a weighted tsvector for Postgres full-text search with the given weight and text."
+ [weight text]
+ ;; tsvector has a max value size of 1048575 bytes, limit to less than that because the multiple values get concatenated together
+ [:setweight [:to_tsvector [:inline (tsv-language)] [:cast (u.str/limit-bytes text search.ingestion/max-searchable-value-length) :text]] [:inline weight]])
diff --git a/src/metabase/util/quick_task.clj b/src/metabase/util/quick_task.clj
index aba169a3ac6..cf9c1e16a11 100644
--- a/src/metabase/util/quick_task.clj
+++ b/src/metabase/util/quick_task.clj
@@ -24,5 +24,6 @@
"Submit a task to the single thread executor. This will attempt to serialize repeated requests to sync tables. It
obviously cannot work across multiple instances."
^Future [^Callable f]
+ {:pre [(some? f)]}
(let [task (bound-fn* f)]
(.submit ^ExecutorService @executor ^Callable task)))
diff --git a/test/metabase/search/appdb/index_test.clj b/test/metabase/search/appdb/index_test.clj
index 55ad686dd31..df99d9740b3 100644
--- a/test/metabase/search/appdb/index_test.clj
+++ b/test/metabase/search/appdb/index_test.clj
@@ -476,6 +476,24 @@
:collection_id coll-id})]
(fetch "indexed-entity" :model_id [:in [(model-id miv) (model-id miv2)]]))))))))))
+(deftest indexed-entity-last-test
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card model (assoc (mt/card-with-source-metadata-for-query
+ (mt/mbql-query products {:fields [$id $title]
+ :limit 1}))
+ :type "model"
+ :database_id (mt/id)
+ :collection_id coll-id)
+ :model/ModelIndex model-index {:model_id (:id model)
+ :pk_ref (mt/$ids :products $id)
+ :value_ref (mt/$ids :products $title)
+ :schedule "0 0 0 * * *"
+ :state "initial"
+ :creator_id (mt/user->id :rasta)}]
+ (model-index/add-values! model-index)
+ (is (= "indexed-entity" (last (into [] (map :model) (search.ingestion/searchable-documents))))))))
+
(deftest ^:synchronized table-cleanup-test
(when (search/supports-index?)
;; this test destroys the actual current index, regrettably
diff --git a/test/metabase/search/appdb/scoring_test.clj b/test/metabase/search/appdb/scoring_test.clj
index 89cf8cd95eb..2e8fd6b50b8 100644
--- a/test/metabase/search/appdb/scoring_test.clj
+++ b/test/metabase/search/appdb/scoring_test.clj
@@ -73,7 +73,8 @@
(map (comp keyword u/->kebab-case-en name second))
;; Remove db-specific fields
(remove #{:search-vector :query}))
- (vals (scoring/scorers {:search-string ""})))
+ (vals (scoring/scorers {:search-engine :search.engine/appdb
+ :search-string ""})))
(set (cons :model (keys search.spec/attr-types))))))))
;; ---- index-ony rankers ----
diff --git a/test/metabase/search/appdb/specializations/postgres_test.clj b/test/metabase/search/appdb/specializations/postgres_test.clj
index 546f803c630..c7ccdd3e093 100644
--- a/test/metabase/search/appdb/specializations/postgres_test.clj
+++ b/test/metabase/search/appdb/specializations/postgres_test.clj
@@ -1,82 +1,3 @@
(ns metabase.search.appdb.specializations.postgres-test
(:require
- [clojure.test :refer :all]
- [metabase.app-db.core :as mdb]
- [metabase.search.appdb.specialization.postgres :as search.postgres]
- [metabase.test.util :as tu]
- [metabase.util.i18n :as i18n]))
-
-(def search-expr #'search.postgres/to-tsquery-expr)
-
-(deftest to-tsquery-expr-test
- (is (= "'a' & 'b' & 'c':*"
- (search-expr "a b c")))
-
- (is (= "'a' & 'b' & 'c':*"
- (search-expr "a AND b AND c")))
-
- (is (= "'a' & 'b' & 'c'"
- (search-expr "a b \"c\"")))
-
- (is (= "'a' & 'b' | 'c':*"
- (search-expr "a b or c")))
-
- (is (= "'this' & !'that':*"
- (search-expr "this -that")))
-
- (testing "hyphens"
- (is (= "'[ops' & 'monitoring]' & '-' & 'available':*"
- (search-expr "[ops monitoring] - available")))
- (is (= "'[ops' & 'monitoring]' & '--' & 'available':*"
- (search-expr "[ops monitoring] -- available")))
- (is (= "'[ops' & 'monitoring]' & 'not-available':*"
- (search-expr "[ops monitoring] not-available"))))
-
- (is (= "'a' & 'b' & 'c' <-> 'd' & 'e' | 'b' & 'e':*"
- (search-expr "a b \" c d\" e or b e")))
-
- (is (= "'ab' <-> 'and' <-> 'cde' <-> 'f' | !'abc' & 'def' & 'ghi' | 'jkl' <-> 'mno' <-> 'or' <-> 'pqr'"
- (search-expr "\"ab and cde f\" or -abc def AND ghi OR \"jkl mno OR pqr\"")))
-
- (is (= "'big' & 'data' | 'business' <-> 'intelligence' | 'data' & 'wrangling':*"
- (search-expr "Big Data oR \"Business Intelligence\" OR data and wrangling")))
-
- (testing "unbalanced quotes"
- (is (= "'big' <-> 'data' & 'big' <-> 'mistake':*"
- (search-expr "\"Big Data\" \"Big Mistake")))
- (is (= "'something'"
- (search-expr "something \""))))
-
- (is (= "'partial' <-> 'quoted' <-> 'and' <-> 'or' <-> '-split':*"
- (search-expr "\"partial quoted AND OR -split")))
-
- (testing "dangerous characters"
- (is (= "'you' & '<-' & 'pointing':*"
- (search-expr "you <- pointing"))))
-
- (testing "backslash"
- (is (= "'test\\\\':*" (search-expr "test\\"))))
-
- (testing "single quotes"
- (is (= "'you''re':*"
- (search-expr "you're")))))
-
-(deftest available-tsv-languages
- (when (= :postgres (mdb/db-type))
- (let [available @#'search.postgres/available-tsv-languages]
- (is (= :english (:en available)))
- (is (= :german (:de available)))
- (is (nil? (:ko available))))))
-
-(deftest tsv-language
- (when (= :postgres (mdb/db-type))
- (binding [i18n/*site-locale-override* "en"]
- (is (= "english" (#'search.postgres/tsv-language))))
- (binding [i18n/*site-locale-override* "de"]
- (is (= "german" (#'search.postgres/tsv-language))))
- (binding [i18n/*site-locale-override* "pt_BR"]
- (is (= "portuguese" (#'search.postgres/tsv-language))))
- (binding [i18n/*site-locale-override* "ko"]
- (is (= "simple" (#'search.postgres/tsv-language))))
- (tu/with-temporary-setting-values [search-language "custom-value"]
- (is (= "custom-value" (#'search.postgres/tsv-language))))))
+ [clojure.test :refer :all]))
diff --git a/test/metabase/search/ingestion_test.clj b/test/metabase/search/ingestion_test.clj
index 6e55536f297..72eba5daa20 100644
--- a/test/metabase/search/ingestion_test.clj
+++ b/test/metabase/search/ingestion_test.clj
@@ -1,7 +1,9 @@
(ns metabase.search.ingestion-test
(:require
[clojure.test :refer :all]
- [metabase.search.ingestion :as search.ingestion]))
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.search.spec :as search.spec]
+ [metabase.test :as mt]))
(deftest extract-model-and-id
(is (= ["action" "1895"] (#'search.ingestion/extract-model-and-id ["action" [:= 1895 :this.id]])))
@@ -11,3 +13,15 @@
(is (= ["dataset" "1901"] (#'search.ingestion/extract-model-and-id ["dataset" [:and [:= true true] [:= :this.id 1901] [:= "Card" "Card"]]])))
(is (= nil (#'search.ingestion/extract-model-and-id ["dataset" [:and [:= true true] [:= :this.model_id 1901] [:= "Card" "Card"]]])))
(is (= nil (#'search.ingestion/extract-model-and-id ["indexed-entity" [:and [:= 26 :this.model_index_id] [:= 38004300 :this.model_pk]]]))))
+
+(deftest search-items-count-test
+ (testing "search-items-count returns correct count with various searchable items"
+ (mt/with-empty-h2-app-db!
+ (with-redefs [search.spec/search-models #{"card" "dashboard"}]
+ (mt/with-temp [:model/Collection coll {:name "Test Collection"}
+ :model/Card _ {:name "Test Card 1" :collection_id (:id coll)}
+ :model/Card _ {:name "Test Card 2" :collection_id (:id coll)}
+ :model/Dashboard _ {:name "Test Dashboard 1" :collection_id (:id coll)}
+ :model/Dashboard _ {:name "Test Dashboard 2" :collection_id (:id coll)}]
+ (let [n (search.ingestion/search-items-count)]
+ (is (= 4 n))))))))
diff --git a/test/metabase/search/util_test.clj b/test/metabase/search/util_test.clj
index 35a6b788ec4..1c027b1f852 100644
--- a/test/metabase/search/util_test.clj
+++ b/test/metabase/search/util_test.clj
@@ -1,7 +1,10 @@
(ns metabase.search.util-test
(:require
[clojure.test :refer :all]
- [metabase.search.util :as search.util]))
+ [metabase.app-db.core :as mdb]
+ [metabase.search.util :as search.util]
+ [metabase.test.util :as tu]
+ [metabase.util.i18n :as i18n]))
(def ^:private impossible? search.util/impossible-condition?)
@@ -17,3 +20,82 @@
(is (not (impossible? [:and [:= 1 :this.id] [:!= "card" "dashboard"]])))
(is (not (impossible? [:or [:= 1 :this.id] [:!= "card" "dashboard"]])))
(is (impossible? [:or [:= "oh" "no"] [:= "card" "dashboard"]])))
+
+;;; ============================================================================
+;;; Postgres-specific utility tests
+;;; ============================================================================
+
+(def search-expr #'search.util/to-tsquery-expr)
+
+(deftest to-tsquery-expr-test
+ (is (= "'a' & 'b' & 'c':*"
+ (search-expr "a b c")))
+
+ (is (= "'a' & 'b' & 'c':*"
+ (search-expr "a AND b AND c")))
+
+ (is (= "'a' & 'b' & 'c'"
+ (search-expr "a b \"c\"")))
+
+ (is (= "'a' & 'b' | 'c':*"
+ (search-expr "a b or c")))
+
+ (is (= "'this' & !'that':*"
+ (search-expr "this -that")))
+
+ (testing "hyphens"
+ (is (= "'[ops' & 'monitoring]' & '-' & 'available':*"
+ (search-expr "[ops monitoring] - available")))
+ (is (= "'[ops' & 'monitoring]' & '--' & 'available':*"
+ (search-expr "[ops monitoring] -- available")))
+ (is (= "'[ops' & 'monitoring]' & 'not-available':*"
+ (search-expr "[ops monitoring] not-available"))))
+
+ (is (= "'a' & 'b' & 'c' <-> 'd' & 'e' | 'b' & 'e':*"
+ (search-expr "a b \" c d\" e or b e")))
+
+ (is (= "'ab' <-> 'and' <-> 'cde' <-> 'f' | !'abc' & 'def' & 'ghi' | 'jkl' <-> 'mno' <-> 'or' <-> 'pqr'"
+ (search-expr "\"ab and cde f\" or -abc def AND ghi OR \"jkl mno OR pqr\"")))
+
+ (is (= "'big' & 'data' | 'business' <-> 'intelligence' | 'data' & 'wrangling':*"
+ (search-expr "Big Data oR \"Business Intelligence\" OR data and wrangling")))
+
+ (testing "unbalanced quotes"
+ (is (= "'big' <-> 'data' & 'big' <-> 'mistake':*"
+ (search-expr "\"Big Data\" \"Big Mistake")))
+ (is (= "'something'"
+ (search-expr "something \""))))
+
+ (is (= "'partial' <-> 'quoted' <-> 'and' <-> 'or' <-> '-split':*"
+ (search-expr "\"partial quoted AND OR -split")))
+
+ (testing "dangerous characters"
+ (is (= "'you' & '<-' & 'pointing':*"
+ (search-expr "you <- pointing"))))
+
+ (testing "backslash"
+ (is (= "'test\\\\':*" (search-expr "test\\"))))
+
+ (testing "single quotes"
+ (is (= "'you''re':*"
+ (search-expr "you're")))))
+
+(deftest available-tsv-languages-test
+ (when (= :postgres (mdb/db-type))
+ (let [available @#'search.util/available-tsv-languages]
+ (is (= :english (:en available)))
+ (is (= :german (:de available)))
+ (is (nil? (:ko available))))))
+
+(deftest tsv-language-test
+ (when (= :postgres (mdb/db-type))
+ (binding [i18n/*site-locale-override* "en"]
+ (is (= "english" (#'search.util/tsv-language))))
+ (binding [i18n/*site-locale-override* "de"]
+ (is (= "german" (#'search.util/tsv-language))))
+ (binding [i18n/*site-locale-override* "pt_BR"]
+ (is (= "portuguese" (#'search.util/tsv-language))))
+ (binding [i18n/*site-locale-override* "ko"]
+ (is (= "simple" (#'search.util/tsv-language))))
+ (tu/with-temporary-setting-values [search-language "custom-value"]
+ (is (= "custom-value" (#'search.util/tsv-language))))))
diff --git a/test/metabase/test/util/namespace.clj b/test/metabase/test/util/namespace.clj
index 301dc35bf76..2c92ff466ed 100644
--- a/test/metabase/test/util/namespace.clj
+++ b/test/metabase/test/util/namespace.clj
@@ -8,10 +8,6 @@
(defonce ^{:doc "Vector of symbols of all Metabase namespaces, excluding test namespaces. This is intended
for use by various test routines that need to load related namespaces.
- DEPRECATED: Using this is an anti-pattern, it messes up our ability to analyze the code and find dependencies between
- namespaces or to topographically sort them correctly during compilation. See
- https://metaboat.slack.com/archives/CKZEMT1MJ/p1734635053499399 or ask Cam for more info.
-
This was moved from metabase.util.jvm for testing purposes only."}
^:deprecated metabase-namespace-symbols
(vec (sort (for [ns-symb (ns.find/find-namespaces (classpath/system-classpath))