Skip to content

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

[QP] Override `LIMIT` for pivot queries to ensure consistent results (#71033)

Braden Shepherdsonb42c2f660523
diff --git a/frontend/src/metabase-types/api/dataset.ts b/frontend/src/metabase-types/api/dataset.ts
index e63c195db90..fe87cf82b01 100644
--- a/frontend/src/metabase-types/api/dataset.ts
+++ b/frontend/src/metabase-types/api/dataset.ts
@@ -99,6 +99,7 @@ export interface DatasetData {
insights?: Insight[] | null;
results_metadata: ResultsMetadata;
rows_truncated: number;
+ pivot_rows_truncated?: number;
requested_timezone?: string;
results_timezone?: string;
download_perms?: DownloadPermission;
diff --git a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.ts b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.ts
index ab2801a0b87..89f2d7ed034 100644
--- a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.ts
+++ b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.ts
@@ -239,6 +239,11 @@ export function checkRenderable(
if (!databaseSupportsPivotTables(query)) {
throw new Error(t`This database does not support pivot tables.`);
}
+ if (data.pivot_rows_truncated != null) {
+ throw new Error(
+ t`Too many rows for a pivot table. Please add a filter or remove breakouts to reduce the number of rows.`,
+ );
+ }
}
export const leftHeaderCellSizeAndPositionGetter = (
diff --git a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.ts
index e14e29c4006..7494902bc24 100644
--- a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.ts
@@ -10,6 +10,7 @@ import {
import type { HeaderItem } from "./types";
import {
addMissingCardBreakouts,
+ checkRenderable,
getColumnValues,
getLeftHeaderWidths,
isColumnValid,
@@ -298,6 +299,33 @@ describe("Visualizations > Visualizations > PivotTable > utils", () => {
});
});
+ describe("checkRenderable", () => {
+ it("should throw when pivot_rows_truncated is set", () => {
+ const data = {
+ cols: [
+ createMockColumn({ source: "breakout", name: "field-1" }),
+ createMockColumn({ source: "aggregation", name: "count" }),
+ ],
+ rows: [],
+ pivot_rows_truncated: 100000,
+ };
+ expect(() => checkRenderable([{ data }] as any, {} as any)).toThrow(
+ /Too many rows/,
+ );
+ });
+
+ it("should not throw when pivot_rows_truncated is not set", () => {
+ const data = {
+ cols: [
+ createMockColumn({ source: "breakout", name: "field-1" }),
+ createMockColumn({ source: "aggregation", name: "count" }),
+ ],
+ rows: [],
+ };
+ expect(() => checkRenderable([{ data }] as any, {} as any)).not.toThrow();
+ });
+ });
+
describe("getColumnValues", () => {
it("can collect column values from left header data", () => {
const data = [
diff --git a/src/metabase/query_processor/pivot.clj b/src/metabase/query_processor/pivot.clj
index f44d3664124..dfca83a9328 100644
--- a/src/metabase/query_processor/pivot.clj
+++ b/src/metabase/query_processor/pivot.clj
@@ -238,7 +238,8 @@
"Build the version of [[qp.pipeline/*reduce*]] used at the top level for running pivot queries."
[info :- [:maybe ::lib.schema.info/info]
more-queries :- [:sequential ::lib.schema/query]
- vrf :- [:fn {:error/message "volatile"} volatile?]]
+ vrf :- [:fn {:error/message "volatile"} volatile?]
+ pivot-limit :- [:maybe nat-int?]]
(when (seq more-queries)
;; execute holds open a connection from [[execute-reducible-query]] so we need to manage connections
;; in the reducing part reduce fn. The default run fn is what orchestrates this together and we just
@@ -247,10 +248,18 @@
;; signature usually has metadata in place of driver but we are hijacking
(fn multiple-reducing [rff {::keys [driver]} query]
(assert driver (format "Expected 'metadata' returned by %s" `append-queries-execute-fn))
- (let [respond (fn respond* [metadata reducible-rows]
- (let [rf (rff metadata)]
+ (let [master-row-count (volatile! 0)
+ respond (fn respond* [metadata reducible-rows]
+ (let [rf (rff metadata)
+ counting-rf (fn counting-rf*
+ ([] (rf))
+ ([acc] (rf acc))
+ ([acc row]
+ (vswap! master-row-count inc)
+ (rf acc row)))]
+ (assert (ifn? rf))
(try
- (transduce identity (completing rf) reducible-rows)
+ (transduce identity (completing counting-rf) reducible-rows)
(catch Throwable e
(throw (ex-info (tru "Error reducing result rows: {0}" (ex-message e))
{:type qp.error-type/qp}
@@ -259,36 +268,48 @@
;; we don't want that now do we. Replace the reduce function with something simple that's not going to do
;; anything crazy like close our output stream prematurely; we can let the top-level reduce function worry
;; about that.
- acc (binding [qp.pipeline/*execute* orig-execute
- qp.pipeline/*reduce* (fn [rff metadata reducible-rows]
- (let [rf (rff metadata)]
- (transduce identity rf reducible-rows)))]
- (-> (qp.pipeline/*execute* driver query respond)
- (process-queries-append-results more-queries @vrf info)))]
+ first-result (binding [qp.pipeline/*execute* orig-execute
+ qp.pipeline/*reduce* (fn [rff metadata reducible-rows]
+ (let [rf (rff metadata)]
+ (transduce identity rf reducible-rows)))]
+ (qp.pipeline/*execute* driver query respond))
+ truncated? (and pivot-limit (>= @master-row-count pivot-limit))
+ acc (if truncated?
+ first-result
+ (binding [qp.pipeline/*execute* orig-execute
+ qp.pipeline/*reduce* (fn [rff metadata reducible-rows]
+ (let [rf (rff metadata)]
+ (transduce identity rf reducible-rows)))]
+ (process-queries-append-results first-result more-queries @vrf info)))
+ result (@vrf acc)]
;; completion arity can't be threaded because the value is derefed too early
- (qp.pipeline/*result* (@vrf acc)))))))
+ (qp.pipeline/*result* (cond-> result
+ (and truncated? (map? result))
+ (assoc-in [:data :pivot_rows_truncated] @master-row-count))))))))
(mu/defn- append-queries-rff-and-fns
"RFF and QP pipeline functions to use when executing pivot queries."
[info :- [:maybe ::lib.schema.info/info]
rff :- ::qp.schema/rff
- more-queries :- [:sequential ::lib.schema/query]]
+ more-queries :- [:sequential ::lib.schema/query]
+ pivot-limit :- [:maybe nat-int?]]
(let [vrf (volatile! nil)]
- {:rff (append-queries-rff rff vrf)
- :execute (append-queries-execute-fn more-queries)
- :reduce (append-queries-reduce-fn info more-queries vrf)}))
+ {:rff (append-queries-rff rff vrf)
+ :execute (append-queries-execute-fn more-queries)
+ :reduce (append-queries-reduce-fn info more-queries vrf pivot-limit)}))
(mu/defn- process-multiple-queries
"Allows the query processor to handle multiple queries, stitched together to appear as one"
[[{:keys [info], :as first-query} & more-queries] :- [:sequential ::lib.schema/query]
- rff :- ::qp.schema/rff]
+ rff :- ::qp.schema/rff
+ pivot-limit :- [:maybe nat-int?]]
(if (empty? more-queries)
;; Single query - use normal QP pipeline to preserve userland metadata
(qp/process-query (cond-> first-query
(seq info) qp/userland-query)
rff)
;; Multiple queries - use custom pivot pipeline
- (let [{:keys [rff execute reduce]} (append-queries-rff-and-fns info rff more-queries)
+ (let [{:keys [rff execute reduce]} (append-queries-rff-and-fns info rff more-queries pivot-limit)
first-query (cond-> first-query
(seq info) qp/userland-query)]
(binding [qp.pipeline/*execute* (or execute qp.pipeline/*execute*)
@@ -461,6 +482,20 @@
:qp.pivot/num-remapped-breakouts num-remapped-breakouts
:qp.pivot/remapped-indexes remap)))
+(def ^:dynamic ^:private *pivot-max-result-rows*
+ "Maximum number of result rows for each pivot sub-query. Divided by the number of aggregations since each aggregation
+ adds a column to the output, so fewer rows are needed to fill the pivot table."
+ 200000)
+
+(defn- pivot-query-max-rows
+ "Calculate the per-sub-query row limit for pivot queries: `floor(pivot-max-result-rows / num-aggregations)`.
+ Falls back to `pivot-max-result-rows` if there are no aggregations (shouldn't happen for pivot queries)."
+ [query]
+ (let [num-aggs (count (lib/aggregations query))]
+ (if (pos? num-aggs)
+ (quot *pivot-max-result-rows* num-aggs)
+ *pivot-max-result-rows*)))
+
(mu/defn run-pivot-query
"Run the pivot query. You are expected to wrap this call in [[metabase.query-processor.streaming/streaming-response]]
yourself."
@@ -478,8 +513,10 @@
(pivot-options query (get query :viz-settings))
(pivot-options query (get-in query [:info :visualization-settings]))
(not-empty (select-keys query [:pivot-rows :pivot-cols :pivot-measures :show-row-totals :show-column-totals])))
+ pivot-limit (pivot-query-max-rows query)
query (-> query
(assoc-in [:middleware :pivot-options] pivot-opts)
+ (assoc-in [:constraints :max-results] pivot-limit)
add-canonical-col-info)
all-queries (generate-queries query pivot-opts)]
- (process-multiple-queries all-queries rff))))))
+ (process-multiple-queries all-queries rff pivot-limit))))))
diff --git a/test/metabase/query_processor/pivot_test.clj b/test/metabase/query_processor/pivot_test.clj
index 08b094a157c..d0163b13071 100644
--- a/test/metabase/query_processor/pivot_test.clj
+++ b/test/metabase/query_processor/pivot_test.clj
@@ -827,3 +827,47 @@
(mt/formatted-rows
[str str int int int]
(qp.pivot/run-pivot-query query))))))))
+
+(deftest ^:parallel pivot-query-uses-custom-limit-test
+ (testing "Pivot queries use a custom higher limit instead of the caller's constraints, so data stays consistent"
+ (mt/test-drivers (qp.pivot.test-util/applicable-drivers)
+ ;; The pivot-query has 2 aggregations (count, sum-of-quantity), so the pivot limit is 200k/2 = 100k.
+ ;; Even though we pass max-results=50, the pivot limit overrides it, so all rows come through.
+ (let [query (qp.pivot.test-util/pivot-query)
+ query (assoc query :constraints {:max-results 50})
+ results (qp.pivot/run-pivot-query query)
+ rows (mt/formatted-rows [str str str int int int] results)
+ ;; pivot-grouping is column index 3 (state, source, category, pivot-grouping, count, sum)
+ ;; Group 0 = all breakouts (detail rows)
+ ;; Group 7 = grand total (no breakouts)
+ detail-rows (filter #(zero? (nth % 3)) rows)
+ grand-total-row (first (filter #(= 7 (nth % 3)) rows))
+ detail-count-sum (reduce + (map #(nth % 4) detail-rows))
+ grand-total-count (nth grand-total-row 4)]
+ (testing "All detail rows are returned (not truncated to caller's max-results)"
+ (is (> (count detail-rows) 50)
+ "Detail rows should exceed the caller's max-results=50 because the pivot limit overrides it"))
+ (testing "The grand total row exists"
+ (is (some? grand-total-row)))
+ (testing "Detail rows sum to the grand total — data is consistent"
+ (is (= detail-count-sum grand-total-count)
+ (str "Detail count sum (" detail-count-sum ") should equal grand total ("
+ grand-total-count ") because pivot uses its own higher limit")))))))
+
+(deftest ^:parallel pivot-query-short-circuits-when-master-hits-limit-test
+ (testing "When the master pivot query hits the row limit, remaining sub-queries are skipped and truncation is signaled"
+ (mt/test-drivers (qp.pivot.test-util/applicable-drivers)
+ ;; Use the standard pivot-query but override the pivot limit to be very small.
+ ;; The master query (state × source × category) produces ~200+ rows.
+ ;; With *pivot-max-result-rows* 20, the limit is 20/2=10 per sub-query.
+ (binding [qp.pivot/*pivot-max-result-rows* 20]
+ (let [query (qp.pivot.test-util/pivot-query)
+ results (qp.pivot/run-pivot-query query)
+ rows (mt/rows results)]
+ (testing "Only master query rows are returned (no subtotals/totals since sub-queries were skipped)"
+ ;; All rows should be pivot-grouping=0 (the master query's group)
+ (is (every? #(zero? (nth % 3)) rows)
+ "All rows should be from the master query (pivot-grouping=0)"))
+ (testing "The result includes pivot_rows_truncated flag"
+ (is (= 10 (get-in results [:data :pivot_rows_truncated]))
+ "Should signal truncation with the row count")))))))