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
Dwh gc parallel (#81382)
Ben Grabow2bfd3189076e
diff --git a/.github/workflows/test.cleanup-dwh-data.yml b/.github/workflows/test.cleanup-dwh-data.ymlindex 66db86572de..25a4c893e32 100644--- a/.github/workflows/test.cleanup-dwh-data.yml+++ b/.github/workflows/test.cleanup-dwh-data.yml@@ -39,7 +39,7 @@ jobs:name: Sweep orphaned test dataif: ${{ github.repository == 'metabase/metabase' }}runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}- timeout-minutes: 20+ timeout-minutes: 60env:CI: 'true'# Snowflakediff --git a/modules/drivers/redshift/test/metabase/test/data/redshift.clj b/modules/drivers/redshift/test/metabase/test/data/redshift.cljindex 67d464717fc..6b48cd94c54 100644--- a/modules/drivers/redshift/test/metabase/test/data/redshift.clj+++ b/modules/drivers/redshift/test/metabase/test/data/redshift.clj@@ -13,6 +13,7 @@[clojure.java.jdbc :as jdbc][clojure.string :as str][clojure.test :refer :all]+ [com.climate.claypoole :as cp][java-time.api :as t][metabase.driver :as driver][metabase.driver.ddl.interface :as ddl.i]@@ -304,37 +305,46 @@(catch Exception e(fallback e))))+(defn- with-gc-pool!+ "Map `f` over every cluster+database at once. They are separate servers -- waiting on them one at a time made the+ sweep cost the sum of their latencies rather than the worst of them."+ [f]+ (let [servers (gc-connection-details)]+ (cp/with-shutdown! [pool (cp/threadpool (count servers))]+ (doall (cp/pmap pool f servers)))))+(defmethod tx/gc-orphans! :redshift[driver {:keys [temp-data-hours]}];; Redshift schema names carry their own creation time, so we scan for age via the name(into []- (mapcat (fn [details]- (let [server (server-label details)]- (with-gc-connection- driver details- (fn [^java.sql.Connection conn]- (with-open [stmt (.createStatement conn)]- (mapv #(assoc % :server server)- (drop-orphan-schemas! stmt (orphan-schemas conn temp-data-hours)))))- (fn [e]- [{:server server, :name nil, :status :failed, :error (ex-message e)}])))))- (gc-connection-details)))+ cat+ (with-gc-pool!+ (fn [details]+ (let [server (server-label details)]+ (with-gc-connection+ driver details+ (fn [^java.sql.Connection conn]+ (with-open [stmt (.createStatement conn)]+ (mapv #(assoc % :server server)+ (drop-orphan-schemas! stmt (orphan-schemas conn temp-data-hours)))))+ (fn [e]+ [{:server server, :name nil, :status :failed, :error (ex-message e)}])))))))(defmethod tx/count-datasets :redshift[driver](into {}- (map (fn [details]- (let [server (server-label details)]- [server (with-gc-connection- driver details- ;; every schema on the cluster, catalog schemas included: the number worth watching is- ;; total pressure toward the max-tables limit, not our share of it- (fn [^java.sql.Connection conn]- (reduce (fn [n _] (inc n)) 0 (fetch-schemas conn)))- (fn [e]- (log/errorf "[redshift] could not count schemas on %s: %s" server (ex-message e))- nil))])))- (gc-connection-details)))+ (with-gc-pool!+ (fn [details]+ (let [server (server-label details)]+ [server (with-gc-connection+ driver details+ ;; every schema on the cluster, catalog schemas included: the number worth watching is+ ;; total pressure toward the max-tables limit, not our share of it+ (fn [^java.sql.Connection conn]+ (reduce (fn [n _] (inc n)) 0 (fetch-schemas conn)))+ (fn [e]+ (log/errorf "[redshift] could not count schemas on %s: %s" server (ex-message e))+ nil))])))))(defn- create-session-schema! [^java.sql.Connection conn](with-open [stmt (.createStatement conn)]diff --git a/modules/drivers/snowflake/test/metabase/test/data/snowflake.clj b/modules/drivers/snowflake/test/metabase/test/data/snowflake.cljindex 91bd9519ebf..7cee6a22931 100644--- a/modules/drivers/snowflake/test/metabase/test/data/snowflake.clj+++ b/modules/drivers/snowflake/test/metabase/test/data/snowflake.clj@@ -2,6 +2,7 @@(:require[clojure.java.jdbc :as jdbc][clojure.string :as str]+ [com.climate.claypoole :as cp][metabase.driver :as driver][metabase.driver.sql-jdbc.connection :as sql-jdbc.conn][metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]@@ -157,27 +158,75 @@(with-open [stmt (.createStatement conn)](apply f stmt args)))))+(def ^:private drop-workers+ "Connections used to drop databases at once. Each `DROP DATABASE` is a round trip of roughly half a second and a+ backlog runs to thousands, which is what overran the job's first real run. Snowflake caps a session at 8 concurrent+ statements by default, so more workers than this buys queueing, not throughput."+ 8)++(def ^:private untrack-batch-size+ "Names per `DELETE` when clearing tracking rows. Snowflake locks the whole table for DML, so this is one statement+ at a time by design -- the win is round trips, not concurrency."+ 500)++(defn- drop-one!+ [^java.sql.Statement stmt dataset-name]+ #_{:clj-kondo/ignore [:discouraged-var]}+ (println "[Snowflake] Deleting old dataset:" dataset-name)+ (try+ (.execute stmt (format "DROP DATABASE IF EXISTS \"%s\";" dataset-name))+ {:name dataset-name, :status :deleted}+ ;; usually just another job deleting the same dataset at the same time+ (catch Exception e+ {:name dataset-name, :status :failed, :error (ex-message e)})))++(defn- drop-chunk!+ "Drop one worker's share on a connection of its own: a JDBC Statement cannot be shared across threads, and+ reconnecting per database would cost more than the drop does."+ [dataset-names]+ (with-write-stmt!+ (fn [^java.sql.Statement stmt]+ (mapv #(drop-one! stmt %) dataset-names))))++(defn- untrack!+ "Forget these databases. Kept out of the workers: every row lives in one table, and Snowflake serializes DML on a+ table, so per-database deletes would have undone the parallelism they ran alongside."+ [dataset-names]+ (doseq [batch (partition-all untrack-batch-size dataset-names)]+ (jdbc/execute! (no-db-connection-spec)+ (into [(format "delete from metabase_test_tracking.PUBLIC.datasets where name in (%s)"+ (str/join "," (repeat (count batch) "?")))]+ batch))))+(defn- drop-datasets!- "Drop each named test database and un-track it, reporting per database whether it went. See [[tx/gc-orphans!]] for- the shape."+ "Un-track each named test database and then drop it, reporting per database whether it went. See [[tx/gc-orphans!]]+ for the shape.++ Un-tracking comes first so that being killed partway -- the GitHub job hitting its timeout -- leaves recoverable+ state. A database that is present but untracked is collected again by the next sweep, which ages an untracked+ `sha_` database from `created`, necessarily older than the `accessed_at` that made it eligible here. Dropping+ first would instead strand tracking rows for databases that no longer exist, and the sweep enumerates from+ `information_schema`, so it would never revisit them and the table would grow without bound.++ Each `DROP DATABASE IF EXISTS` is atomic and idempotent on its own, so no individual delete can be torn in half+ and the parallelism costs nothing in recoverability."[dataset-names];; nothing to drop is the common case on a healthy night; don't open a connection to discover that(if (empty? dataset-names)[]- (with-write-stmt!- (fn [^java.sql.Statement stmt]- (mapv (fn [dataset-name]- #_{:clj-kondo/ignore [:discouraged-var]}- (println "[Snowflake] Deleting old dataset:" dataset-name)- (try- (.execute stmt (format "DROP DATABASE IF EXISTS \"%s\";" dataset-name))- (.execute stmt (format "delete from metabase_test_tracking.PUBLIC.datasets where name = '%s';"- dataset-name))- {:name dataset-name, :status :deleted}- ;; usually just another job deleting the same dataset at the same time- (catch Exception e- {:name dataset-name, :status :failed, :error (ex-message e)})))- dataset-names)))))+ (if-let [untrack-error (try+ (untrack! dataset-names)+ nil+ (catch Exception e (ex-message e)))]+ ;; dropping anyway would strand exactly the rows we failed to clear, so drop nothing+ [{:name nil+ :status :failed+ :error (format "could not clear tracking rows for %d database(s), so dropped none of them: %s"+ (count dataset-names) untrack-error)}]+ (let [chunks (partition-all (max 1 (long (Math/ceil (/ (count dataset-names) (double drop-workers)))))+ dataset-names)]+ (cp/with-shutdown! [pool (cp/threadpool (min drop-workers (count chunks)))]+ (into [] cat (doall (cp/pmap pool drop-chunk! chunks))))))));;; --------------------------------- Orphan GC ----------------------------------;;;diff --git a/test/metabase/test/data/gc.clj b/test/metabase/test/data/gc.cljindex a339aa69bcb..d02abd0c5cc 100644--- a/test/metabase/test/data/gc.clj+++ b/test/metabase/test/data/gc.clj@@ -3,6 +3,7 @@(:require[clojure.java.io :as io][clojure.string :as str]+ [com.climate.claypoole :as cp][metabase.test.data.interface :as tx][metabase.util.json :as json][metabase.util.log :as log]))@@ -35,28 +36,58 @@(str/split (or drivers "") #",")))default-drivers))+(defn- census+ "Datasets on each of a driver's servers, best effort: a count we cannot take must not cost us the sweep.++ Runs on its own thread, which is why the skip is bound here rather than around the whole job: a `binding` does not+ reach pool threads, and losing it would let Redshift's before-run hook create the very session schema this job+ would then leak nightly."+ [driver]+ (binding [tx/*skip-before-run?* true]+ (try+ (tx/count-datasets driver)+ (catch Exception e+ (log/errorf "[%s] could not count datasets: %s" (name driver) (ex-message e))+ {}))))++(defn- log-census!+ "One line per driver before anything is deleted, so a run that is killed partway still says what it was up against."+ [driver->counts]+ (doseq [[driver counts] driver->counts]+ (log/infof "[%s] %s dataset(s) before sweep%s"+ (name driver)+ (if (empty? counts) "unknown" (reduce + 0 (remove nil? (vals counts))))+ (if (empty? counts)+ ""+ (str " — " (str/join ", " (for [[server n] (sort-by key counts)]+ (format "%s: %s" server (if (nil? n) "unknown" n))))))))+ (log/infof "%s dataset(s) before sweep, across %d driver(s)"+ (reduce + 0 (for [counts (vals driver->counts), n (vals counts) :when (some? n)] n))+ (count driver->counts)))+(defn- sweep-driver!"Sweep one driver and take a census of what is left, each best effort. A driver that cannot connect at all, or a- census that fails, must cost neither the other drivers nor the deletions this one did manage."- [driver options]- (let [results (try- (vec (tx/gc-orphans! driver options))- (catch Exception e- [{:name nil, :status :failed, :error (ex-message e)}]))- remaining (try- (tx/count-datasets driver)- (catch Exception e- (log/errorf "[%s] could not count remaining datasets: %s" (name driver) (ex-message e))- {}))- {deleted :deleted, failed :failed} (group-by :status results)]- (log/infof "[%s] %d deleted, %d failed" (name driver) (count deleted) (count failed))- (doseq [{dataset-name :name, :keys [error]} failed]- (log/errorf "[%s] %s: %s" (name driver) (or dataset-name "<server unreachable>") error))- {:driver (name driver)- :deleted (vec deleted)- :failed (vec failed)- :counts {:deleted (count deleted), :failed (count failed)}- :remaining remaining}))+ census that fails, must cost neither the other drivers nor the deletions this one did manage.++ `before` is this driver's pre-sweep census, passed in rather than retaken so the report's before and after come+ from the same numbers the log reported."+ [driver before options]+ (binding [tx/*skip-before-run?* true]+ (let [results (try+ (vec (tx/gc-orphans! driver options))+ (catch Exception e+ [{:name nil, :status :failed, :error (ex-message e)}]))+ remaining (census driver)+ {deleted :deleted, failed :failed} (group-by :status results)]+ (log/infof "[%s] %d deleted, %d failed" (name driver) (count deleted) (count failed))+ (doseq [{dataset-name :name, :keys [error]} failed]+ (log/errorf "[%s] %s: %s" (name driver) (or dataset-name "<server unreachable>") error))+ {:driver (name driver)+ :deleted (vec deleted)+ :failed (vec failed)+ :counts {:deleted (count deleted), :failed (count failed)}+ :before before+ :remaining remaining})))(defn- build-report[options driver-reports]@@ -88,13 +119,16 @@(when (and error (or server dataset-name)) ": ")error))-(defn- render-driver [{:keys [driver counts remaining deleted failed]}]+(defn- render-driver [{:keys [driver counts before remaining deleted failed]}](str (format "### %s — %d deleted, %d failed\n\n" driver (:deleted counts) (:failed counts))(if (empty? remaining)- "Remaining datasets: unknown\n\n"- (str "Remaining datasets:\n\n"+ "Datasets: unknown\n\n"+ (str "Datasets, before and after:\n\n"(str/join "\n" (for [[server n] (sort-by key remaining)]- (format "- `%s`: %s" server (if (nil? n) "unknown" n))))+ (format "- `%s`: %s → %s"+ server+ (let [b (get before server)] (if (nil? b) "unknown" b))+ (if (nil? n) "unknown" n))))"\n\n"))(render-names "Deleted" deleted render-object)(render-names "Failed" failed render-object)))@@ -139,14 +173,17 @@(throw (ex-info (format "%s must be a whole number of hours >= %d; refusing to sweep with %s"k floor (pr-str v)){:option k, :value v}))))- ;; we want the extensions, not their before-run hooks: Redshift's creates a session schema, which this job would- ;; then leak nightly- (binding [tx/*skip-before-run?* true]- (let [report (build-report options (mapv #(sweep-driver! % options) (parse-drivers drivers)))]- ;; write before throwing: the report is most wanted on the runs that fail- (write-report! report (or report-dir default-report-dir))- ;; fail loudly rather than going green having deleted nothing- (when (pos? (get-in report [:totals :failed]))- (throw (ex-info (format "%d object(s) could not be deleted"- (get-in report [:totals :failed]))- {:errors (into [] (comp (mapcat :failed) (map :error)) (:drivers report))})))))))+ (let [swept (let [ds (parse-drivers drivers)]+ ;; drivers share nothing, so the job costs the slowest one rather than the sum of all three+ (cp/with-shutdown! [pool (cp/threadpool (count ds))]+ (let [before (zipmap ds (doall (cp/pmap pool census ds)))]+ (log-census! before)+ (doall (cp/pmap pool #(sweep-driver! % (get before %) options) ds)))))+ report (build-report options swept)]+ ;; write before throwing: the report is most wanted on the runs that fail+ (write-report! report (or report-dir default-report-dir))+ ;; fail loudly rather than going green having deleted nothing+ (when (pos? (get-in report [:totals :failed]))+ (throw (ex-info (format "%d object(s) could not be deleted"+ (get-in report [:totals :failed]))+ {:errors (into [] (comp (mapcat :failed) (map :error)) (:drivers report))}))))))