Skip to content

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

Notification temp storage across dashboard (#76355)

dpsutton6701de190dc5
diff --git a/src/metabase/notification/payload/execute.clj b/src/metabase/notification/payload/execute.clj
index 314bef45ee7..d35b0dad62a 100644
--- a/src/metabase/notification/payload/execute.clj
+++ b/src/metabase/notification/payload/execute.clj
@@ -161,72 +161,95 @@
streamed straight to disk. See [[metabase.notification.payload.temp-storage]] for more details."
20000)
+(def ^:private squeezed-spill-threshold
+ "Once a notification is already holding [[cells-to-disk-threshold]] cells in memory across all its cards, additional
+ cards spill at this much lower per-card cell count - so many small cards can't collectively exhaust memory. We keep
+ a floor (rather than spilling everything) so trivially tiny results aren't needlessly written to disk."
+ 500)
+
+(defn- new-spill-budget
+ "Build the shared [[metabase.notification.payload.temp-storage/ResidentBudget]] for one notification's cards."
+ []
+ (notification.temp-storage/make-resident-budget
+ {:per-card cells-to-disk-threshold
+ :resident-cap cells-to-disk-threshold
+ :floor squeezed-spill-threshold}))
+
(defn execute-dashboard-subscription-card
"Returns subscription result for a card.
+ `spill-budget` is the shared [[metabase.notification.payload.temp-storage/ResidentBudget]] for the whole
+ notification, so memory held by sibling cards influences when this card spills to disk. When omitted (e.g. executing a
+ card in isolation), a private budget is used so only the per-card spill limit applies.
+
This function should be executed under pulse's creator permissions."
- [{:keys [card_id dashboard_id] :as dashcard} parameters]
- (log/with-context {:card_id card_id}
- (try
- (when-let [card (t2/select-one :model/Card :id card_id :archived false)]
- (let [dashboard (t2/select-one :model/Dashboard :id dashboard_id)
- multi-cards (dashboard-card/dashcard->multi-cards dashcard)
- result-fn (fn [card-id]
- (let [card (if (= card-id (:id card))
- card
- (t2/select-one :model/Card :id card-id))]
- {:card card
- :dashcard dashcard
- ;; TODO should this be dashcard?
- :type :card
- :result (-> (qp.dashboard/process-query-for-dashcard
- :dashboard dashboard
- :card card
- :dashcard dashcard
- :context :dashboard-subscription
- :export-format :api
- :parameters parameters
- :constraints {}
- :middleware {:process-viz-settings? true
- :js-int-to-string? false
- :add-default-userland-constraints? false}
- :make-run (fn make-run [qp _export-format]
- (^:once fn* [query info]
- (qp
- (qp/userland-query query info)
- ;; Pass streaming rff with 2000 row threshold
- (notification.temp-storage/notification-rff
- cells-to-disk-threshold
- {:dashboard_id dashboard_id
- :card_id card-id
- :dashcard_id (u/the-id dashcard)})))))
- fixup-viz-settings
- format-qp-result)}))
- result (result-fn card_id)
- series-results (mapv (comp result-fn :id) multi-cards)]
- (log/debugf "Dashcard has %d series" (count multi-cards))
- (log/debugf "Result has %d rows" (-> result :result :row_count))
- (doseq [series-result series-results]
- (log/with-context {:series_card_id (-> series-result :card :id)}
- (log/debugf "Series result has %d rows" (-> series-result :result :row_count))))
- (when-not (and (get-in dashcard [:visualization_settings :card.hide_empty])
- (is-card-empty? (assoc card :result (:result result))))
- (update result :dashcard assoc :series-results series-results))))
- (catch Throwable e
- (log/warnf e "Error running query for Card %s" (:card_id dashcard))))))
+ ([dashcard parameters]
+ (execute-dashboard-subscription-card dashcard parameters (new-spill-budget)))
+ ([{:keys [card_id dashboard_id] :as dashcard} parameters spill-budget]
+ (log/with-context {:card_id card_id}
+ (try
+ (when-let [card (t2/select-one :model/Card :id card_id :archived false)]
+ (let [dashboard (t2/select-one :model/Dashboard :id dashboard_id)
+ multi-cards (dashboard-card/dashcard->multi-cards dashcard)
+ result-fn (fn [card-id]
+ (let [card (if (= card-id (:id card))
+ card
+ (t2/select-one :model/Card :id card-id))]
+ {:card card
+ :dashcard dashcard
+ ;; TODO should this be dashcard?
+ :type :card
+ :result (-> (qp.dashboard/process-query-for-dashcard
+ :dashboard dashboard
+ :card card
+ :dashcard dashcard
+ :context :dashboard-subscription
+ :export-format :api
+ :parameters parameters
+ :constraints {}
+ :middleware {:process-viz-settings? true
+ :js-int-to-string? false
+ :add-default-userland-constraints? false}
+ :make-run (fn make-run [qp _export-format]
+ (^:once fn* [query info]
+ (qp
+ (qp/userland-query query info)
+ ;; Pass streaming rff with 2000 row threshold
+ (notification.temp-storage/notification-rff
+ {:budget spill-budget}
+ {:dashboard_id dashboard_id
+ :card_id card-id
+ :dashcard_id (u/the-id dashcard)})))))
+ fixup-viz-settings
+ format-qp-result)}))
+ result (result-fn card_id)
+ series-results (mapv (comp result-fn :id) multi-cards)]
+ (log/debugf "Dashcard has %d series" (count multi-cards))
+ (log/debugf "Result has %d rows" (-> result :result :row_count))
+ (doseq [series-result series-results]
+ (log/with-context {:series_card_id (-> series-result :card :id)}
+ (log/debugf "Series result has %d rows" (-> series-result :result :row_count))))
+ (when-not (and (get-in dashcard [:visualization_settings :card.hide_empty])
+ (is-card-empty? (assoc card :result (:result result))))
+ (update result :dashcard assoc :series-results series-results))))
+ (catch Throwable e
+ (log/warnf e "Error running query for Card %s" (:card_id dashcard)))))))
(defn- dashcard->part
"Given a dashcard returns its part based on its type.
+ `spill-budget` is the notification-wide [[metabase.notification.payload.temp-storage/ResidentBudget]] shared across
+ all dashcards.
+
The result will follow the pulse's creator permissions."
- [dashcard parameters]
+ [dashcard parameters spill-budget]
(assert api/*current-user-id* "Makes sure you wrapped this with a `with-current-user`.")
(cond
(:card_id dashcard)
(log/with-context {:card_id (:card_id dashcard)}
(let [parameters (merge-default-values parameters)]
;; Streaming to disk is now handled by the query processor rff
- (-> (execute-dashboard-subscription-card dashcard parameters)
+ (-> (execute-dashboard-subscription-card dashcard parameters spill-budget)
(m/update-existing :dashcard resolve-inline-parameters parameters))))
(virtual-card-of-type? dashcard "iframe")
@@ -259,9 +282,12 @@
(assoc :type :text)))))
(defn- dashcards->part
- [dashcards parameters]
+ "Render `dashcards` to parts, sharing `spill-budget` across them so memory held by earlier cards can push later (large)
+ cards to spill to disk instead of collectively exhausting heap. The budget is created once per dashboard (spanning all
+ tabs) by the caller, not here, so a multi-tab dashboard shares a single budget."
+ [dashcards parameters spill-budget]
(let [ordered-dashcards (sort dashboard-card/dashcard-comparator dashcards)]
- (doall (keep #(dashcard->part % parameters) ordered-dashcards))))
+ (doall (keep #(dashcard->part % parameters spill-budget) ordered-dashcards))))
(mr/def ::Part
"Part."
@@ -280,23 +306,29 @@
[::mc/default :map]])
(mu/defn execute-dashboard :- [:sequential ::Part]
- "Execute a dashboard and return its parts."
- [dashboard-id user-id parameters]
- (request/with-current-user user-id
- (if (render-tabs? dashboard-id)
- (let [tabs (t2/hydrate (t2/select :model/DashboardTab :dashboard_id dashboard-id) :tab-cards)
- tabs-with-cards (filter #(seq (:cards %)) tabs)
- should-render-tab? (< 1 (count tabs-with-cards))]
- (doall (flatten (for [{:keys [cards] :as tab} tabs-with-cards]
- (do
- (log/debugf "Rendering tab %s with %d cards" (:name tab) (count cards))
- (concat
- (when should-render-tab?
- [(tab->part tab)])
- (dashcards->part cards parameters)))))))
- (let [dashcards (t2/select :model/DashboardCard :dashboard_id dashboard-id)]
- (log/debugf "Rendering dashboard with %d cards" (count dashcards))
- (dashcards->part dashcards parameters)))))
+ "Execute a dashboard and return its parts.
+
+ `spill-budget` is the shared [[metabase.notification.payload.temp-storage/ResidentBudget]] for the whole dashboard
+ (all tabs), so cards can't collectively exhaust heap regardless of how they're split into tabs. The 3-arity uses the
+ production default ([[new-spill-budget]]); pass your own (e.g. with lower limits) to the 4-arity for testing."
+ ([dashboard-id user-id parameters]
+ (execute-dashboard dashboard-id user-id parameters (new-spill-budget)))
+ ([dashboard-id user-id parameters spill-budget]
+ (request/with-current-user user-id
+ (if (render-tabs? dashboard-id)
+ (let [tabs (t2/hydrate (t2/select :model/DashboardTab :dashboard_id dashboard-id) :tab-cards)
+ tabs-with-cards (filter #(seq (:cards %)) tabs)
+ should-render-tab? (< 1 (count tabs-with-cards))]
+ (doall (flatten (for [{:keys [cards] :as tab} tabs-with-cards]
+ (do
+ (log/debugf "Rendering tab %s with %d cards" (:name tab) (count cards))
+ (concat
+ (when should-render-tab?
+ [(tab->part tab)])
+ (dashcards->part cards parameters spill-budget)))))))
+ (let [dashcards (t2/select :model/DashboardCard :dashboard_id dashboard-id)]
+ (log/debugf "Rendering dashboard with %d cards" (count dashcards))
+ (dashcards->part dashcards parameters spill-budget))))))
(mu/defn execute-card :- [:maybe ::Part]
"Returns the result for a card."
@@ -317,8 +349,10 @@
(qp
(qp/userland-query query info)
;; Pass streaming rff with 2000 row threshold
+ ;; a standalone card has no sibling cards, so it
+ ;; uses its own (unshared) spill budget
(notification.temp-storage/notification-rff
- cells-to-disk-threshold
+ {:budget (new-spill-budget)}
{:card-id card-id})))))
fixup-viz-settings
format-qp-result))]
diff --git a/src/metabase/notification/payload/temp_storage.clj b/src/metabase/notification/payload/temp_storage.clj
index e0c23a8fc15..823ee207ad5 100644
--- a/src/metabase/notification/payload/temp_storage.clj
+++ b/src/metabase/notification/payload/temp_storage.clj
@@ -140,7 +140,7 @@
Object
(cleanup! [_] nil))
-(deftype StreamingTempFileStorage [^File file context]
+(deftype StreamingTempFileStorage [^File file file-context]
Cleanable
(cleanup! [_]
(when (.exists file)
@@ -159,13 +159,13 @@
Object
(toString [_]
(if (.exists file)
- (format "#StreamingTempFileStorage{:file %s, :size %s, :context %s}"
+ (format "#StreamingTempFileStorage{:file %s, :size %s, :file-context %s}"
(.getName file)
(human-readable-size (.length file))
- (pr-str context))
- (format "#StreamingTempFileStorage{:file %s (deleted), :context %s}"
+ (pr-str file-context))
+ (format "#StreamingTempFileStorage{:file %s (deleted), :file-context %s}"
(.getName file)
- (pr-str context))))
+ (pr-str file-context))))
(equals [_this other]
(and (instance? StreamingTempFileStorage other)
@@ -178,122 +178,219 @@
[^StreamingTempFileStorage storage ^java.io.Writer w]
(.write w (.toString storage)))
+(def ^:private ResidentBudget
+ "Shared mutable budget threaded across all of a notification's cards (created once per notification by
+ [[make-resident-budget]]). `:resident` is an atom tracking the cells currently held in memory across cards;
+ the rest are the cell limits used to decide when a query spills to disk. See [[should-spill?]]."
+ [:map
+ [:resident [:fn #(instance? clojure.lang.IAtom %)]]
+ [:per-card pos-int?] ; spill a single query once it alone holds this many cells in memory
+ [:resident-cap pos-int?] ; once resident cells exceed this across cards, squeeze remaining queries down to `:floor`
+ [:floor pos-int?]]) ; ...but never spill a query holding fewer than this (no point writing tiny results)
+
+(def ^:private NotificationRffOptions
+ "Options controlling how [[notification-rff]] decides when to spill to disk."
+ [:map
+ ;; shared across a notification's cards so they can't collectively exhaust memory. A standalone query just passes its
+ ;; own freshly-made budget.
+ [:budget ResidentBudget]])
+
+(defn make-resident-budget
+ "Create a shared [[ResidentBudget]] for one notification. `limits` is a map of `:per-card`/`:resident-cap`/`:floor`
+ cell counts. Created once (e.g. per dashboard) and passed to every card's [[notification-rff]] via `:budget` so that
+ many small cards can't collectively exhaust memory."
+ [limits]
+ (assoc limits :resident (atom 0)))
+
+(defn- should-spill?
+ "Given the shared `budget` and the cells `this-query` currently holds in memory, decide whether to spill it to disk.
+ Spill when this query alone is large, or when this query plus what sibling cards already hold resident would push total
+ in-memory cells past the cap and this query isn't trivially tiny. We add `this-query` to `@resident` because the
+ current card hasn't folded itself into the resident total yet (that happens at completion), so `@resident` alone
+ understates live memory while this card is accumulating."
+ [{:keys [resident per-card resident-cap floor]} this-query]
+ (or (>= this-query per-card)
+ (and (>= (+ @resident this-query) resident-cap)
+ (>= this-query floor))))
+
+;; ----------------------------------------------------------------------------------------------------------------- ;;
+;; Disk-backed row storage
+;;
+;; Side storage for a single notification query's rows, used alongside the query processor's own reducing accumulator
+;; (the `result` map - see [[metabase.query-processor.reducible/default-rff]]). Rows accumulate in an in-memory transient
+;; vector until the cell threshold is crossed, at which point everything accumulated is spilled to a temp file and
+;; subsequent rows are streamed straight to disk.
+;;
+;; State lives in two places, by design:
+;; :state - an `(atom state-map)` of plain immutable fields, updated with pure `swap!` fns:
+;; :row-count total rows seen
+;; :cell-count cells (values) currently held in memory (0 once spilled)
+;; :streaming? whether we've spilled and are now writing straight to disk
+;; :file the spill File, once streaming
+;; :output-stream the spill DataOutputStream, once streaming
+;; :truncated? whether the file grew past the size cap and rows are being dropped
+;; :rows - a `(volatile! transient-vector)` of the in-memory rows. This is kept OUT of the atom: a transient is a
+;; mutable, single-thread value and `conj!` mutates in place, which would be unsafe inside a `swap!` fn (atoms may
+;; retry their update fn). The rff is single-threaded, so a volatile is the right container - no CAS, no retry.
+;; I/O (opening/writing/closing the file) likewise happens as explicit statements in the fns below, never inside `swap!`.
+;; ----------------------------------------------------------------------------------------------------------------- ;;
+
+(defn- new-row-storage
+ "Create the row storage for one query. `budget` is the shared [[ResidentBudget]] (this query reads it to decide spills
+ and, if it stays in memory, folds its cells into it at completion); `file-context` is captured in the spill file's
+ preamble and on the resulting StreamingTempFileStorage."
+ [budget file-context]
+ {:state (atom {:row-count 0
+ :cell-count 0
+ :streaming? false
+ :file nil
+ :output-stream nil
+ :truncated? false})
+ :rows (volatile! (transient []))
+ :budget budget
+ :file-context file-context})
+
+(defn- spill-to-disk!
+ "Transition from in-memory accumulation to disk streaming: open a temp file, write the preamble + streaming sentinel,
+ flush the rows accumulated so far, then flip the state into streaming mode and release the in-memory rows."
+ [{:keys [state rows file-context]}]
+ (let [opened (open-streaming-file!)
+ new-file (:file opened)
+ ^DataOutputStream new-os (:output-stream opened)]
+ (try
+ (nippy/freeze-to-out! new-os {:preamble file-context})
+ (.flush new-os)
+ (nippy/freeze-to-out! new-os ::streaming)
+ (.flush new-os)
+ (doseq [row (persistent! @rows)]
+ (write-row-to-stream! new-os row))
+ (vreset! rows (transient [])) ; release memory
+ (swap! state assoc
+ :streaming? true
+ :file new-file
+ :output-stream new-os)
+ (catch Exception e
+ (u/ignore-exceptions (.close new-os))
+ (u/ignore-exceptions (io/delete-file new-file))
+ (throw e)))))
+
+(defn- add-row!
+ "Store one `row` (in memory, or appended to the spill file if already streaming). Returns true to keep reducing, or
+ false once truncation has kicked in and the caller should stop."
+ [{:keys [state rows budget file-context] :as row-storage} row]
+ (let [{:keys [streaming? ^DataOutputStream output-stream ^File file]}
+ (swap! state update :row-count inc)]
+ (if streaming?
+ ;; already spilled: write straight to disk, truncating (stop reducing) if the file grew past 1.3x the size cap
+ (let [max-bytes (notification.settings/notification-temp-file-size-max-bytes)]
+ (write-row-to-stream! output-stream row)
+ (if (and (pos? max-bytes)
+ (> (.length file) (* 1.3 max-bytes)))
+ (do
+ (swap! state assoc :truncated? true)
+ (log/warnf "Results have exceeded 1.3 times of `notification-temp-file-size-max-bytes` of %s (max: %s). Truncating query results. %s"
+ (human-readable-size (.length file))
+ (human-readable-size max-bytes)
+ (when file-context (format "(%s)" (pr-str file-context))))
+ false)
+ true))
+ ;; still in memory: accumulate the row (in the sibling volatile) and its cells, then let the policy decide whether
+ ;; to spill given the cells this query holds and the cells resident across the notification. We never truncate
+ ;; while in memory, so always keep reducing.
+ (let [_ (vswap! rows conj! row)
+ cell-count (:cell-count (swap! state update :cell-count + (count row)))]
+ (when (should-spill? budget cell-count)
+ (log/infof "Spilling to disk (%d cells, %d rows in memory)" cell-count (:row-count @state))
+ (spill-to-disk! row-storage))
+ true))))
+
+(defn- finish!
+ "Fold the stored rows (or a file reference), `:row_count`, and stats into the query processor's `result` map. A query
+ that stays in memory folds its cells into the shared [[ResidentBudget]] so sibling cards see the added memory pressure;
+ a query that spilled adds nothing (its rows are on disk, not resident)."
+ [{:keys [state rows budget file-context]} result]
+ (let [{:keys [row-count cell-count streaming? truncated?
+ ^DataOutputStream output-stream ^File file]} @state]
+ (if streaming?
+ ;; close the file and hand back a file reference; nothing is resident in memory
+ (try
+ (.close output-stream)
+ (let [file-size (.length file)
+ max-bytes (notification.settings/notification-temp-file-size-max-bytes)
+ storage (cond truncated? :truncated
+ (zero? max-bytes) :not-limited
+ (< max-bytes file-size) :above-threshold
+ :else :disk)]
+ (analytics/inc! :metabase-notification/temp-storage {:storage storage})
+ (log/infof "💾 Stored %d rows to disk: %s (never loaded into memory)%s"
+ row-count
+ (human-readable-size file-size)
+ (if truncated? " (note query results were truncated)" ""))
+ (-> result
+ (assoc :row_count row-count
+ :status :completed
+ :data.rows-file-size file-size
+ :notification/storage (if truncated? :truncated :disk)
+ :notification/resident-cells 0)
+ (cond-> truncated? (assoc :notification/truncated? true))
+ (assoc-in [:data :rows] (StreamingTempFileStorage. file file-context))))
+ (catch Exception e
+ (u/ignore-exceptions (.close output-stream))
+ (throw e)))
+ ;; stayed under threshold: fold this query's cells into the shared resident total, then hand back the in-memory
+ ;; rows (reporting the cells held resident).
+ (do
+ (swap! (:resident budget) + cell-count)
+ (analytics/inc! :metabase-notification/temp-storage {:storage :memory})
+ (log/infof "✓ Completed with %d rows in memory (under threshold)" row-count)
+ (-> result
+ (assoc :row_count row-count
+ :status :completed
+ :notification/storage :memory
+ :notification/resident-cells cell-count)
+ (assoc-in [:data :rows] (persistent! @rows)))))))
+
(mu/defn notification-rff :- ::qp.schema/rff
- "Reducing function factory for notifications that streams to disk when threshold exceeded.
+ "Reducing function factory for notifications that streams to disk when a threshold is exceeded.
Returns an rff (function that takes metadata and returns an rf) that:
- Accumulates rows in memory initially
- - Once max-cell-count is reached, switches to streaming mode
- - In streaming mode, writes all accumulated rows to disk then streams subsequent rows
- - Final result contains either in-memory rows or a StreamingTempFileStorage reference
+ - Once the spill threshold is reached, spills accumulated rows to disk and streams the rest
+ - Final result contains either in-memory rows or a StreamingTempFileStorage reference, plus stats:
+ `:notification/storage` (:memory | :disk | :truncated) and `:notification/resident-cells` (cells held in memory,
+ 0 once spilled).
Parameters:
- - max-cell-count: Maximum number of \"cells\" or values to keep in memory before streaming to disk.
- - context: Optional context map to include in temp file preamble (for debugging)"
- ([max-cell-count]
- (notification-rff max-cell-count {}))
- ([max-cell-count context]
+ - options: a map describing when to switch to disk. Keys:
+ - :budget (required) - a shared [[ResidentBudget]] (from [[make-resident-budget]]) tracking memory across a whole
+ notification's cards, so many small cards can't collectively exhaust memory. A standalone query passes its own
+ freshly-made budget.
+ - file-context: Optional map describing the data being stored (e.g. the originating card/dashcard). It is captured
+ in the temp file preamble and on the resulting StreamingTempFileStorage (for debugging)."
+ ([options :- NotificationRffOptions]
+ (notification-rff options {}))
+ ([options :- NotificationRffOptions file-context]
(fn rff [metadata]
- (let [row-count (volatile! 0)
- cell-count (volatile! 0)
- rows (volatile! (transient []))
- streaming? (volatile! false)
- streaming-state (volatile! nil)] ; {:file File :output-stream DataOutputStream}
+ ;; `row-storage` is OUR side storage for rows (it spills to disk); the query processor's reducing accumulator is
+ ;; the `result` map, which we thread through untouched until completion - exactly like
+ ;; [[metabase.query-processor.reducible/default-rff]]'s `row-count`/`rows` volatiles.
+ (let [row-storage (new-row-storage (:budget options) file-context)]
(fn notification-rf
;; Init arity
([]
{:data metadata})
- ;; Completion arity
+ ;; Completion arity - fold the stored rows (or a file reference) and stats into `result`.
([result]
{:pre [(map? (unreduced result))]}
- (let [result (unreduced result)]
- (if @streaming?
- ;; Close the streaming file and return TempFileStorage
- (let [{:keys [^DataOutputStream output-stream ^File file]} @streaming-state]
- (try
- (.close output-stream)
- (let [file-size (.length file)
- max-bytes (notification.settings/notification-temp-file-size-max-bytes)]
- (analytics/inc! :metabase-notification/temp-storage
- {:storage (cond (:notification/truncated? @streaming-state) :truncated
- (zero? max-bytes) :not-limited
- (< max-bytes file-size) :above-threshold
- :else :disk)})
- (log/infof "💾 Stored %d rows to disk: %s (never loaded into memory)%s"
- @row-count
- (human-readable-size file-size)
- (if (:notification/truncated? @streaming-state)
- " (note query results were truncated)"
- ""))
- (-> result
- (assoc :row_count @row-count
- :status :completed
- :data.rows-file-size file-size)
- (cond-> (:notification/truncated? @streaming-state)
- (assoc :notification/truncated? true))
- (assoc-in [:data :rows] (StreamingTempFileStorage. file context))))
- (catch Exception e
- (u/ignore-exceptions (.close output-stream))
- (throw e))))
- ;; Return in-memory rows
- (do
- (analytics/inc! :metabase-notification/temp-storage
- {:storage :memory})
- (log/infof "✓ Completed with %d rows in memory (under threshold)" @row-count)
- (-> result
- (assoc :row_count @row-count
- :status :completed)
- (assoc-in [:data :rows] (persistent! @rows)))))))
-
- ;; Step arity - accumulate rows
+ (finish! row-storage (unreduced result)))
+
+ ;; Step arity - store the row beside `result`, then thread `result` onward (stopping if truncated).
([result row]
- ;; unconditionally increment row count and add rows to internal volatile transient collector. If we are
- ;; streaming to disk, we periodically flush this to disk; if we are collecting in memory the collection is
- ;; used the same as in the default-rff
- (vswap! row-count inc)
- (if @streaming?
- ;; Already streaming - write row directly to file
- (let [{:keys [^DataOutputStream output-stream ^File file]} @streaming-state]
- (write-row-to-stream! output-stream row)
- (if (and (pos? (notification.settings/notification-temp-file-size-max-bytes))
- (> (.length file) (* 1.3 (notification.settings/notification-temp-file-size-max-bytes))))
- (do (vswap! streaming-state assoc :notification/truncated? true)
- (log/warnf "Results have exceeded 1.3 times of `notification-temp-file-size-max-bytes` of %s (max: %s). Truncating query results. %s"
- (human-readable-size (.length file))
- (human-readable-size (notification.settings/notification-temp-file-size-max-bytes))
- (when context (format "(%s)" (pr-str context))))
- (reduced result))
- result))
- (do
- (vswap! rows conj! row)
- (vswap! cell-count #(+ % (count row)))
- ;; Check if we've hit the threshold to switch to disk based streaming
- (when (>= @cell-count max-cell-count)
- (log/infof "Cell count reached threshold (%d, %d rows), switching to streaming mode"
- max-cell-count @row-count)
- ;; Open streaming file
- (let [{:keys [file ^DataOutputStream output-stream]} (open-streaming-file!)]
- (try
- ;; Write preamble
- (nippy/freeze-to-out! output-stream {:preamble context})
- (.flush output-stream)
- ;; Write sentinel indicating streaming format
- (nippy/freeze-to-out! output-stream ::streaming)
- (.flush output-stream)
- ;; Write all accumulated rows
- (doseq [row (persistent! @rows)]
- (write-row-to-stream! output-stream row))
- ;; Switch to streaming mode
- (vreset! streaming? true)
- (vreset! rows (transient [])) ; Clear memory
- (vreset! streaming-state {:file file :output-stream output-stream})
- (catch Exception e
- (u/ignore-exceptions (.close output-stream))
- (u/ignore-exceptions (io/delete-file file))
- (throw e)))))
- result))))))))
+ (if (add-row! row-storage row)
+ result
+ (reduced result))))))))
;; ------------------------------------------------------------------------------------------------;;
;; Public APIs ;;
diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.clj
index 81ed40738ea..6bb3d63ff87 100644
--- a/test/metabase/driver/postgres_test.clj
+++ b/test/metabase/driver/postgres_test.clj
@@ -2096,7 +2096,9 @@
FROM generate_series(1, 5000) AS i;"
results (qp/process-query (mt/native-query {:query sql})
(temp-storage/notification-rff
- 5000 {:context 'complex-types-in-notification-payload}))]
+ {:budget (temp-storage/make-resident-budget
+ {:per-card 5000 :resident-cap Long/MAX_VALUE :floor Long/MAX_VALUE})}
+ {:context 'complex-types-in-notification-payload}))]
(is (integer? (:data.rows-file-size results)))
(is (temp-storage/streaming-temp-file? (-> results :data :rows)))
(is (=? [1
diff --git a/test/metabase/notification/payload/execute_test.clj b/test/metabase/notification/payload/execute_test.clj
index 1fcf5e9502f..f2172cf03fd 100644
--- a/test/metabase/notification/payload/execute_test.clj
+++ b/test/metabase/notification/payload/execute_test.clj
@@ -3,6 +3,7 @@
(:require
[clojure.test :refer :all]
[metabase.notification.payload.execute :as notification.payload.execute]
+ [metabase.notification.payload.temp-storage :as temp-storage]
[metabase.test :as mt]))
(set! *warn-on-reflection* true)
@@ -49,3 +50,35 @@
result (:result part)]
(is (= :card (:type part)))
(check-result-structure result))))))
+
+(defn- card-parts [parts]
+ (filter #(= :card (:type %)) parts))
+
+(defn- spilled-part? [part]
+ (temp-storage/streaming-temp-file? (-> part :result :data :rows)))
+
+(deftest tabbed-dashboard-shares-one-spill-budget-test
+ (testing "the resident-memory budget is shared across a multi-tab dashboard, so cards in different tabs collectively
+ count toward the spill cap (otherwise many small cards across tabs could exhaust memory)"
+ ;; Each card selects exactly 3 fields with a :limit of 100 -> exactly 300 cells per card (deterministic, not
+ ;; dependent on the seeded table's shape). Two cards per tab = 600 cells, under the 1000-cell cap WITHIN a tab,
+ ;; so nothing would spill if each tab had its own budget. Across both tabs the shared running total reaches 1200,
+ ;; crossing the cap, so a SHARED budget forces the later cards to spill.
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query venues
+ {:fields [$id $name $price]
+ :limit 100})}
+ :model/Dashboard {dash-id :id} {}
+ :model/DashboardTab {tab1 :id} {:dashboard_id dash-id :name "Tab 1" :position 0}
+ :model/DashboardTab {tab2 :id} {:dashboard_id dash-id :name "Tab 2" :position 1}
+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id tab1 :card_id card-id}
+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id tab1 :card_id card-id}
+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id tab2 :card_id card-id}
+ :model/DashboardCard _ {:dashboard_id dash-id :dashboard_tab_id tab2 :card_id card-id}]
+ (let [budget (temp-storage/make-resident-budget {:per-card 100000 :resident-cap 1000 :floor 100})
+ parts (card-parts (notification.payload.execute/execute-dashboard
+ dash-id (mt/user->id :rasta) [] budget))]
+ (is (= 4 (count parts)) "all four cards render")
+ (is (some spilled-part? parts)
+ "with a shared budget the cumulative cells across tabs cross the cap, so a later card spills to disk")
+ ;; clean up any temp files we created
+ (doseq [p parts] (temp-storage/cleanup! (-> p :result :data :rows)))))))
diff --git a/test/metabase/notification/payload/temp_storage_test.clj b/test/metabase/notification/payload/temp_storage_test.clj
index 1d298097455..8da9a11b9ed 100644
--- a/test/metabase/notification/payload/temp_storage_test.clj
+++ b/test/metabase/notification/payload/temp_storage_test.clj
@@ -8,10 +8,15 @@
(set! *warn-on-reflection* true)
(defn- run-rff
- "Helper to run notification-rff with given max-rows and row data."
- [max-rows row-data]
- (let [metadata {:cols [{:name "id"} {:name "value"}]}
- rff (temp-storage/notification-rff max-rows {})
+ "Helper to run notification-rff with a per-query cell spill threshold (or a full options map) and row data. A bare int
+ `n` becomes a `:budget` whose `:per-card` limit spills once this query holds `n` or more cells in memory."
+ [threshold-or-options row-data]
+ (let [options (if (map? threshold-or-options)
+ threshold-or-options
+ {:budget (temp-storage/make-resident-budget
+ {:per-card threshold-or-options :resident-cap Long/MAX_VALUE :floor Long/MAX_VALUE})})
+ metadata {:cols [{:name "id"} {:name "value"}]}
+ rff (temp-storage/notification-rff options {})
rf (rff metadata)]
(transduce identity rf row-data)))
@@ -95,7 +100,9 @@
(deftest streaming-data-integrity-test
(testing "Repeated values preserve correctly"
(let [metadata {:cols (for [c ["a" "b" "c" "d" "e"]] {:name c})}
- rff (temp-storage/notification-rff 5 {})
+ rff (temp-storage/notification-rff
+ {:budget (temp-storage/make-resident-budget {:per-card 4 :resident-cap Long/MAX_VALUE :floor Long/MAX_VALUE})}
+ {})
rf (rff metadata)
data (for [i (range 6)] (vec (repeat 5 i)))
result (transduce identity rf data)
@@ -134,6 +141,63 @@
(is (not (realized? storage)))
(temp-storage/cleanup! storage))))
+;; ------------------------------------------------------------------------------------------------;;
+;; Cross-card resident budget ;;
+;; ------------------------------------------------------------------------------------------------;;
+
+(defn- run-card!
+ "Run one card's worth of `n` single-cell rows through `notification-rff` sharing `budget`. Returns the result map.
+ Single-cell rows mean cell-count == row-count, so the budget math is easy to reason about."
+ [budget n]
+ (let [rff (temp-storage/notification-rff {:budget budget} {})
+ rf (rff {:cols [{:name "a"}]})]
+ (transduce identity rf (vec (repeat n [1])))))
+
+(defn- resident [budget]
+ @(:resident budget))
+
+(defn- storage-of [result]
+ (:notification/storage result))
+
+(deftest cross-card-budget-test
+ (testing "a card whose cells alone exceed :per-card spills even on a cold dashboard"
+ (let [budget (temp-storage/make-resident-budget {:per-card 20 :resident-cap 1000 :floor 5})
+ result (run-card! budget 25)]
+ (is (= :disk (storage-of result)))
+ (is (zero? (resident budget)) "spilled cards add nothing to resident")
+ (temp-storage/cleanup! (get-in result [:data :rows]))))
+ (testing "in-memory cards fold their cells into the shared resident total; spilled cards add 0"
+ (let [budget (temp-storage/make-resident-budget {:per-card 20 :resident-cap 1000 :floor 5})
+ a (run-card! budget 8)]
+ (is (= :memory (storage-of a)))
+ (is (= 8 (resident budget)) "first in-memory card folds its 8 cells in")
+ (let [b (run-card! budget 7)]
+ (is (= :memory (storage-of b)))
+ (is (= 15 (resident budget)) "second in-memory card adds to the running total"))))
+ (testing "once resident is over the cap, later non-tiny cards spill (resident stays put)"
+ (let [budget (temp-storage/make-resident-budget {:per-card 100 :resident-cap 20 :floor 5})]
+ (reset! (:resident budget) 25) ; sibling cards already hold 25 cells, over the cap of 20
+ (let [c (run-card! budget 8)] ; 8 > floor (5), resident over cap -> spill
+ (is (= :disk (storage-of c)))
+ (is (= 25 (resident budget)) "spilled card leaves resident unchanged")
+ (temp-storage/cleanup! (get-in c [:data :rows])))))
+ (testing "tiny cards (below :floor) stay in memory even when resident is over the cap"
+ (let [budget (temp-storage/make-resident-budget {:per-card 100 :resident-cap 20 :floor 5})]
+ (reset! (:resident budget) 25) ; already over the cap
+ (let [d (run-card! budget 4)] ; 4 < floor (5) -> stays in memory despite over-cap resident
+ (is (= :memory (storage-of d)))
+ (is (= 29 (resident budget)) "tiny in-memory card still folds its cells in"))))
+ (testing "the in-flight card's own cells count toward the cap (combined check) - regression"
+ ;; resident sits just under the cap; a card that is individually under :per-card but whose cells push
+ ;; (resident + this-query) over the cap must spill. Before the combined check this case was missed.
+ (let [budget (temp-storage/make-resident-budget {:per-card 100 :resident-cap 20 :floor 5})]
+ (run-card! budget 19) ; resident -> 19 (just under cap 20)
+ (is (= 19 (resident budget)))
+ (let [b (run-card! budget 15)] ; 15 < per-card, but 19+15=34 > 20 and 15 > floor -> spill
+ (is (= :disk (storage-of b)))
+ (is (= 19 (resident budget)) "the over-cap card spills rather than riding up in memory")
+ (temp-storage/cleanup! (get-in b [:data :rows]))))))
+
(deftest fidelity
(testing "Untruncated results should be equal"
(let [query (mt/mbql-query orders)]
@@ -141,7 +205,9 @@
(mt/with-temporary-setting-values [notification-temp-file-size-max-bytes (* 10 1024 1024)]
(let [qp-results (mt/process-query query)
temp-file-results (mt/process-query query
- (temp-storage/notification-rff 20000))]
+ (temp-storage/notification-rff
+ {:budget (temp-storage/make-resident-budget
+ {:per-card 20000 :resident-cap Long/MAX_VALUE :floor Long/MAX_VALUE})}))]
(is (not (:notification/truncated? temp-file-results)))
(is (temp-storage/streaming-temp-file? (-> temp-file-results :data :rows)))
(is (= (-> qp-results :data :rows)