Skip to content

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

Bound pr-str when logging LLM errors (#74796)

Chris Truter2520cb43c24a
diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.clj
index e6f14ea3757..52c5c3a1336 100644
--- a/src/metabase/metabot/agent/core.clj
+++ b/src/metabase/metabot/agent/core.clj
@@ -15,6 +15,7 @@
[metabase.metabot.provider-util :as provider-util]
[metabase.metabot.scope :as scope]
[metabase.metabot.self :as self]
+ [metabase.metabot.self.core :as self.core]
[metabase.metabot.tools :as tools]
[metabase.util :as u]
[metabase.util.json :as json]
@@ -628,7 +629,7 @@
(cond
(and api-error status)
(log/errorf e "Agent loop API error: %s status=%s provider=%s body=%s"
- msg status provider (pr-str body))
+ msg status provider (self.core/body-for-log body))
api-error
(log/errorf e "Agent loop API error: %s provider=%s" msg provider)
diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.clj
index 7acb8d3e447..471d45d71f9 100644
--- a/src/metabase/metabot/self/core.clj
+++ b/src/metabase/metabot/self/core.clj
@@ -3,6 +3,7 @@
[clj-http.client :as http]
[clojure.java.io :as io]
[clojure.string :as str]
+ [clojure.walk :as walk]
[metabase.llm.settings :as llm]
[metabase.premium-features.core :as premium-features]
[metabase.util :as u]
@@ -576,15 +577,30 @@
s
(str (subs s 0 limit) "…")))
+(defn- bounded-pr-str
+ "`pr-str` a body for error surfacing without first allocating an unbounded string.
+ Walks the body and slices every string leaf to `limit` before printing — so a parsed
+ JSON map like `{:detail \"<1MB>\"}` doesn't allocate the full 1MB leaf inside `pr-str`
+ only for the caller to truncate it back down. Collections also render under
+ `*print-length*`/`*print-level*` to bound element count and nesting depth."
+ [body limit]
+ (let [slice (fn [x] (cond-> x (string? x) (truncate-to limit)))]
+ (binding [*print-length* 100
+ *print-level* 10]
+ (pr-str (walk/postwalk slice body)))))
+
(defn- truncate-to-preview-limit
"Cap `s` at [[max-body-preview-chars]] with a trailing ellipsis when it overflows."
[s]
(truncate-to s max-body-preview-chars))
-(defn- body-for-log
- "Bounded `pr-str` of a coerced body for warn/error log lines, capped at [[max-body-log-chars]]."
+(defn body-for-log
+ "Bounded `pr-str` of a coerced body for warn/error log lines, capped at [[max-body-log-chars]].
+ Public so the agent loop's error logging bounds the body the same way.
+ Assumes a bounded input (a decoded ≤[[max-body-slurp-chars]] body) — the walk bounds rendered
+ output, not traversal, so a large unbounded collection would still be fully walked."
[body]
- (truncate-to (pr-str body) max-body-log-chars))
+ (truncate-to (bounded-pr-str body max-body-log-chars) max-body-log-chars))
(defn- body-preview
"Short snippet of an upstream response body for the user-facing exception message.
@@ -601,15 +617,12 @@
(string? head) head
:else nil))
:else nil)
- ;; Surface *some* context to the user even for unrecognised shapes — the warn
- ;; signals operators to add the new envelope shape to [[extract-error-message]].
- ;; Truncate once: the warn line shouldn't carry a multi-MB pr-str any more than
- ;; the user-facing exception message should.
+ ;; Surface *some* context in the message even for unrecognised shapes — a raw pr-str
+ ;; beats a bare "HTTP 500" with no clue what the upstream said. rethrow-api-error! logs
+ ;; the (bounded) body once already, so we don't warn again here.
s (or extracted
(when (and (or (map? body) (sequential? body)) (seq body))
- (let [capped (truncate-to-preview-limit (pr-str body))]
- (log/warnf "body-preview: unrecognised error body shape; pr-str=%s" capped)
- capped)))]
+ (truncate-to-preview-limit (bounded-pr-str body max-body-preview-chars))))]
(some-> s str/trim not-empty truncate-to-preview-limit)))
(def ^:private auth-error-statuses
diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.clj
index 0119c9ad5fd..455866a1fcd 100644
--- a/test/metabase/metabot/self_test.clj
+++ b/test/metabase/metabot/self_test.clj
@@ -891,7 +891,9 @@
(is (every? nil? (map body-preview [{} []])))
(msgs))]
(is (empty? msgs))))
- (testing "non-empty maps/arrays without a recognised error field pr-str into the preview + warn"
+ (testing "non-empty maps/arrays without a recognised error field pr-str into the preview, no warn"
+ ;; rethrow-api-error! already emits a single warn at the failure boundary with the (bounded) body,
+ ;; so body-preview must not emit a second warn for unrecognised shapes — that's a duplicate.
(let [bodies [{:request-id "abc" :trace ["frame1"]}
[42 :kw]
[{:request-id "abc"}]
@@ -901,9 +903,8 @@
(is (= (pr-str b) (body-preview b))
(str "pr-str fallback for " (pr-str b))))
(msgs))]
- (is (= (count bodies) (count msgs))
- "one warn line per pr-str fallback")
- (is (every? #(re-find #"unrecognised error body shape" (:message %)) msgs))))
+ (is (empty? msgs)
+ "body-preview must not warn — rethrow-api-error! logs the (bounded) body once already")))
(testing "JSON arrays probe their first element"
(is (= "rate limited" (body-preview [{:error {:message "rate limited"}} {:type "x"}])))
(is (= "first message" (body-preview ["first message" "ignored"]))))
@@ -912,6 +913,39 @@
(is (str/ends-with? preview "…"))
(is (= 501 (count preview)))))))
+(deftest ^:parallel body-for-log-bounding-test
+ (let [body-for-log #'self.core/body-for-log
+ bounded-pr-str #'self.core/bounded-pr-str
+ max-log @#'self.core/max-body-log-chars]
+ (testing "a huge string body is sliced before pr-str, never rendered in full"
+ ;; Proof of pre-truncation: without it, bounded-pr-str would print all 1M chars before
+ ;; the caller could truncate. The printed result stays near the limit instead.
+ (is (< (count (bounded-pr-str (apply str (repeat 1000000 \x)) max-log))
+ (+ max-log 10))))
+ (testing "body-for-log caps a huge string at max-body-log-chars with an ellipsis"
+ (let [out (body-for-log (apply str (repeat 1000000 \x)))]
+ (is (str/ends-with? out "…"))
+ (is (= (inc max-log) (count out)))))
+ (testing "a many-element collection renders under *print-length* and stays bounded"
+ (let [out (body-for-log (vec (range 100000)))]
+ (is (<= (count out) max-log))
+ (is (str/includes? out "...") "the *print-length* elision marker is present")))
+ (testing "a small recognised body is left untouched by the bounds"
+ (is (= (pr-str {:error {:message "nope"}})
+ (body-for-log {:error {:message "nope"}}))))
+ (testing "a huge string leaf inside a collection is sliced before pr-str renders the parent"
+ ;; Regression: previously `bounded-pr-str` only pre-sliced *top-level* strings.
+ ;; A map with a near-cap string leaf (e.g. parsed JSON `{:detail "<1MB>"}`)
+ ;; would allocate the whole leaf inside pr-str and rely on the outer truncate-to
+ ;; to cap the result — wasteful on the error path. Now nested string leaves
+ ;; get sliced too.
+ (let [body {:detail (apply str (repeat 1000000 \x))}
+ out (bounded-pr-str body max-log)]
+ (is (<= (count out) (+ max-log 100))
+ "bounded-pr-str should not render the full huge string leaf")
+ (is (str/includes? out ":detail")
+ "the map structure should still survive past the slicing")))))
+
(defn- caught
"Run `thunk` and return the thrown exception, or nil if it didn't throw."
[thunk]