Skip to content

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

Add /ee/python-transforms/test-run to preview a run (#64362)

Dan Stoned12930529f92
diff --git a/enterprise/backend/src/metabase_enterprise/transforms/instrumentation.clj b/enterprise/backend/src/metabase_enterprise/transforms/instrumentation.clj
index 013979d70ea..c991d0ede58 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms/instrumentation.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms/instrumentation.clj
@@ -31,7 +31,7 @@
(mu/defn record-stage-start!
"Record the start of a transform stage."
- [job-run-id :- pos-int?
+ [job-run-id :- [:maybe pos-int?]
stage-label :- ::stage-label]
(let [stage-type (label-to-stage stage-label)]
(log/infof "Transform stage started: run-id=%d type=%s label=%s" job-run-id (name stage-type) (name stage-label))
@@ -41,7 +41,7 @@
(mu/defn record-stage-completion!
"Record the successful completion of a transform stage."
- [job-run-id :- pos-int?
+ [job-run-id :- [:maybe pos-int?]
stage-label :- ::stage-label
duration-ms :- int?]
(let [stage-type (label-to-stage stage-label)]
@@ -53,7 +53,7 @@
(mu/defn record-stage-failure!
"Record the failure of a transform stage."
- [job-run-id :- pos-int?
+ [job-run-id :- [:maybe pos-int?]
stage-label :- ::stage-label
duration-ms :- int?]
(let [stage-type (label-to-stage stage-label)]
@@ -108,7 +108,7 @@
(mu/defn record-data-transfer!
"Record metrics about data transfer (size and rows)."
- [job-run-id :- pos-int?
+ [job-run-id :- [:maybe pos-int?]
stage-label :- ::stage-label
bytes :- [:maybe int?]
rows :- [:maybe int?]]
@@ -166,7 +166,7 @@
(mu/defn record-python-api-call!
"Record metrics about Python API calls."
- [job-run-id :- pos-int?
+ [job-run-id :- [:maybe pos-int?]
duration-ms :- int?
status :- [:enum :success :error :timeout]]
(log/infof "Python API call %s: run-id=%d duration=%dms" (name status) job-run-id duration-ms)
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj
index 6954f7addb8..d59ec61bb70 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj
@@ -1,10 +1,18 @@
(ns metabase-enterprise.transforms-python.api
(:require
+ [clojure.java.io :as io]
+ [clojure.string :as str]
[metabase-enterprise.transforms-python.models.python-library :as python-library]
+ [metabase-enterprise.transforms-python.python-runner :as python-runner]
+ [metabase-enterprise.transforms-python.s3 :as s3]
+ [metabase-enterprise.transforms-python.settings :as transforms-python.settings]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
- [metabase.api.util.handlers :as handlers]))
+ [metabase.api.util.handlers :as handlers]
+ [metabase.util :as u]
+ [metabase.util.i18n :as i18n]
+ [metabase.util.json :as json]))
(api.macros/defendpoint :get "/library/:path"
"Get the Python library for user modules."
@@ -24,6 +32,60 @@
(api/check-superuser)
(python-library/update-python-library-source! path (:source body)))
+(api.macros/defendpoint :post "/test-run"
+ :- [:map
+ [:logs :string]
+ [:error {:optional true} [:map [:message i18n/LocalizedString]]]
+ [:output {:optional true} [:map [:rows :any]]]]
+ "Evaluate an ad-hoc python transform on a sample of input data.
+ Intended for short runs for early feedback. Input/output/timeout limits apply."
+ [_
+ _
+ {:keys [code
+ source_tables
+ output_row_limit
+ per_input_row_limit]
+ :or {output_row_limit 100
+ per_input_row_limit 100}}
+ :- [:map
+ [:code :string]
+ [:source_tables [:map-of :string :int]]
+ [:output_row_limit {:optional true} [:and :int [:> 1] [:<= 100]]]
+ [:per_input_row_limit {:optional true} [:and :int [:> 1] [:<= 100]]]]]
+ (api/check-superuser)
+ ;; NOTE: we do not test database support, as there is no write target.
+ (with-open [shared-storage-ref (s3/open-shared-storage! source_tables)]
+ (let [server-url (transforms-python.settings/python-runner-url)
+ _ (python-runner/copy-tables-to-s3! {:shared-storage @shared-storage-ref
+ :table-name->id source_tables
+ :limit per_input_row_limit})
+ {runner-status :status
+ runner-body :body}
+ (python-runner/execute-python-code-http-call!
+ {:server-url server-url
+ :code code
+ :request-id (u/generate-nano-id)
+ :table-name->id source_tables
+ :timeout-secs (transforms-python.settings/python-runner-test-run-timeout-seconds)
+ :shared-storage @shared-storage-ref})
+ events (python-runner/read-events @shared-storage-ref)
+ run-logs (str/join "\n" (map :message events))]
+ (cond
+ (:timeout runner-body)
+ {:logs run-logs
+ :error {:message (i18n/deferred-tru "Python execution timed out")}}
+
+ (not= 200 runner-status)
+ {:logs run-logs
+ :error {:message (i18n/deferred-tru "Python execution failure (exit code {0})" (:exit_code runner-body "?"))}}
+
+ :else
+ {:logs run-logs
+ :output (with-open [in (python-runner/open-output @shared-storage-ref)
+ rdr (io/reader in)]
+ (let [sample-rows (take output_row_limit (line-seq rdr))]
+ {:rows (mapv json/decode (remove str/blank? sample-rows))}))}))))
+
(def ^{:arglists '([request respond raise])} routes
"`/api/ee/transforms-python` routes."
(handlers/routes
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj
index 810ea7b4dea..2b667319915 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj
@@ -262,8 +262,7 @@
output-manifest (python-runner/read-output-manifest @shared-storage-ref)
events (python-runner/read-events @shared-storage-ref)]
(.close log-future-ref) ; early close to force any writes to flush
- (when (seq events)
- (replace-python-logs! message-log events))
+ (replace-python-logs! message-log events)
(if (not= 200 status)
(do
(when (:timeout body)
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj
index f420f1f2734..06427e90138 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj
@@ -146,8 +146,9 @@
:else
v))
-(defn- write-table-data-to-file! [{:keys [db-id driver table-id fields-meta temp-file cancel-chan]}]
- (let [query {:source-table table-id}]
+(defn- write-table-data-to-file! [{:keys [db-id driver table-id fields-meta temp-file cancel-chan limit]}]
+ {:pre [(or (nil? limit) (pos-int? limit))]}
+ (let [query (cond-> {:source-table table-id} limit (assoc :limit limit))]
(execute-mbql-query driver db-id query
(fn [{cols-meta :cols} reducible-rows]
(with-open [os (io/output-stream temp-file)]
@@ -173,7 +174,7 @@
(defn execute-python-code-http-call!
"Calls the /execute endpoint of the python runner. Blocks until the run either succeeds or fails and returns
the response from the server."
- [{:keys [server-url code run-id table-name->id shared-storage]}]
+ [{:keys [server-url code request-id run-id table-name->id shared-storage timeout-secs]}]
(let [{:keys [objects]} shared-storage
{:keys [output output-manifest events]} objects
@@ -183,8 +184,8 @@
payload {:code code
:library (t2/select-fn->fn :path :source :model/PythonLibrary)
- :timeout (transforms-python.settings/python-runner-timeout-seconds)
- :request_id run-id
+ :timeout (or timeout-secs (transforms-python.settings/python-runner-timeout-seconds))
+ :request_id (or request-id run-id)
:output_url (:url output)
:output_manifest_url (:url output-manifest)
:events_url (:url events)
@@ -251,7 +252,8 @@
[{:keys [run-id
shared-storage
table-name->id
- cancel-chan]}]
+ cancel-chan
+ limit]}]
;; TODO there's scope for some parallelism here, in particular across different databases
(doseq [[table-name table-id] table-name->id
:let [{:keys [s3-client bucket-name objects]} shared-storage
@@ -272,7 +274,8 @@
:table-id table-id
:fields-meta fields-meta
:temp-file tmp-data-file
- :cancel-chan cancel-chan}))
+ :cancel-chan cancel-chan
+ :limit limit}))
(with-open [writer (io/writer tmp-meta-file)]
(json/encode-to manifest writer {}))
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/settings.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/settings.clj
index 850eb8e4de0..f0f1fdee36a 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_python/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/settings.clj
@@ -124,3 +124,14 @@
:export? false
:encryption :no
:audit :getter)
+
+(setting/defsetting python-runner-test-run-timeout-seconds
+ (deferred-tru "Timeout in seconds for Python script test runs. Defaults to 1 minute (60 seconds).")
+ :type :integer
+ :visibility :admin
+ :default 60
+ :feature :transforms-python
+ :doc false
+ :export? false
+ :encryption :no
+ :audit :getter)
diff --git a/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj b/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj
index 9bd003ed532..a770f70b88e 100644
--- a/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj
@@ -1,8 +1,10 @@
-(ns metabase-enterprise.transforms-python.api-test
+(ns ^:mb/driver-tests ^:mb/transforms-python-test metabase-enterprise.transforms-python.api-test
"Tests for /api/ee/transforms-python endpoints."
(:require
+ [clojure.string :as str]
[clojure.test :refer :all]
[metabase-enterprise.transforms-python.models.python-library :as python-library]
+ [metabase-enterprise.transforms.test-dataset :as transforms-dataset]
[metabase.test :as mt]
[toucan2.core :as t2]))
@@ -87,3 +89,97 @@
(is (= "Invalid library path. Only 'common' is currently supported."
(:message (mt/user-http-request :crowberto :put 400 "ee/transforms-python/library/invalid-path"
{:source "def test(): pass"}))))))))
+
+(deftest test-run-test
+ (mt/with-premium-features #{:transforms :transforms-python}
+ (let [program ["import pandas as pd"
+ "import sys"
+ "def transform():"
+ " print(\"out1\")"
+ " print(\"err1\", file=sys.stderr)"
+ " print(\"out2\")"
+ " print(\"err2\", file=sys.stderr)"
+ " return pd.DataFrame({'x': [42, 43]})"]
+ body {:source_tables {}, :code (str/join "\n" program)}
+ {:keys [error logs output]} (mt/user-http-request :crowberto :post 200 "ee/transforms-python/test-run" body)]
+ (is (nil? error))
+ (is (str/includes? logs "out1\nerr1\nout2\nerr2"))
+ (is (= {:rows [{:x 42} {:x 43}]} output)))))
+
+(defn- test-run [& {:keys [program user features source-tables extra-opts]
+ :or {program ["import pandas as pd" "def transform():" " return pd.DataFrame()"]
+ user :crowberto
+ source-tables {}
+ features #{:transforms :transforms-python}}}]
+ (let [body (merge {:source_tables source-tables, :code (str/join "\n" program)} extra-opts)]
+ (mt/with-premium-features features
+ (mt/user-http-request-full-response user :post "ee/transforms-python/test-run" body))))
+
+(deftest test-run-with-inputs-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/python)
+ (mt/dataset transforms-dataset/transforms-test
+ (let [program ["def transform(customers):" " return customers"]
+ source-tables {"customers" (mt/id :transforms_customers)}
+ {:keys [status body]} (test-run :program program :source-tables source-tables)]
+ (is (= 200 status))
+ (is (nil? (:error body)))
+ (is (seq (:rows (:output body))))))))
+
+(deftest test-run-empty-results-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/python)
+ (mt/dataset transforms-dataset/transforms-test
+ (let [program ["import pandas as pd" "def transform(customers):" " return pd.DataFrame()"]
+ source-tables {"customers" (mt/id :transforms_customers)}
+ {:keys [status body]} (test-run :program program :source-tables source-tables)]
+ (is (= 200 status))
+ (is (nil? (:error body)))
+ (is (empty? (:rows (:output body))))))))
+
+(deftest test-run-error-test
+ (let [program ["import pandas as pd" "def transform():" " totallynotsourcecode"]
+ {:keys [status body]} (test-run :program program)]
+ (is (= 200 status))
+ (is (=? {:message "Python execution failure (exit code 1)"} (:error body)))
+ (is (str/includes? (:logs body "") "Traceback"))))
+
+(deftest test-run-feature-test
+ (is (=? {:status 402} (test-run :features #{})))
+ (testing "transforms alone is not enough"
+ (is (=? {:status 402} (test-run :features #{:transforms}))))
+ (is (=? {:status 200} (test-run :features #{:transforms :transforms-python}))))
+
+(deftest test-run-permissions-test
+ (is (=? {:status 403} (test-run :user :rasta)))
+ (is (=? {:status 200} (test-run :user :crowberto))))
+
+(deftest test-run-input-limit-test
+ (testing "maximum"
+ (is (=? {:status 400} (test-run :extra-opts {:per_input_row_limit 10000}))))
+ (testing "minimum"
+ (is (=? {:status 400} (test-run :extra-opts {:per_input_row_limit 0}))))
+ (testing "truncates sources"
+ (mt/dataset transforms-dataset/transforms-test
+ (let [program ["def transform(customers):" " return customers"]
+ source-tables {"customers" (mt/id :transforms_customers)}
+ response (test-run :program program :source-tables source-tables :extra-opts {:per_input_row_limit 2})]
+ (is (=? {:body {:output {:rows #(= 2 (count %))}}} response))))))
+
+(deftest test-run-output-limit-test
+ (testing "maximum"
+ (is (=? {:status 400} (test-run :extra-opts {:output_row_limit 10000}))))
+ (testing "minimum"
+ (is (=? {:status 400} (test-run :extra-opts {:output_row_limit 0}))))
+ (testing "truncates outputs"
+ (let [program ["import pandas as pd" "def transform():" " return pd.DataFrame({'x': [1,2,3,4]})"]
+ response (test-run :program program :extra-opts {:output_row_limit 2})]
+ (is (=? {:body {:output {:rows #(= 2 (count %))}}} response)))))
+
+(deftest test-run-timeout-test
+ (let [program ["import pandas as pd"
+ "import time"
+ "def transform():"
+ " time.sleep(30)"
+ " return pd.DataFrame()"]]
+ (mt/with-temporary-setting-values [python-runner-test-run-timeout-seconds 1]
+ (let [response (test-run :program program)]
+ (is (=? {:body {:error {:message "Python execution timed out"}}} response))))))
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index cb9d4d39387..e2b312dda1f 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -689,6 +689,7 @@ export interface EnterpriseSettings extends Settings {
"python-storage-s-3-container-endpoint"?: string | null;
"python-storage-s-3-path-style-access"?: boolean | null;
"python-runner-timeout-seconds"?: number | null;
+ "python-runner-test-run-timeout-seconds"?: number | null;
/**
* @deprecated
*/