The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Support library-retrieval using pgvector on the appdb (#78682)
Chris Truter836d5568ac21
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex eeeec6b9388..4908bcde706 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -3239,6 +3239,7 @@{:team "Metabot":api #{metabase-enterprise.entity-retrieval.init}:uses #{analytics-interface+ app-dbcollectionsentity-retrievalhealth-inspector@@ -3566,7 +3567,8 @@metabase-enterprise.semantic-search.db.datasourcemetabase-enterprise.semantic-search.embeddingmetabase-enterprise.semantic-search.embedding-health- metabase-enterprise.semantic-search.init}+ metabase-enterprise.semantic-search.init+ metabase-enterprise.semantic-search.util}:uses #{activity-feedanalyticsanalytics-interfacediff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.cljindex b50ab206dd5..b82583967ba 100644--- a/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.clj+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.clj@@ -5,6 +5,7 @@OSS shims live in [[metabase.entity-retrieval.mirror]]; the background sync they nudge is the[[metabase-enterprise.entity-retrieval.task.sync]] Quartz job."(:require+ [clojure.core.memoize :as memoize][clojure.string :as str][clojurewerkz.quartzite.jobs :as jobs][honey.sql :as sql]@@ -14,7 +15,9 @@[metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource][metabase-enterprise.semantic-search.embedding :as embedding][metabase-enterprise.semantic-search.embedding-health :as embedding-health]+ [metabase-enterprise.semantic-search.util :as semantic.util][metabase.analytics-interface.core :as analytics]+ [metabase.app-db.core :as mdb][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.util :as u][metabase.util.log :as log]@@ -30,24 +33,82 @@[[metabase-enterprise.entity-retrieval.task.sync]]."(jobs/key "metabase-enterprise.entity-retrieval.sync.job"))-(defn pgvector-configured?- "True when a dedicated pgvector store is configured (MB_PGVECTOR_DB_URL).- Deliberately excludes pgvector-on-the-app-db: entity retrieval's tables are not yet schema-isolated- (bare `library_entity_index*` names, dropped and recreated on rebuild), so it stays dedicated-only- until they are.- The sync task gates scheduling on this rather than [[available?]], so the periodic safety net exists- even when the library-retrieval feature is turned on after startup (a common onboarding flow).- A plain URL check, not [[metabase-enterprise.semantic-search.db.datasource/pgvector-mode]]: mode- resolution can probe the app db, which a dedicated-only scheduling gate has no business doing."- []- (semantic.db.datasource/dedicated-url-configured?))-(defn- licensed?"Without a library, there is nothing one is entitled to retrieve."[](and (premium-features/has-feature? :library)(premium-features/has-feature? :library-retrieval)))+(defn pgvector-schedulable?+ "Whether this instance could have a pgvector store: a dedicated one, or an app db that might host one.+ Env and license only, never a query -- the sync task schedules on this, and resolving+ [[metabase-enterprise.semantic-search.db.datasource/pgvector-mode]] would probe the app db of instances+ that can't use the answer.+ Licensing an app-db instance post-boot needs a restart before the job schedules."+ []+ (or (semantic.db.datasource/dedicated-url-configured?)+ (and (licensed?)+ (= :postgres (mdb/db-type)))))++(def ^:private schema-privilege-sql+ "NULL when the schema does not exist, otherwise whether this role may both use it and create in it.+ Two calls rather than `'USAGE, CREATE'`: a comma-separated list reads as OR, which USAGE alone passes."+ "SELECT CASE WHEN to_regnamespace(?) IS NULL THEN NULL+ ELSE has_schema_privilege(?, 'USAGE') AND has_schema_privilege(?, 'CREATE')+ END AS privileged")++(defn- app-db-schema-usable?*+ "Whether this role can hold the index in [[index-table/index-schema]].+ Privileges, not existence: USAGE without CREATE passes a mere existence check, then fails in+ [[index-table/ensure-tables!]].+ A database failure reads as unusable, so an outage can't throw out of the fire-and-forget+ [[request-entity-sync!]]."+ []+ (let [schema index-table/index-schema]+ (try+ (if-some [privileged (:privileged (jdbc/execute-one!+ (mdb/data-source)+ [schema-privilege-sql schema schema schema]+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))]+ privileged+ ;; Not there yet -- can this role create it? Rolled back, so nothing is persisted here.+ (do+ (jdbc/with-transaction [tx (mdb/data-source) {:rollback-only true}]+ (jdbc/execute! tx [(format "CREATE SCHEMA IF NOT EXISTS %s" (semantic.util/quote-ident schema))]))+ true))+ (catch InterruptedException e+ (throw e))+ (catch Exception e+ (log/debug e "The application database user cannot host the library retrieval schema")+ false))))++(defonce ^{:doc "Set once [[app-db-schema-usable?*]] has answered yes. Rebound by tests."}+ app-db-schema-confirmed?+ (atom false))++(def ^:private retry-app-db-schema-probe+ "[[app-db-schema-usable?*]], re-run at most every five minutes."+ (memoize/ttl app-db-schema-usable?* :ttl/threshold (* 5 60 1000)))++;; A latch that closes once we detect the necessary schema.+;; This way we retry until the resource is ready, but don't leave it disabled for TTL on transient failures.+(defn- app-db-schema-usable?+ "Whether this role can hold the index, cached. [[available?]] asks on every write nudge and every search,+ and the underlying check can attempt DDL."+ []+ (swap! app-db-schema-confirmed? #(or % (retry-app-db-schema-probe))))++(defn pgvector-configured?+ "Whether a pgvector store is resolvable, dedicated or on the app db.+ The app-db arm checks this feature's own schema: semantic search's predicate answers for+ `semantic_search`, so a role that can use that one but not create ours would read as ready and then fail+ every reconcile.+ Probes the app db, so check the license first (see [[available?]])."+ []+ (and (semantic.db.datasource/pgvector-configured?)+ (or (semantic.db.datasource/dedicated-url-configured?)+ (app-db-schema-usable?))))+(defn- embedder-configured?"Whether an embedding backend is configured: without one we can neither index nor retrieve."[]@@ -61,8 +122,9 @@Re-evaluate this per use, as this configuration is dynamic."[]- (and (pgvector-configured?)- (licensed?)+ ;; License first: [[pgvector-configured?]] can probe the app db, and an unlicensed instance must not.+ (and (licensed?)+ (pgvector-configured?)(embedder-configured?)))(defn- missing-table-error?@@ -75,14 +137,16 @@(u/full-exception-chain e))))(defn- dependencies- "Entity retrieval's necessary conditions, as a `{:store, :embedder, :licenses}` map of booleans."+ "Entity retrieval's necessary conditions, as a `{:store, :embedder, :licenses}` map of booleans.+ `:store` reads false when unlicensed rather than being resolved, which would query the app db."[]- {:store (pgvector-configured?)- :embedder (embedder-configured?)- :licenses (licensed?)})+ (let [licensed (licensed?)]+ {:store (and licensed (pgvector-configured?))+ :embedder (embedder-configured?)+ :licenses licensed}))(defn- index-populated? [ds]- (boolean (seq (jdbc/execute! ds [(format "SELECT 1 FROM \"%s\" LIMIT 1" index-table/*vectors-table*)]))))+ (boolean (seq (jdbc/execute! ds [(format "SELECT 1 FROM %s LIMIT 1" (index-table/vectors-table-sql))]))))(defn- probe-index"The `:index` map — `{:status <enum>}`, plus `:error` on `:unreachable`. A compatible metadata row is@@ -331,7 +395,7 @@pgvector(-> (sql.helpers/select :entity_type :entity_local_id :doc_type :doc_text[[:raw distance] :distance])- (sql.helpers/from (keyword index-table/*vectors-table*))+ (sql.helpers/from (keyword (index-table/vectors-table)));; Exact scan, no HNSW: the blended order-by can't use an ANN index, and the;; library set is tiny.(sql.helpers/order-by [[:raw (ranking-sql distance)] :asc])diff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/health.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/health.cljindex 949e7e489d3..6259e262c4b 100644--- a/enterprise/backend/src/metabase_enterprise/entity_retrieval/health.clj+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/health.clj@@ -100,7 +100,7 @@(entity-class-set(map (juxt :entity_type :entity_local_id)(jdbc/execute! ds- [(format "SELECT DISTINCT entity_type, entity_local_id FROM \"%s\"" index-table/*vectors-table*)]+ [(format "SELECT DISTINCT entity_type, entity_local_id FROM %s" (index-table/vectors-table-sql))]{:builder-fn jdbc.rs/as-unqualified-lower-maps}))))(defn- library-and-indexed-classes*@@ -136,8 +136,8 @@(try(let [sql (format (str "WITH observed AS (SELECT clock_timestamp() AS at) ""SELECT EXTRACT(EPOCH FROM ((SELECT at FROM observed) - reconciled_at)) AS age "- "FROM \"%s\" WHERE id = 1")- index-table/*meta-table*)+ "FROM %s WHERE id = 1")+ (index-table/meta-table-sql)){:keys [age]} (jdbc/execute-one! ds [sql] {:builder-fn jdbc.rs/as-unqualified-lower-maps})](cond(nil? age)diff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/index_table.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/index_table.cljindex d639dfc32e3..47ff16af8fc 100644--- a/enterprise/backend/src/metabase_enterprise/entity_retrieval/index_table.clj+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/index_table.clj@@ -23,23 +23,66 @@[clojure.string :as str][honey.sql :as sql][honey.sql.helpers :as sql.helpers]+ [metabase-enterprise.semantic-search.util :as semantic.util][metabase.util.log :as log][next.jdbc :as jdbc][next.jdbc.result-set :as jdbc.rs])(:import+ (java.sql SQLException)(java.time Instant)))(set! *warn-on-reflection* true)+(def index-schema+ "Schema holding the library entity index, in a dedicated store and on the app db alike.+ Its own, not semantic search's: [[metabase-enterprise.semantic-search.db.migration.impl]] wipes the+ schema it is given, and in a dedicated store that is the default schema these tables used to sit in."+ "library_retrieval")+;; TODO (Chris 2026-07-14) -- these names carry no version, so an on-disk upgrade has nothing to key off.;; Revisit when the semantic-search indexing mechanism is reworked, sharing its scheme.-(def ^:dynamic *vectors-table*- "Vectors table name. Dynamic so tests can rebind it to an isolated table."- "library_entity_index")+(def default-tables+ "Where the index lives. Qualified in both modes, so nothing here can resolve against an application+ table, and a semantic-search migration cannot reach it."+ {:schema index-schema+ :vectors (str index-schema ".library_entity_index")+ :meta (str index-schema ".library_entity_index_meta")})++(def legacy-tables+ "The unqualified names used before [[index-schema]] existed. [[adopt-legacy-tables!]] moves them."+ {:vectors "library_entity_index"+ :meta "library_entity_index_meta"})++(def ^:dynamic *tables*+ "Table names to use, or nil for [[default-tables]]. Bound by tests to isolated names."+ nil)++(defn tables+ "The index's table names, as a `{:schema :vectors :meta}` map."+ []+ (or *tables* default-tables))++(defn vectors-table+ "Name of the vectors table, schema-qualified.+ For raw SQL use [[vectors-table-sql]]: interpolated into `\"%s\"`, a qualified name reads as one+ identifier."+ []+ (:vectors (tables)))++(defn meta-table+ "Name of the meta table, schema-qualified. For raw SQL use [[meta-table-sql]]."+ []+ (:meta (tables)))++(defn vectors-table-sql+ "[[vectors-table]] quoted for interpolation into raw SQL."+ []+ (semantic.util/quote-table (vectors-table)))-(def ^:dynamic *meta-table*- "Meta table name. Dynamic so tests can rebind it to an isolated table."- "library_entity_index_meta")+(defn meta-table-sql+ "[[meta-table]] quoted for interpolation into raw SQL."+ []+ (semantic.util/quote-table (meta-table)))(def schema-version"Canonical version of the index's *document format* — both the vectors table schema and the@@ -72,7 +115,7 @@(str "'[" (str/join ", " embedding) "]'::vector"))(defn- create-meta-table-sql []- (-> (sql.helpers/create-table (keyword *meta-table*) :if-not-exists)+ (-> (sql.helpers/create-table (keyword (meta-table)) :if-not-exists)(sql.helpers/with-columns[[:id :smallint [:primary-key] [:default 1] [:check [:= :id 1]]][:provider :text :not-null]@@ -87,7 +130,7 @@sql-format-quoted))(defn- create-vectors-table-sql [dims]- (-> (sql.helpers/create-table (keyword *vectors-table*) :if-not-exists)+ (-> (sql.helpers/create-table (keyword (vectors-table)) :if-not-exists)(sql.helpers/with-columns[[:doc_id :text [:primary-key]][:entity_type :text :not-null]@@ -107,14 +150,14 @@(defn- read-meta [tx](jdbc/execute-one! tx- [(format "SELECT provider, model_name, vector_dimensions, schema_version FROM \"%s\" WHERE id = 1"- *meta-table*)]+ [(format "SELECT provider, model_name, vector_dimensions, schema_version FROM %s WHERE id = 1"+ (meta-table-sql))]{:builder-fn jdbc.rs/as-unqualified-lower-maps}))(defn- write-meta! [tx embedding-model](let [{:keys [provider model_name vector_dimensions schema_version]} (model-identity embedding-model)](jdbc/execute! tx- (-> (sql.helpers/insert-into (keyword *meta-table*))+ (-> (sql.helpers/insert-into (keyword (meta-table)))(sql.helpers/values [{:id 1:provider provider:model_name model_name@@ -129,38 +172,73 @@(defn- create-tables! [tx dims](jdbc/execute! tx (create-vectors-table-sql dims)))+(defn- table-exists?+ "Whether `table-name` resolves, schema-qualified or on the search path."+ [tx table-name]+ (some? (:exists (jdbc/execute-one! tx ["SELECT to_regclass(?) AS exists" table-name]+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))))++(defn- ensure-schema!+ "Create the index's schema. Nothing else creates it: semantic search provisions its own, and library+ retrieval runs without semantic search."+ [tx]+ (when-let [schema (:schema (tables))]+ (try+ (jdbc/execute! tx [(format "CREATE SCHEMA IF NOT EXISTS %s" (semantic.util/quote-ident schema))])+ (catch SQLException e+ (throw (ex-info (format (str "Failed to create the %s schema for the library entity index."+ " Grant CREATE on the database to the Metabase user.")+ schema)+ {:type ::schema-creation-failed, :schema schema}+ e))))))++(defn- adopt-legacy-tables!+ "Move an index built before [[index-schema]] existed into it, preserving its rows.+ Without this, the qualified tables would be created empty beside the old ones and the whole library+ would be re-embedded. A no-op once moved: the unqualified name no longer resolves."+ [tx]+ (when (= default-tables (tables))+ (doseq [k [:vectors :meta]]+ (let [legacy (k legacy-tables)]+ (when (and (table-exists? tx legacy)+ (not (table-exists? tx (k default-tables))))+ (log/infof "Moving %s into the %s schema" legacy index-schema)+ (jdbc/execute! tx [(format "ALTER TABLE %s SET SCHEMA %s"+ (semantic.util/quote-ident legacy)+ (semantic.util/quote-ident index-schema))]))))))+(defn vectors-table-exists?"Whether the configured entity-retrieval vectors table exists."[tx]- (some? (:exists (jdbc/execute-one! tx [(format "SELECT to_regclass('%s') AS exists" *vectors-table*)]- {:builder-fn jdbc.rs/as-unqualified-lower-maps}))))+ (table-exists? tx (vectors-table)))(defn- meta-column-exists? [tx column](some? (jdbc/execute-one! tx [(str "SELECT 1 FROM pg_attribute"" WHERE attrelid = to_regclass(?) AND attname = ? AND NOT attisdropped")- *meta-table* column])))+ (meta-table) column])))(defn- can-alter-meta-table? [tx](:owns_table(jdbc/execute-one! tx[(str "SELECT pg_has_role(c.relowner, 'USAGE') AS owns_table"" FROM pg_class c WHERE c.oid = to_regclass(?)")- *meta-table*]+ (meta-table)]{:builder-fn jdbc.rs/as-unqualified-lower-maps})))(defonce ^:private warned-about-missing-reconciled-at (atom #{}))(defn- warn-about-missing-reconciled-at-once! []- (let [[warned-before _] (swap-vals! warned-about-missing-reconciled-at conj *meta-table*)]- (when-not (contains? warned-before *meta-table*)- (log/warnf "Cannot add reconciled_at to %s because the current role does not own it" *meta-table*))))+ (let [table (meta-table)+ [warned-before _] (swap-vals! warned-about-missing-reconciled-at conj table)]+ (when-not (contains? warned-before table)+ (log/warnf "Cannot add reconciled_at to %s because the current role does not own it" table))))(defn- ensure-reconciled-at-column! [tx](or (meta-column-exists? tx "reconciled_at")(if (can-alter-meta-table? tx)(do- (jdbc/execute! tx [(format "ALTER TABLE \"%s\" ADD COLUMN IF NOT EXISTS reconciled_at timestamp with time zone"- *meta-table*)])+ (jdbc/execute! tx [(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS reconciled_at timestamp with time zone"+ (meta-table-sql))])true)(do;; An ALTER permission error would abort ensure-tables!'s transaction. Grant-only installations can@@ -175,12 +253,14 @@no-op for legacy meta tables the current database role cannot upgrade."[tx reconciled-at](when (meta-column-exists? tx "reconciled_at")- (jdbc/execute! tx [(format "UPDATE \"%s\" SET reconciled_at = ? WHERE id = 1" *meta-table*)+ (jdbc/execute! tx [(format "UPDATE %s SET reconciled_at = ? WHERE id = 1"+ (meta-table-sql))reconciled-at])))(defn- clear-reconciled-at! [tx](when (meta-column-exists? tx "reconciled_at")- (jdbc/execute! tx [(format "UPDATE \"%s\" SET reconciled_at = NULL WHERE id = 1" *meta-table*)])))+ (jdbc/execute! tx [(format "UPDATE %s SET reconciled_at = NULL WHERE id = 1"+ (meta-table-sql))])))(defn index-status"Compatibility of the built index against `embedding-model` and [[schema-version]]:@@ -209,6 +289,10 @@(jdbc/with-transaction [tx pgvector](jdbc/execute! tx [(format "SELECT pg_advisory_xact_lock(%d)" ensure-lock-id)])(jdbc/execute! tx (sql/format (sql.helpers/create-extension :vector :if-not-exists)))+ (ensure-schema! tx)+ ;; Before any CREATE below: those are IF NOT EXISTS, so creating first would leave an empty qualified+ ;; table for the move to refuse, and the whole library would be re-embedded.+ (adopt-legacy-tables! tx)(jdbc/execute! tx (create-meta-table-sql));; CREATE TABLE IF NOT EXISTS does not add columns to an existing table. Upgrade when this role owns it;;; grant-only roles keep reconciling without the optional freshness timestamp.@@ -223,7 +307,8 @@:created)(not= stored current)- (do (jdbc/execute! tx [(format "DROP TABLE IF EXISTS \"%s\"" *vectors-table*)])+ (do (jdbc/execute! tx [(format "DROP TABLE IF EXISTS %s"+ (vectors-table-sql))])(create-tables! tx dims)(write-meta! tx embedding-model):rebuilt)diff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.cljindex da4fd974fa9..651ed421d2c 100644--- a/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.clj+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.clj@@ -241,8 +241,8 @@[conn](u/index-by :doc_id #(select-keys % [:entity_type :entity_local_id])(jdbc/execute! conn- [(format "SELECT doc_id, entity_type, entity_local_id FROM \"%s\""- index-table/*vectors-table*)]+ [(format "SELECT doc_id, entity_type, entity_local_id FROM %s"+ (index-table/vectors-table-sql))]{:builder-fn jdbc.rs/as-unqualified-lower-maps})))(defn- stored-docs-for-entity@@ -255,8 +255,8 @@(comp (filter #(= target-class (entity-class %)))(map (juxt :doc_id #(select-keys % [:entity_type :entity_local_id]))))(jdbc/execute! conn- [(format "SELECT doc_id, entity_type, entity_local_id FROM \"%s\" WHERE entity_local_id = ?"- index-table/*vectors-table*)+ [(format "SELECT doc_id, entity_type, entity_local_id FROM %s WHERE entity_local_id = ?"+ (index-table/vectors-table-sql))entity-local-id]{:builder-fn jdbc.rs/as-unqualified-lower-maps}))))@@ -289,7 +289,7 @@docs)](when (seq records)(jdbc/execute! conn- (-> (sql.helpers/insert-into (keyword index-table/*vectors-table*))+ (-> (sql.helpers/insert-into (keyword (index-table/vectors-table)))(sql.helpers/values (vec records))(sql.helpers/on-conflict :doc_id)(sql.helpers/do-nothing)@@ -299,7 +299,7 @@(defn- delete-rows! [conn doc-ids](when (seq doc-ids)(jdbc/execute! conn- (-> (sql.helpers/delete-from (keyword index-table/*vectors-table*))+ (-> (sql.helpers/delete-from (keyword (index-table/vectors-table)))(sql.helpers/where [:in :doc_id (vec doc-ids)])(sql/format {:quoted true})))))@@ -316,8 +316,8 @@(jdbc/execute-one! conn[(format (str "SELECT count(*) AS documents, ""count(distinct (entity_type, entity_local_id)) AS entities "- "FROM \"%s\"")- index-table/*vectors-table*)]+ "FROM %s")+ (index-table/vectors-table-sql))]{:builder-fn jdbc.rs/as-unqualified-lower-maps})]{:documents documents :entities entities}))diff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/task/sync.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/task/sync.cljindex 0e2ed552d4e..67b1d1fc1d4 100644--- a/enterprise/backend/src/metabase_enterprise/entity_retrieval/task/sync.clj+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/task/sync.clj@@ -40,10 +40,9 @@(def ^:private ^Duration run-frequency (Duration/parse "PT15M"))(defmethod task/init! ::OsiAiContextSync [_]- ;; Gate scheduling on pgvector being configured (boot-fixed), NOT on available? — the job body- ;; self-gates on the feature flag, so scheduling here lets the periodic safety net (and the- ;; write-path trigger's target job) exist even when the license is enabled after startup.- (when (entity-retrieval.core/pgvector-configured?)+ ;; Gate on the boot-safe check, NOT on available? — the job body self-gates, so scheduling here lets the+ ;; periodic safety net (and the write-path trigger's target job) exist before the store is reachable.+ (when (entity-retrieval.core/pgvector-schedulable?)(let [job (jobs/build(jobs/of-type OsiAiContextSync)(jobs/store-durably)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.cljindex cbbbd357d2a..05f09f64400 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.semantic-search.db.migration.impl(:require[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.util :as semantic.util][metabase.collections.curation :as collections.curation]@@ -22,13 +23,39 @@Their presence in a to-be-wiped dedicated database means MB_PGVECTOR_DB_URL was pointed at an app db."#{"core_user" "metabase_database"})+(def ^:private dlq-table-pattern+ "One dead-letter queue per index, `dlq_<index-id>`+ (see [[metabase-enterprise.semantic-search.dlq/dlq-table-name-kw]])."+ #"\Adlq_\d+\z")++(def ^:private repair-table-pattern+ "Repair's scratch tables, `repair_<millis>_<6 chars>`+ (see [[metabase-enterprise.semantic-search.repair/repair-table-name]])."+ #"\Arepair_\d+_[a-z0-9]{6}\z")++(defn- semantic-search-table?+ "Whether a bare table name is one this module creates: a control table, an index table, a DLQ, or a+ repair scratch table.+ Name *shapes*, not prefixes — a dedicated store's default schema is shared, and a cohabitant is free to+ call something `index_history`. [[semantic.index/index-table-name?]] is the same contract orphan+ cleanup uses to decide what it may drop."+ [index-metadata {:keys [tablename]}]+ (boolean+ (or (contains? (into #{} (map #(semantic.util/table-name-part (index-metadata %)))+ [:metadata-table-name :control-table-name :gate-table-name])+ tablename)+ (semantic.index/index-table-name? tablename)+ (re-matches dlq-table-pattern tablename)+ (re-matches repair-table-pattern tablename))))+(defn- drop-all-but-migration-table"Destructive: clears out semantic-search storage ahead of recreating it from scratch.When index-metadata carries a `:schema` (shared app-db mode) ONLY tables inside that schema may bedropped — the application's tables live in other schemas and must never be touched here.Without a `:schema` the database is assumed dedicated to semantic search and its default schema is- wiped; refuses outright when the database looks like a Metabase app db (MB_PGVECTOR_DB_URL pointed at- the application database would otherwise destroy it here, on first init)."+ swept, but only for tables [[semantic-search-table?]] recognizes — library retrieval keeps its index+ there too. Refuses outright when the database looks like a Metabase app db (MB_PGVECTOR_DB_URL pointed+ at the application database would otherwise destroy it here, on first init)."[index-metadata tx](let [schema (:schema index-metadata)tables (jdbc/execute! tx@@ -45,13 +72,19 @@[:= :schemaname [:raw "current_schema()"]][:<> :tablename [:inline "migration"]]])}){:builder-fn jdbc.rs/as-unqualified-lower-maps})]+ ;; the sentinel scan reads every table in scope, not just ours: an app db is recognized by tables we+ ;; would never drop(when (and (nil? schema)(some (comp app-db-sentinel-tables :tablename) tables))(throw (ex-info (str "Refusing to reset the semantic search database: it contains Metabase application"" tables. Point MB_PGVECTOR_DB_URL at a dedicated pgvector database, or unset it to"" share the application database in the isolated semantic_search schema."){:type ::refused-app-db-wipe})))- (doseq [{:keys [schemaname tablename]} tables]+ (doseq [{:keys [schemaname tablename]}+ (cond->> tables+ ;; the module's own schema holds nothing else, so a reset there is free to clear leftovers+ ;; from older naming schemes. A dedicated store's default schema is shared.+ (nil? schema) (filter (partial semantic-search-table? index-metadata)))](jdbc/execute! tx(sql/format{:drop-table [[[:raw (str (semantic.util/quote-ident schemaname) "."diff --git a/enterprise/backend/test/metabase_enterprise/entity_retrieval/appdb_mode_test.clj b/enterprise/backend/test/metabase_enterprise/entity_retrieval/appdb_mode_test.cljnew file mode 100644index 00000000000..13fd354f896--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/entity_retrieval/appdb_mode_test.clj@@ -0,0 +1,150 @@+(ns metabase-enterprise.entity-retrieval.appdb-mode-test+ "End-to-end round trip for the library entity index on pgvector-on-the-app-db: no MB_PGVECTOR_DB_URL,+ every table inside the library_retrieval schema, sharing the app-db pool.++ Opt-in and self-gated like [[metabase-enterprise.semantic-search.appdb-pgvector-mode-test]]: the round+ trip installs the vector extension and drops the library_retrieval schema on cleanup, so it runs only+ with MB_APPDB_PGVECTOR_MODE_TEST=true, set by the appdb-mode CI job.+ No test-util once-fixture: that gates on the dedicated-harness MB_PGVECTOR_DB_URL, which is what this+ namespace runs without."+ (:require+ [clojure.test :refer [deftest is testing use-fixtures]]+ [metabase-enterprise.entity-retrieval.core :as entity-retrieval.core]+ [metabase-enterprise.entity-retrieval.index-table :as index-table]+ [metabase-enterprise.entity-retrieval.reconcile :as reconcile]+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]+ [metabase-enterprise.semantic-search.db.migration.impl :as semantic.migration.impl]+ [metabase-enterprise.semantic-search.embedding :as semantic.embedding]+ [metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]+ [metabase.app-db.core :as mdb]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [next.jdbc :as jdbc]+ [next.jdbc.result-set :as jdbc.rs]))++(set! *warn-on-reflection* true)++;; the mode probe answers only once the app db is set up, and this namespace can be the first thing a+;; fresh test JVM runs+(use-fixtures :once (fixtures/initialize :db :test-users))++(defn- tables-in-schema+ [connectable schema]+ (->> (jdbc/execute! connectable+ ["SELECT tablename FROM pg_tables WHERE schemaname = ?" schema]+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})+ (map :tablename)+ set))++(defn- schema-exists?+ [connectable schema]+ (boolean (seq (jdbc/execute! connectable+ ["SELECT 1 FROM information_schema.schemata WHERE schema_name = ?" schema]+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))))++(defn- appdb-can-host-library-index?+ "The extension, plus this feature's own schema. Gating on semantic search's check instead would let the+ harness pass where a role that can use `semantic_search` but not create ours fails in production."+ []+ (and (= :postgres (mdb/db-type))+ (try+ (and (semantic.db.datasource/check-app-db-pgvector-support)+ (#'entity-retrieval.core/app-db-schema-usable?*))+ (catch Exception _ false))))++(defn- opted-in?+ []+ (Boolean/parseBoolean (System/getenv "MB_APPDB_PGVECTOR_MODE_TEST")))++(deftest ^:synchronized appdb-library-index-round-trip-test+ (cond+ (not (opted-in?))+ (testing "destructive round trip requires the MB_APPDB_PGVECTOR_MODE_TEST opt-in — skipping"+ (is true))++ (not (appdb-can-host-library-index?))+ (testing "opted in, but the app db can't host the index — the CI service must be misconfigured"+ (is false "the appdb-mode job expects a pgvector-capable Postgres app db"))++ (schema-exists? (mdb/data-source) index-table/index-schema)+ (testing "opted in, but a library_retrieval schema already exists — refusing to clobber it"+ (is false "the appdb-mode job should start from a fresh app db"))++ :else+ (mt/with-premium-features #{:library :library-retrieval}+ ;; near-identical vectors, so the query lands on its document and nothing else+ (semantic.tu/with-mock-embeddings {"Dog Training Guide" [0.12 -0.34 0.56 -0.78]+ "puppy" [0.13 -0.33 0.57 -0.77]}+ (with-redefs [semantic.db.datasource/db-url nil+ semantic.db.datasource/data-source (atom nil)+ ;; a cooldown left open by another test would make pgvector-mode read :unavailable+ semantic.db.datasource/app-db-pgvector-support (atom nil)+ semantic.db.datasource/probe-cooldown-timer (atom nil)+ semantic.db.datasource/logged-pgvector-absent? (atom false)+ ;; latching a yes here would leak into every later test in this JVM+ entity-retrieval.core/app-db-schema-confirmed? (atom false)+ semantic.embedding/get-configured-model (fn [] semantic.tu/mock-embedding-model)]+ (let [app-db (mdb/data-source)]+ (try+ (testing "the app db serves as the store, with no dedicated URL"+ (is (= :app-db (semantic.db.datasource/pgvector-mode)))+ (is (true? (entity-retrieval.core/available?)))+ (is (= index-table/default-tables (index-table/tables))))+ (let [ds (semantic.db.datasource/ensure-initialized-data-source!)+ public-before (tables-in-schema app-db "public")]+ (is (identical? app-db ds) "app-db mode shares the application pool")+ ;; an index built before the schema existed, standing in for an upgrading instance. Its+ ;; rows must survive: rebuilding instead would re-embed the whole library.+ ;; ensure-tables! installs the extension, but this table predates that call and its+ ;; vector(4) column needs the type to exist already+ (jdbc/execute! app-db ["CREATE EXTENSION IF NOT EXISTS vector"])+ (jdbc/execute! app-db ["CREATE TABLE library_entity_index+ (doc_id text primary key, entity_type text, entity_local_id bigint,+ doc_type text, doc_text text, doc_embedding vector(4))"])+ (jdbc/execute! app-db ["INSERT INTO library_entity_index+ VALUES ('legacy-doc', 'table', 1, 'name', 'legacy', '[0,0,0,0]')"])+ (mt/with-temp [:model/Collection {lib-id :id} {:type "library" :location "/"}+ :model/Collection {data-id :id} {:type "library-data"+ :location (str "/" lib-id "/")}+ :model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id+ :collection_id data-id+ :is_published true+ :active true+ :name "dog_training_guide"+ :display_name "Dog Training Guide"}]+ (testing "adoption keeps the rows an upgrading instance already embedded"+ ;; asserted here rather than after the reconcile, which GCs any document the library+ ;; no longer implies -- including this synthetic one+ (index-table/ensure-tables! ds semantic.tu/mock-embedding-model)+ (is (= 1 (:count (jdbc/execute-one!+ app-db+ [(format "SELECT count(*) AS count FROM %s WHERE doc_id = 'legacy-doc'"+ (index-table/vectors-table-sql))]+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})))+ "moved, not recreated empty -- otherwise the whole library re-embeds"))+ (reconcile/reconcile! ds (constantly semantic.tu/mock-embedding-model))+ (testing "both tables live inside the library_retrieval schema"+ (is (= #{"library_entity_index" "library_entity_index_meta"}+ (tables-in-schema app-db index-table/index-schema))))+ (testing "the pre-existing index was moved, not left behind"+ (is (not (contains? (tables-in-schema app-db "public") "library_entity_index"))))+ (testing "the application schema is untouched"+ (is (= public-before (tables-in-schema app-db "public"))))+ (testing "retrieval round-trips through the app-db pool"+ (is (= [{:model "table" :id table-id}]+ (->> (entity-retrieval.core/search "puppy" 5)+ (map :entity)+ distinct+ vec))))+ (testing "a semantic-search wipe cannot reach the library index"+ ;; the reason for a separate schema: this drops every table in the schema it is given+ (jdbc/with-transaction [tx app-db]+ (#'semantic.migration.impl/drop-all-but-migration-table+ semantic.index-metadata/app-db-index-metadata tx))+ (is (= #{"library_entity_index" "library_entity_index_meta"}+ (tables-in-schema app-db index-table/index-schema))))))+ (finally+ (jdbc/execute! app-db [(format "DROP SCHEMA IF EXISTS %s CASCADE"+ index-table/index-schema)])))))))))diff --git a/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj b/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.cljindex 0ed1ade8b40..d6a56faeb91 100644--- a/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj+++ b/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj@@ -130,8 +130,8 @@(mt/with-dynamic-fn-redefs [semantic.embedding/get-configured-model (constantly semantic.tu/mock-embedding-model)](with-redefs [semantic.db.datasource/db-url "jdbc:postgresql://stub"](mt/with-premium-features #{}- (is (true? (entity-retrieval.core/pgvector-configured?))- "scheduling gates on pgvector config, not the license, so a post-boot license still syncs")+ (is (true? (entity-retrieval.core/pgvector-schedulable?))+ "a dedicated URL schedules the sync job unlicensed, so a post-boot license still syncs")(is (false? (entity-retrieval.core/available?))))(mt/with-premium-features #{:library-retrieval}(is (false? (entity-retrieval.core/available?))@@ -141,12 +141,38 @@":library without :library-retrieval does not entitle the tool"))(mt/with-premium-features #{:library :library-retrieval}(is (true? (entity-retrieval.core/available?)))))- ;; no URL -> unconfigured and unavailable regardless of license, even on a pgvector-capable- ;; Postgres app db: entity retrieval's tables aren't schema-isolated yet, so it stays dedicated-only- (with-redefs [semantic.db.datasource/db-url nil]- (mt/with-premium-features #{:library :library-retrieval}- (is (false? (entity-retrieval.core/pgvector-configured?)))- (is (false? (entity-retrieval.core/available?))))))+ (testing "no dedicated URL: the app db serves when it can host pgvector"+ ;; the schema probe is Postgres-only SQL, so leaving it live would read as unusable on the H2 and+ ;; MySQL app-db runs -- the mode is what this case is about+ (with-redefs [semantic.db.datasource/db-url nil+ entity-retrieval.core/app-db-schema-usable? (constantly true)]+ (mt/with-dynamic-fn-redefs [semantic.db.datasource/pgvector-mode (constantly :app-db)]+ (mt/with-premium-features #{:library :library-retrieval}+ (is (true? (entity-retrieval.core/available?)))))+ (mt/with-dynamic-fn-redefs [semantic.db.datasource/pgvector-mode (constantly :unavailable)]+ (mt/with-premium-features #{:library :library-retrieval}+ (is (false? (entity-retrieval.core/available?)))))))+ (testing "the app-db arm checks this feature's own schema, not semantic search's"+ (with-redefs [semantic.db.datasource/db-url nil]+ (mt/with-dynamic-fn-redefs [semantic.db.datasource/pgvector-mode (constantly :app-db)]+ (mt/with-premium-features #{:library :library-retrieval}+ (with-redefs [entity-retrieval.core/app-db-schema-usable? (constantly false)]+ (is (false? (entity-retrieval.core/available?))+ "a role that can use semantic_search but cannot create library_retrieval is not ready"))+ (with-redefs [entity-retrieval.core/app-db-schema-usable? (constantly true)]+ (is (true? (entity-retrieval.core/available?))))))))+ (testing "a dedicated store needs no app-db schema check"+ (with-redefs [semantic.db.datasource/db-url "jdbc:postgresql://stub"+ entity-retrieval.core/app-db-schema-usable? #(throw (ex-info "must not probe" {}))]+ (mt/with-premium-features #{:library :library-retrieval}+ (is (true? (entity-retrieval.core/available?))))))+ (testing "an unlicensed instance resolves no store: doing so probes the app db"+ (with-redefs [semantic.db.datasource/db-url nil]+ (mt/with-dynamic-fn-redefs [semantic.db.datasource/pgvector-mode+ #(throw (ex-info "must not probe" {}))]+ (mt/with-premium-features #{}+ (is (false? (entity-retrieval.core/pgvector-schedulable?)))+ (is (false? (entity-retrieval.core/available?))))))))(testing "fully licensed + pgvector, but no way to compute embeddings -> unavailable"(with-redefs [semantic.db.datasource/db-url "jdbc:postgresql://stub"](mt/with-premium-features #{:library :library-retrieval}@@ -154,6 +180,25 @@(mt/with-dynamic-fn-redefs [semantic.embedding/get-configured-model (constantly {:provider "no-embedder"})](is (false? (entity-retrieval.core/available?)))))))))+(deftest app-db-schema-check-caching-test+ (let [answers (atom nil)+ probe (fn [] (let [[answer & remaining] @answers]+ (reset! answers (vec remaining))+ answer))]+ (testing "a confirmed yes latches: an app-db hiccup reads as no, and must not take retrieval offline"+ (reset! answers [true false])+ (with-redefs [entity-retrieval.core/app-db-schema-confirmed? (atom false)+ entity-retrieval.core/retry-app-db-schema-probe probe]+ (is (true? (#'entity-retrieval.core/app-db-schema-usable?)))+ (is (true? (#'entity-retrieval.core/app-db-schema-usable?)))+ (is (= [false] @answers) "the probe was not consulted again")))+ (testing "a no is re-checked, so a privilege granted while we run gets picked up"+ (reset! answers [false true])+ (with-redefs [entity-retrieval.core/app-db-schema-confirmed? (atom false)+ entity-retrieval.core/retry-app-db-schema-probe probe]+ (is (false? (#'entity-retrieval.core/app-db-schema-usable?)))+ (is (true? (#'entity-retrieval.core/app-db-schema-usable?)))))))+(deftest entity-retrieval-availability-requires-a-closed-breaker-test(mt/with-premium-features #{:library-retrieval}(let [recovery-requested? (atom false)]@@ -218,8 +263,8 @@ds (semantic.db.datasource/ensure-initialized-data-source!)](mt/with-dynamic-fn-redefs [semantic.embedding/get-configured-model(constantly semantic.tu/mock-embedding-model)]- (binding [index-table/*vectors-table* (str "library_entity_index_test_" suffix)- index-table/*meta-table* (str "library_entity_index_meta_test_" suffix)]+ (binding [index-table/*tables* {:vectors (str "library_entity_index_test_" suffix)+ :meta (str "library_entity_index_meta_test_" suffix)}](try(testing "configured + licensed but no index table yet -> unavailable"(is (true? (entity-retrieval.core/available?)))@@ -241,8 +286,8 @@(is (false? (entity-retrieval.core/entity-retrieval-available?))))))(finally(jdbc/execute! ds [(str "DROP TABLE IF EXISTS "- index-table/*vectors-table* ", "- index-table/*meta-table*)]))))))))))+ (index-table/vectors-table) ", "+ (index-table/meta-table))]))))))))))(deftest ^:sequential ranks-by-similarity-test(testing "search ranks library documents by cosine similarity, nearest first"@@ -253,8 +298,8 @@q "the query"](mt/with-dynamic-fn-redefs [semantic.embedding/get-configured-model(constantly semantic.tu/mock-embedding-model)]- (binding [index-table/*vectors-table* (str "library_entity_index_test_" suffix)- index-table/*meta-table* (str "library_entity_index_meta_test_" suffix)]+ (binding [index-table/*tables* {:vectors (str "library_entity_index_test_" suffix)+ :meta (str "library_entity_index_meta_test_" suffix)}];; the two tables' name docs embed "near"/"far"; q ties "near" exactly and is orthogonal to "far".(semantic.tu/with-mock-embeddings {q [1.0 0.0 0.0 0.0]"near" [1.0 0.0 0.0 0.0]@@ -274,8 +319,8 @@(mirror/search q 10))))(finally(jdbc/execute! ds [(str "DROP TABLE IF EXISTS "- index-table/*vectors-table* ", "- index-table/*meta-table*)]))))))))))))+ (index-table/vectors-table) ", "+ (index-table/meta-table))]))))))))))))(defn- put-ai-context!"PUT an ai_context entry through the CRUD API."@@ -302,8 +347,8 @@[:structured-output :data]))](mt/with-dynamic-fn-redefs [semantic.embedding/get-configured-model(constantly semantic.tu/mock-embedding-model)]- (binding [index-table/*vectors-table* (str "library_entity_index_test_" suffix)- index-table/*meta-table* (str "library_entity_index_meta_test_" suffix)]+ (binding [index-table/*tables* {:vectors (str "library_entity_index_test_" suffix)+ :meta (str "library_entity_index_meta_test_" suffix)}];; the curated synonym ties the query exactly; the table's own name "orders" is orthogonal.(semantic.tu/with-mock-embeddings {q [1.0 0.0 0.0 0.0]synonym [1.0 0.0 0.0 0.0]@@ -333,11 +378,11 @@ds[(format (str "SELECT 1 FROM \"%s\" ""WHERE doc_type = 'synonym' AND entity_local_id = %d")- index-table/*vectors-table* table-id)])))))+ (index-table/vectors-table) table-id)])))))(finally(jdbc/execute! ds [(str "DROP TABLE IF EXISTS "- index-table/*vectors-table* ", "- index-table/*meta-table*)]))))))))))))+ (index-table/vectors-table) ", "+ (index-table/meta-table))]))))))))))))(deftest ^:sequential doc-type-boost-breaks-ties-test(testing "on a distance tie, a name match outranks a synonym match (blended ORDER BY, not raw NN)"@@ -349,8 +394,8 @@synonym "a curated synonym"](mt/with-dynamic-fn-redefs [semantic.embedding/get-configured-model(constantly semantic.tu/mock-embedding-model)]- (binding [index-table/*vectors-table* (str "library_entity_index_test_" suffix)- index-table/*meta-table* (str "library_entity_index_meta_test_" suffix)]+ (binding [index-table/*tables* {:vectors (str "library_entity_index_test_" suffix)+ :meta (str "library_entity_index_meta_test_" suffix)}];; alpha's name and beta's curated synonym both tie the query exactly; beta's name is orthogonal.(semantic.tu/with-mock-embeddings {q [1.0 0.0 0.0 0.0]"alpha" [1.0 0.0 0.0 0.0]@@ -371,8 +416,8 @@(mapv (juxt (comp :id :entity) :doc_type) (take 2 (mirror/search q 10)))))(finally(jdbc/execute! ds [(str "DROP TABLE IF EXISTS "- index-table/*vectors-table* ", "- index-table/*meta-table*)]))))))))))))+ (index-table/vectors-table) ", "+ (index-table/meta-table))]))))))))))))(deftest ^:sequential search-degrades-on-dimension-mismatch-test;; A post-upgrade embedding-dimension change leaves the query vector incompatible with the index column@@ -384,8 +429,8 @@ds (semantic.db.datasource/ensure-initialized-data-source!)](mt/with-dynamic-fn-redefs [semantic.embedding/get-configured-model(constantly semantic.tu/mock-embedding-model)]- (binding [index-table/*vectors-table* (str "library_entity_index_test_" suffix)- index-table/*meta-table* (str "library_entity_index_meta_test_" suffix)]+ (binding [index-table/*tables* {:vectors (str "library_entity_index_test_" suffix)+ :meta (str "library_entity_index_meta_test_" suffix)}](mt/with-temp [:model/Collection {lib-id :id} {:type "library" :location "/"}:model/Collection {data-id :id} {:type "library-data" :location (str "/" lib-id "/")}:model/Database {db-id :id} {}@@ -398,5 +443,5 @@(semantic.tu/with-mock-embeddings {"q" [1.0]}(is (= [] (entity-retrieval.core/search "q" 10))))(finally- (jdbc/execute! ds [(str "DROP TABLE IF EXISTS \"" index-table/*vectors-table*- "\", \"" index-table/*meta-table* "\"")])))))))))))+ (jdbc/execute! ds [(str "DROP TABLE IF EXISTS \"" (index-table/vectors-table)+ "\", \"" (index-table/meta-table) "\"")])))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/entity_retrieval/index_table_test.clj b/enterprise/backend/test/metabase_enterprise/entity_retrieval/index_table_test.cljindex e16bc4eaa4d..5d7e096e210 100644--- a/enterprise/backend/test/metabase_enterprise/entity_retrieval/index_table_test.clj+++ b/enterprise/backend/test/metabase_enterprise/entity_retrieval/index_table_test.clj@@ -39,6 +39,51 @@(is (re-find #"pg_has_role\(c\.relowner, 'USAGE'\)" @query)"a NOINHERIT member cannot use the owner role's ALTER privilege without SET ROLE")))+(deftest table-names-are-schema-qualified-test+ (testing "both stores put the index in its own schema, out of reach of a semantic-search wipe"+ (is (= {:schema "library_retrieval"+ :vectors "library_retrieval.library_entity_index"+ :meta "library_retrieval.library_entity_index_meta"}+ (index-table/tables))))+ (testing "rendered as separate identifiers"+ ;; interpolating the qualified name into "%s" would read as one identifier containing a dot+ (is (= "\"library_retrieval\".\"library_entity_index\"" (index-table/vectors-table-sql)))+ (is (= "\"library_retrieval\".\"library_entity_index_meta\"" (index-table/meta-table-sql)))))++(deftest schema-is-provisioned-test+ (let [statements (atom [])]+ (with-redefs-fn {#'jdbc/execute! (fn [_ sql] (swap! statements conj (first sql)) nil)}+ #(#'index-table/ensure-schema! ::tx))+ (is (= ["CREATE SCHEMA IF NOT EXISTS \"library_retrieval\""] @statements)+ "nothing else creates it: semantic search provisions its own, and we run without semantic search")))++(deftest legacy-tables-are-moved-not-rebuilt-test+ (let [statements (atom [])+ exists (atom #{"library_entity_index" "library_entity_index_meta"})]+ (with-redefs-fn {#'index-table/table-exists? (fn [_ table] (contains? @exists table))+ #'jdbc/execute! (fn [_ sql] (swap! statements conj (first sql)) nil)}+ (fn []+ (testing "an index built before the schema existed is moved, keeping its rows"+ (#'index-table/adopt-legacy-tables! ::tx)+ (is (= ["ALTER TABLE \"library_entity_index\" SET SCHEMA \"library_retrieval\""+ "ALTER TABLE \"library_entity_index_meta\" SET SCHEMA \"library_retrieval\""]+ @statements)))+ (testing "and left alone once moved"+ (reset! statements [])+ (reset! exists #{"library_retrieval.library_entity_index"+ "library_retrieval.library_entity_index_meta"})+ (#'index-table/adopt-legacy-tables! ::tx)+ (is (empty? @statements)))+ (testing "a qualified table standing beside a leftover legacy one keeps its rows"+ (reset! statements [])+ (reset! exists #{"library_entity_index"+ "library_entity_index_meta"+ "library_retrieval.library_entity_index"+ "library_retrieval.library_entity_index_meta"})+ (#'index-table/adopt-legacy-tables! ::tx)+ (is (empty? @statements)+ "SET SCHEMA onto an occupied name errors, aborting the whole ensure-tables! transaction"))))))+(deftest reconcile-watermark-precedes-appdb-read-test(let [events (atom [])](mt/with-dynamic-fn-redefs [reconcile/capture-reconcile-watermark (fn [_]diff --git a/enterprise/backend/test/metabase_enterprise/entity_retrieval/reconcile_test.clj b/enterprise/backend/test/metabase_enterprise/entity_retrieval/reconcile_test.cljindex b61dbebc098..e1693850d91 100644--- a/enterprise/backend/test/metabase_enterprise/entity_retrieval/reconcile_test.clj+++ b/enterprise/backend/test/metabase_enterprise/entity_retrieval/reconcile_test.clj@@ -84,19 +84,19 @@`(when semantic.db.datasource/db-url(let [suffix# (System/nanoTime)~ds-sym (semantic.db.datasource/ensure-initialized-data-source!)]- (binding [index-table/*vectors-table* (str "library_entity_index_test_" suffix#)- index-table/*meta-table* (str "library_entity_index_meta_test_" suffix#)]+ (binding [index-table/*tables* {:vectors (str "library_entity_index_test_" suffix#)+ :meta (str "library_entity_index_meta_test_" suffix#)}](try~@body(finally(jdbc/execute! ~ds-sym [(str "DROP TABLE IF EXISTS "- index-table/*vectors-table* ", "- index-table/*meta-table*)])))))))+ (index-table/vectors-table) ", "+ (index-table/meta-table))])))))))(defn- index-rows [ds](jdbc/execute! ds[(format "SELECT doc_id, entity_type, entity_local_id, doc_type, doc_text FROM \"%s\""- index-table/*vectors-table*)]+ (index-table/vectors-table))]{:builder-fn jdbc.rs/as-unqualified-lower-maps}))(defn- docs-for@@ -107,7 +107,7 @@(defn- reconciled-at! [ds](:reconciled_at (jdbc/execute-one! ds- [(format "SELECT reconciled_at FROM \"%s\" WHERE id = 1" index-table/*meta-table*)]+ [(format "SELECT reconciled_at FROM \"%s\" WHERE id = 1" (index-table/meta-table))]{:builder-fn jdbc.rs/as-unqualified-lower-maps})))(deftest ^:sequential reconcile-lifecycle-test@@ -210,7 +210,7 @@(is (seq (docs-for ds "table" table-id)))(testing "a schema-version mismatch alone also triggers the rebuild"(jdbc/execute! ds [(format "UPDATE \"%s\" SET schema_version = schema_version - 1"- index-table/*meta-table*)])+ (index-table/meta-table))])(is (= :rebuilt (index-table/ensure-tables! ds new-model)))(is (= [] (index-rows ds))))(testing "the rebuild heals the meta row, so it doesn't recur on the next sync"diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/migration_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/migration_test.cljindex f23671908fd..147ebf61df6 100644--- a/enterprise/backend/test/metabase_enterprise/semantic_search/migration_test.clj+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/migration_test.clj@@ -90,15 +90,28 @@(deftest dedicated-reset-stays-in-default-schema-test(mt/with-premium-features #{:semantic-search}(semantic.tu/with-test-db-defaults!- (testing "the dedicated-mode reset wipes only the default schema — cohabitant schemas survive"+ (testing "the dedicated-mode reset drops only its own tables, by schema and by name"(let [pgvector (semantic.env/get-pgvector-datasource!)](jdbc/execute! pgvector ["CREATE SCHEMA cohabitant"])(jdbc/execute! pgvector ["CREATE TABLE cohabitant.precious (id int)"])- (jdbc/execute! pgvector ["CREATE TABLE doomed (id int)"])+ ;; a real index table shape: index_<provider>_<model>_<dims>+ (jdbc/execute! pgvector ["CREATE TABLE index_mock_model_4 (id int)"])+ ;; library retrieval shares a dedicated store, and used to keep its index unqualified here+ (jdbc/execute! pgvector ["CREATE TABLE library_entity_index (id int)"])+ ;; a cohabitant is free to share our prefixes without matching any name we generate+ (jdbc/execute! pgvector ["CREATE TABLE index_history (id int)"])+ (jdbc/execute! pgvector ["CREATE TABLE dlq_backlog (id int)"])+ (jdbc/execute! pgvector ["CREATE TABLE repair_log (id int)"])(semantic.db.connection/with-migrate-tx [tx](semantic.db.migration/maybe-migrate! tx {:index-metadata semantic.index-metadata/default-index-metadata}))(is (true? (semantic.util/table-exists? pgvector "cohabitant.precious")))- (is (false? (semantic.util/table-exists? pgvector "public.doomed"))))))))+ (is (true? (semantic.util/table-exists? pgvector "public.library_entity_index"))+ "another module's table in the same schema is not ours to drop")+ (testing "sharing a prefix is not enough — only names this module generates are dropped"+ (is (true? (semantic.util/table-exists? pgvector "public.index_history")))+ (is (true? (semantic.util/table-exists? pgvector "public.dlq_backlog")))+ (is (true? (semantic.util/table-exists? pgvector "public.repair_log"))))+ (is (false? (semantic.util/table-exists? pgvector "public.index_mock_model_4"))))))))(deftest dedicated-reset-refuses-app-db-test(mt/with-premium-features #{:semantic-search}@@ -124,9 +137,9 @@(semantic.db.connection/with-migrate-tx [tx](semantic.db.migration/maybe-migrate!tx {:index-metadata semantic.index-metadata/default-index-metadata}))- (testing "migration proceeds: the module tables are created and the stray table is wiped"+ (testing "migration proceeds: the module tables are created, and a table that isn't ours is left"(is (true? (semantic.util/table-exists? pgvector "public.index_metadata")))- (is (false? (semantic.util/table-exists? pgvector "public.databasechangelog")))))))))+ (is (true? (semantic.util/table-exists? pgvector "public.databasechangelog")))))))))(defn- executions-overlap?"Check if any two executions overlap in time. Each entry is [tid :started/:ended timestamp].