Skip to content

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

Add gate table tombstone cleanup to semantic search index cleanup task (#62605)

Noah Mossc6a9193bff49
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
index 628e8c09987..9ce9f7d94d9 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index_metadata.clj
@@ -152,6 +152,16 @@
[(keyword (str (:gate-table-name index-metadata) "_gated_at")) :if-not-exists]
[(keyword (:gate-table-name index-metadata)) :gated_at :id])
:quoted true))
+ (log/info "Creating gate table tombstone cleanup index if not exists")
+ ;; Partial index on nil documents in the gate table to optimize identification of old tombstones
+ (jdbc/execute!
+ pgvector
+ (sql/format
+ {:create-index
+ [[(keyword (str (:gate-table-name index-metadata) "_tombstone_cleanup")) :if-not-exists]
+ [(keyword (:gate-table-name index-metadata)) :gated_at]]
+ :where [:and [:= :document nil] [:= :document_hash nil]]}
+ :quoted true))
nil))
(defn drop-tables-if-exists!
@@ -351,7 +361,4 @@
(-> (get-active-index-state pgvector index-metadata)
:metadata-row
:indexer_last_poll
- class)
- (find-best-index! pgvector index-metadata embedding-model)
- (record-new-index-table! pgvector index-metadata (:index (find-best-index! pgvector index-metadata embedding-model)))
- (activate-index! pgvector index-metadata (:id (:metadata-row (find-best-index! pgvector index-metadata embedding-model)))))
+ class))
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj
index 13fc3c6863e..bfced913d22 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj
@@ -141,3 +141,11 @@
:export? false
:visibility :internal
:doc "Number of hours to retain stale semantic search indexes before cleanup.")
+
+(defsetting tombstone-retention-hours
+ (deferred-tru "Number of hours to retain tombstone records in the gate table before cleanup.")
+ :type :integer
+ :default 24
+ :encryption :no
+ :export? false
+ :visibility :internal)
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj
index 046746c1262..08c8c0d9c07 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj
@@ -19,6 +19,8 @@
(set! *warn-on-reflection* true)
(defn- orphan-index-tables
+ "Returns a list of semantic search index tables which are not referenced in the metadata table.
+ Not expected to occur, but if it does, these tables can be dropped."
[pgvector {:keys [metadata-table-name]}]
(let [orphaned-tables-sql
(-> {:select [:t.table_name]
@@ -33,6 +35,9 @@
(map :table_name))))
(defn- stale-index-tables
+ "Returns a list of semantic search index tables that are considered stale and can be dropped.
+ An index is considered stale if it is not the active index and has not been used or updated
+ within the retention period defined in settings."
[pgvector {:keys [metadata-table-name control-table-name]}]
(let [retention-cutoff (t/minus (t/offset-date-time) (t/hours (semantic.settings/stale-index-retention-hours)))
stale-index-sql (-> {:select [:meta.table_name]
@@ -50,11 +55,53 @@
(->> (jdbc/execute! pgvector stale-index-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})
(map :table_name))))
+(defn- indexer-ran-recently?
+ "Check if the indexer has run within the specified number of hours."
+ [metadata-row hours-ago]
+ (when-let [last-poll-inst (t/instant (:indexer_last_poll metadata-row))]
+ (t/after?
+ last-poll-inst
+ (t/minus (t/instant) (t/hours hours-ago)))))
+
+(defn- get-active-index-metadata-row
+ "Get the metadata row for the currently active index."
+ [pgvector {:keys [metadata-table-name control-table-name]}]
+ (jdbc/execute-one! pgvector
+ (-> {:select [:m.*]
+ :from [[(keyword control-table-name) :c]]
+ :join [[(keyword metadata-table-name) :m] [:= :m.id :c.active_id]]}
+ (sql/format :quoted true))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps}))
+
+(defn- cleanup-old-gate-tombstones!
+ "Cleans up old tombstone records from the gate table, if the indexer has run recently.
+ Ensures that the gate table does not grow indefinitely with old tombstone records
+ (where document and document_hash are null)."
+ [pgvector index-metadata]
+ (try
+ (let [retention-hours (semantic.settings/tombstone-retention-hours)
+ active-metadata-row (get-active-index-metadata-row pgvector index-metadata)]
+ (if-not (indexer-ran-recently? active-metadata-row retention-hours)
+ (log/infof "Skipping tombstone cleanup: indexer has not run within the last %s hours"
+ retention-hours)
+ (let [{:keys [gate-table-name]} index-metadata
+ retention-cutoff (t/minus (t/offset-date-time)
+ (t/hours retention-hours))
+ tombstone-cleanup-sql (-> {:delete-from [(keyword gate-table-name)]
+ :where [:and
+ [:= :document nil]
+ [:= :document_hash nil]
+ [:< :gated_at retention-cutoff]]}
+ (sql/format :quoted true))
+ deleted-count (::jdbc/update-count (jdbc/execute-one! pgvector tombstone-cleanup-sql))]
+ (when (pos? deleted-count)
+ (log/infof "Cleaned up %d old tombstone records from gate table" deleted-count)))))
+ (catch Exception e
+ (log/error e "Failed to clean up tombstone records from gate table"))))
+
(defn- cleanup-stale-indexes!
- []
- (let [pgvector (semantic.env/get-pgvector-datasource!)
- index-metadata (semantic.env/get-index-metadata)
- stale-table-names (map keyword (stale-index-tables pgvector index-metadata))
+ [pgvector index-metadata]
+ (let [stale-table-names (map keyword (stale-index-tables pgvector index-metadata))
orphaned-table-names (map keyword (orphan-index-tables pgvector index-metadata))
tables-to-drop (concat stale-table-names orphaned-table-names)
drop-table-sql (sql/format
@@ -65,13 +112,20 @@
(log/info "Dropping stale/orphaned semantic search index:" table-name))
(jdbc/execute! pgvector drop-table-sql))))
+(defn- cleanup-stale-indexes-and-gate-tombstones!
+ []
+ (let [pgvector (semantic.env/get-pgvector-datasource!)
+ index-metadata (semantic.env/get-index-metadata)]
+ (cleanup-stale-indexes! pgvector index-metadata)
+ (cleanup-old-gate-tombstones! pgvector index-metadata)))
+
(def ^:private cleanup-job-key (jobs/key "metabase.task.semantic-index-cleanup.job"))
(def ^:private cleanup-trigger-key (triggers/key "metabase.task.semantic-index-cleanup.trigger"))
(task/defjob ^{DisallowConcurrentExecution true
:doc "Clean up inactive semantic search index tables"}
SemanticIndexCleanup [_ctx]
- (cleanup-stale-indexes!))
+ (cleanup-stale-indexes-and-gate-tombstones!))
(defmethod task/init! ::SemanticIndexCleanup [_]
(let [job (jobs/build
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj
index 88a54bab36a..86b46828eb2 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj
@@ -10,7 +10,13 @@
[metabase-enterprise.semantic-search.task.index-cleanup :as sut]
[metabase-enterprise.semantic-search.test-util :as semantic.tu]
[metabase.test :as mt]
- [next.jdbc :as jdbc]))
+ [metabase.util.json :as json]
+ [next.jdbc :as jdbc]
+ [next.jdbc.result-set :as jdbc.rs])
+ (:import
+ (org.postgresql.util PGobject)))
+
+(set! *warn-on-reflection* true)
(use-fixtures :once #'semantic.tu/once-fixture)
@@ -26,7 +32,7 @@
(defn- insert-metadata-with-timestamps!
"Insert an index metadata row using record-new-index-table! and then update timestamps for testing."
[pgvector index-metadata {:keys [table-name provider model-name vector-dimensions
- index-created-at indexer-last-seen]
+ index-created-at indexer-last-poll]
:or {provider "ollama"
model-name "test-model"
vector-dimensions 1024}}]
@@ -36,12 +42,12 @@
:vector-dimensions vector-dimensions})
index-id (semantic.index-metadata/record-new-index-table! pgvector index-metadata index)]
;; Update the timestamps that we need for testing
- (when (or index-created-at indexer-last-seen)
+ (when (or index-created-at indexer-last-poll)
(jdbc/execute! pgvector
(-> (sql.helpers/update (keyword (:metadata-table-name index-metadata)))
(sql.helpers/set (cond-> {}
index-created-at (assoc :index_created_at index-created-at)
- indexer-last-seen (assoc :indexer_last_seen indexer-last-seen)))
+ indexer-last-poll (assoc :indexer_last_poll indexer-last-poll)))
(sql.helpers/where [:= :id index-id])
(sql/format :quoted true))))
index-id))
@@ -86,8 +92,7 @@
:index-created-at recent-time})
(let [active-index-id (insert-metadata-with-timestamps! pgvector index-metadata
{:table-name active-table
- :index-created-at old-time
- :indexer-last-seen old-time})]
+ :index-created-at old-time})]
(set-active-index! pgvector (:control-table-name index-metadata) active-index-id))
(is (semantic.tu/table-exists-in-db? stale-table))
(is (semantic.tu/table-exists-in-db? orphaned-table))
@@ -98,7 +103,7 @@
(with-redefs [semantic.env/get-pgvector-datasource! (constantly pgvector)
semantic.env/get-index-metadata (constantly index-metadata)]
(mt/with-temporary-setting-values [semantic.settings/stale-index-retention-hours retention-hours]
- (cleanup-stale-indexes!)))
+ (cleanup-stale-indexes! pgvector index-metadata)))
(is (not (semantic.tu/table-exists-in-db? stale-table)))
(is (not (semantic.tu/table-exists-in-db? orphaned-table)))
(is (semantic.tu/table-exists-in-db? recent-table))
@@ -117,11 +122,105 @@
:provider "ollama"
:model-name "test-model"
:vector-dimensions 1024
- :index-created-at old-time
- :indexer-last-seen nil})
+ :index-created-at old-time})
(is (not (semantic.tu/table-exists-in-db? nonexistent-table)))
(with-redefs [semantic.settings/stale-index-retention-hours (constantly retention-hours)
semantic.env/get-pgvector-datasource! (constantly pgvector)
semantic.env/get-index-metadata (constantly index-metadata)]
- (cleanup-stale-indexes!)
+ (cleanup-stale-indexes! pgvector index-metadata)
(is (not (semantic.tu/table-exists-in-db? nonexistent-table))))))))))
+
+(deftest tombstone-cleanup-test
+ (mt/with-premium-features #{:semantic-search}
+ (let [pgvector semantic.tu/db
+ index-metadata (semantic.tu/unique-index-metadata)
+ retention-hours (semantic.settings/tombstone-retention-hours)
+ old-time (t/minus (t/offset-date-time) (t/hours (inc retention-hours)))
+ recent-time (t/minus (t/offset-date-time) (t/hours (dec retention-hours)))
+ cleanup-old-tombstones! #'sut/cleanup-old-gate-tombstones!]
+ (with-open [_ (semantic.tu/open-metadata! pgvector index-metadata)]
+ (semantic.index-metadata/ensure-control-row-exists! pgvector index-metadata)
+ (let [active-index-id (insert-metadata-with-timestamps! pgvector index-metadata
+ {:table-name "tombstone_cleanup_3test_index"
+ :index-created-at old-time
+ :indexer-last-poll old-time})]
+ (set-active-index! pgvector (:control-table-name index-metadata) active-index-id))
+ (let [{:keys [gate-table-name metadata-table-name]} index-metadata]
+ (testing "when indexer has not run recently, skips cleanup of old tombstone records"
+ (jdbc/execute! pgvector
+ (-> (sql.helpers/insert-into (keyword gate-table-name))
+ (sql.helpers/values
+ [{:id "old-tombstone-1"
+ :model "card"
+ :model_id "321"
+ :updated_at old-time
+ :gated_at old-time
+ :document nil
+ :document_hash nil}])
+ (sql/format :quoted true)))
+ (cleanup-old-tombstones! pgvector index-metadata)
+
+ ;; Verify no records were deleted since indexer hasn't run recently
+ (let [remaining-records (jdbc/execute! pgvector
+ (-> (sql.helpers/select [:*])
+ (sql.helpers/from (keyword gate-table-name))
+ (sql.helpers/order-by :id)
+ (sql/format :quoted true))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ remaining-ids (map :id remaining-records)]
+ (is (contains? (set remaining-ids) "old-tombstone-1"))))
+
+ (testing "when indexer has run recently, cleans up old tombstone records and preserves recent ones and non-tombstones"
+ ;; Update metadata for active index to have recent indexer_last_poll time
+ (let [active-index-metadata (semantic.index-metadata/get-active-index-state pgvector index-metadata)]
+ (jdbc/execute! pgvector
+ (-> {:update (keyword metadata-table-name)
+ :set {:indexer_last_poll recent-time}
+ :where [:= :id (-> active-index-metadata :metadata-row :id)]}
+ (sql/format :quoted true))))
+ (let [gate-table-name (:gate-table-name index-metadata)]
+ (jdbc/execute! pgvector
+ (-> (sql.helpers/insert-into (keyword gate-table-name))
+ (sql.helpers/values
+ [{:id "old-tombstone-2"
+ :model "card"
+ :model_id "123"
+ :updated_at old-time
+ :gated_at old-time
+ :document nil
+ :document_hash nil}
+ {:id "old-tombstone-3"
+ :model "dashboard"
+ :model_id "456"
+ :updated_at old-time
+ :gated_at old-time
+ :document nil
+ :document_hash nil}
+ {:id "recent-tombstone"
+ :model "card"
+ :model_id "789"
+ :updated_at recent-time
+ :gated_at recent-time
+ :document nil
+ :document_hash nil}
+ {:id "non-tombstone"
+ :model "card"
+ :model_id "101"
+ :updated_at old-time
+ :gated_at old-time
+ :document (doto (PGobject.)
+ (.setType "jsonb")
+ (.setValue (json/encode {:content "some content"})))
+ :document_hash "hash123"}])
+ (sql/format :quoted true)))
+ (cleanup-old-tombstones! pgvector index-metadata)
+
+ ;; Verify only old tombstones were deleted after cleanup task runs
+ (let [remaining-records (jdbc/execute! pgvector
+ (-> (sql.helpers/select [:*])
+ (sql.helpers/from (keyword gate-table-name))
+ (sql.helpers/order-by :id)
+ (sql/format :quoted true))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})
+ remaining-ids (map :id remaining-records)]
+ (is (= #{"recent-tombstone" "non-tombstone"} (set remaining-ids)))))))))))
diff --git a/test/metabase/warehouse_schema/api/table_test.clj b/test/metabase/warehouse_schema/api/table_test.clj
index ba93cb79458..5596547dca5 100644
--- a/test/metabase/warehouse_schema/api/table_test.clj
+++ b/test/metabase/warehouse_schema/api/table_test.clj
@@ -5,6 +5,7 @@
[clojure.test :refer :all]
[metabase.api.response :as api.response]
[metabase.api.test-util :as api.test-util]
+ [metabase.driver :as driver]
[metabase.driver.util :as driver.u]
[metabase.events.core :as events]
[metabase.permissions.models.data-permissions :as data-perms]