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
[perf] Add `lib.computed`, optimize wide tables and deep user queries (#65364)
Braden Shepherdson1217fca9a4b2
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex cb045e42545..b7cf45820c4 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -605,6 +605,7 @@:api #{metabase.lib.binningmetabase.lib.binning.utilmetabase.lib.card+ metabase.lib.computed ; temporarily so that `qp.compile` can use it as lib memoization evolvesmetabase.lib.coremetabase.lib.equalitymetabase.lib.fielddiff --git a/src/metabase/lib/aggregation.cljc b/src/metabase/lib/aggregation.cljcindex 7104d94f44d..13b50a3f57d 100644--- a/src/metabase/lib/aggregation.cljc+++ b/src/metabase/lib/aggregation.cljc@@ -3,6 +3,7 @@(:require[medley.core :as m][metabase.lib.common :as lib.common]+ [metabase.lib.computed :as lib.computed][metabase.lib.dispatch :as lib.dispatch][metabase.lib.equality :as lib.equality][metabase.lib.hierarchy :as lib.hierarchy]@@ -45,6 +46,7 @@(resolve-aggregation-by-name query stage-number (aggregations query stage-number) ag-name))([query stage-number ags ag-name :- :string]+ ;; PERF: Index these by name on the stage?(m/find-first(fn [aggregation](= (lib.metadata.calculation/column-name query stage-number aggregation) ag-name))@@ -82,19 +84,25 @@[querystage-number[_ag {:keys [base-type effective-type display-name], agg-name :name, :as _opts} _uuid, :as ag-ref]]- (let [aggregation (resolve-aggregation query stage-number ag-ref)]- (merge- (lib.metadata.calculation/metadata query stage-number aggregation)- {:lib/source :source/aggregations- :lib/source-uuid (:lib/uuid (second aggregation))}- (when base-type- {:base-type base-type})- (when effective-type- {:effective-type effective-type})- (when agg-name- {:name agg-name})- (when display-name- {:display-name display-name}))))+ ;; PERF: This could be split into two, separately-cache operations: One for the underlying aggregation's metadata+ ;; and one for the remix created by the ref's customized `:display-name` etc.+ ;; Note that there's cache eviction issues with indexing just by the UUID here - it needs to be the whole ref.+ (lib.computed/with-cache-ephemeral* query [:aggregation-metadata/by-ref stage-number ag-ref]+ (fn []+ (let [aggregation (resolve-aggregation query stage-number ag-ref)]+ (merge+ (lib.metadata.calculation/metadata query stage-number aggregation)+ {:lib/source :source/aggregations+ :lib/source-uuid (:lib/uuid (second aggregation))}++ (when base-type+ {:base-type base-type})+ (when effective-type+ {:effective-type effective-type})+ (when agg-name+ {:name agg-name})+ (when display-name+ {:display-name display-name}))))));;; TODO -- merge this stuff into `defop` somehow.diff --git a/src/metabase/lib/card.cljc b/src/metabase/lib/card.cljcindex 031c2eb346d..816dae2cd48 100644--- a/src/metabase/lib/card.cljc+++ b/src/metabase/lib/card.cljc@@ -3,6 +3,7 @@(:require[medley.core :as m][metabase.lib.binning :as lib.binning]+ [metabase.lib.computed :as lib.computed][metabase.lib.field.util :as lib.field.util][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation]@@ -251,18 +252,21 @@_stage-number :- :intcard :- ::lib.schema.metadata/cardoptions :- [:maybe ::lib.metadata.calculation/returned-columns.options]]- (mapv (fn [col]- (assoc col :lib/source :source/card, :lib/card-id (:id card)))- (if (= (:type card) :metric)- (let [metric-query (-> card- :dataset-query- (lib.util/update-query-stage -1 dissoc :aggregation :breakout))]- (lib.metadata.calculation/returned-columns- (assoc metric-query :lib/metadata (:lib/metadata query))- -1- (lib.util/query-stage metric-query -1)- options))- (card-returned-columns query card))))+ (lib.computed/with-cache-sticky* query+ [::returned-columns (:id card) (lib.metadata.calculation/cacheable-options options)]+ (fn []+ (mapv (fn [col]+ (assoc col :lib/source :source/card, :lib/card-id (:id card)))+ (if (= (:type card) :metric)+ (let [metric-query (-> card+ :dataset-query+ (lib.util/update-query-stage -1 dissoc :aggregation :breakout))]+ (lib.metadata.calculation/returned-columns+ (assoc metric-query :lib/metadata (:lib/metadata query))+ -1+ (lib.util/query-stage metric-query -1)+ options))+ (card-returned-columns query card))))))(mu/defn source-card-type :- [:maybe ::lib.schema.metadata/card.type]"The type of the query's source-card, if it has one."diff --git a/src/metabase/lib/computed.cljc b/src/metabase/lib/computed.cljcnew file mode 100644index 00000000000..f08ba95b168--- /dev/null+++ b/src/metabase/lib/computed.cljc@@ -0,0 +1,102 @@+(ns metabase.lib.computed+ "A first cut at smarter, more granular memoization of derived data about queries.++ Only a corner of the vision is implemented here so far, it's expanding as needed in response to user perf issues."+ (:require+ [metabase.util :as u]+ [metabase.util.log :as log]))++(def ^:private weak-map+ "A global weak map using queries as keys. Since CLJ(S) maps are immutable, if the map changes it is a new pointer,+ and hence a new cache key. Since the keys of a weak map are weakly held, the map entries will be GC'd when the query+ is, avoiding any extra memory retention."+ #?(:clj (java.util.Collections/synchronizedMap (java.util.WeakHashMap.))+ :cljs (js/WeakMap.)))++(def ^:dynamic *computed-cache*+ "Dynamic var that holds an atom used for caching derived values for [[with-cache-sticky*]].++ `nil` by default, meaning would-be sticky values are actually cached in the weak map, keyed by query. That's more+ ephemeral than they're declared to be, but it's better than nothing.++ It is always safe, in terms of correctness, to bind this to an `(atom {})` before making lib calls, even with+ multiple queries and edits to queries. This atom is used by [[with-cache-sticky*]], which is only used for+ \"global\" things that apply across queries, like the metadata or columns of a card.++ However, there is no LRU or other eviction logic, and so the memory use will continue to grow as it is held.+ The best approach is to bind this var around a well-defined chunk of related lib calls like `qp.preprocess`.++ Soon this limitation should be removed by making queries `map`-likes with a private atom and evict-on-update."+ nil)++(defn- weak-atoms [query]+ #?(:clj (.computeIfAbsent ^java.util.WeakHashMap weak-map query+ (fn [_]+ {:sticky (atom {})+ :weak (atom {})}))+ :cljs (if (.has weak-map query)+ (.get weak-map query)+ (let [m {:sticky (atom {})+ :weak (atom {})}]+ (.set weak-map query m)+ m))))++(defn ^:dynamic *cache-hit-hook*+ "A function `(f cache-key)` called whenever the sticky or ephemeral caches are hit.++ Can be overridden for testing. The default just does a [[log/debug]]."+ [cache-key]+ (log/debug (str (u/colorize :green "HIT: ") (name (first cache-key)) " " (hash (rest cache-key)))))++(defn ^:dynamic *cache-miss-hook*+ "A function `(f cache-key)` called whenever the sticky or ephemeral caches are missed.++ Can be overridden for testing. The default just does a [[log/debug]]."+ [cache-key]+ (log/debug (str (u/colorize :red "MISS: ") (name (first cache-key)) " " (hash (rest cache-key)))))++(defn- cache-through [*atom cache-key f]+ (let [output (get-in @*atom cache-key ::not-found)]+ (if (not= output ::not-found)+ (do (*cache-hit-hook* cache-key)+ output)+ (let [output (f)]+ (swap! *atom assoc-in cache-key output)+ (*cache-miss-hook* cache-key)+ output))))++(defn with-cache-none*+ "A dummy cache function that doesn't actually cache anything, but has the same interface as [[with-cache-sticky*]]+ and friends.++ This is useful for debugging test failures, to see if a particular instance of caching is what's breaking your test.++ It always misses, running the input function every time."+ [_query _cache-key f]+ (f))++;; TODO: Put a macro around this for convenience.+(defn with-cache-sticky*+ "Implements the [[with-cache]] macro.++ Returns the cached value at `cache-key` (a path). If the value doesn't exist yet, runs the factory function and+ caches the value.++ When [[*computed-cache*]] is bound to an atom, these values persist as long as that atom. When [[*computed-cache*]]+ is not set, this uses the same weak map on queries as [[with-cache-ephemeral*]], which is more fragile but better+ than not caching at all.++ No eviction, these values last as long as [[*computed-cache*]] does."+ [query cache-key f]+ (cache-through (or *computed-cache* (-> query weak-atoms :sticky)) cache-key f))++;; TODO: Put a macro around this for convenience.+(defn with-cache-ephemeral*+ "Implements the [[with-cache]] macro.++ Returns the cached value at `cache-key` (a path). If the value doesn't exist yet, runs the factory function and+ caches the value.++ Bound to a weak map using the query as a key, so all cached values are forgotten and GC'd when a query is updated."+ [query cache-key f]+ (cache-through (-> query weak-atoms :weak) cache-key f))diff --git a/src/metabase/lib/expression.cljc b/src/metabase/lib/expression.cljcindex ab3c12401aa..434abb6a29a 100644--- a/src/metabase/lib/expression.cljc+++ b/src/metabase/lib/expression.cljc@@ -6,6 +6,7 @@[malli.core :as mc][medley.core :as m][metabase.lib.common :as lib.common]+ [metabase.lib.computed :as lib.computed][metabase.lib.hierarchy :as lib.hierarchy][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation]@@ -72,10 +73,7 @@(when (lib.util/first-stage? query stage-number)(when-let [source-card-id (lib.util/source-card-id query)](when-let [source-card (lib.metadata/card query source-card-id)]- (u/prog1 (resolve-expression ((#?(:clj requiring-resolve :cljs resolve) 'metabase.lib.query/query)- (lib.metadata/->metadata-provider query)- (:dataset-query source-card))- expression-name)+ (u/prog1 (resolve-expression (:dataset-query source-card) expression-name)(when <>(log/warnf "Found expression %s in source card %d. Next time, use a :field name ref!"(pr-str expression-name) source-card-id))))))@@ -91,21 +89,24 @@(mu/defmethod lib.metadata.calculation/metadata-method :expression :- ::lib.metadata.calculation/visible-column[query stage-number [_expression opts expression-name, :as expression-ref-clause]]- (merge {:lib/type :metadata/column- ;; TODO (Cam 8/7/25) -- is the source UUID of an expression ref supposed to be the ID of the ref, or the ID- ;; of the expression definition??- :lib/source-uuid (:lib/uuid opts)- :name expression-name- :lib/expression-name expression-name- :lib/source-column-alias expression-name- :display-name (lib.metadata.calculation/display-name query stage-number expression-ref-clause)- :base-type (lib.metadata.calculation/type-of query stage-number expression-ref-clause)- :lib/source :source/expressions}- (when-let [unit (lib.temporal-bucket/raw-temporal-bucket expression-ref-clause)]- {:metabase.lib.field/temporal-unit unit})- (when lib.metadata.calculation/*propagate-binning-and-bucketing*- (when-let [unit (lib.temporal-bucket/raw-temporal-bucket expression-ref-clause)]- {:inherited-temporal-unit unit}))))+ (lib.computed/with-cache-ephemeral* query [:expression-metadata/by-ref stage-number expression-ref-clause+ (lib.metadata.calculation/cacheable-options {})]+ (fn []+ (merge {:lib/type :metadata/column+ ;; TODO (Cam 8/7/25) -- is the source UUID of an expression ref supposed to be the ID of the ref, or the ID+ ;; of the expression definition??+ :lib/source-uuid (:lib/uuid opts)+ :name expression-name+ :lib/expression-name expression-name+ :lib/source-column-alias expression-name+ :display-name (lib.metadata.calculation/display-name query stage-number expression-ref-clause)+ :base-type (lib.metadata.calculation/type-of query stage-number expression-ref-clause)+ :lib/source :source/expressions}+ (when-let [unit (lib.temporal-bucket/raw-temporal-bucket expression-ref-clause)]+ {:metabase.lib.field/temporal-unit unit})+ (when lib.metadata.calculation/*propagate-binning-and-bucketing*+ (when-let [unit (lib.temporal-bucket/raw-temporal-bucket expression-ref-clause)]+ {:inherited-temporal-unit unit}))))))(defmethod lib.temporal-bucket/available-temporal-buckets-method :expression[query stage-number [_expression opts _expr-name, :as expr-clause]]@@ -243,8 +244,8 @@(defmethod lib.metadata.calculation/type-of-method :coalesce[query stage-number [_coalesce _opts expr null-expr]]- (let [expr-type (lib.metadata.calculation/type-of-method query stage-number expr)- null-expr-type (lib.metadata.calculation/type-of-method query stage-number null-expr)]+ (let [expr-type (lib.metadata.calculation/type-of query stage-number expr)+ null-expr-type (lib.metadata.calculation/type-of query stage-number null-expr)](lib.schema.expression.conditional/case-coalesce-return-type [expr-type null-expr-type])));;; believe it or not, a `:case` clause really has the syntax [:case {} [[pred1 expr1] [pred2 expr2] ...]]@@ -258,7 +259,7 @@exprs (cond-> case-exprsfallback(clojure.core/concat [fallback]))- types (map #(lib.metadata.calculation/type-of-method query stage-number %)+ types (map #(lib.metadata.calculation/type-of query stage-number %)exprs)](lib.schema.expression.conditional/case-coalesce-return-type types)))diff --git a/src/metabase/lib/field.cljc b/src/metabase/lib/field.cljcindex 8b918ed28a5..ea9d75f63b1 100644--- a/src/metabase/lib/field.cljc+++ b/src/metabase/lib/field.cljc@@ -6,6 +6,7 @@[medley.core :as m][metabase.lib.aggregation :as lib.aggregation][metabase.lib.binning :as lib.binning]+ [metabase.lib.computed :as lib.computed][metabase.lib.dispatch :as lib.dispatch][metabase.lib.equality :as lib.equality][metabase.lib.expression :as lib.expression]@@ -26,6 +27,7 @@[metabase.lib.temporal-bucket :as lib.temporal-bucket][metabase.lib.types.isa :as lib.types.isa][metabase.lib.util :as lib.util]+ [metabase.lib.walk :as lib.walk][metabase.util :as u][metabase.util.humanization :as u.humanization][metabase.util.i18n :as i18n]@@ -77,6 +79,30 @@(when (every? some? path)(str/join ": " path))))+(defn- clauses-in-stage-by-uuid+ [query stage-number]+ (lib.computed/with-cache-ephemeral* query [::clauses-in-stage-by-uuid stage-number]+ (fn []+ (let [sink (volatile! (transient {}))]+ (lib.walk/walk-clauses-in-stage+ (lib.util/query-stage query stage-number)+ (fn [clause]+ (when-let [lib-uuid (lib.options/uuid clause)]+ (vswap! sink assoc! lib-uuid clause))+ nil))+ (persistent! @sink)))))++(defn- find-stage-index-and-clause-by-uuid+ "Find the clause in `query` with the given `lib-uuid`. Return a [stage-index clause] pair, if found."+ [query stage-number lib-uuid]+ (let [max-stage (lib.util/canonical-stage-index query stage-number)]+ (loop [stage-number 0]+ (if (> stage-number max-stage)+ nil+ (if-let [clause (get (clauses-in-stage-by-uuid query stage-number) lib-uuid)]+ [stage-number clause]+ (recur (inc stage-number)))))))+(defn- field-display-name-initial-display-name[querystage-number@@ -117,7 +143,7 @@(not (or fk-field-id join-alias))(not (str/includes? field-display-name " → "))(when-let [previous-stage-number (lib.util/previous-stage-number query stage-number)]- (lib.util/find-stage-index-and-clause-by-uuid query previous-stage-number source-uuid)))]+ (find-stage-index-and-clause-by-uuid query previous-stage-number source-uuid)))];; The :display-name from the field metadata is probably not a :long display name, so;; if the caller requested a :long name and we can lookup the original clause by the;; source-uuid, use that to get the :long name. This allows display-info to get thediff --git a/src/metabase/lib/metadata.cljc b/src/metabase/lib/metadata.cljcindex e57a059d823..267f4718591 100644--- a/src/metabase/lib/metadata.cljc+++ b/src/metabase/lib/metadata.cljc@@ -2,6 +2,7 @@(:refer-clojure :exclude [every? empty? #?(:clj doseq) #?(:clj for)])(:require[medley.core :as m]+ [metabase.lib.computed :as lib.computed][metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id]@@ -152,8 +153,10 @@"Get metadata for a Card, aka Saved Question, with `card-id`, if it can be found."[metadata-providerable :- ::lib.schema.metadata/metadata-providerablecard-id :- ::lib.schema.id/card]- (some-> (lib.metadata.protocols/card (->metadata-provider metadata-providerable) card-id)- (m/update-existing :dataset-query normalize-query metadata-providerable)))+ (lib.computed/with-cache-sticky* metadata-providerable [:metadata/card card-id :metadata]+ (fn []+ (some-> (lib.metadata.protocols/card (->metadata-provider metadata-providerable) card-id)+ (m/update-existing :dataset-query normalize-query metadata-providerable)))))(mu/defn native-query-snippet :- [:maybe ::lib.schema.metadata/native-query-snippet]"Get metadata for a NativeQuerySnippet with `snippet-id` if it can be found."diff --git a/src/metabase/lib/metadata/cached_provider.cljc b/src/metabase/lib/metadata/cached_provider.cljcindex 3bccb3d5aaa..d0cbd65e3bf 100644--- a/src/metabase/lib/metadata/cached_provider.cljc+++ b/src/metabase/lib/metadata/cached_provider.cljc@@ -112,7 +112,7 @@(u/prog1 (lib.metadata.protocols/metadatas uncached-provider metadata-spec)(doseq [metadata <>k [:id :name]]- (store-in-cache! cache [metadata-type (k metadata)] metadata)))))))+ (store-in-cache! cache [metadata-type k (k metadata)] metadata)))))))(defn- cached-metadatas [cache metadata-type metadata-ids](into []diff --git a/src/metabase/lib/metadata/calculation.cljc b/src/metabase/lib/metadata/calculation.cljcindex e8129240d53..83edea9621e 100644--- a/src/metabase/lib/metadata/calculation.cljc+++ b/src/metabase/lib/metadata/calculation.cljc@@ -5,6 +5,7 @@:cljs [metabase.lib.cache :as lib.cache])[clojure.string :as str][medley.core :as m]+ [metabase.lib.computed :as lib.computed][metabase.lib.dispatch :as lib.dispatch][metabase.lib.field.util :as lib.field.util][metabase.lib.hierarchy :as lib.hierarchy]@@ -108,7 +109,11 @@:cljs-dev true:cljs-release false)(log/warnf "Don't know how to calculate display name for %s. Add an impl for %s for %s"- (pr-str x)+ ;; TODO: (Braden 11/04/2025) This logic would make sense in [[metabase.util]].+ (let [s (pr-str x)]+ (if (> (count s) 2000)+ (str (subs s 0 1500) " ... " (subs s (- (count s) 500)))+ s))`display-name-method(lib.dispatch/dispatch-value x)))(if (and (vector? x)@@ -207,12 +212,14 @@;; otherwise if `:base-type` is specified, we can return that.(:base-type options);; if none of the special cases are true, fall back to [[type-of-method]].- (let [calculated-type (type-of-method query stage-number x)]- ;; if calculated type is not a true type but a placeholder like `:metabase.lib.schema.expression/type.unknown`- ;; or a union of types then fall back to `:type/*`, an actual type.- (if (isa? calculated-type :type/*)- calculated-type- :type/*))))))+ (lib.computed/with-cache-ephemeral* query [:expression-types/by-clause stage-number x]+ (fn []+ (let [calculated-type (type-of-method query stage-number x)]+ ;; if calculated type is not a true type but a placeholder like `:metabase.lib.schema.expression/type.unknown`+ ;; or a union of types then fall back to `:type/*`, an actual type.+ (if (isa? calculated-type :type/*)+ calculated-type+ :type/*))))))))(defmethod type-of-method :default[_query _stage-number expr]@@ -232,16 +239,20 @@;; Otherwise, just get the type of this first arg.(type-of query stage-number expr)))-(defn- cache-key+(defn cacheable-options+ "Includes some dynamic variables etc. in the `options` so the `[[returned-columns]]` can be safely cached."+ [options]+ (assoc options+ ::display-name-style *display-name-style*+ ::propagate-binning-and-bucketing (boolean *propagate-binning-and-bucketing*)+ ::ref-style lib.ref/*ref-style*))++(defn cache-key"Create a cache key to use with [[lib.metadata.cache]]. This includes a few extra keys for the three dynamic variablesthat can affect metadata calculation."[unique-key query stage-number x options](lib.metadata.cache/cache-key- unique-key query stage-number x- (assoc options- ::display-name-style *display-name-style*- ::propagate-binning-and-bucketing (boolean *propagate-binning-and-bucketing*)- ::ref-style lib.ref/*ref-style*)))+ unique-key query stage-number x (cacheable-options options)))(defmulti metadata-method"Impl for [[metadata]]. Implementations that call [[display-name]] should use the `:default` display name style."@@ -550,8 +561,7 @@;; `returned-columns` purposes. As a bonus, this means undocumented options keys that aren't part of the schema;; will effectively be ignored, which sorta forces people to actually go document them.(let [options (select-keys options returned-columns-options-keys)]- (lib.metadata.cache/with-cached-value query (cache-key ::returned-columns query stage-number x options)- (returned-columns-method query stage-number x options))))))+ (returned-columns-method query stage-number x options)))))(mr/def ::visible-column"Schema for a column that should be returned by [[visible-columns]]. A visible column is a column metadata that isdiff --git a/src/metabase/lib/normalize.cljc b/src/metabase/lib/normalize.cljcindex 8bc101704d3..d7d5a83ef02 100644--- a/src/metabase/lib/normalize.cljc+++ b/src/metabase/lib/normalize.cljc@@ -62,6 +62,7 @@(fn [](let [respond identityraise #'*error-fn*] ; capture var rather than the bound value at the time this is eval'ed+ (log/debugf "Building :normalize coercer for schema %s" (pr-str schema))(mc/coercer schema (mtx/transformer mtx/default-value-transformer {:name :normalize}) respond raise)))))(defn normalizediff --git a/src/metabase/lib/pathom/core.cljc b/src/metabase/lib/pathom/core.cljcnew file mode 100644index 00000000000..3a12cf4e079--- /dev/null+++ b/src/metabase/lib/pathom/core.cljc@@ -0,0 +1 @@+(ns metabase.lib.pathom.core)diff --git a/src/metabase/lib/stage.cljc b/src/metabase/lib/stage.cljcindex 48c77f25cef..86dc1842801 100644--- a/src/metabase/lib/stage.cljc+++ b/src/metabase/lib/stage.cljc@@ -5,6 +5,7 @@[clojure.string :as str][metabase.lib.aggregation :as lib.aggregation][metabase.lib.breakout :as lib.breakout]+ [metabase.lib.computed :as lib.computed][metabase.lib.equality :as lib.equality][metabase.lib.expression :as lib.expression][metabase.lib.field.util :as lib.field.util]@@ -296,47 +297,50 @@stage-number :- :int_stage :- ::lib.schema/stage{:keys [include-remaps?], :as options} :- [:maybe ::lib.metadata.calculation/returned-columns.options]]- (or- (existing-stage-metadata query stage-number)- (let [summary-cols (summary-columns query stage-number options)- field-cols (fields-columns query stage-number options)- ;; ... then calculate metadata for this stage- cols (cond- summary-cols- (concat summary-cols field-cols)+ ;; Not including the stage itself in the cache key, since it's not used(!)+ (lib.computed/with-cache-ephemeral* query [::returned-columns stage-number (lib.metadata.calculation/cacheable-options options)]+ (fn []+ (or+ (existing-stage-metadata query stage-number)+ (let [summary-cols (summary-columns query stage-number options)+ field-cols (fields-columns query stage-number options)+ ;; ... then calculate metadata for this stage+ cols (cond+ summary-cols+ (concat summary-cols field-cols)- field-cols- (reduce- (fn [field-cols join]- (add-cols-from-join query stage-number options field-cols join))- field-cols- (lib.join/joins query stage-number))+ field-cols+ (reduce+ (fn [field-cols join]+ (add-cols-from-join query stage-number options field-cols join))+ field-cols+ (lib.join/joins query stage-number))- :else- ;; there is no `:fields` or summary columns (aggregtions or breakouts) which means we return- ;; all the visible columns from the source or previous stage plus all the expressions. We- ;; return only the `:fields` from any joins- (let [;; we don't want to include all visible joined columns, so calculate that separately- source-cols (previous-stage-or-source-visible-columns- query stage-number- {:include-implicitly-joinable? false- :include-remaps? (boolean include-remaps?)})]- (concat- source-cols- (expressions-metadata query stage-number {:include-late-exprs? true})- (lib.metadata.calculation/remapped-columns query stage-number source-cols options)- (lib.join/all-joins-fields-to-add-to-parent-stage query stage-number options))))]- (into []- (comp (lib.field.util/add-source-and-desired-aliases-xform query)- ;; we need to update `:name` to be the deduplicated name here, otherwise viz settings will break (see- ;; longer explanation in [[metabase.lib.stage-test/returned-columns-deduplicate-names-test]]). Only- ;; do this if this is the last stage of the query, just like the QP does! Otherwise we might- ;; accidentally break something else that incorrectly relies on the notoriously unreliable `:name`- ;; key.- (if (lib.util/last-stage? query stage-number)- (map #(assoc % :name (:lib/deduplicated-name %)))- identity))- cols))))+ :else+ ;; there is no `:fields` or summary columns (aggregtions or breakouts) which means we return+ ;; all the visible columns from the source or previous stage plus all the expressions. We+ ;; return only the `:fields` from any joins+ (let [;; we don't want to include all visible joined columns, so calculate that separately+ source-cols (previous-stage-or-source-visible-columns+ query stage-number+ {:include-implicitly-joinable? false+ :include-remaps? (boolean include-remaps?)})]+ (concat+ source-cols+ (expressions-metadata query stage-number {:include-late-exprs? true})+ (lib.metadata.calculation/remapped-columns query stage-number source-cols options)+ (lib.join/all-joins-fields-to-add-to-parent-stage query stage-number options))))]+ (into []+ (comp (lib.field.util/add-source-and-desired-aliases-xform query)+ ;; we need to update `:name` to be the deduplicated name here, otherwise viz settings will break+ ;; (see longer explanation in [[metabase.lib.stage-test/returned-columns-deduplicate-names-test]]).+ ;; Only do this if this is the last stage of the query, just like the QP does! Otherwise we might+ ;; accidentally break something else that incorrectly relies on the notoriously unreliable `:name`+ ;; key.+ (if (lib.util/last-stage? query stage-number)+ (map #(assoc % :name (:lib/deduplicated-name %)))+ identity))+ cols))))))(defmethod lib.metadata.calculation/display-name-method :mbql.stage/native[_query _stage-number _stage _style]diff --git a/src/metabase/lib/util.cljc b/src/metabase/lib/util.cljcindex a3a6670c77f..8cdb784691b 100644--- a/src/metabase/lib/util.cljc+++ b/src/metabase/lib/util.cljc@@ -476,17 +476,6 @@(update :stages #(into [] (take (inc (canonical-stage-index query stage-number))) %)))new-query)))-(defn find-stage-index-and-clause-by-uuid- "Find the clause in `query` with the given `lib-uuid`. Return a [stage-index clause] pair, if found."- ([query lib-uuid]- (find-stage-index-and-clause-by-uuid query -1 lib-uuid))- ([query stage-number lib-uuid]- (first (keep-indexed (fn [idx stage]- (lib.util.match/match-lite-recursive stage- (clause :guard (= lib-uuid (lib.options/uuid clause)))- [idx clause]))- (:stages (drop-later-stages query stage-number))))))-(defn fresh-uuids"Recursively replace all the :lib/uuids in `x` with fresh ones. Useful if you need to attach something to a query morethan once."@@ -511,6 +500,21 @@:elsex)))+(defn fresh-uuids-preserving-aggregation-refs+ "Recursively replace all `:lib/uuid`s on an MBQL structure with fresh ones. Avoids duplicate UUID errors when+ attaching something to a query more than once. This builds on [[fresh-uuids]] to include updating any+ `[:aggregation {} \"uuid\"]` refs to use the corresponding new UUID."+ [query]+ (let [remapping (volatile! (transient {}))+ query (fresh-uuids query (fn [old-uuid new-uuid]+ (vswap! remapping assoc! old-uuid new-uuid)))+ remapping (persistent! @remapping)]+ (lib.util.match/replace query+ [:aggregation opts old-uuid]+ [:aggregation opts (or (remapping old-uuid)+ (throw (ex-info "Could not convert old :aggregation ref to new UUIDs"+ {:aggregation &match})))])))+(mu/defn normalized-query-type :- [:maybe [:enum #_MLv2 :mbql/query #_legacy :query :native #_audit :internal]]"Get the `:lib/type` or `:type` from `query`, even if it is not-yet normalized."[query :- [:maybe :map]]diff --git a/src/metabase/query_processor/middleware/add_remaps.clj b/src/metabase/query_processor/middleware/add_remaps.cljindex 822a8d76dfb..5cf9e742ef9 100644--- a/src/metabase/query_processor/middleware/add_remaps.clj+++ b/src/metabase/query_processor/middleware/add_remaps.clj@@ -238,6 +238,8 @@(apply distinct? remappings)))]]]][:query ::lib.schema/query]])+;; PERF: There's a ton of re-processing of the same fields lists building little indexes, I think that can be consolidated+;; into a more pipelined thing. Not sure how much it buys us, but this is a seriously slow middleware with wide tables.(mu/defn- add-fk-remaps-to-fields :- [:maybe ::lib.schema/fields][infos :- [:maybe [:sequential ::remap-info]]fields :- [:maybe ::lib.schema/fields]]@@ -264,6 +266,7 @@(map (fn [{:keys [original-field-clause new-field-clause]}][(simplify-ref-options original-field-clause) new-field-clause]))infos)+ ;; PERF: More indexing on the same stuff! This really needs to be poured into a common context.new-breakout (add-fk-remaps-rewrite-breakout original->remapped breakout)new-order-by (add-fk-remaps-rewrite-order-by original->remapped order-by)remaps (into []@@ -277,6 +280,7 @@(seq remaps) (assoc ::remaps remaps)));; otherwise return query as-is(cond-> stage+ ;; PERF: This is an edit to the query, busting the caching unnecessarily when there's nothing to remap.(seq previous-stage-remaps) (assoc ::remaps previous-stage-remaps)))))(mu/defn- add-fk-remaps-to-join :- [:maybe ::lib.schema.join/join]diff --git a/src/metabase/query_processor/middleware/fetch_source_query.clj b/src/metabase/query_processor/middleware/fetch_source_query.cljindex b34a2c66492..d7eeb7605d1 100644--- a/src/metabase/query_processor/middleware/fetch_source_query.clj+++ b/src/metabase/query_processor/middleware/fetch_source_query.clj@@ -11,6 +11,7 @@[metabase.lib.schema.common :as lib.schema.common][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata]+ [metabase.lib.util :as lib.util][metabase.lib.walk :as lib.walk][metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.util.persisted-cache :as qp.persisted]@@ -73,6 +74,10 @@(conj (vec (butlast stages)) last-stage)))(update-query [query](-> (lib.query/query metadata-providerable query)+ ;; Now that cards' queries can come out of the AppDB already in MBQL 5, complete with `:lib/uuid`s,+ ;; a card getting joined twice creates duplicate UUID errors!+ ;; This safely re-rolls all the `:lib/uuid`s on the card's query so they won't collide.+ lib.util/fresh-uuids-preserving-aggregation-refs(update :stages update-stages)))](update card :dataset-query update-query))))diff --git a/src/metabase/query_processor/setup.clj b/src/metabase/query_processor/setup.cljindex f8ddeb34e54..963002f16cf 100644--- a/src/metabase/query_processor/setup.clj+++ b/src/metabase/query_processor/setup.clj@@ -6,6 +6,7 @@[metabase.config.core :as config][metabase.driver :as driver][metabase.driver.util :as driver.u]+ [metabase.lib.computed :as lib.computed][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.lib.schema.id :as lib.schema.id]@@ -234,7 +235,8 @@(middleware f))fsetup-middleware)]- (binding [*has-setup* true]+ (binding [*has-setup* true+ lib.computed/*computed-cache* (atom {})](f query)))))(defmacro with-qp-setupdiff --git a/src/metabase/query_processor/util/add_alias_info.clj b/src/metabase/query_processor/util/add_alias_info.cljindex f514cfa44e1..46328f74412 100644--- a/src/metabase/query_processor/util/add_alias_info.clj+++ b/src/metabase/query_processor/util/add_alias_info.clj@@ -283,11 +283,15 @@&match[:field opts _id-or-name]- (let [col (m/find-first #(lib.equality/= % (or (::resolved opts)- (throw (ex-info "Missing ::resolved -- should have been added by add-source-aliases"- {:field-ref &match- :path (concat path &parents)}))))- returned-columns)]+ (let [resolved (or (::resolved opts)+ (throw (ex-info "Missing ::resolved -- should have been added by add-source-aliases"+ {:field-ref &match+ :path (concat path &parents)})))+ ;; PERF: This is quadratic: O(refs-in-stage * returned-columns)!+ ;; There's not a direct way to index this since [[lib.equality/=]] is too fuzzy for that.+ ;; Even a partial fix like (group-by f returned-columns) so that this is scanning a small plausible set+ ;; of matches instead of everything would go a long way!+ col (m/find-first #(lib.equality/= % resolved) returned-columns)](-> &match(lib/update-options (fn [opts](-> optsdiff --git a/test/metabase/lib/field_test.cljc b/test/metabase/lib/field_test.cljcindex 33112b2c4cd..18686ede12e 100644--- a/test/metabase/lib/field_test.cljc+++ b/test/metabase/lib/field_test.cljc@@ -2196,3 +2196,28 @@:when (not= col "TITLE")][:field {} col])}]}]}(lib.field/remove-field query -1 b-title)))))++(deftest ^:parallel find-stage-index-and-clause-by-uuid-test+ (let [query {:database 1+ :lib/type :mbql/query+ :stages [{:lib/type :mbql.stage/mbql+ :source-table 2+ :aggregation [[:count {:lib/uuid "00000000-0000-0000-0000-000000000001"}]]}+ {:lib/type :mbql.stage/mbql+ :filters [[:=+ {:lib/uuid "a1898aa6-4928-4e97-837d-e440ce21085e"}+ [:field {:lib/uuid "1cb2a996-6ba1-45fb-8101-63dc3105c311"} 3]+ "wow"]]}]}]+ (is (= [0 [:count {:lib/uuid "00000000-0000-0000-0000-000000000001"}]]+ (#'lib.field/find-stage-index-and-clause-by-uuid query -1 "00000000-0000-0000-0000-000000000001")))+ (is (= [0 [:count {:lib/uuid "00000000-0000-0000-0000-000000000001"}]]+ (#'lib.field/find-stage-index-and-clause-by-uuid query 0 "00000000-0000-0000-0000-000000000001")))+ (is (= [1 [:field {:lib/uuid "1cb2a996-6ba1-45fb-8101-63dc3105c311"} 3]]+ (#'lib.field/find-stage-index-and-clause-by-uuid query 1 "1cb2a996-6ba1-45fb-8101-63dc3105c311")))+ (is (= [1 [:=+ {:lib/uuid "a1898aa6-4928-4e97-837d-e440ce21085e"}+ [:field {:lib/uuid "1cb2a996-6ba1-45fb-8101-63dc3105c311"} 3]+ "wow"]]+ (#'lib.field/find-stage-index-and-clause-by-uuid query -1 "a1898aa6-4928-4e97-837d-e440ce21085e")))+ (is (nil? (#'lib.field/find-stage-index-and-clause-by-uuid query -1 "00000000-0000-0000-0000-000000000002")))+ (is (nil? (#'lib.field/find-stage-index-and-clause-by-uuid query 0 "a1898aa6-4928-4e97-837d-e440ce21085e")))))diff --git a/test/metabase/lib/metadata/cache_test.cljc b/test/metabase/lib/metadata/cache_test.cljcindex b80da772b16..48c70ca8a40 100644--- a/test/metabase/lib/metadata/cache_test.cljc+++ b/test/metabase/lib/metadata/cache_test.cljc@@ -18,7 +18,7 @@(is (lib.metadata.protocols/cached-metadata-provider? mp1)"Should automatically get wrapped in a cached metadata provider")(testing "Do something to populate the cache"- (is (seq (lib/returned-columns query))))+ (is (seq (lib/visible-columns query))))(testing "After warming the cache..."(let [mp2 (:lib/metadata query)](is (identical? mp1 mp2)@@ -43,11 +43,11 @@(let [num-misses (atom 0)](binding [lib.metadata.cache/*cache-miss-hook* (fn [_k](swap! num-misses inc))]- (is (seq (lib/returned-columns query')))+ (is (seq (lib/visible-columns query')))(is (pos-int? @num-misses)))))- (testing "Calling lib/returned-columns on a query a second time should result in returning cached results (no cache misses)"+ (testing "Calling lib/visible-columns on a query a second time should result in returning cached results (no cache misses)"(let [num-misses (atom 0)](binding [lib.metadata.cache/*cache-miss-hook* (fn [_k](swap! num-misses inc))]- (is (seq (lib/returned-columns query')))+ (is (seq (lib/visible-columns query')))(is (zero? @num-misses)))))))))diff --git a/test/metabase/lib/metadata/calculation_test.cljc b/test/metabase/lib/metadata/calculation_test.cljcindex 9afbc911e81..826da8e4495 100644--- a/test/metabase/lib/metadata/calculation_test.cljc+++ b/test/metabase/lib/metadata/calculation_test.cljc@@ -3,6 +3,7 @@#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))[clojure.test :refer [deftest is testing]][medley.core :as m]+ [metabase.lib.computed :as lib.computed][metabase.lib.core :as lib][metabase.lib.field.util :as lib.field.util][metabase.lib.join :as lib.join]@@ -376,7 +377,7 @@(is (= :quarter (-> (lib/expression-ref query 0 expression-name)(lib/find-matching-column (cols-fn query)):inherited-temporal-unit)))))- (testing "orderable columns do not contain inherited-temporal-unit for expression"+ (testing "orderable columns on stage 0 does not contain inherited-temporal-unit for expression"(is (not (contains? (lib/find-matching-column (lib/expression-ref query 0 expression-name)(lib/orderable-columns query 0)):inherited-temporal-unit))))))@@ -836,24 +837,28 @@(deftest ^:parallel caching-test(let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :venues))(lib/join (meta/table-metadata :categories)))- call-count (atom {:hits 0, :misses 0})]- (doseq [f [#'lib/returned-columns- #'lib/visible-columns]]- (testing f- (binding [lib.metadata.cache/*cache-hit-hook* (fn [_v]- (swap! call-count update :hits inc))- lib.metadata.cache/*cache-miss-hook* (fn [_v]- (swap! call-count update :misses inc))]- (is (seq (f query)))- (let [num-misses (:misses @call-count)]- (is (pos-int? num-misses)- "The first call should result in some cache misses")- (is (pos-int? (:hits @call-count))- "The first call should result in some cache hits for recursive metadata calculation")- (is (seq (f query)))- (is (= num-misses- (:misses @call-count))- "Another call should result in ZERO additional cache misses -- we should be returning the cached value")))))))+ call-count (atom {:hits 0, :misses 0})+ test-fn (fn [f]+ (is (seq (f query)))+ (let [num-misses (:misses @call-count)]+ (is (pos-int? num-misses)+ "The first call should result in some cache misses")+ (is (seq (f query)))+ (is (= num-misses+ (:misses @call-count))+ "Another call should result in ZERO additional cache misses -- the value is cached now")))]+ (testing "lib/returned-columns"+ (binding [lib.computed/*cache-hit-hook* (fn [_v]+ (swap! call-count update :hits inc))+ lib.computed/*cache-miss-hook* (fn [_v]+ (swap! call-count update :misses inc))]+ (test-fn lib/returned-columns)))+ (testing "lib/visible-columns"+ (binding [lib.metadata.cache/*cache-hit-hook* (fn [_v]+ (swap! call-count update :hits inc))+ lib.metadata.cache/*cache-miss-hook* (fn [_v]+ (swap! call-count update :misses inc))]+ (test-fn lib/visible-columns)))))(deftest ^:parallel returned-columns-no-duplicates-test(testing "Don't return columns from a join twice (QUE-1607)"diff --git a/test/metabase/lib/util_test.cljc b/test/metabase/lib/util_test.cljcindex bcc373f44a0..227ffd582c4 100644--- a/test/metabase/lib/util_test.cljc+++ b/test/metabase/lib/util_test.cljc@@ -327,31 +327,6 @@(is (= 2 (lib/stage-count (lib.util/drop-later-stages two-stage-query -1))))(is (= two-stage-query (lib.util/drop-later-stages two-stage-query -1))))-(deftest ^:parallel find-stage-index-and-clause-by-uuid-test- (let [query {:database 1- :lib/type :mbql/query- :stages [{:lib/type :mbql.stage/mbql- :source-table 2- :aggregation [[:count {:lib/uuid "00000000-0000-0000-0000-000000000001"}]]}- {:lib/type :mbql.stage/mbql- :filters [[:=- {:lib/uuid "a1898aa6-4928-4e97-837d-e440ce21085e"}- [:field {:lib/uuid "1cb2a996-6ba1-45fb-8101-63dc3105c311"} 3]- "wow"]]}]}]- (is (= [0 [:count {:lib/uuid "00000000-0000-0000-0000-000000000001"}]]- (lib.util/find-stage-index-and-clause-by-uuid query "00000000-0000-0000-0000-000000000001")))- (is (= [0 [:count {:lib/uuid "00000000-0000-0000-0000-000000000001"}]]- (lib.util/find-stage-index-and-clause-by-uuid query 0 "00000000-0000-0000-0000-000000000001")))- (is (= [1 [:field {:lib/uuid "1cb2a996-6ba1-45fb-8101-63dc3105c311"} 3]]- (lib.util/find-stage-index-and-clause-by-uuid query "1cb2a996-6ba1-45fb-8101-63dc3105c311")))- (is (= [1 [:=- {:lib/uuid "a1898aa6-4928-4e97-837d-e440ce21085e"}- [:field {:lib/uuid "1cb2a996-6ba1-45fb-8101-63dc3105c311"} 3]- "wow"]]- (lib.util/find-stage-index-and-clause-by-uuid query "a1898aa6-4928-4e97-837d-e440ce21085e")))- (is (nil? (lib.util/find-stage-index-and-clause-by-uuid query "00000000-0000-0000-0000-000000000002")))- (is (nil? (lib.util/find-stage-index-and-clause-by-uuid query 0 "a1898aa6-4928-4e97-837d-e440ce21085e")))))-(deftest ^:parallel do-not-add-extra-stages-to-join-test(is (=? {:stages [{:source-table 45060:joins [{:alias "PRODUCTS__via__PRODUCT_ID"diff --git a/test/metabase/query_processor/perf_test.clj b/test/metabase/query_processor/perf_test.cljnew file mode 100644index 00000000000..c8c7c1068e0--- /dev/null+++ b/test/metabase/query_processor/perf_test.clj@@ -0,0 +1,153 @@+(ns metabase.query-processor.perf-test+ (:require+ [criterium.core :as crit]+ [metabase.lib.computed :as lib.computed]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.lib.metadata.cached-provider :as lib.metadata.cached-provider]+ [metabase.lib.test-metadata :as meta]+ [metabase.lib.test-util :as lib.tu]+ [metabase.lib.test-util.metadata-providers.mock :as lib.tu.mock]+ [metabase.query-processor.compile :as qp.compile]+ [metabase.util.malli :as mu]))++ ;; TODO: (Braden 10/31/2025) Benchmarks to add:+ ;; - Dummy stages, eg. a bonus SELECT * stage on top+ ;; - What about 4 stages?+ ;; - Return only a few cols from a huge table+ ;; - Big daisy-chain of joins+ ;; - White-label the user query from the original Oct 2025 perf issue and make it into a test+ ;; case here. It has huge `:case` clauses among other things that make it an excellent example+ ;; of a big, complicated, non-pathological query.++(def ^:private ids-per-table 100000)+(def ^:private db-id 1111)++(defn- id+ ([table-index] (* table-index ids-per-table))+ ([table-index field-index] (+ (id table-index)+ field-index)))++(defn- mock-metadata+ "5 tables with 10 columns each."+ [n-tables fields-each]+ (let [tables (for [index (range 1 (inc n-tables))]+ (merge (meta/table-metadata :orders)+ {:name (str "table_" index)+ :display-name (str "Table " index)+ :db-id db-id+ :id (* index ids-per-table)}))+ fields (for [table tables+ index (range fields-each)]+ (merge (if (zero? index)+ (meta/field-metadata :orders :id)+ (meta/field-metadata :orders :quantity))+ {:id (+ (:id table) index)+ :table-id (:id table)+ :name (if (zero? index)+ "id"+ (str "column_" index))+ :display-name (if (zero? index)+ "ID"+ (str "Column " index))+ :position index+ :database-position index+ :custom-position index}))]+ {:database (merge meta/database+ {:id db-id+ :name "perf-data"})+ :tables tables+ :fields fields}))++(def ^:private mock-metadata-small (mock-metadata 5 10))+(def ^:private mock-metadata-medium (mock-metadata 5 100))+(def ^:private mock-metadata-large (mock-metadata 5 1000))+(def ^:private mock-metadata-huge (mock-metadata 5 10000))++(defn- mp-factory [mock-data]+ (-> mock-data+ lib.tu.mock/mock-metadata-provider+ lib.metadata.cached-provider/cached-metadata-provider))++(defn- mp-small []+ (mp-factory mock-metadata-small))+(defn- mp-medium []+ (mp-factory mock-metadata-medium))+(defn- mp-large []+ (mp-factory mock-metadata-large))+(defn- mp-huge []+ (mp-factory mock-metadata-huge))++;; WARN: Be careful with [[mp-huge]]! Its tables are 10k columns wide and it can take several seconds to preprocess+;; and compile queries against it. Running a single analysis is fine, but don't try to `crit/benchmark` it or you'll+;; be waiting tens of minutes!++(defn- trivial-query+ "Given a `MetadataProvider`, return a basic query that selects everything from table 1."+ [mp]+ (lib/query mp (lib.metadata/table mp (id 1))))++(defn- compile-time+ "Given a query, compiles it several times and returns the stats."+ [mp-fn query-fn mem-fn]+ (crit/report-result+ (crit/quick-benchmark+ (mu/disable-enforcement+ (binding [lib.computed/*computed-cache* (mem-fn)]+ (qp.compile/compile (query-fn (mp-fn)))))+ {})))++(defn- computed-cache-on []+ (atom {}))+(defn- computed-cache-off []+ nil)++(comment+ ;; Preprocesses and compiles a query, with the `lib.computed` cache set throughout.+ ;; Useful for testing performance impact from the REPL for the large queries above.+ ;; Returns [nanoseconds result].+ (mu/disable-enforcement+ (let [compcache (atom {})]+ (binding [lib.computed/*computed-cache* compcache]+ (crit/time-body+ (let [mp (mp-small)+ q (trivial-query mp)]+ (update (qp.compile/compile q) :query count))))))++ (let [mp (mp-small)+ q1 (trivial-query mp)+ mp (lib.tu/metadata-provider-with-card-from-query mp 12 q1)+ card (lib.metadata/card mp 12)+ q2 (lib/query mp card)]+ (lib/returned-columns (lib/query q2 (:dataset-query card))))++ ;; Runs Criterium benchmarks for a more statistically sound measurement of the speed of compiling various queries.+ ;; Pass computed-cache-on or computed-cache-off as the third argument to control whether the lib.computed memoization+ ;; is happening or not.+ ;; Back of the envelope analysis from the birth of lib.computed, on my 2022 M1 Max:+ ;; - Adding lib.computed added about 1ms of overhead to this trivial query against mp-small.+ ;; - For mp-small, 2.5ms before lib.computed; now 2.8ms with the cache disabled and 2.6ms with it enabled.+ ;; - For mp-medium, 21ms before lib.computed; now 20.2 with the cache disabled and 19.6ms with it enabled.+ ;; - A small win for a trivial query with 100 columns in the table.+ ;; - For mp-large, 460ms before lib.computed; now 253ms with cache disabled and 255ms with it enabled.+ ;; - For mp-huge, it took about 62s each previously. Now about 11s with caching disabled and 8.8s with it enabled.+ ;; Note that the lib.computed/*computed-cache* doesn't actually help much with these straight table queries;+ ;; it's much more significant with nested queries, complex expressions and multiple joins.+ (compile-time mp-small trivial-query computed-cache-off)+ (compile-time mp-small trivial-query computed-cache-on)+ (compile-time mp-medium trivial-query computed-cache-off)+ (compile-time mp-medium trivial-query computed-cache-on)+ (compile-time mp-large trivial-query computed-cache-off)+ (compile-time mp-large trivial-query computed-cache-on)++ ;; WARN: Don't run this one unless you're going to lunch, it's really slow to run that many times even with the+ ;; lib.computed caching on.+ #_(compile-time mp-huge trivial-query computed-cache-on)++ ;; Instead, here's a single run with mp-huge:+ ;; Takes 11114ms with caching off, and 8825ms with it on for me.+ (crit/time-body+ (mu/disable-enforcement+ (binding [lib.computed/*computed-cache* (computed-cache-off)]+ (-> (qp.compile/compile (trivial-query (mp-huge)))+ (update :query count))))))diff --git a/test/metabase/query_processor_test/model_test.clj b/test/metabase/query_processor_test/model_test.cljindex b10b1584ab5..c5940651b14 100644--- a/test/metabase/query_processor_test/model_test.clj+++ b/test/metabase/query_processor_test/model_test.clj@@ -2,7 +2,6 @@(:require[clojure.test :refer [deftest is testing]][medley.core :as m]- [metabase.lib.convert :as lib.convert][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation]@@ -23,8 +22,7 @@[(lib/=(lib.metadata/field mp (mt/id :products :id))(lib.metadata/field mp (mt/id :reviews :product_id)))])- (lib/with-join-fields :all)))- lib.convert/->legacy-MBQL)+ (lib/with-join-fields :all)))):database-id (mt/id):name "Products+Reviews":type :model}]})@@ -40,8 +38,7 @@(m/find-first (comp #{"Price"} :display-name)))))(lib/breakout $q (-> (m/find-first (comp #{"Reviews → Created At"} :display-name)(lib/breakoutable-columns $q))- (lib/with-temporal-bucket :month)))- (lib.convert/->legacy-MBQL $q)))+ (lib/with-temporal-bucket :month))))):database-id (mt/id):name "Products+Reviews Summary":type :model}]})