Skip to content

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

Don't resolve inactive tables in portable FK resolution (#75397)

Chris Truter701ae375624a
diff --git a/src/metabase/models/serialization/resolve/mp.clj b/src/metabase/models/serialization/resolve/mp.clj
index 5a08cd42871..954273339b5 100644
--- a/src/metabase/models/serialization/resolve/mp.clj
+++ b/src/metabase/models/serialization/resolve/mp.clj
@@ -56,7 +56,7 @@
(:name (lib.metadata/database metadata-provider)))
(defn- matching-tables-via-provider
- "Return all tables matching `table-name` in `metadata-provider`, post-filtered by `schema`
+ "Return active tables matching `table-name` in `metadata-provider`, post-filtered by `schema`
(`schema` may be `nil` for schemaless databases).
Used as a fallback for mock and checker providers. NOT safe for production: the
@@ -69,18 +69,24 @@
(->> (lib.metadata.protocols/metadatas metadata-provider
{:lib/type :metadata/table
:name #{table-name}})
- (filter #(= (:schema %) schema))))
+ ;; By-name lookups skip the provider's SQL `active = true` filter (it only guards
+ ;; enumerate-all queries), so inactive rows reach here. `false?` keeps mocks with no
+ ;; `:active` key.
+ (filter #(and (= (:schema %) schema)
+ (not (false? (:active %)))))))
(defn- matching-tables-via-app-db
- "Return all tables matching the `(db-id, schema, table-name)` triple by direct application-DB
+ "Return active tables matching the `(db-id, schema, table-name)` triple by direct application-DB
query — same shape `resolve.db/import-table-fk` has always used. Bypasses the metadata
provider entirely.
+ Filters `:active true` in the WHERE clause so stale FKs to inactive tables don't resolve.
+
Defective `(db_id, schema, name)` duplicates (allowed by the
`001_update_migrations.yaml` `is_defective_duplicate` carve-out for pre-constraint rows)
return more than one candidate so [[find-table]] can raise `:ambiguous-table`."
[db-id schema table-name]
- (t2/select :metadata/table :db_id db-id :schema schema :name table-name))
+ (t2/select :metadata/table :db_id db-id :schema schema :name table-name :active true))
(defn- app-db-backed-provider?
"True when `metadata-provider` is part of the production app-DB-backed wrapper chain
@@ -105,6 +111,11 @@
prompts the agent with a hallucinated `source-table:` would otherwise receive a list of
schemas / tables they cannot otherwise see.
+ For the same reason this single message covers both a never-existed miss and an inactive
+ match — [[table-candidates]] drops inactive rows upstream, so both reach [[find-table]] as 0
+ candidates. Branching the wording on whether an inactive row exists would be an existence
+ oracle, so both get this identical message.
+
The LLM can still self-correct in one turn by calling `entity_details` on the parent
database; the message points it at that path."
[_metadata-provider [_path-db-name _path-schema _path-table-name :as path]]
@@ -126,7 +137,9 @@
provider's cache disagree about whether a table exists (e.g. provider holds a cached row
for a table that was just deleted, or vice versa). In that last case the provider's view
becomes authoritative, since the alternative is a confusing `:unknown-table` raised for a
- table the caller can plainly see via `entity_details`."
+ table the caller can plainly see via `entity_details`.
+
+ Returns only active tables — both helpers drop inactive (`:active false`) rows."
[metadata-provider db-id schema table-name]
(or (when (and db-id (app-db-backed-provider? metadata-provider))
(seq (matching-tables-via-app-db db-id schema table-name)))
@@ -138,7 +151,10 @@
On miss, the thrown ex-info carries actionable, tiered hints (see
[[unknown-table-ex-info]]) so the LLM can self-correct on the next turn instead of
re-hallucinating the same bad path. All error branches are marked
- `:agent-error? true` so the outer tool wrapper relays the message verbatim."
+ `:agent-error? true` so the outer tool wrapper relays the message verbatim.
+
+ Inactive (`:active false`) tables are dropped by [[table-candidates]], so a stale FK to one
+ surfaces here as a 0-candidate miss."
[metadata-provider [path-db-name path-schema path-table-name :as path]]
(let [{current-db :name, current-db-id :id} (lib.metadata/database metadata-provider)]
(when-not (= path-db-name current-db)
diff --git a/test/metabase/models/serialization/resolve/mp_test.clj b/test/metabase/models/serialization/resolve/mp_test.clj
index 7466f9a43af..97ed6a82d9b 100644
--- a/test/metabase/models/serialization/resolve/mp_test.clj
+++ b/test/metabase/models/serialization/resolve/mp_test.clj
@@ -6,6 +6,7 @@
Phase-2 additions (step 11): `import-fk` for `Card` by entity_id."
(:require
+ [clojure.string :as str]
[clojure.test :refer [deftest is testing use-fixtures]]
[metabase.lib-be.core :as lib-be]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
@@ -141,6 +142,50 @@
(is (= (:id raw-orders) (resolve/import-table-fk r [(:name db) "RAW" "ORDERS"])))
(is (= (:id clean-orders) (resolve/import-table-fk r [(:name db) "CLEAN" "ORDERS"])))))))
+(deftest import-table-fk-inactive-table-test
+ (testing "a portable FK to an inactive table (deleted / re-uploaded CSV) must NOT resolve"
+ ;; A deleted / re-uploaded upload leaves an inactive app-DB row whose warehouse table is gone;
+ ;; a stale FK to it must miss, with a message identical to a never-existed miss (asserted
+ ;; below) since distinguishing them would be an existence oracle.
+ (mt/with-temp [:model/Database db {:name (str "Uploads " (random-uuid)) :engine :h2}
+ :model/Table _gone {:name "metabot2_38513168ae9131" :schema "PUBLIC"
+ :db_id (:id db) :active false}]
+ (let [mp (lib-be/application-database-metadata-provider (:id db))
+ r (resolve.mp/import-resolver mp)]
+ (try
+ (resolve/import-table-fk r [(:name db) "PUBLIC" "metabot2_38513168ae9131"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (.getMessage e)]
+ (is (= :unknown-table (:error d)))
+ (is (= 400 (:status-code d)))
+ (is (true? (:agent-error? d)))
+ (is (re-find #"entity_details" msg) "message points the LLM at entity_details to re-list")
+ (testing "inactive-row miss is indistinguishable from a never-existed miss (no oracle)"
+ (let [never-existed (try (resolve/import-table-fk r [(:name db) "PUBLIC" "never_existed_xyz"])
+ (catch clojure.lang.ExceptionInfo e2 (.getMessage e2)))]
+ ;; same wording modulo the echoed portable FK (which the caller supplied either way)
+ (is (= (str/replace msg #"\[.*?\]" "[FK]")
+ (str/replace never-existed #"\[.*?\]" "[FK]"))))))))))))
+
+(deftest matching-tables-via-provider-drops-inactive-test
+ (testing "matching-tables-via-provider filters the inactive rows the provider surfaces by name"
+ ;; Isolates the provider-side filter. By-name `metadatas` lookups skip the provider's SQL
+ ;; `active = true` clause (it only guards enumerate-all queries), so the inactive row reaches
+ ;; `matching-tables-via-provider`, whose filter is the only thing that drops it.
+ (mt/with-temp [:model/Database db {:name (str "Uploads " (random-uuid)) :engine :h2}
+ :model/Table _gone {:name "metabot2_deadbeefcafe01" :schema "PUBLIC"
+ :db_id (:id db) :active false}]
+ (let [mp (lib-be/application-database-metadata-provider (:id db))]
+ (testing "the provider DOES surface the inactive row on a raw by-name lookup"
+ (is (= [false]
+ (mapv :active
+ (lib.metadata.protocols/metadatas
+ mp {:lib/type :metadata/table :name #{"metabot2_deadbeefcafe01"}})))))
+ (testing "...but matching-tables-via-provider drops it"
+ (is (empty? (#'resolve.mp/matching-tables-via-provider mp "PUBLIC" "metabot2_deadbeefcafe01"))))))))
+
(deftest ^:parallel import-table-fk-error-test
(testing "unknown table name → :unknown-table, agent-error?, 400, no info leak"
(let [r (resolve.mp/import-resolver mp-simple)]