From a8b22287533ca72c3c09d59d5c0facadd2973703 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 24 Nov 2026 21:45:42 +0000 Subject: [PATCH] fix: bind datatable() args as literals and read _FLOW_PATH on previews (#12638) Co-authored-by: Claude Opus 5.5 --- backend/windmill-common/src/jobs.rs | 2 ++ backend/windmill-common/src/worker.rs | 19 ++++++++++++++++++- backend/windmill-queue/src/jobs.rs | 2 +- backend/windmill-types/src/jobs.rs | 17 +++++++++++++---- backend/windmill-worker/src/common.rs | 16 ++++++++++++++++ .../windmill-worker/src/duckdb_executor.rs | 10 ++++++++-- backend/windmill-worker/src/pg_executor.rs | 13 +++++++++---- python-client/wmill/wmill/client.py | 8 +++++++- typescript-client/sqlUtils.ts | 10 ++++++++-- 9 files changed, 82 insertions(+), 15 deletions(-) diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index 2e5dafe1b2..ecc2143c1c 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -841,6 +841,8 @@ mod reserved_args_tests { ("_MODULES\u{0}", r#"{"m.py": "evil"}"#), ("_TEMP_SCRIPT_REFS", r#"{"f/a/b": "deadbeef"}"#), ("_TEMP_SCRIPT_REFS\u{0}", r#"{"f/a/b": "deadbeef"}"#), + ("_FLOW_PATH", r#""u/alice/prod_db?""#), + ("_FLOW_PATH\u{0}", r#""u/alice/prod_db?""#), // Neighbours that must not be caught by a prefix/contains match. ("_TEMP_SCRIPT_REFS_", r#"1"#), ("entrypoint", r#""main""#), diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index 05e2ad17ce..b6ef53a892 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -868,7 +868,7 @@ fn format_pull_query(peek: String) -> String { j.same_worker, j.pre_run_error, j.visible_to_owner, j.tag, j.concurrent_limit, j.concurrency_time_window_s, j.flow_innermost_root_job, j.root_job, j.timeout, j.flow_step_id, j.cache_ttl, q.cache_ignore_s3_path, q.runnable_settings_handle, j.priority, j.raw_code, j.raw_lock, j.raw_flow, - j.script_entrypoint_override, j.preprocessed, p.job_token_scopes, COALESCE(pj.runnable_path, j.args->>'_FLOW_PATH') as parent_runnable_path, + j.script_entrypoint_override, j.preprocessed, p.job_token_scopes, COALESCE(pj.runnable_path, CASE WHEN j.kind = 'preview' THEN j.args->>'_FLOW_PATH' END) as parent_runnable_path, COALESCE(p.email, j.permissioned_as_email) as permissioned_as_email, p.username as permissioned_as_username, p.is_admin as permissioned_as_is_admin, p.is_operator as permissioned_as_is_operator, p.groups as permissioned_as_groups, p.folders as permissioned_as_folders, p.end_user_email as permissioned_as_end_user_email, p.viewer_data_access, p.mcp_client @@ -1294,6 +1294,10 @@ pub struct SqlAnnotations { // `wmill datatable serve` to map Postgres results onto the wire protocol // without re-stringifying every JSON value. pub raw_output: bool, + // The job's args are values bound to the query's parameters, passed on as they are: + // `$var:`/`$res:` strings and `$`-prefixed reserved variable names in them stay text. + // Emitted by the SDKs' `datatable()`/`ducklake()` helpers, whose args are run-time data. + pub literal_args: bool, } impl SqlAnnotations { @@ -4154,6 +4158,19 @@ mod tests { assert!(combined.prepare); } + #[test] + fn test_sql_literal_args_annotation() { + // As the SDK helpers emit it, among the other leading annotations. + let sdk = SqlAnnotations::parse( + "-- result_collection=last_statement_first_row\n-- literal_args\n-- role analytics\n-- $1 arg1\nSELECT $1::TEXT", + ); + assert!(sdk.literal_args); + + assert!(!SqlAnnotations::parse("-- $1 arg1\nSELECT $1::TEXT").literal_args); + // Only the leading comment block is read: a value cannot switch it on or off. + assert!(!SqlAnnotations::parse("SELECT 1;\n-- literal_args").literal_args); + } + #[test] fn test_no_network_annotation() { assert!(PythonAnnotations::parse("# sandbox\n# no_network\ndef main(): pass").no_network); diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index e1317a975f..cb3865151a 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -9479,7 +9479,7 @@ pub async fn get_same_worker_job( v2_job.raw_code, v2_job.raw_lock, v2_job.raw_flow, - COALESCE(pj.runnable_path, v2_job.args->>'_FLOW_PATH') as parent_runnable_path, + COALESCE(pj.runnable_path, CASE WHEN v2_job.kind = 'preview' THEN v2_job.args->>'_FLOW_PATH' END) as parent_runnable_path, p.email as permissioned_as_email, p.username as permissioned_as_username, p.is_admin as permissioned_as_is_admin, p.is_operator as permissioned_as_is_operator, p.groups as permissioned_as_groups, p.folders as permissioned_as_folders, p.end_user_email as permissioned_as_end_user_email, p.viewer_data_access, p.mcp_client diff --git a/backend/windmill-types/src/jobs.rs b/backend/windmill-types/src/jobs.rs index 4a3fe6bdbb..836cc5ee6a 100644 --- a/backend/windmill-types/src/jobs.rs +++ b/backend/windmill-types/src/jobs.rs @@ -743,10 +743,15 @@ pub const MODULES_ARG: &str = "_MODULES"; /// honor it on every `JobKind::Preview` job. pub const TEMP_SCRIPT_REFS_ARG: &str = "_TEMP_SCRIPT_REFS"; +/// Job-arg key the preview route sets server-side from its `flow_path` field, so a step +/// tested from the flow editor sees its flow's path. `WM_FLOW_PATH`, `WM_STATE_PATH` and +/// `WM_OBJECT_PATH` derive from it; the worker honors it only on `JobKind::Preview` jobs. +pub const FLOW_PATH_ARG: &str = "_FLOW_PATH"; + /// Job-arg keys that steer *how* a runnable runs rather than what it is given: which /// function the worker calls instead of `main` ([`ENTRYPOINT_OVERRIDE`]), what module files -/// are written into the job directory ([`MODULES_ARG`]) and where its workspace imports -/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]). +/// are written into the job directory ([`MODULES_ARG`]), where its workspace imports +/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]) and where its state lives ([`FLOW_PATH_ARG`]). /// /// Each is legitimate for a caller that runs code it authored under its own identity (the /// script editor's preprocessor test, dynamic-select helpers, the CLI, workflow-as-code), so @@ -754,8 +759,12 @@ pub const TEMP_SCRIPT_REFS_ARG: &str = "_TEMP_SCRIPT_REFS"; /// payload runs under somebody else's identity — an HTTP route body, a native trigger /// message, a public app viewer's inputs — which is what `sanitize_untrusted_args` in /// `windmill_common::jobs` drops. -pub const RESERVED_CONTROL_ARGS: [&str; 3] = - [ENTRYPOINT_OVERRIDE, MODULES_ARG, TEMP_SCRIPT_REFS_ARG]; +pub const RESERVED_CONTROL_ARGS: [&str; 4] = [ + ENTRYPOINT_OVERRIDE, + MODULES_ARG, + TEMP_SCRIPT_REFS_ARG, + FLOW_PATH_ARG, +]; /// Reserved job-arg key holding the inbound W3C `traceparent` captured from the /// request that enqueued the job (run endpoints). It rides the `args` jsonb like diff --git a/backend/windmill-worker/src/common.rs b/backend/windmill-worker/src/common.rs index 6dc98f1cda..381b004ca1 100644 --- a/backend/windmill-worker/src/common.rs +++ b/backend/windmill-worker/src/common.rs @@ -142,6 +142,22 @@ pub async fn build_args_values( } } +/// The job's args exactly as submitted, for a query annotated `-- literal_args`: unlike +/// [`build_args_values`], no `$var:`/`$res:`/`$encrypted:` reference and no `$`-prefixed +/// reserved variable in them is resolved. +pub fn build_literal_args_values(job: &MiniPulledJob) -> HashMap { + job.args + .iter() + .flat_map(|args| args.0.iter()) + .map(|(k, v)| { + ( + k.to_string(), + serde_json::from_str(v.get()).unwrap_or_else(|_| serde_json::Value::Null), + ) + }) + .collect() +} + #[tracing::instrument(level = "trace", skip_all)] pub async fn create_args_and_out_file( client: &AuthedClient, diff --git a/backend/windmill-worker/src/duckdb_executor.rs b/backend/windmill-worker/src/duckdb_executor.rs index 2ef8607de4..bbdc6b3267 100644 --- a/backend/windmill-worker/src/duckdb_executor.rs +++ b/backend/windmill-worker/src/duckdb_executor.rs @@ -21,7 +21,9 @@ use windmill_queue::{append_logs, CanceledBy, MiniPulledJob}; use windmill_types::s3::S3Object; use crate::agent_workers::{get_datatable_resource_from_agent_http, get_ducklake_from_agent_http}; -use crate::common::{build_args_values, get_reserved_variables, OccupancyMetrics}; +use crate::common::{ + build_args_values, build_literal_args_values, get_reserved_variables, OccupancyMetrics, +}; use crate::duckdb_runner::{RequestMode, RunnerMode, RunnerRequest}; use crate::handle_child::run_future_with_polling_update_job_poller; #[cfg(feature = "mysql")] @@ -1412,7 +1414,11 @@ pub async fn do_duckdb( } else { collection_strategy }; - let mut job_args = build_args_values(job, client, conn).await?; + let mut job_args = if annotations.literal_args { + build_literal_args_values(job) + } else { + build_args_values(job, client, conn).await? + }; let reserved_variables = get_reserved_variables(job, &client.token, conn, parent_runnable_path).await?; diff --git a/backend/windmill-worker/src/pg_executor.rs b/backend/windmill-worker/src/pg_executor.rs index 6c7b0af2e2..6c2b613b4b 100644 --- a/backend/windmill-worker/src/pg_executor.rs +++ b/backend/windmill-worker/src/pg_executor.rs @@ -38,8 +38,9 @@ use windmill_queue::{CanceledBy, MiniPulledJob}; use crate::agent_workers::get_datatable_resource_from_agent_http; use crate::common::{ - build_args_values, get_reserved_variables, narrow_sql_int, s3_mode_args_to_worker_data, - s3_stream_and_upload_with_logs, sizeof_val, OccupancyMetrics, S3ModeWorkerData, + build_args_values, build_literal_args_values, get_reserved_variables, narrow_sql_int, + s3_mode_args_to_worker_data, s3_stream_and_upload_with_logs, sizeof_val, OccupancyMetrics, + S3ModeWorkerData, }; use crate::handle_child::run_future_with_polling_update_job_poller; use crate::sanitized_sql_params::sanitize_and_interpolate_unsafe_sql_args; @@ -1100,7 +1101,12 @@ pub async fn do_postgresql( parent_runnable_path: Option, run_inline: bool, ) -> error::Result> { - let mut pg_args = build_args_values(job, client, conn).await?; + let annotations = windmill_common::worker::SqlAnnotations::parse(query); + let mut pg_args = if annotations.literal_args { + build_literal_args_values(job) + } else { + build_args_values(job, client, conn).await? + }; let inline_db_res_path = parse_db_resource(&query); @@ -1185,7 +1191,6 @@ pub async fn do_postgresql( .await; } - let annotations = windmill_common::worker::SqlAnnotations::parse(query); let collection_strategy = if annotations.raw_output || annotations.return_last_result { // raw_output emits a single envelope from the last statement, so the // multi-statement collection modes don't apply. diff --git a/python-client/wmill/wmill/client.py b/python-client/wmill/wmill/client.py index 81a98dcece..9e90a216cb 100644 --- a/python-client/wmill/wmill/client.py +++ b/python-client/wmill/wmill/client.py @@ -2723,6 +2723,11 @@ def stream_result(stream) -> None: for text in stream: append_to_result_stream(text) +# Tells the executor that the args are bound values, to pass on as they are, so a value +# that reads like `$var:u/alice/key` reaches the database as that text. A server that +# predates the annotation ignores it. +_LITERAL_ARGS_ANNOTATION = "-- literal_args\n" + # Interpolated into a `-- role ` line, so a value carrying a newline could append # statements of its own. Mirrors the server's own role-name rule. _ROLE_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,63}$") @@ -2768,6 +2773,7 @@ class DataTableClient: # Must lead: the executor's annotation parser stops at the first non-comment line. if self.role is not None: sql = f"-- role {self.role}\n" + sql + sql = _LITERAL_ARGS_ANNOTATION + sql return SqlQuery( sql, lambda sql: self.client.run_inline_script_preview( @@ -2806,7 +2812,7 @@ class DucklakeClient: args_dict[key] = value args_def += f"-- ${key} ({infer_sql_type(value)})\n" attach = f"ATTACH 'ducklake://{self.name}' AS dl;USE dl;\n" - sql = args_def + attach + sql + sql = _LITERAL_ARGS_ANNOTATION + args_def + attach + sql return SqlQuery( sql, lambda sql: self.client.run_inline_script_preview( diff --git a/typescript-client/sqlUtils.ts b/typescript-client/sqlUtils.ts index f29ff4e423..2ea3750763 100644 --- a/typescript-client/sqlUtils.ts +++ b/typescript-client/sqlUtils.ts @@ -133,6 +133,11 @@ interface SqlProvider { providerName: string; } +// Tells the executor that the args are bound values, to pass on as they are, so a value +// that reads like `$var:u/alice/key` reaches the database as that text. A server that +// predates the annotation ignores it. +const LITERAL_ARGS_ANNOTATION = "-- literal_args\n"; + // Interpolated into a `-- role ` line, so a value carrying a newline could append // statements of its own. Mirrors the server's own role-name rule. const ROLE_NAME_RE = /^[A-Za-z0-9_-]{1,63}$/; @@ -151,7 +156,8 @@ function datatableProvider( providerName: "datatable", language: "postgresql", extraArgs: { database: `datatable://${name}` }, - annotations: () => (role !== undefined ? `-- role ${role}\n` : ""), + annotations: () => + LITERAL_ARGS_ANNOTATION + (role !== undefined ? `-- role ${role}\n` : ""), formatArgDecl: (argNum) => `-- $${argNum} arg${argNum}`, formatArgUsage: (argNum, explicitType, inferredType) => explicitType !== undefined @@ -166,7 +172,7 @@ function ducklakeProvider(name: string, schema?: string): SqlProvider { providerName: "ducklake", language: "duckdb", extraArgs: {}, - annotations: () => "", + annotations: () => LITERAL_ARGS_ANNOTATION, formatArgDecl: (argNum, argType) => `-- $arg${argNum} (${argType})`, formatArgUsage: (argNum) => `$arg${argNum}`, // `USE dl."schema"` sets the active schema so unqualified tables resolve there.