Skip to content

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

Add search debug API to explain why an entity is missing from results (#75132)

Chris Truter632949fe3dd8
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/core.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/core.clj
index 9454883386d..128d0377869 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/core.clj
@@ -139,6 +139,16 @@
model
ids))))
+(defenterprise diagnose
+ "Enterprise implementation of the semantic search engine-owned diagnostic stages."
+ :feature :semantic-search
+ [search-ctx expected-model expected-id]
+ (let [pgvector (semantic.env/get-pgvector-datasource!)
+ index-metadata (semantic.env/get-index-metadata)]
+ (if-not (index-active? pgvector index-metadata)
+ {:type :missing-from-index :details {:reason :no-active-index}}
+ (semantic.pgvector-api/diagnose pgvector index-metadata search-ctx expected-model expected-id))))
+
;; NOTE:
;; we're currently not returning stats from `init!` as the async nature means
;; we'd report skewed values for the `metabase-search` metrics.
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
index 8a99eb38fd3..7069f0528b5 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
@@ -539,38 +539,37 @@
[:is :personal_owner_id nil]
[:= :personal_owner_id current-user-id]]))
-(defn- search-filters
- "Generate WHERE conditions based on search context filters."
+(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 models created-at created-by last-edited-at last-edited-by
table-db-id ids display-type] :as search-context}]
- (let [conditions (filter some?
- [(personal-collection-filter search-context)
- (when (some? archived?)
- [:= :archived archived?])
- (when (some? verified)
- [:= :verified verified])
- (when (seq models)
- [:in :model models])
- (when (seq created-by)
- [:in :creator_id created-by])
- (when (seq last-edited-by)
- [:in :last_editor_id last-edited-by])
- (when table-db-id
- [:= :database_id table-db-id])
- (when (seq ids)
- [:in :model_id (map str ids)])
- (when (seq display-type)
- [:in :display_type display-type])
- (when (and created-at (:start created-at) (:end created-at))
- [:between :model_created_at
- (LocalDate/parse (:start created-at))
- (LocalDate/parse (:end created-at))])
- (when (and last-edited-at (:start last-edited-at) (:end last-edited-at))
- [:between :model_updated_at
- (LocalDate/parse (:start last-edited-at))
- (LocalDate/parse (:end last-edited-at))])])]
- (when (seq conditions)
- (into [:and] conditions))))
+ (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])]
+ [:models (when (seq models) [:in :model models])]
+ [: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]
@@ -935,6 +934,56 @@
{: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))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
index 199d04ac901..8fbf30b7f20 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/pgvector_api.clj
@@ -87,6 +87,12 @@
(let [{:keys [index]} (ensure-active-index-state pgvector index-metadata)]
(semantic.index/query-index pgvector index search-context)))
+(defn diagnose
+ "Engine-owned diagnostic stages for the active semantic index. See [[semantic.index/diagnose-row]]."
+ [pgvector index-metadata search-context model id]
+ (let [{:keys [index]} (ensure-active-index-state pgvector index-metadata)]
+ (semantic.index/diagnose-row pgvector index search-context model id)))
+
(defn index-documents!
"Indexes documents into the active semantic search index.
Documents are upserted - existing documents with same id are replaced.
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/debug_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/debug_test.clj
new file mode 100644
index 00000000000..b4cec95dc15
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/debug_test.clj
@@ -0,0 +1,48 @@
+(ns metabase-enterprise.semantic-search.debug-test
+ "Engine-owned diagnostic stages for the semantic search index. Mirrors the appdb coverage in
+ [[metabase.search.debug-test]], but exercises [[semantic.index/diagnose-row]] directly against the
+ mock-indexed pgvector test database (gated on MB_PGVECTOR_DB_URL via [[semantic.tu/once-fixture]])."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.env :as semantic.env]
+ [metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once #'semantic.tu/once-fixture)
+
+(defn- diagnose-row! [search-context model id]
+ (semantic.index/diagnose-row (semantic.env/get-pgvector-datasource!) semantic.tu/mock-index search-context model id))
+
+(deftest ^:synchronized semantic-diagnose-test
+ (mt/with-premium-features #{:semantic-search}
+ (mt/as-admin
+ (semantic.tu/with-test-db! {:mode :mock-indexed}
+ (let [card-id (t2/select-one-pk :model/Card :name "Dog Training Guide")
+ all {:models ["card" "dashboard" "table"] :archived? false}]
+ (testing "a matching query is a candidate"
+ (is (=? {:type :candidate}
+ (diagnose-row! (assoc all :search-string "puppy") "card" card-id))))
+ (testing "a query whose embedding is beyond the cosine cutoff is not-matching"
+ (is (=? {:type :not-matching :details {:max-cosine-distance 0.7 :distance number?}}
+ (diagnose-row! (assoc all :search-string "zzzznomatchzzz") "card" card-id))))
+ (testing "excluded by a structural filter, attributed to the specific filter"
+ (is (=? {:type :filtered :details {:excluded-by :models}}
+ (diagnose-row! {:models ["dashboard"] :search-string "puppy"} "card" card-id))))
+ (testing "absent from the index is missing-from-index"
+ (is (=? {:type :missing-from-index}
+ (diagnose-row! (assoc all :search-string "puppy") "card" Integer/MAX_VALUE)))))))))
+
+(deftest ^:synchronized semantic-not-permitted-test
+ (testing "permissions are checked before structural filters, so an unreadable row reports :permissions even when
+ a structural filter would also drop it"
+ (mt/with-premium-features #{:semantic-search}
+ (semantic.tu/with-test-db! {:mode :mock-indexed}
+ (let [{card-id :id coll-id :collection_id} (t2/select-one [:model/Card :id :collection_id]
+ :name "Dog Training Guide")]
+ (mt/with-non-admin-groups-no-collection-perms (t2/select-one :model/Collection :id coll-id)
+ (mt/with-test-user :rasta
+ ;; :models ["dashboard"] would also exclude this card structurally; permission denial must win.
+ (is (=? {:type :filtered :details {:excluded-by :permissions}}
+ (diagnose-row! {:models ["dashboard"] :search-string "puppy"} "card" card-id))))))))))
diff --git a/src/metabase/search/api.clj b/src/metabase/search/api.clj
index 0efb9c84449..7ad0d6fa6d5 100644
--- a/src/metabase/search/api.clj
+++ b/src/metabase/search/api.clj
@@ -16,11 +16,13 @@
[metabase.search.task.search-index :as task.search-index]
[metabase.task.core :as task]
[metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
- [ring.util.response :as response]))
+ [ring.util.response :as response]
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -157,6 +159,93 @@
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
;;
+(def ^:private search-request-schema
+ "Query-parameter schema shared by `GET /api/search` and `GET /api/search/debug`."
+ [:map
+ [:q {:optional true} [:maybe :string]]
+ ;; no `:optional true`: default-value-transformer skips defaults for absent optional keys, so it's
+ ;; what makes `:default :api` actually apply when the param is omitted
+ [:context {:default :api} search.config/Context]
+ [:archived {:default false} [:maybe :boolean]]
+ [:collection {:optional true} [:maybe ms/PositiveInt]]
+ [:table_db_id {:optional true} [:maybe ms/PositiveInt]]
+ [:models {:optional true} [:maybe (ms/QueryVectorOf search/SearchableModel)]]
+ [:filter_items_in_personal_collection {:optional true} [:maybe [:enum "all" "only" "only-mine" "exclude" "exclude-others"]]]
+ [:created_at {:optional true} [:maybe ms/NonBlankString]]
+ [:created_by {:optional true} [:maybe (ms/QueryVectorOf ms/PositiveInt)]]
+ [:display_type {:optional true} [:maybe (ms/QueryVectorOf ms/NonBlankString)]]
+ [:last_edited_at {:optional true} [:maybe ms/NonBlankString]]
+ [:last_edited_by {:optional true} [:maybe (ms/QueryVectorOf ms/PositiveInt)]]
+ [:model_ancestors {:default false} [:maybe :boolean]]
+ [:search_engine {:optional true} [:maybe string?]]
+ [:vector_search_strategy {:optional true} [:maybe (into [:enum] (map name) search.config/vector-search-strategies)]]
+ [:search_native_query {:optional true} [:maybe :boolean]]
+ [:verified {:optional true} [:maybe true?]]
+ [:ids {:optional true} [:maybe (ms/QueryVectorOf ms/PositiveInt)]]
+ [:calculate_available_models {:optional true} [:maybe true?]]
+ [:include_dashboard_questions {:default false} [:maybe :boolean]]
+ [:include_metadata {:default false} [:maybe :boolean]]
+ [:non_temporal_dim_ids {:optional true} [:maybe ms/NonBlankString]]
+ [:has_temporal_dim {:optional true} [:maybe :boolean]]])
+
+(def ^:private search-debug-request-schema
+ (conj search-request-schema
+ [:expected_result_type search/SearchableModel]
+ [:expected_result_id ms/PositiveInt]
+ [:for_user_id {:optional true} [:maybe ms/PositiveInt]]))
+
+(defn- params->search-context
+ "Build a search context from the raw `GET /api/search` query params. Shared by the search and debug endpoints."
+ [{:keys [q context archived models verified ids]
+ calculate-available-models :calculate_available_models
+ collection :collection
+ created-at :created_at
+ created-by :created_by
+ filter-items-in-personal-collection :filter_items_in_personal_collection
+ display-type :display_type
+ include-dashboard-questions :include_dashboard_questions
+ last-edited-at :last_edited_at
+ last-edited-by :last_edited_by
+ model-ancestors :model_ancestors
+ search-engine :search_engine
+ vector-search-strategy :vector_search_strategy
+ search-native-query :search_native_query
+ table-db-id :table_db_id
+ include-metadata :include_metadata
+ non-temporal-dim-ids :non_temporal_dim_ids
+ has-temporal-dim :has_temporal_dim}]
+ (search/search-context
+ {:archived archived
+ :collection collection
+ :context context
+ :created-at created-at
+ :created-by (set created-by)
+ :current-user-id api/*current-user-id*
+ :is-impersonated-user? (perms/impersonated-user?)
+ :is-sandboxed-user? (perms/sandboxed-user?)
+ :is-superuser? api/*is-superuser?*
+ :current-user-perms @api/*current-user-permissions-set*
+ :filter-items-in-personal-collection filter-items-in-personal-collection
+ :last-edited-at last-edited-at
+ :last-edited-by (set last-edited-by)
+ :limit (request/limit)
+ :model-ancestors? model-ancestors
+ :models (not-empty (set models))
+ :offset (request/offset)
+ :search-engine search-engine
+ :vector-search-strategy vector-search-strategy
+ :search-native-query search-native-query
+ :search-string (some-> q str/trim not-empty)
+ :table-db-id table-db-id
+ :verified verified
+ :ids (set ids)
+ :calculate-available-models? calculate-available-models
+ :include-dashboard-questions? include-dashboard-questions
+ :include-metadata? include-metadata
+ :non-temporal-dim-ids (process-non-temporal-dim-ids non-temporal-dim-ids)
+ :has-temporal-dim has-temporal-dim
+ :display-type (set display-type)}))
+
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-query-params-use-kebab-case
:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :get "/"
@@ -191,84 +280,10 @@
A search query that has both filters applied will only return models and cards."
[_route-params
- {:keys [q context archived models verified ids]
- calculate-available-models :calculate_available_models
- collection :collection
- created-at :created_at
- created-by :created_by
- filter-items-in-personal-collection :filter_items_in_personal_collection
- display-type :display_type
- include-dashboard-questions :include_dashboard_questions
- last-edited-at :last_edited_at
- last-edited-by :last_edited_by
- model-ancestors :model_ancestors
- search-engine :search_engine
- vector-search-strategy :vector_search_strategy
- search-native-query :search_native_query
- table-db-id :table_db_id
- include-metadata :include_metadata
- non-temporal-dim-ids :non_temporal_dim_ids
- has-temporal-dim :has_temporal_dim}
- :- [:map
- [:q {:optional true} [:maybe :string]]
- ;; no `:optional true`: default-value-transformer skips defaults for absent optional keys, so it's
- ;; what makes `:default :api` actually apply when the param is omitted
- [:context {:default :api} search.config/Context]
- [:archived {:default false} [:maybe :boolean]]
- [:collection {:optional true} [:maybe ms/PositiveInt]]
- [:table_db_id {:optional true} [:maybe ms/PositiveInt]]
- [:models {:optional true} [:maybe (ms/QueryVectorOf search/SearchableModel)]]
- [:filter_items_in_personal_collection {:optional true} [:maybe [:enum "all" "only" "only-mine" "exclude" "exclude-others"]]]
- [:created_at {:optional true} [:maybe ms/NonBlankString]]
- [:created_by {:optional true} [:maybe (ms/QueryVectorOf ms/PositiveInt)]]
- [:display_type {:optional true} [:maybe (ms/QueryVectorOf ms/NonBlankString)]]
- [:last_edited_at {:optional true} [:maybe ms/NonBlankString]]
- [:last_edited_by {:optional true} [:maybe (ms/QueryVectorOf ms/PositiveInt)]]
- [:model_ancestors {:default false} [:maybe :boolean]]
- [:search_engine {:optional true} [:maybe string?]]
- [:vector_search_strategy {:optional true} [:maybe (into [:enum] (map name) search.config/vector-search-strategies)]]
- [:search_native_query {:optional true} [:maybe :boolean]]
- [:verified {:optional true} [:maybe true?]]
- [:ids {:optional true} [:maybe (ms/QueryVectorOf ms/PositiveInt)]]
- [:calculate_available_models {:optional true} [:maybe true?]]
- [:include_dashboard_questions {:default false} [:maybe :boolean]]
- [:include_metadata {:default false} [:maybe :boolean]]
- [:non_temporal_dim_ids {:optional true} [:maybe ms/NonBlankString]]
- [:has_temporal_dim {:optional true} [:maybe :boolean]]]]
+ query-params :- search-request-schema]
(api/check-valid-page-params (request/limit) (request/offset))
(try
- (u/prog1 (search/search
- (search/search-context
- {:archived archived
- :collection collection
- :context context
- :created-at created-at
- :created-by (set created-by)
- :current-user-id api/*current-user-id*
- :is-impersonated-user? (perms/impersonated-user?)
- :is-sandboxed-user? (perms/sandboxed-user?)
- :is-superuser? api/*is-superuser?*
- :current-user-perms @api/*current-user-permissions-set*
- :filter-items-in-personal-collection filter-items-in-personal-collection
- :last-edited-at last-edited-at
- :last-edited-by (set last-edited-by)
- :limit (request/limit)
- :model-ancestors? model-ancestors
- :models (not-empty (set models))
- :offset (request/offset)
- :search-engine search-engine
- :vector-search-strategy vector-search-strategy
- :search-native-query search-native-query
- :search-string (some-> q str/trim not-empty)
- :table-db-id table-db-id
- :verified verified
- :ids (set ids)
- :calculate-available-models? calculate-available-models
- :include-dashboard-questions? include-dashboard-questions
- :include-metadata? include-metadata
- :non-temporal-dim-ids (process-non-temporal-dim-ids non-temporal-dim-ids)
- :has-temporal-dim has-temporal-dim
- :display-type (set display-type)}))
+ (u/prog1 (search/search (params->search-context query-params))
(analytics/inc! :metabase-search/response-ok)
(analytics/observe! :metabase-search/response-results (:total <>)))
(catch Exception e
@@ -277,6 +292,35 @@
(analytics/inc! :metabase-search/response-error)))
(throw e))))
+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-query-params-use-kebab-case
+ :metabase/validate-defendpoint-has-response-schema]}
+(api.macros/defendpoint :get "/debug"
+ "Superuser-only. Explain why `expected_result_id` / `expected_result_type` does not appear in the results of
+ the given search query. Accepts every `GET /api/search` parameter plus the two expected-result parameters, and
+ returns `{:type ..., :details ...}` for the first stage that drops the item: `not-searchable`,
+ `missing-from-index`, `not-permitted`, `filtered`, `not-matching`, or the terminal `matched` / `ranked-out`.
+
+ - `for_user_id`: diagnose from another user's perspective (defaults to you). Permission and visibility checks run
+ as that user, so a `not-permitted` result means *they* can't see the item.
+
+ Not supported for `indexed-entity` (its id is compound)."
+ [_route-params
+ {expected-result-type :expected_result_type
+ expected-result-id :expected_result_id
+ for-user-id :for_user_id
+ :as query-params} :- search-debug-request-schema]
+ (api/check-superuser)
+ (api/check-valid-page-params (request/limit) (request/offset))
+ (when (= "indexed-entity" expected-result-type)
+ (throw (ex-info (tru "Search debug is not supported for the indexed-entity model.") {:status-code 400})))
+ (letfn [(diagnose [] (search/diagnose (params->search-context query-params)
+ expected-result-type expected-result-id))]
+ (if (and for-user-id (not= for-user-id api/*current-user-id*))
+ ;; Build the context and run every permission/visibility check from the target user's perspective.
+ (do (api/check-404 (t2/exists? :model/User :id for-user-id))
+ (request/with-current-user for-user-id (diagnose)))
+ (diagnose))))
+
(def ^{:arglists '([request respond raise])} routes
"`/api/search` routes."
(api.macros/ns-handler *ns* +engine-cookie))
diff --git a/src/metabase/search/appdb/core.clj b/src/metabase/search/appdb/core.clj
index cf040f83528..fd02e9c96f3 100644
--- a/src/metabase/search/appdb/core.clj
+++ b/src/metabase/search/appdb/core.clj
@@ -13,6 +13,7 @@
[metabase.search.config :as search.config]
[metabase.search.engine :as search.engine]
[metabase.search.filter :as search.filter]
+ [metabase.search.impl :as search.impl]
[metabase.search.ingestion :as search.ingestion]
[metabase.search.permissions :as search.permissions]
[metabase.search.settings :as search.settings]
@@ -112,6 +113,30 @@
true (sql.helpers/where (or-null permitted-clause))
personal-clause (sql.helpers/where (or-null personal-clause)))))
+(defn- filter-layers
+ "Ordered `[label add-clauses-fn]` pairs that layer the structural + permission `WHERE` clauses onto an index
+ query. Defined once so [[results]] and the debug [[diagnose]] probe share the exact same chain, and so the
+ diagnostic can attribute exclusion to the first layer (per-permission, then per-filter) that drops a row."
+ [search-ctx]
+ (concat
+ [[:collection-permissions (partial add-collection-join-and-where-clauses search-ctx)]
+ [:table-permissions (partial add-table-where-clauses search-ctx)]
+ [:transform-source-type #(sql.helpers/where % (search.filter/transform-source-type-where-clause
+ search-ctx
+ :search_index.model
+ :search_index.source_type))]]
+ (for [[filter-key clause] (search.filter/filter-clauses search-ctx)]
+ [filter-key #(sql.helpers/where % clause)])))
+
+(defn- base-filtered-query
+ "The structural + permission filtered index query (no scoring), parameterized by `search-string`. Passing a
+ blank/nil `search-string` drops the fulltext predicate while keeping every other filter (see
+ `specialization/base-query`)."
+ [search-ctx search-string select-items]
+ (reduce (fn [qry [_ f]] (f qry))
+ (search.index/search-query search-string search-ctx select-items)
+ (filter-layers search-ctx)))
+
(defn- results
[{:keys [search-engine search-string] :as search-ctx}]
;; Check whether there is a query-able index.
@@ -151,15 +176,8 @@
(log/warn "Returning search results even though they may be stale. Queue size:" (pending-updates)))))
(let [weights (search.config/weights search-ctx)
scorers (search.scoring/scorers search-ctx)
- query (->> (search.index/search-query search-string search-ctx [:legacy_input])
- (add-collection-join-and-where-clauses search-ctx)
- (add-table-where-clauses search-ctx)
- (#(sql.helpers/where % (search.filter/transform-source-type-where-clause
- search-ctx
- :search_index.model
- :search_index.source_type)))
- (search.scoring/with-scores search-ctx scorers)
- (search.filter/with-filters search-ctx))]
+ query (->> (base-filtered-query search-ctx search-string [:legacy_input])
+ (search.scoring/with-scores search-ctx scorers))]
(->> (t2/query query)
(map (partial rehydrate weights (keys scorers)))))
(catch Exception e
@@ -187,6 +205,65 @@
t2/query
(into #{} (map :model)))))
+(defn- restrict-to-row [model id qry]
+ (sql.helpers/where qry [:and
+ [:= :search_index.model model]
+ [:= :search_index.model_id (str id)]]))
+
+(defn- row-present? [qry]
+ (-> qry
+ (assoc :select [[[:inline 1] :one]] :limit 1)
+ (dissoc :order-by)
+ t2/query
+ seq
+ boolean))
+
+(defn- first-excluding-layer
+ "Apply the structural + permission [[filter-layers]] cumulatively to the row-restricted, text-free query.
+ Returns the label of the first layer after which the row disappears, or nil if it survives all layers."
+ [search-ctx model id]
+ (loop [qry (->> (search.index/search-query nil search-ctx [:model_id])
+ (restrict-to-row model id))
+ layers (filter-layers search-ctx)]
+ (when-let [[[label f] & more] (seq layers)]
+ (let [qry' (f qry)]
+ (if-not (row-present? qry')
+ label
+ (recur qry' more))))))
+
+(defn- appdb-diagnose
+ [search-ctx model id]
+ (let [active (search.index/active-table)]
+ (if (nil? active)
+ {:type :missing-from-index :details {:reason :no-active-index}}
+ (let [index-row (t2/select-one active :model model :model_id (str id))]
+ (cond
+ (nil? index-row)
+ {:type :missing-from-index :details {:active-table active}}
+
+ ;; Perms-first invariant from `search.engine/diagnose`: an access denial is reported ahead of any query
+ ;; filter. The post-query permission check runs first since it can deny rows the SQL layers admit
+ ;; (archived-write, table query perms, …). For read-checked models, that means a collection/table denial
+ ;; may be reported as the generic `:permissions` instead of the more specific SQL-layer label.
+ ;; Inside `first-excluding-layer` the SQL permission layers (collection/table) likewise precede the
+ ;; structural filter clauses (including `:models`).
+ :else
+ (if-not (search.impl/check-result-permissions search-ctx (rehydrate {} [] index-row))
+ {:type :filtered :details {:excluded-by :permissions}}
+ (if-let [layer (first-excluding-layer search-ctx model id)]
+ {:type :filtered :details {:excluded-by layer}}
+ (let [search-string (:search-string search-ctx)]
+ (if (and (not (str/blank? search-string))
+ (not (row-present? (->> (base-filtered-query search-ctx search-string [:model_id])
+ (restrict-to-row model id)))))
+ {:type :not-matching
+ :details {:search-string search-string :search-native-query (boolean (:search-native-query search-ctx))}}
+ {:type :candidate :details {:search-string search-string}})))))))))
+
+(defmethod search.engine/diagnose :search.engine/appdb
+ [search-ctx model id]
+ (appdb-diagnose search-ctx model id))
+
(defn- populate-index! [context]
(search.index/index-docs! context (search.ingestion/searchable-documents)))
diff --git a/src/metabase/search/core.clj b/src/metabase/search/core.clj
index 3d08756d77b..d173c740573 100644
--- a/src/metabase/search/core.clj
+++ b/src/metabase/search/core.clj
@@ -5,6 +5,7 @@
[metabase.analytics.core :as analytics.core]
[metabase.lib-be.core :as lib-be]
[metabase.search.config :as search.config]
+ [metabase.search.debug :as search.debug]
[metabase.search.engine :as search.engine]
[metabase.search.impl :as search.impl]
[metabase.search.ingestion :as search.ingestion]
@@ -25,6 +26,8 @@
(p/import-vars
[search.config
SearchableModel]
+ [search.debug
+ diagnose]
[search.engine
model-set]
[search.impl
diff --git a/src/metabase/search/debug.clj b/src/metabase/search/debug.clj
new file mode 100644
index 00000000000..6dede7d8927
--- /dev/null
+++ b/src/metabase/search/debug.clj
@@ -0,0 +1,84 @@
+(ns metabase.search.debug
+ "Diagnostics for the search debug API: explain why a given entity does *not* appear in a search query's results.
+ See [[diagnose]]."
+ (:require
+ [metabase.search.engine :as search.engine]
+ [metabase.search.impl :as search.impl]
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.schema :as ms]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private DiagnosisResult
+ [:map [:type :keyword] [:details :map]])
+
+(defn- not-searchable-result
+ "Engine-independent first stage: does the spec say this row should be indexed at all? `nil` means it should."
+ [expected-model expected-id]
+ (case (search.ingestion/indexable-row? expected-model expected-id)
+ :no-spec {:type :not-searchable :details {:reason :no-spec :search-model expected-model}}
+ :not-found {:type :not-searchable :details {:reason :does-not-exist :search-model expected-model}}
+ :excluded {:type :not-searchable :details {:reason :excluded-by-where :search-model expected-model}}
+ :indexable nil))
+
+(def ^:private permission-exclusions
+ "`:excluded-by` keys that mean an *access-control* denial rather than a query filter the user chose. Engines emit
+ these under `:filtered`; we promote them to `:not-permitted` so the debug consumer can tell 'you can't see it'
+ apart from 'your query excluded it'."
+ #{:collection-permissions :table-permissions :permissions})
+
+(defn- split-not-permitted
+ "Promote a permission-denial `:filtered` result to `:not-permitted` (see [[permission-exclusions]])."
+ [result]
+ (cond-> result
+ (and (= :filtered (:type result))
+ (contains? permission-exclusions (-> result :details :excluded-by)))
+ (assoc :type :not-permitted)))
+
+(defn- in-results?
+ "Run the actual ranked search and check whether `(expected-model, expected-id)` is in the returned page."
+ [search-ctx expected-model expected-id]
+ (->> (:data (search.impl/search search-ctx))
+ (some (fn [row] (and (= expected-model (:model row)) (= expected-id (:id row)))))
+ boolean))
+
+(defn- terminal-result
+ "Turn an engine `:candidate` into the terminal `:matched` (actually returned) or `:ranked-out` (would be a
+ candidate, but ranked below the result/distance limit)."
+ [search-ctx expected-model expected-id candidate]
+ (if (in-results? search-ctx expected-model expected-id)
+ {:type :matched :details (assoc (:details candidate) :would-be-candidate? true)}
+ {:type :ranked-out :details (assoc (:details candidate) :would-be-candidate? true
+ :note "passes all stages; ranked below the result/distance limit")}))
+
+(mu/defn diagnose :- DiagnosisResult
+ "Explain why `expected-model`/`expected-id` does not appear in the results of the search described by `search-ctx`.
+ Returns `{:type ..., :details ...}` for the *first* disqualifying stage, in this precedence order:
+
+ - `:not-searchable` the spec says this row should not be indexed (no spec, or its `:where` excludes it).
+ - `:missing-from-index` the spec would index it, but it is absent from the resolved engine's active index.
+ - `:not-permitted` present in the index but excluded by an access-control check (the user can't see it).
+ - `:filtered` present in the index but excluded by a structural filter the query chose
+ (archived, collection scope, created-by, models, …) — everything except the match.
+ - `:not-matching` passes the filters but does not match the fulltext/semantic query.
+ - `:matched` passes every stage and is actually present in the returned page.
+ - `:ranked-out` passes every stage but was ranked below the result/distance limit.
+
+ Permission checks run from `search-ctx`'s `:current-user-id` perspective, so callers can diagnose on behalf of
+ another user (see the `for_user_id` parameter of the API). The engine-owned stages (`:missing-from-index`,
+ `:filtered`/`:not-permitted`, `:not-matching`, `:candidate`) come from [[metabase.search.engine/diagnose]]; the
+ engine-independent stages are decided here. `:details` always carries the resolved engine. `:not-searchable`
+ reflects current spec/DB truth, so it wins even if a stale index row lingers."
+ [search-ctx :- :map
+ expected-model :- ms/NonBlankString
+ expected-id :- pos-int?]
+ (let [engine-details {:resolved-engine (:search-engine search-ctx)
+ :default-engine (search.engine/default-engine)}
+ result (or (not-searchable-result expected-model expected-id)
+ (let [r (split-not-permitted
+ (search.engine/diagnose search-ctx expected-model expected-id))]
+ (if (= :candidate (:type r))
+ (terminal-result search-ctx expected-model expected-id r)
+ r)))]
+ (update result :details merge engine-details)))
diff --git a/src/metabase/search/engine.clj b/src/metabase/search/engine.clj
index 8911660df20..001f5d6e8dc 100644
--- a/src/metabase/search/engine.clj
+++ b/src/metabase/search/engine.clj
@@ -28,6 +28,22 @@
{:arglists '([search-context])}
:search-engine)
+(defmulti diagnose
+ "Explain why `(expected-model, expected-id)` does not appear in the index/query stages this engine owns.
+ Returns `{:type ..., :details ...}` for the first engine-owned stage that drops it
+ (`:missing-from-index`, `:filtered`, or `:not-matching`), or `{:type :candidate, :details ...}` if it passes
+ every engine-owned stage.
+ Engine-independent stages (`:not-searchable`, terminal `:matched`/`:ranked-out`) are handled by the caller in
+ [[metabase.search.debug]].
+
+ The `:filtered` `:details` `:excluded-by` value names the filter that dropped the row; shared keys (e.g. `:models`,
+ `:created-by`, `:archived?`) are consistent across engines. Access-control exclusions are also reported under
+ `:filtered` here — `:collection-permissions`/`:table-permissions`/`:permissions` (appdb) or `:permissions`
+ (semantic) — and [[metabase.search.debug]] promotes those to `:not-permitted`; engines should check them before
+ structural filters so access denial wins."
+ {:arglists '([search-context expected-model expected-id])}
+ (fn [{engine :search-engine} _ _] engine))
+
(defmulti score "For legacy search: perform the in-memory ranking"
{:arglists '([search-context result])}
(fn [{engine :search-engine} _]
diff --git a/src/metabase/search/filter.clj b/src/metabase/search/filter.clj
index 0b8e9f57c10..39d6f9668f6 100644
--- a/src/metabase/search/filter.clj
+++ b/src/metabase/search/filter.clj
@@ -177,31 +177,41 @@
[:!= model-col [:inline "transform"]]
(transform-source-type-where-clause search-context source-type-col)]))
-(defn with-filters
- "Return a HoneySQL clause corresponding to all the optional search filters."
- [search-context qry]
- (as-> qry qry
- (sql.helpers/where qry (if (seq (:models search-context))
- [:in :search_index.model (:models search-context)]
- ;; Ideally, we would not get this far, and bail out earlier.
- [:= 1 2]))
- (sql.helpers/where qry (when-let [ids (:ids search-context)]
- [:and
- [:in :search_index.model_id (map str ids)]
- ;; NOTE: we limit id-based search to only a subset of the models
- ;; TODO this should just become part of the model spec e.g. :search-by-id?
- [:in :search_index.model ["card" "dataset" "metric" "dashboard" "action"]]]))
- (sql.helpers/where qry [:or
+(defn filter-clauses
+ "Ordered seq of `[filter-key honeysql-clause]` for the structural filters implied by `search-context`.
+ [[with-filters]] ANDs these into the query; the search debug API uses the keys to attribute which specific
+ filter excludes a given row."
+ [search-context]
+ (keep
+ identity
+ (concat
+ [[:models (if (seq (:models search-context))
+ [:in :search_index.model (:models search-context)]
+ ;; Ideally, we would not get this far, and bail out earlier.
+ [:= 1 2])]]
+ (when-let [ids (:ids search-context)]
+ [[:ids [:and
+ [:in :search_index.model_id (map str ids)]
+ ;; NOTE: we limit id-based search to only a subset of the models
+ ;; TODO this should just become part of the model spec e.g. :search-by-id?
+ [:in :search_index.model ["card" "dataset" "metric" "dashboard" "action"]]]]])
+ [[:dashboard-questions [:or
;; leverage the fact that only card-related models populate this attribute
[:= nil :search_index.dashboard_id]
(when (:include-dashboard-questions? search-context)
- [:not= [:inline 0] [:coalesce :search_index.dashboardcard_count [:inline 0]]])])
- (reduce (fn [qry {t :type :keys [context-key required-feature supported-value? field]}]
- (or (when-some [v (get search-context context-key)]
- (assert (supported-value? v) (str "Unsupported value for " context-key " - " v))
- (when (or (nil? required-feature) (premium-features/has-feature? required-feature))
- (when-some [c (where-clause* t (keyword (str "search_index." field)) v)]
- (sql.helpers/where qry c))))
- qry))
- qry
- (vals (dissoc search.config/filters :id :native-query)))))
+ [:not= [:inline 0] [:coalesce :search_index.dashboardcard_count [:inline 0]]])]]]
+ (for [{t :type :keys [context-key required-feature supported-value? field]}
+ (vals (dissoc search.config/filters :id :native-query))
+ :let [v (get search-context context-key)]]
+ (when (some? v)
+ (assert (supported-value? v) (str "Unsupported value for " context-key " - " v))
+ (when (or (nil? required-feature) (premium-features/has-feature? required-feature))
+ (when-some [c (where-clause* t (keyword (str "search_index." field)) v)]
+ [context-key c])))))))
+
+(defn with-filters
+ "Return a HoneySQL clause corresponding to all the optional search filters."
+ [search-context qry]
+ (reduce (fn [qry [_ c]] (sql.helpers/where qry c))
+ qry
+ (filter-clauses search-context)))
diff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.clj
index 15e0cec657e..d409dec8d66 100644
--- a/src/metabase/search/impl.clj
+++ b/src/metabase/search/impl.clj
@@ -27,6 +27,10 @@
(set! *warn-on-reflection* true)
(defmulti ^:private check-permissions-for-model
+ "Whether the current user (per `search-ctx`) may see `search-result`, applying the per-model post-query
+ permission rules. The query already filters most rows out in SQL; this catches the archived-write check and the
+ table / indexed-entity special cases. Used in the [[search]] pipeline and, via [[check-result-permissions]], by
+ the search debug API."
{:arglists '([search-ctx search-result])}
(fn [_search-ctx search-result] ((comp keyword :model) search-result)))
@@ -242,6 +246,9 @@
(defmethod search.engine/model-set :default [search-ctx]
(search.engine/model-set (apply-default-engine search-ctx)))
+(defmethod search.engine/diagnose :default [search-ctx expected-model expected-id]
+ (search.engine/diagnose (apply-default-engine search-ctx) expected-model expected-id))
+
(mr/def ::search-context.input
[:map {:closed true}
[:search-string [:maybe ms/NonBlankString]]
@@ -389,6 +396,12 @@
;; Collections require some transformation before being scored and returned by search.
(cond-> (t2/instance-of? :model/Collection instance) map-collection))))
+(defn check-result-permissions
+ "Run the post-query permission check on a single raw engine result map (the rehydrated shape an engine's
+ `results` produces). Returns a boolean. Public for the search debug API."
+ [search-ctx result]
+ (check-permissions-for-model search-ctx (normalize-result result)))
+
(defn- add-can-write [search-ctx row]
(if (some #(mi/instance-of? % row) [:model/Dashboard :model/Card :model/Collection])
(assoc row :can_write (can-write? search-ctx row))
diff --git a/src/metabase/search/ingestion.clj b/src/metabase/search/ingestion.clj
index c250c806536..25ddde12112 100644
--- a/src/metabase/search/ingestion.clj
+++ b/src/metabase/search/ingestion.clj
@@ -203,6 +203,28 @@
(defn- search-items-reducible []
(reduce u/rconcat [] (map spec-index-reducible search.spec/search-models)))
+(defn indexable-row?
+ "Whether the row identified by `search-model` + `id` would be indexed, i.e. it satisfies the spec's `:where`.
+ `id` is the toucan PK of the underlying model (not the compound `indexed-entity` id). Returns:
+
+ - `:no-spec` the model is not searchable
+ - `:not-found` no such row exists in the underlying table
+ - `:excluded` the row exists but the spec's `:where` filters it out
+ - `:indexable` ingestion would index it"
+ [search-model id]
+ (if-not (contains? (set search.spec/search-models) search-model)
+ :no-spec
+ (let [spec (search.spec/spec search-model)
+ indexed? (-> (spec-index-query-where search-model [:= :this.id id])
+ (assoc :select [[[:inline 1] :one]] :limit 1)
+ t2/query
+ seq
+ boolean)]
+ (cond
+ indexed? :indexable
+ (t2/exists? (:model spec) :id id) :excluded
+ :else :not-found))))
+
(def ^:private max-document-error-logs 10)
(defn- query->documents [query-reducible]
diff --git a/src/metabase/search/semantic/core.clj b/src/metabase/search/semantic/core.clj
index 2b36a9fd4d8..e3a4dd2c5c0 100644
--- a/src/metabase/search/semantic/core.clj
+++ b/src/metabase/search/semantic/core.clj
@@ -51,6 +51,13 @@
[_searchable-documents]
(oss-semantic-search-error))
+(defenterprise diagnose
+ "Engine-owned diagnostic stages (`missing-from-index` / `filtered` / `not-matching` / `candidate`) for the
+ semantic search index. See [[metabase.search.debug/diagnose]]."
+ metabase-enterprise.semantic-search.core
+ [_search-ctx _expected-model _expected-id]
+ (oss-semantic-search-error))
+
;; Search engine method implementations
(defmethod search.engine/supported-engine? :search.engine/semantic [_]
@@ -68,6 +75,10 @@
[_search-ctx]
search.config/all-models)
+(defmethod search.engine/diagnose :search.engine/semantic
+ [search-ctx expected-model expected-id]
+ (diagnose search-ctx expected-model expected-id))
+
(defmethod search.engine/update! :search.engine/semantic
[_ document-reducible]
(try
diff --git a/test/metabase/search/debug_test.clj b/test/metabase/search/debug_test.clj
new file mode 100644
index 00000000000..a431ec59468
--- /dev/null
+++ b/test/metabase/search/debug_test.clj
@@ -0,0 +1,180 @@
+(ns metabase.search.debug-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.api.common :as api]
+ [metabase.permissions.core :as perms]
+ [metabase.permissions.util :as perms-util]
+ [metabase.search.appdb.index :as search.index]
+ [metabase.search.config :as search.config]
+ [metabase.search.core :as search]
+ [metabase.search.ingestion :as search.ingestion]
+ [metabase.search.test-util :as search.tu]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(use-fixtures :each (fn [thunk]
+ (binding [search.ingestion/*force-sync* true]
+ (thunk))))
+
+(defn- diagnose
+ "Build a search context from the currently bound API user (plus `overrides`) and run [[search/diagnose]]."
+ [overrides expected-model expected-id]
+ (search/diagnose
+ (search/search-context
+ (merge {:current-user-id api/*current-user-id*
+ :current-user-perms @api/*current-user-permissions-set*
+ :is-superuser? api/*is-superuser?*
+ :is-impersonated-user? (perms-util/impersonated-user?)
+ :is-sandboxed-user? (perms-util/sandboxed-user?)
+ :archived false
+ :context :default
+ :search-string nil
+ :models search.config/all-models
+ :model-ancestors? false}
+ overrides))
+ expected-model expected-id))
+
+(deftest ^:synchronized not-searchable-test
+ (testing "A card inside a document is excluded by the spec's :where clause"
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Doc"}
+ :model/Card {card-id :id} {:name "In A Document" :document_id doc-id}]
+ (mt/with-test-user :crowberto
+ (is (=? {:type :not-searchable :details {:reason :excluded-by-where :search-model "card"}}
+ (diagnose {:search-string "document"} "card" card-id))))))
+ (testing "A model with no search spec"
+ (mt/with-test-user :crowberto
+ (is (=? {:type :not-searchable :details {:reason :no-spec :search-model "user"}}
+ (diagnose {} "user" 1)))))
+ (testing "A searchable model whose row does not exist is reported as such, not excluded-by-where"
+ (mt/with-test-user :crowberto
+ (is (=? {:type :not-searchable :details {:reason :does-not-exist :search-model "card"}}
+ (diagnose {:search-string "x"} "card" Integer/MAX_VALUE))))))
+
+(deftest ^:synchronized missing-from-index-test
+ (when (search/supports-index?)
+ (testing "A card the spec would index but which is absent from the active index"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {card-id :id} {:name "Quarterly Revenue"}]
+ (search/reindex! {:async? false :in-place? true})
+ (t2/delete! (search.index/active-table) :model "card" :model_id (str card-id))
+ (mt/with-test-user :crowberto
+ (is (=? {:type :missing-from-index :details {:active-table some?}}
+ (diagnose {:search-string "quarterly"} "card" card-id)))))))))
+
+(deftest ^:synchronized filtered-test
+ (when (search/supports-index?)
+ (testing "Excluded by a structural filter (created-by)"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {card-id :id} {:name "Quarterly Revenue" :creator_id (mt/user->id :crowberto)}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-test-user :crowberto
+ (is (=? {:type :filtered :details {:excluded-by :created-by}}
+ (diagnose {:search-string "quarterly" :created-by #{(mt/user->id :rasta)}} "card" card-id)))))))
+ (testing "Excluded because the model is not among the requested/applicable models"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {card-id :id} {:name "Quarterly Revenue"}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-test-user :crowberto
+ (is (=? {:type :filtered :details {:excluded-by :models}}
+ (diagnose {:search-string "quarterly" :models #{"dashboard"}} "card" card-id)))))))))
+
+(deftest ^:synchronized not-permitted-test
+ (when (search/supports-index?)
+ (testing "A row the user cannot read is :not-permitted, not :filtered"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Collection coll {:name "Locked"}
+ :model/Card {card-id :id} {:name "Quarterly Revenue" :collection_id (:id coll)}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-non-admin-groups-no-collection-perms coll
+ (mt/with-test-user :rasta
+ (is (=? {:type :not-permitted :details {:excluded-by :collection-permissions}}
+ (diagnose {:search-string "quarterly"} "card" card-id))))))))
+ (testing "A read-checked model denied by collection permissions reports the post-query permission label"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Collection coll {:name "Locked"}
+ :model/Card {metric-id :id} {:name "Quarterly Metric"
+ :collection_id (:id coll)
+ :type :metric}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-non-admin-groups-no-collection-perms coll
+ (mt/with-test-user :rasta
+ (is (=? {:type :not-permitted :details {:excluded-by :permissions}}
+ (diagnose {:search-string "quarterly"} "metric" metric-id))))))))
+ (testing "A denial from the post-query permission check wins over an overlapping structural filter"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Collection coll {:name "Read Only"}
+ :model/Card {card-id :id} {:name "Quarterly Revenue"
+ :collection_id (:id coll)
+ :creator_id (mt/user->id :crowberto)
+ :archived true}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-non-admin-groups-no-collection-perms coll
+ (mt/with-temp [:model/PermissionsGroup group {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta)
+ :group_id (:id group)}]
+ (perms/grant-collection-read-permissions! group (:id coll))
+ (mt/with-test-user :rasta
+ ;; the archived search needs write perms (rasta is read-only) and `:created-by` also excludes the
+ ;; row structurally; the access denial must win.
+ (is (=? {:type :not-permitted :details {:excluded-by :permissions}}
+ (diagnose {:search-string "quarterly"
+ :archived true
+ :created-by #{(mt/user->id :rasta)}}
+ "card" card-id)))))))))))
+
+(deftest ^:synchronized not-matching-test
+ (when (search/supports-index?)
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {card-id :id} {:name "Quarterly Revenue"}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-test-user :crowberto
+ (is (=? {:type :not-matching :details {:search-string "zzzznomatch"}}
+ (diagnose {:search-string "zzzznomatch"} "card" card-id))))))))
+
+(deftest ^:synchronized matched-test
+ (when (search/supports-index?)
+ (testing "A card matching the query is reported as actually returned"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {card-id :id} {:name "Quarterly Revenue"}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-test-user :crowberto
+ (is (=? {:type :matched :details {:would-be-candidate? true}}
+ (diagnose {:search-string "quarterly"} "card" card-id)))))))))
+
+(deftest ^:synchronized endpoint-test
+ (when (search/supports-index?)
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {card-id :id} {:name "Quarterly Revenue"}]
+ (search/reindex! {:async? false :in-place? true})
+ (testing "superuser gets a diagnosis"
+ (is (=? {:type "matched"}
+ (mt/user-http-request :crowberto :get 200 "search/debug"
+ :q "quarterly" :expected_result_type "card" :expected_result_id card-id))))
+ (testing "non-superuser is forbidden"
+ (mt/user-http-request :rasta :get 403 "search/debug"
+ :q "quarterly" :expected_result_type "card" :expected_result_id card-id))
+ (testing "indexed-entity is rejected"
+ (mt/user-http-request :crowberto :get 400 "search/debug"
+ :q "x" :expected_result_type "indexed-entity" :expected_result_id 1))
+ (testing "for_user_id with an unknown user is a 404"
+ (mt/user-http-request :crowberto :get 404 "search/debug"
+ :q "quarterly" :expected_result_type "card" :expected_result_id card-id
+ :for_user_id Integer/MAX_VALUE))))))
+
+(deftest ^:synchronized for-user-id-test
+ (when (search/supports-index?)
+ (testing "An admin can diagnose from another user's perspective via for_user_id"
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Collection coll {:name "Locked"}
+ :model/Card {card-id :id} {:name "Quarterly Revenue" :collection_id (:id coll)}]
+ (search/reindex! {:async? false :in-place? true})
+ (mt/with-non-admin-groups-no-collection-perms coll
+ (testing "as the admin (default), the card is visible"
+ (is (=? {:type "matched"}
+ (mt/user-http-request :crowberto :get 200 "search/debug"
+ :q "quarterly" :expected_result_type "card" :expected_result_id card-id))))
+ (testing "as a user who can't read the collection, it is not-permitted"
+ (is (=? {:type "not-permitted" :details {:excluded-by "collection-permissions"}}
+ (mt/user-http-request :crowberto :get 200 "search/debug"
+ :q "quarterly" :expected_result_type "card" :expected_result_id card-id
+ :for_user_id (mt/user->id :rasta)))))))))))