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
(ns metabase-enterprise.search.semantic.index
(:require
[buddy.core.codecs :as buddy-codecs]
[buddy.core.hash :as buddy-hash]
[clojure.set :as set]
[clojure.string :as str]
[com.climate.claypoole :as cp]
[honey.sql :as sql]
[honey.sql.helpers :as sql.helpers]
[honey.sql.pg-ops :as sql.pg-ops]
[java-time.api :as t]
[metabase-enterprise.search.semantic.appdb-scoring :as appdb-scoring]
[metabase-enterprise.search.semantic.db :as semantic-search.db]
;; TODO: extract schema code to go under db.migration
[metabase-enterprise.search.semantic.embedding :as embedding]
[metabase-enterprise.search.semantic.scoring :as scoring]
[metabase-enterprise.search.semantic.settings :as semantic-settings]
[metabase-enterprise.search.semantic.util :as semantic.util]
[metabase.analytics-interface.core :as analytics]
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
[metabase.search.config :as search.config]
[metabase.search.core :as search]
[metabase.tracing.core :as tracing]
[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]
[toucan2.core :as t2])
(:import
[com.mchange.v2.c3p0 PooledDataSource]
[java.nio.charset StandardCharsets]
[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.search.semantic.db.datasource/init-db!))
(def db @@(requiring-resolve 'metabase-enterprise.search.semantic.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})))
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
(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_" (u/generate-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]
[:personal_owner_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]
[:collection_type :text]
[:root_collection_type :text]
[:data_layer :text]
[:data_authority :text]
;; Precomputed "verified or curated content" flag — see metabase.collections.curation/curated?
[:curated :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- to-boolean
"MySQL booleans are represented as 0/1, so we must ensure we're casting them to
real booleans when inserting them into our postgres db"
[b]
{:pre [(some? b)]}
(cond
(boolean? b) b
(= 0 b) false
(= 1 b) true
:else (throw (ex-info "Unexpected boolean value" {:v b}))))
(defn- batch-resolve-personal-owner-ids
"Given a seq of collection-ids, return a map of collection-id -> personal_owner_id.
Collections not in any personal tree will be absent from the map.
Uses at most 2 queries regardless of the number of collection-ids."
[collection-ids]
(when-let [collection-ids (not-empty (set (remove nil? collection-ids)))]
(let [colls (semantic-search.db/collection-owners-and-locations collection-ids)
{personal true
non-personal false} (group-by (comp some? :personal_owner_id) colls)
direct (into {} (map (juxt :id :personal_owner_id)) personal)
roots (keep (fn [{:keys [id location]}]
(when-let [root-id (some-> location (str/split #"/" 3) second parse-long)]
[id root-id]))
non-personal)
unknown-roots (set/difference (set (map second roots)) (set (keys direct)))
root-id->owner (into direct
(map (juxt :id :personal_owner_id))
(when (seq unknown-roots)
(semantic-search.db/personal-collection-owners unknown-roots)))]
(into direct
(keep (fn [[coll-id root-id]]
(when-let [owner (get root-id->owner root-id)]
[coll-id owner])))
roots))))
(defn- doc->db-record
"Convert a document to a database record with a provided embedding."
[owner-ids {:keys [model id embedding searchable_text embeddable_text native_query 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 collection_type root_collection_type
data_layer data_authority curated] :as doc}]
{:model model
:model_id id
:collection_id collection_id
:personal_owner_id (get owner-ids collection_id)
:creator_id creator_id
:database_id database_id
:last_editor_id last_editor_id
:name (or (:name doc) "")
:content embeddable_text
:display_type display_type
:archived (some-> archived to-boolean)
:official_collection (some-> official_collection to-boolean)
:pinned (some-> pinned to-boolean)
:verified (some-> verified to-boolean)
:collection_type collection_type
:root_collection_type root_collection_type
:data_layer data_layer
:data_authority data_authority
:curated (some-> curated to-boolean)
: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 is already JSON-encoded in ->document; encode only if it's still a map (e.g., in tests)
:legacy_input [:cast (if (string? legacy_input) legacy_input (json/encode legacy_input)) :jsonb]
:metadata [:cast (json/encode (dissoc doc :embedding)) :jsonb]
:embedding [:raw (format-embedding embedding)]
:text_search_vector (if (:name doc)
[:||
(search/weighted-tsvector "A" (:name doc))
(search/weighted-tsvector "B" (or searchable_text ""))]
(search/weighted-tsvector "A" (or searchable_text "")))
:text_search_with_native_query_vector
(if (:name doc)
[:||
(search/weighted-tsvector "A" (:name doc))
(search/weighted-tsvector "B"
(str/join " " (remove str/blank? [(or searchable_text "")
(or native_query "")])))]
(search/weighted-tsvector "A"
(str/join " " (remove str/blank? [(or searchable_text "")
(or native_query "")]))))})
(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-gauge! :metabase-search/semantic-index-size))
(catch Exception e
(log/warnf "Failed to set :metabase-search/semantic-index-size metric: %s" (ex-message e)))))
(defn- batch-update!
[connectable table-name records->sql documents]
(when (seq documents)
(u/prog1 (->> documents (map :model) frequencies)
(u/profile (str "Semantic index database update of " (count documents) " documents " <>)
(let [owner-ids (batch-resolve-personal-owner-ids (map :collection_id documents))]
(doseq [batch (->> (map #(doc->db-record owner-ids %) documents)
(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 hash-identifier-if-exceeds-pg-limit
"Sometimes we need to generate new table/index names, such as when forcing a new index despite no change in index parameters.
When we do so we need to be sure any index names do not exceed the postgres limit for names. This function will hash the identifier
if it exceeds the length, and will get a name like index_${sha1} instead.
Table names produced here must stay recognizable by [[index-table-name?]].
Note: The index parameters will still be available in index_metadata"
[identifier]
(if (<= (alength (.getBytes ^String identifier StandardCharsets/UTF_8)) 63)
identifier
(str "index_" (buddy-codecs/bytes->hex (buddy-hash/sha1 identifier)))))
(defn model-table-suffix
"Returns a new suffix for a table name, based on current timestamp"
[]
(mod (.toEpochSecond (t/offset-date-time)) 10000000))
(defn model-table-name
"Returns a default table name for a model. If the table name would exceed the 63 byte postgres limit, a hashed name is preferred.
Table names produced here must stay recognizable by [[index-table-name?]]."
[embedding-model]
(let [{:keys [model-name provider vector-dimensions embedding-space-id]} embedding-model
provider-name (embedding/abbrev-provider-name provider)
abbrev-model-name (embedding/abbrev-model-name model-name)
space-suffix (when embedding-space-id
(subs (buddy-codecs/bytes->hex (buddy-hash/sha1 embedding-space-id)) 0 12))
ideal-table-name (str "index_" provider-name "_" abbrev-model-name "_" vector-dimensions
(when space-suffix (str "_e" space-suffix)))]
(hash-identifier-if-exceeds-pg-limit ideal-table-name)))
(def ^:private index-table-name-pattern
"Recognizes every table-name shape produced by [[model-table-name]] (optionally with the force-reset
suffix appended by [[metabase-enterprise.search.semantic.pgvector-api/fresh-index]]),
[[hash-identifier-if-exceeds-pg-limit]], and the legacy pre-BOT-337 naming era:
index_<provider>_<model>_<dims> legacy name
index_<provider>_<model>_<dims>_e<12-hex> immutable-space name
either modern name followed by _<digits> force-reset suffix ([[model-table-suffix]])
index_<40-hex-sha1> names exceeding the 63-byte pg identifier limit
index_table_<anything> legacy pre-BOT-337 naming (index_table_<provider>_<model>_<dims>)
The provider/model segments are only lightly sanitized (see [[embedding/abbrev-model-name]]), so no
character class is assumed for them; the trailing _<digits> (vector dimensions or force-reset suffix)
gives the modern shapes their structure, while the index_table_ prefix — used exclusively by the
legacy era — claims anything under it. Deliberately does NOT match the control-plane tables
(index_metadata, index_control, index_gate): no trailing _<digits>, not 40-hex, not index_table_."
#"\Aindex_(?:.+_\d+(?:_e[0-9a-f]{12})?(?:_\d+)?|[0-9a-f]{40}|table_.+)\z")
(defn index-table-name?
"Does the bare (schema- and qualifier-stripped) table name look like a semantic-search index table?
Matching names are orphan-cleanup candidates, i.e. may be dropped if not registered in the metadata
table; see [[index-table-name-pattern]] for the shapes."
[bare-table-name]
(boolean (re-matches index-table-name-pattern bare-table-name)))
(defn default-index
"Returns the default index spec for a model."
[embedding-model & {:keys [table-name]}]
(let [table-name (or table-name (model-table-name embedding-model))]
{:embedding-model embedding-model
:table-name table-name
;; Must equal db.migration.impl/dynamic-schema-version — a freshly created index already has the
;; latest schema, so recording an older version would mark it stale on creation. Kept as a literal
;; (not a require) to avoid an index → impl → index-metadata → index cycle; bump both together.
:version 5}))
(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"))))
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))))
(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 & {:as opts}]
(when (seq documents)
(let [text->docs (group-by :embeddable_text documents)
embeddable-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 embeddable-texts)})
(let [[new-texts existing-embeddings] (partition-existing-embeddings connectable index embeddable-texts)]
(if-not (seq existing-embeddings)
[embeddable-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!
opts)))
(merge-with + stats)))))
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
(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 & {:as opts}]
(cp/future pool (upsert-index-batch! connectable index documents opts)))
(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}}]
(tracing/with-span :search "search.semantic.index-upsert" {}
(not-empty
(let [pool @index-update-executor
results (transduce
(comp (partition-all *batch-size*)
(map (if serial?
#(upsert-index-batch! connectable index % {:type :index :record-tokens? true})
#(upsert-index-pooled! pool connectable index % {:type :index :record-tokens? true}))))
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]
;; index names are bare: an index lands in its table's schema and cannot be schema-qualified
(let [index-name (str (semantic.util/table-name-part (:table-name index)) suffix)]
(hash-identifier-if-exceeds-pg-limit index-name)))
(defn schema-qualified-index-name
"The index name qualified with its table's schema (when the table has one), for catalog lookups —
an index lives in the same schema as its table."
[index index-name]
(let [[schema _] (semantic.util/qualified-table-parts (:table-name index))]
(cond->> index-name schema (str schema "."))))
(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-hnsw-index-if-not-exists!
"Create the HNSW index on the `embedding` column of `index`'s table, if it does not already exist.
HNSW indexes are expensive to build and maintain, so we only create one when an instance is configured for
an HNSW-index-backed vector-search strategy (`:hnsw` or `:hnsw-iterative-*`; see
[[metabase.search.config/hnsw-index-backed-strategies]], [[create-index-table-if-not-exists!]], and the
async build triggered by [[metabase-enterprise.search.semantic.settings/semantic-search-vector-strategy]]).
Pass `concurrently? true` to build with `CREATE INDEX CONCURRENTLY` (for a populated table whose writes
shouldn't be locked out); it must run outside a transaction."
[connectable index & {:keys [concurrently?] :or {concurrently? false}}]
(let [{:keys [table-name]} index
;; HoneySQL emits CONCURRENTLY in the wrong position (before INDEX), so splice it into the
;; formatted statement instead: `CREATE INDEX CONCURRENTLY IF NOT EXISTS ...` is valid Postgres.
[sql & params] (sql-format-quoted
(sql.helpers/create-index
[(keyword (hnsw-index-name index)) :if-not-exists]
[(keyword table-name) :using-hnsw [[:raw "embedding vector_cosine_ops"]]]))
sql (cond-> sql
concurrently? (str/replace-first "CREATE INDEX " "CREATE INDEX CONCURRENTLY "))]
(jdbc/execute! connectable (into [sql] params))))
(defn drop-index-concurrently-if-exists!
"Drop `index-name` without blocking writes. Must run outside a transaction."
[connectable index-name]
(jdbc/execute! connectable
[(str "DROP INDEX CONCURRENTLY IF EXISTS " (semantic.util/quote-table index-name))]))
(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.
The HNSW index is only created when the instance is configured for an HNSW-index-backed vector-search
strategy (`:hnsw` or `:hnsw-iterative-*`); under `:brute-force` it is skipped, and built just-in-time when
an index-backed strategy is later configured (see [[create-hnsw-index-if-not-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)
(try
(jdbc/execute! connectable (sql/format (sql.helpers/create-extension :vector :if-not-exists)))
(catch Exception e
;; Extension install commonly fails on privileges (may need superuser); give the operator the way out.
(throw (ex-info (str "Failed to install the pgvector extension. Have a privileged user run"
" CREATE EXTENSION vector; on this database, or set MB_PGVECTOR_DB_URL to a"
" database where it is installed.")
{:type ::extension-install-failed}
e))))
(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))
(when (contains? search.config/hnsw-index-backed-strategies
(semantic-settings/semantic-search-vector-strategy))
(create-hnsw-index-if-not-exists! connectable index))
(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
;; let an already-actionable error (e.g. the pgvector-extension guidance) surface unwrapped
(if (= ::extension-install-failed (:type (ex-data e)))
(throw 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\\_%'"]))
(defn- personal-collection-filter
"Generate a WHERE condition for personal collection filtering based on the filter type.
| Filter | Personal | Others' Personal | Shared Coll. | No Coll. |
|----------------|----------|------------------|--------------|----------|
| all | ✅ | ✅ | ✅ | ✅ |
| only-mine | ✅ | ❌ | ❌ | ❌ |
| only | ✅ | ✅ | ❌ | ❌ |
| exclude | ❌ | ❌ | ✅ | ✅ |
| exclude-others | ✅ | ❌ | ✅ | ✅ |"
[{:keys [filter-items-in-personal-collection current-user-id]}]
(case (or filter-items-in-personal-collection "all")
"all"
nil
"only-mine"
[:= :personal_owner_id current-user-id]
"only"
[:is-not :personal_owner_id nil]
"exclude"
[:is :personal_owner_id nil]
"exclude-others"
[:or
[:is :personal_owner_id nil]
[:= :personal_owner_id current-user-id]]))
(defn- filter-conditions
"Ordered `[filter-key where-condition]` pairs for the structural filters implied by `search-context`. The
search query ANDs these together (see [[search-filters]]); the search debug API uses the keys to attribute
which specific filter excludes a given row."
[{:keys [archived? verified curated? models created-at created-by last-edited-at last-edited-by
table-db-id ids display-type] :as search-context}]
(keep
(fn [[k clause]] (when clause [k clause]))
[[:personal-collection (personal-collection-filter search-context)]
[:archived? (when (some? archived?) [:= :archived archived?])]
[:verified (when (some? verified) [:= :verified verified])]
;; "Verified or curated content" — precomputed flag (collections.curation/curated?)
[:curated (when (some? curated?) [:= :curated curated?])]
;; search.impl sets :models to the applicable models; an empty (but present) set means filters left no
;; applicable model (e.g. curated + non-curatable entity-types), so match nothing rather than omitting the
;; predicate (= all models)
[:models (cond
(seq models) [:in :model models]
(some? models) [:= [:inline 1] [:inline 0]])]
[:created-by (when (seq created-by) [:in :creator_id created-by])]
[:last-edited-by (when (seq last-edited-by) [:in :last_editor_id last-edited-by])]
[:table-db-id (when table-db-id [:= :database_id table-db-id])]
[:ids (when (seq ids) [:in :model_id (map str ids)])]
[:display-type (when (seq display-type) [:in :display_type display-type])]
[:created-at (when (and created-at (:start created-at) (:end created-at))
[:between :model_created_at
(LocalDate/parse (:start created-at))
(LocalDate/parse (:end created-at))])]
[:last-edited-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))])]]))
(defn- search-filters
"Generate WHERE conditions based on search context filters."
[search-context]
(when-let [conditions (seq (map second (filter-conditions search-context)))]
(into [:and] conditions)))
(def ^:private common-search-columns
[[:id :id]
[:model :model]
[:model_id :model_id]
[:collection_id :collection_id]
[:personal_owner_id :personal_owner_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]
[:collection_type :collection_type]
[:root_collection_type :root_collection_type]
[:data_layer :data_layer]
[:data_authority :data_authority]
[:curated :curated]
[: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]
[:legacy_input :legacy_input]])
(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.
:join [[[:to_tsquery ^:allow-raw-sql [:inline tsv-lang] [:lift ts-search-expr]]
:query] [:= 1 1]]
:where (let [ts-query-filter [sql.pg-ops/atat vector-column :query]]
(if (seq filters)
(into [:and ts-query-filter] [filters])
ts-query-filter))
:order-by [[:keyword_rank :asc]]
:limit (semantic-settings/semantic-search-results-limit)}))
(def ^:private ^:const max-cosine-distance "Cut-off used to filter semantic search results" 0.7)
(defn- hnsw-search-query
"Build the semantic vector subquery using the HNSW index, applying `filters` after candidate selection."
[index embedding-literal filters]
;; The inner `vector_candidates` CTE is a pure vector search (ORDER BY distance LIMIT) so the planner uses
;; the HNSW index. HNSW is an approximate-nearest-neighbour index, so its results are approximate regardless
;; of filtering -- that's the trade-off we accept for its speed. Running the filters only in the outer query
;; adds a separate problem: under-fetch. The fixed-size candidate set is picked before the filters apply, so
;; when the globally-closest rows are dominated by a cluster the filters reject, we can return fewer rows than
;; asked for -- or none at all. `brute-force-search-query` sidesteps both by skipping the index and scanning
;; every filtered row.
;; TODO: only pull in necessary extra columns from configured filters
(let [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)}
;; `semantic_rank` feeds the RRF scorer; `semantic_distance` feeds the semantic-distance scorer.
base-query {:with [[:vector_candidates hnsw-query]]
:select (into common-search-columns
[[[:raw "row_number() OVER (ORDER BY distance ASC)"] :semantic_rank]
[:distance :semantic_distance]])
: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- brute-force-search-query
"Build the semantic vector subquery as an exact, filter-first search over the rows matching `filters`."
[index embedding-literal filters]
;; The filtered rows and their cosine distance are computed once, inside a MATERIALIZED CTE: that fences
;; the planner off the HNSW index (so the scan is exact) and stores the `distance` column, so the outer
;; query reads it rather than recomputing it. The cutoff and ranking run in the outer query.
;; We deliberately don't push the cutoff into the CTE to avoid materializing rows beyond it: that would
;; either recompute the distance for the qual, or need a subquery optimization fence (Postgres pulls a
;; plain subquery back up and re-inlines the expression) -- not worth it for an exact scan that already
;; touches every filtered row.
(let [filtered-query (cond-> {:select (into common-search-columns
[[[:raw (str "embedding <=> " embedding-literal)] :distance]])
:from [(keyword (:table-name index))]}
filters (assoc :where filters))]
{:with [[:vector_candidates filtered-query :materialized]]
:select (into common-search-columns
[[[:raw "row_number() OVER (ORDER BY distance ASC)"] :semantic_rank]
[:distance :semantic_distance]])
:from [:vector_candidates]
:where [:<= :distance max-cosine-distance]
:order-by [[:semantic_rank :asc]]
:limit (semantic-settings/semantic-search-results-limit)}))
(defn- hnsw-iterative-search-query
"Build the semantic vector subquery as an index-backed iterative scan with `filters` applied inline."
[index embedding-literal filters]
;; The filters live inside the ordered/limited candidate scan (unlike `hnsw-search-query`, which
;; post-filters), so the planner can pick the HNSW index and pgvector's iterative scan keeps pulling
;; neighbours until the limit is met or `hnsw.max_scan_tuples` is hit.
;; The recall/latency trade-off is governed by the iterative-scan GUCs (see `vector-session-settings`),
;; not the SQL shape.
;; The cutoff stays in the outer query (like `hnsw-search-query`) so the inner scan fills up to the limit
;; before trimming.
(let [inner (cond-> {: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)}
filters (assoc :where filters))]
{:with [[:vector_candidates inner]]
:select (into common-search-columns
[[[:raw "row_number() OVER (ORDER BY distance ASC)"] :semantic_rank]
[:distance :semantic_distance]])
:from [:vector_candidates]
:where [:<= :distance max-cosine-distance]
:order-by [[:semantic_rank :asc]]}))
(defn- vector-search-strategy
"Resolve the vector-search strategy for `search-context`, falling back to the configured default setting."
[search-context]
(or (:vector-search-strategy search-context)
(semantic-settings/semantic-search-vector-strategy)))
(def ^:private iterative-strategy->guc
"Iterative vector-search strategies mapped to pgvector's `hnsw.iterative_scan` GUC value.
The strategy keyword encodes the ordering, so there is no separate order knob."
{:hnsw-iterative-relaxed "relaxed_order"
:hnsw-iterative-strict "strict_order"})
(defn- semantic-search-query
"Build the semantic vector subquery, dispatching on the resolved [[vector-search-strategy]].
`:brute-force` is exact and filter-first; the `:hnsw-iterative-*` strategies are index-backed with inline
filters and an iterative scan; `:hnsw` (the default) is approximate, index-backed and post-filters."
[index embedding search-context]
(let [filters (search-filters search-context)
embedding-literal (format-embedding embedding)
strategy (vector-search-strategy search-context)]
(cond
(= :brute-force strategy) (brute-force-search-query index embedding-literal filters)
(iterative-strategy->guc strategy) (hnsw-iterative-search-query index embedding-literal filters)
(= :hnsw strategy) (hnsw-search-query index embedding-literal filters)
:else (do (log/warnf "Unknown vector-search strategy %s; falling back to :brute-force" (pr-str strategy))
(brute-force-search-query index embedding-literal filters)))))
(defn- explain?
"Whether to run the gated EXPLAIN (ANALYZE) instrumentation for `search-context`, falling back to the
configured default setting."
[search-context]
(if (contains? search-context :vector-search-explain?)
(boolean (:vector-search-explain? search-context))
(semantic-settings/semantic-search-explain)))
(defn- vector-session-settings
"`SET LOCAL` statements for the pgvector session GUCs implied by `search-context`, as a (possibly empty)
vector of single-element `[sql]` statement vectors.
Only the `:hnsw-iterative-*` strategies set the iterative-scan GUCs; any strategy may request
`force-index?`.
Each knob falls back to its EE setting when unset on the context."
[search-context]
;; Values come from a fixed map or validated positive integers, so they are safe to interpolate (GUC
;; names and values can't be passed as bound parameters).
;; They are clamped to pgvector's GUC ranges (ef_search 1..1000, max_scan_tuples 32-bit) because an
;; out-of-range SET LOCAL raises mid-transaction and would fail the whole search; the API schema enforces
;; the same ranges, the clamp covers the settings path.
(let [iterative-guc (iterative-strategy->guc (vector-search-strategy search-context))
clamp (fn [v lo hi] (-> v (max lo) (min hi)))]
(cond-> []
iterative-guc
(conj [(str "SET LOCAL hnsw.iterative_scan = " iterative-guc)]
[(format "SET LOCAL hnsw.ef_search = %d"
(clamp (or (:vector-search-ef-search search-context)
(semantic-settings/semantic-search-ef-search))
1 1000))]
[(format "SET LOCAL hnsw.max_scan_tuples = %d"
(clamp (or (:vector-search-max-scan-tuples search-context)
(semantic-settings/semantic-search-max-scan-tuples))
1 Integer/MAX_VALUE))])
(:vector-search-force-index? search-context)
(conj ["SET LOCAL enable_seqscan = off"]))))
(defn- run-in-vector-session!
"Apply the [[vector-session-settings]] for `search-context` on a transaction over `db`, then call
`(f conn)` with that transaction.
`SET LOCAL` resets at COMMIT, so the pooled connection is left clean.
When no session settings are needed and instrumentation is off, `f` is called directly on `db` (no
transaction) to keep the default strategy's hot path unchanged."
[db search-context f]
(let [stmts (vector-session-settings search-context)]
(if (and (empty? stmts) (not (explain? search-context)))
(f db)
(jdbc/with-transaction [tx db]
(doseq [stmt stmts]
(jdbc/execute! tx stmt))
(f tx)))))
(defn- flatten-ctes
"Flatten nested :with clauses into a single top-level :with.
PostgreSQL doesn't support nested CTEs, so we need to extract all nested :with clauses
and put them at the top level.
Takes a query map and returns {:ctes [...] :query query-without-with}"
[query]
(if-not (:with query)
{:ctes [] :query query}
(let [ctes (reduce
;; `assoc` swaps the (possibly flattened) inner query back into the binding while preserving the
;; CTE name and any trailing opts (e.g. `:materialized`), so they survive hoisting.
(fn [acc [_cte-name cte-query & _opts :as cte-binding]]
(let [{:keys [ctes query]} (flatten-ctes cte-query)]
(into acc (conj ctes (assoc cte-binding 1 query)))))
[]
(:with query))]
{:ctes ctes
:query (dissoc query :with)})))
(defn- hybrid-select
"For a given `col-name` return a :coalesce expression to reference it from the outer hybrid search query.
(hybrid-coalesce :model_id) -> [:coalesce :v.model_id :t.model_id]"
([col-name-and-alias]
(hybrid-select col-name-and-alias "v." "t."))
([[col-name col-alias] vector-prefix text-prefix]
(let [prefix #(keyword (str %1 (name %2)))]
[[:coalesce (prefix vector-prefix col-name) (prefix text-prefix col-name)] col-alias])))
(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 (into
(mapv hybrid-select common-search-columns)
[[:v.semantic_rank :semantic_rank]
[:v.semantic_distance :semantic_distance]
[:t.keyword_rank :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- scored-search-query
"Build a hybrid search query with additional `scorers`"
[index embedding search-context scorers]
;; The purpose of this query is just to project the coalesced hybrid columns with standard names so the scorers know
;; what to call them (e.g. :model rather than [:coalesced :v.model :t.model]). Likewise, the :search_index alias
;; allows us to re-use scoring expressions between the appdb and semantic backends without adjusting column names.
;;
;; We flatten the nested CTEs because PostgreSQL doesn't support nested WITH clauses.
;; The hybrid-query contains nested :with clauses from semantic-search-query and keyword-search-query,
;; which we extract and place at the top level.
(let [hybrid-query (hybrid-search-query index embedding search-context)
{:keys [ctes query]} (flatten-ctes hybrid-query)
all-ctes (conj ctes [:hybrid_results query])
full-query {:with all-ctes
:select [:id :model_id :model :content :verified :legacy_input :semantic_rank :semantic_distance :keyword_rank]
:from [[:hybrid_results :search_index]]
:limit (semantic-settings/semantic-search-results-limit)}]
(scoring/with-scores search-context scorers full-query)))
(defn- legacy-input-with-score
"Extracts the (already-decoded) `:legacy_input` map from `row` and attaches the total score
plus per-scorer breakdown."
[weights scorers row]
(assoc (:legacy_input row)
:score (:total_score row 1.0)
:all-scores (scoring/all-scores weights scorers row)))
(defn- decode-legacy-input
"Decode `row`s `:legacy_input` JSONB PGobject into a Clojure map."
[row]
;; BOT-1543: some existing rows have legacy_input stored as a JSON string rather than a JSON
;; object, so one decode yields a string; decode once more in that case.
(update row :legacy_input
(fn [pgo]
(let [decoded (decode-pgobject pgo)]
(cond-> decoded (string? decoded) json/decode+kw)))))
(defn- compute-collection-id-only-search-models
"Compute search-models whose read perms are determined fully by their collection id."
[]
;; `search/specifications` must run before reading the registry: its `t2/resolve-model` calls load the
;; model namespaces that populate it. Otherwise cold start caches an empty set for the JVM lifetime.
(let [specs (search/specifications)
registered-t2-models (perms/collection-id-only-read-models)
registered-search-models (set (keys (perms/collection-based-visibility-search-models)))]
;; Two sources:
;; (1) string-form registrations, whose spec's `:model` is a different t2-model (e.g. ModelIndex)
;; and wouldn't be picked up by the filter below;
;; (2) every spec whose `:model` was registered via the keyword form — `mi/can-read?` dispatches on
;; the t2-model, so sibling specs like "dataset"/"metric" that share `:model/Card` are covered
;; by one registration.
(into registered-search-models
(comp (filter (fn [[_ spec]] (contains? registered-t2-models (:model spec))))
(map key))
specs)))
(def ^:private collection-id-only-search-models
"Search-models whose read perms are determined fully by their collection id.
Wrapped in `delay` so the registry can populate before first read."
(delay (compute-collection-id-only-search-models)))
(defn- filter-read-permitted
"Returns the subset of `docs` whose t2 instances pass `mi/can-read?` for the current user."
[docs]
(let [timer (u/start-timer)
doc->t2-model (fn [doc] (:model (search/spec (:model doc))))
fast-set @collection-id-only-search-models
{fast-docs true slow-docs false} (group-by #(contains? fast-set (:model %)) docs)
;; Fast path: for models registered via `perms/define-collection-based-visibility!`, `mi/can-read?` is
;; definitionally `(perms/can-read-via-parent-collection? (:collection_id instance))`, so we skip the
;; t2/select and check perms straight from the denormalized `:collection_id` on the index row.
;; Calling the shared helper means fast and slow paths run the same code for these models.
;; Memoizing dedupes the perm check across docs that share a collection.
;;
;; Trade-off: the indexed `:collection_id` is eventually-consistent, so a moved/deleted row may appear
;; in results until the next reindex. Click-through still enforces live perms.
coll-readable? (memoize perms/can-read-via-parent-collection?)
fast-filtered (filterv #(coll-readable? (:collection_id %)) fast-docs)
slow-t2-instances (vec
(for [[t2-model docs] (group-by doc->t2-model slow-docs)
t2-instance (semantic-search.db/instances t2-model (map :id docs))]
t2-instance))
doc->t2 (comp (u/index-by (juxt :id t2/model) slow-t2-instances)
(juxt :id doc->t2-model))
slow-filtered (filterv (fn [doc] (some-> doc doc->t2 mi/can-read?)) slow-docs)
result (into fast-filtered slow-filtered)
time-ms (u/since-ms timer)]
(log/debug "Permission filtering" {:before-count (count docs)
:after-count (count result)
:fast-count (count fast-docs)
:slow-count (count slow-docs)
:slow-fetched-count (count slow-t2-instances)
:time-ms time-ms})
(analytics/inc! :metabase-search/semantic-permission-filter-ms time-ms)
result))
(defn- filter-by-collection-id
"Filter documents by collection and all descendant collections."
[docs collection-id]
(let [collection-ids (keep :collection_id docs)
collections-map (when (seq collection-ids)
(->> (semantic-search.db/collection-locations collection-ids)
(into {} (map (juxt :id identity)))))]
(filterv (fn [doc]
(let [doc-collection-id (:collection_id doc)]
(or (= doc-collection-id collection-id)
(when doc-collection-id
(when-let [collection (get collections-map doc-collection-id)]
(str/starts-with? (:location collection) (str "/" collection-id "/")))))))
docs)))
(defn- apply-collection-id-filter
"Apply collection ID filtering with logging."
[search-context docs]
(let [collection-id (:collection search-context)]
(if (nil? collection-id)
docs
(let [timer (u/start-timer)
filtered-docs (filter-by-collection-id docs collection-id)
time-ms (u/since-ms timer)]
(log/debug "Collection filter" {:collection-id collection-id
:before (count docs)
:after (count filtered-docs)
:dropped (- (count docs) (count filtered-docs))
:time_ms time-ms})
(analytics/inc! :metabase-search/semantic-collection-id-filter-ms time-ms)
filtered-docs))))
(defn- reducible-search-query
"Extracted so can be redefd in tests."
[db query]
(jdbc/plan db (sql-format-quoted query) {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
(defn- warm-connection-pool-async!
"Warm `db` with one pooled connection on a background thread, unless it already holds an idle one
(or isn't a c3p0 pool at all, e.g. a plain datasource in tests).
Fire-and-forget: failures surface on the real query that follows."
[db]
(u/ignore-exceptions
(when (and (instance? PooledDataSource db)
(zero? (.getNumIdleConnectionsDefaultUser ^PooledDataSource db)))
(future
(u/ignore-exceptions
;; Closing a pooled connection returns it to the pool, where it waits idle for the query.
(.close (.getConnection ^PooledDataSource db)))))))
;; ----------------------------------------------------------------------------------------------------------
;; Gated vector-search instrumentation
;;
;; When `vector-search-explain?` is set (per-request) or `semantic-search-explain` (setting) is on, we
;; re-run the inner vector subquery under EXPLAIN (ANALYZE) to measure how the chosen strategy actually
;; behaves: which plan the index-table scan got, how many tuples it visited, how long the inner query took,
;; and how that compares to a filter-first scan's candidate pool.
;; It is off by default because the EXPLAIN re-executes the inner query.
;; ----------------------------------------------------------------------------------------------------------
(defn- explain->element
"Coerce the single `EXPLAIN (… FORMAT JSON)` result value into its one plan element
(`{\"Plan\" {…} \"Execution Time\" …}`)."
[explain-value]
(let [decoded (cond
(instance? PGobject explain-value) (json/decode (unwrap-pgobject explain-value))
(string? explain-value) (json/decode explain-value)
:else explain-value)]
(first decoded)))
(defn- find-scan-node
"Depth-first search of an EXPLAIN plan tree for the scan node over `table-name`.
EXPLAIN reports \"Relation Name\" unqualified, so compare on the bare name part."
[plan table-name]
(let [bare-name (semantic.util/table-name-part table-name)
search (fn search [node]
(when (map? node)
(if (and (#{"Seq Scan" "Index Scan" "Index Only Scan" "Bitmap Heap Scan"} (get node "Node Type"))
(= bare-name (get node "Relation Name")))
node
(some search (get node "Plans")))))]
(search plan)))
(defn- scan-node-metrics
"Pull the index-table scan node out of an EXPLAIN plan tree and summarise it: the plan node chosen, the
HNSW index used (nil for a seq scan), the tuples actually visited (returned + filtered out), and the
node's total execution time."
[plan table-name]
(when-let [node (find-scan-node plan table-name)]
;; EXPLAIN reports per-loop averages, and for a parallel scan (the likely plan for the brute-force
;; baseline) loops = workers: row totals need the multiply, but per-loop "Actual Total Time" already
;; approximates wall clock because the workers run concurrently, so the time must NOT be multiplied
(let [loops (get node "Actual Loops" 1)
actual-rows (* (get node "Actual Rows" 0) loops)
removed (* (get node "Rows Removed by Filter" 0) loops)]
{:node-type (get node "Node Type")
:index-name (get node "Index Name")
:actual-rows actual-rows
:rows-removed-by-filter removed
:tuples-scanned (+ actual-rows removed)
:inner-ms (get node "Actual Total Time" 0)
:shared-hit (get node "Shared Hit Blocks")
:shared-read (get node "Shared Read Blocks")})))
(defn- explain-vector-subquery
"Run the inner vector subquery under EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) on `conn` and return its
[[scan-node-metrics]] plus the subquery's total execution time.
Re-executes the inner query."
[conn index embedding search-context]
(let [[sql & params] (sql-format-quoted (semantic-search-query index embedding search-context))
explain-sql (str "EXPLAIN (ANALYZE true, BUFFERS true, FORMAT JSON) " sql)
element (-> (jdbc/execute-one! conn (into [explain-sql] params)) vals first explain->element)]
(assoc (scan-node-metrics (get element "Plan") (:table-name index))
:execution-ms (get element "Execution Time")
:planning-ms (get element "Planning Time"))))
(defn- prefilter-pool-size
"Count of index rows the non-vector filters alone select -- the candidate pool a filter-first
(brute-force) scan would compute distances over.
The vector scan's `tuples-scanned` relative to this is the overfetch."
[conn index search-context]
(let [filters (search-filters search-context)
q (cond-> {:select [[[:raw "count(*)"] :n]] :from [(keyword (:table-name index))]}
filters (assoc :where filters))]
(:n (jdbc/execute-one! conn (sql-format-quoted q) {:builder-fn jdbc.rs/as-unqualified-lower-maps}))))
(defn- record-vector-instrumentation!
"Measure and report how the resolved strategy executed the inner vector subquery: EXPLAIN ANALYZE the
distance-limiting scan and count the prefilter pool, then log a structured line and bump the analytics
counters. Returns the scan metrics map (with `:prefilter-pool-size`) for the caller's time waterfall, or nil.
Never throws -- instrumentation failures must not break search."
[conn index embedding search-context raw-count]
(try
(let [strategy (name (vector-search-strategy search-context))
scan (explain-vector-subquery conn index embedding search-context)
pool (prefilter-pool-size conn index search-context)]
(log/info "Semantic vector-search instrumentation"
(merge {:strategy strategy
:prefilter-pool-size pool
:raw-count raw-count
:used-index? (some? (:index-name scan))
:overfetch-ratio (when (and pool (pos? pool) (:tuples-scanned scan))
(double (/ (:tuples-scanned scan) pool)))}
scan))
(analytics/inc! :metabase-search/semantic-vector-inner-ms {:strategy strategy} (or (:inner-ms scan) 0))
(analytics/inc! :metabase-search/semantic-vector-tuples-scanned {:strategy strategy} (or (:tuples-scanned scan) 0))
(analytics/inc! :metabase-search/semantic-prefilter-pool-size {:strategy strategy} (or pool 0))
(analytics/inc! :metabase-search/semantic-vector-scan-used-index
{:strategy strategy :plan-node (or (:node-type scan) "unknown")} 1)
(assoc scan :prefilter-pool-size pool))
(catch Exception e
(log/warnf "Failed to record vector-search instrumentation: %s" (ex-message e))
nil)))
(defn- time-waterfall
"Build a stage-by-stage time breakdown (ms + integer % of `total-ms`) for the gated instrumentation. Stages
is a seq of `[label ms]`; the distance-limiting scan is reported as a subset of the db-query stage (the rest
of db-query is the hybrid join + in-db scoring), so its % is of the whole request, not additive."
[total-ms stages]
(let [pct (fn [ms] (when (and ms total-ms (pos? total-ms)) (Math/round (double (* 100 (/ ms total-ms))))))]
{:total-ms (some-> total-ms double)
:stages (vec (for [[label ms] stages]
{:stage label :ms (some-> ms double) :pct (pct ms)}))}))
(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 [index-name (schema-qualified-index-name index (hnsw-index-name index))
index-state (when (contains? search.config/hnsw-index-backed-strategies
(vector-search-strategy search-context))
(semantic.util/index-state db index-name))
search-context (cond-> search-context
(= :building index-state) (assoc :vector-search-strategy :brute-force))]
;; `:vector-search-allow-missing-index?` is a deliberate opt-out for callers that want the inner
;; query to run without the HNSW index (e.g. the strategy matrix test probing the exact seq-scan
;; path). A concurrent build also uses that exact path until PostgreSQL marks the index ready; an
;; absent or abandoned invalid index fails fast.
(when (and (contains? search.config/hnsw-index-backed-strategies (vector-search-strategy search-context))
(not (:vector-search-allow-missing-index? search-context))
(contains? #{nil :invalid} index-state))
(throw (ex-info (str "HNSW-index-backed vector-search strategy requested but no usable HNSW index exists. "
"The index is absent or was abandoned invalid. It will be rebuilt by the next "
"maintenance pass; retry shortly, or pass :vector-search-allow-missing-index? true "
"to bypass this check.")
{:table-name (:table-name index)
:strategy (vector-search-strategy search-context)})))
(let [timer (u/start-timer)
;; Warm the pool concurrently with the embedding round-trip: the pool holds zero idle
;; connections by default (see semantic-search.db.datasource), so the first search after an
;; idle period would otherwise pay the connection handshake serially on top of the embedding
;; latency.
_ (warm-connection-pool-async! db)
embedding (tracing/with-span :search "search.semantic.embedding"
{:search.semantic/provider (:provider embedding-model)
:search.semantic/model-name (:model-name embedding-model)}
(embedding/get-embedding embedding-model
(embedding/prefix-search-query embedding-model search-string)
{:type :query :record-tokens? true}))
embedding-time-ms (u/since-ms timer)
db-timer (u/start-timer)
weights (search.config/weights search-context)
scorers (scoring/semantic-scorers (:table-name index) search-context)
query (scored-search-query index embedding search-context scorers)
xform (comp (map decode-legacy-input)
(map (partial legacy-input-with-score weights (keys scorers))))
;; Run the query (and any gated instrumentation) inside a vector session so the iterative-scan
;; GUCs from `vector-session-settings` apply on the same connection. Falls back to the plain
;; datasource path for the default strategy with instrumentation off. The query duration is
;; captured before the instrumentation runs, so the EXPLAIN re-execution and prefilter count
;; don't inflate the latency signal they exist to analyze.
db-query-ms* (volatile! 0.0)
instrumentation-ms* (volatile! 0.0)
session-result (run-in-vector-session!
db
search-context
(fn [conn]
(let [results (tracing/with-span :search "search.semantic.db-query"
{:search/query-length (count search-string)}
(into [] xform (reducible-search-query conn query)))]
(vreset! db-query-ms* (u/since-ms db-timer))
{:results results
;; Time the gated EXPLAIN/prefilter re-run separately so it can be its own
;; waterfall stage rather than silently inflating the other stages' shares of
;; total-time-ms.
:scan (when (explain? search-context)
(let [t (u/start-timer)
scan (record-vector-instrumentation! conn index embedding
search-context (count results))]
(vreset! instrumentation-ms* (u/since-ms t))
scan))})))
raw-results (:results session-result)
vector-scan (:scan session-result)
db-query-time-ms @db-query-ms*
instrumentation-time-ms @instrumentation-ms*
filter-timer (u/start-timer)
filtered-results (tracing/with-span :search "search.semantic.permission-filter"
{:search.semantic/raw-count (count raw-results)}
(->> raw-results
filter-read-permitted
(apply-collection-id-filter search-context)
(mapv search/collapse-id)))
filter-time-ms (u/since-ms filter-timer)
appdb-scorers (appdb-scoring/appdb-scorers search-context)
appdb-scores-timer (u/start-timer)
final-results (->> filtered-results
(scoring/with-appdb-scores search-context appdb-scorers weights))
appdb-scores-time-ms (u/since-ms appdb-scores-timer)
total-time-ms (u/since-ms timer)]
(log/debug "Semantic search"
{:search-string-length (count search-string)
:raw-results-count (count raw-results)
:final-results-count (count final-results)
:embedding-time-ms embedding-time-ms
:db-query-time-ms db-query-time-ms
:filter-time-ms filter-time-ms
:appdb-scores-time-ms appdb-scores-time-ms
:total-time-ms total-time-ms})
;; Gated time waterfall: where the request went, with the distance-limiting scan broken out of the
;; db-query stage (the rest of db-query is the hybrid join + in-db scoring). The EXPLAIN/prefilter
;; instrumentation is itself a stage so its cost doesn't silently inflate the others' shares of
;; total-time-ms.
(when (explain? search-context)
(log/info "Semantic search time waterfall"
(time-waterfall total-time-ms
[[:embedding embedding-time-ms]
[:distance-scan (:inner-ms vector-scan)]
[:db-query db-query-time-ms]
[:perm-filter filter-time-ms]
[:appdb-scores appdb-scores-time-ms]
[:instrumentation instrumentation-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)
(analytics/inc! :metabase-search/semantic-appdb-scores-ms
appdb-scores-time-ms)
(analytics/inc! :metabase-search/semantic-search-ms
{:embedding-model (:name embedding-model)}
total-time-ms)
(comment
(jdbc/execute! db (sql-format-quoted query)))
{:results final-results
:raw-count (count raw-results)})))))
(defn- row-present?
"Whether a single `(model, id)` row survives `where` against the index `table`."
[db table model id where]
(some? (jdbc/execute-one! db (sql-format-quoted
{:select [[[:inline 1] :one]]
:from [table]
:where (into [:and [:= :model model] [:= :model_id (str id)]]
(when where [where]))})
{:builder-fn jdbc.rs/as-unqualified-lower-maps})))
(defn diagnose-row
"Engine-owned diagnostic stages for the semantic index: returns `{:type ..., :details ...}` for the first of
`:missing-from-index` / `:filtered` / `:not-matching` that drops `(model, id)`, or `:candidate` if it survives
every engine-owned stage. The caller ([[metabase.search.debug]]) handles the engine-independent stages."
[db index search-context model id]
(let [table (keyword (:table-name index))
row (jdbc/execute-one! db (sql-format-quoted
{:select [:model :model_id :legacy_input]
:from [table]
:where [:and [:= :model model] [:= :model_id (str id)]]})
{:builder-fn jdbc.rs/as-unqualified-lower-maps})]
(cond
(nil? row)
{:type :missing-from-index :details {:table (:table-name index)}}
:else
;; Check access control before structural filters so a not-permitted row is reported as such even when a
;; query filter would also drop it (matches the appdb engine, where the permission layers come first).
(if (empty? (filter-read-permitted [(:legacy_input (decode-legacy-input row))]))
{:type :filtered :details {:excluded-by :permissions}}
(if-let [excluded-by (some (fn [[k clause]] (when-not (row-present? db table model id clause) k))
(filter-conditions search-context))]
{:type :filtered :details {:excluded-by excluded-by}}
(let [search-string (:search-string search-context)]
(if (str/blank? search-string)
{:type :candidate :details {}}
(let [embedding (embedding/get-embedding (:embedding-model index) search-string
{:type :query :record-tokens? true})
distance (-> (jdbc/execute-one! db (sql-format-quoted
{:select [[[:raw (str "embedding <=> " (format-embedding embedding))] :distance]]
:from [table]
:where [:and [:= :model model] [:= :model_id (str id)]]})
{:builder-fn jdbc.rs/as-unqualified-lower-maps})
:distance)]
;; A row beyond the cosine cutoff is dropped by the vector arm; the keyword arm may still surface it
;; via RRF, so treat it as a candidate within the cutoff and only call it not-matching past it.
(if (and distance (> distance max-cosine-distance))
{:type :not-matching :details {:max-cosine-distance max-cosine-distance :distance distance}}
{:type :candidate :details {:distance distance}})))))))))
(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) {:record-tokens? true}))
(def scorers (scoring/semantic-scorers (:table-name index) 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)))
(scored-search-query index embed search-ctx scorers)
(sql-format-quoted (scored-search-query index embed search-ctx scorers))
(jdbc/execute! db (sql-format-quoted (scored-search-query index embed search-ctx scorers)))
(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.search.semantic.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"})
;; REPL scratch; metabase.test is off-limits to this module's real code
#_{:clj-kondo/ignore [:metabase/modules]}
(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.search.semantic.db.datasource/init-db!))
(def db @@(requiring-resolve 'metabase-enterprise.search.semantic.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 {:record-tokens? true}))
(def scorers (scoring/semantic-scorers (:table-name index) search-context))
;; 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)))
(def scored-sql (sql-format-quoted (scored-search-query index embedding search-context scorers)))
;; do in repl ->
#_(explain-analyze-query db semantic-sql)
#_(explain-analyze-query db keyword-sql)
#_(explain-analyze-query db hybrid-sql)
#_(explain-analyze-query db scored-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]
;; REPL scratch; println shows batch progress on stdout
#_{:clj-kondo/ignore [:discouraged-var]}
(println "Processing batch starting with " (first batch))
(Thread/sleep 2000)
{:count (count batch)})
(defn logging-range [n]
;; REPL scratch; println shows lazy realization on stdout
#_{:clj-kondo/ignore [:discouraged-var]}
(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)))