diff --git a/Cargo.lock b/Cargo.lock index 90191e29..3382eec0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -645,9 +645,9 @@ dependencies = [ [[package]] name = "nix" -version = "0.31.3" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" dependencies = [ "bitflags", "cfg-if", @@ -737,9 +737,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "openjd-expr" -version = "0.15.0" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "379859f4b71a91967f6600d2204691c62f04e27b6cdd9f3ea2e4f6c22ff691b3" +checksum = "3a69ad1a8af6c2b5c877b909b7092f86e32230d5c3db1282c9929ab9ff5c0f09" dependencies = [ "regex", "regex-syntax", @@ -756,9 +756,9 @@ dependencies = [ [[package]] name = "openjd-model" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a24e459b033edce4ca749dcb9600dae160e0d6cd50f920b02ac867367c5631a" +checksum = "6396daa61c5f9247a2882cef8d96e980af7c287ec8cbdb3150b888d280701963" dependencies = [ "indexmap", "openjd-expr", @@ -766,6 +766,7 @@ dependencies = [ "serde", "serde-saphyr", "serde_json", + "serde_path_to_error", "thiserror", ] @@ -788,9 +789,9 @@ dependencies = [ [[package]] name = "openjd-sessions" -version = "0.10.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78edbce036740c750ec32f149d17a985c42ff32ccfc4da66e0530c1ff8cdcd5a" +checksum = "d6a3de38386cc29320294900b20b2bc128f80558ecbfbea099d11858a8bebe36" dependencies = [ "bitflags", "futures-util", @@ -1199,9 +1200,9 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "ruff_python_ast" -version = "0.0.21" +version = "0.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df8f77693e5f11e7d574c84a8dd63190142ae683749f5ef019bafeffb952fd19" +checksum = "5bd02b9405a7e86ed6e6aacc4e59c56133056710905b349f21a869f8b4fe08f8" dependencies = [ "aho-corasick", "arrayvec", @@ -1221,9 +1222,9 @@ dependencies = [ [[package]] name = "ruff_python_parser" -version = "0.0.21" +version = "0.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c567873f6a0e094d3f72b37862a8420a6eb4b3fc2950b4975e5a61b46aab3acc" +checksum = "10171887063911117307ee71ba7e427a700688872f5d35d5ae13cb8c0ce2d43d" dependencies = [ "bitflags", "bstr", @@ -1245,9 +1246,9 @@ dependencies = [ [[package]] name = "ruff_python_trivia" -version = "0.0.21" +version = "0.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78209bfee4543e650edffee040849c5ca828a05d60c7d3b8b53bb63d2dd49a70" +checksum = "7737931983c94972d8349ab1912c9bdd217797dbae8443396856be68f80e62d6" dependencies = [ "itertools 0.15.0", "memchr", @@ -1260,9 +1261,9 @@ dependencies = [ [[package]] name = "ruff_source_file" -version = "0.0.21" +version = "0.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2159c6129bf08ecde949e8aca0edc5411fbcbaaecdbd401fd75385f5a74e95" +checksum = "8817991fb23fd89d9c7e31668e513a4d17801d2349efb5a74fc765bd9c6f63d9" dependencies = [ "memchr", "ruff_text_size", @@ -1270,18 +1271,18 @@ dependencies = [ [[package]] name = "ruff_text_size" -version = "0.0.21" +version = "0.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb9ffcbeaefe5f3a7bef2c80dbf591a0fa1f9ec22c5ce7bf4f4c2397104e6496" +checksum = "012da5266aedc8e80cf437981526c85a7f55645ea2b063375e0a19bf05365c21" dependencies = [ "get-size2", ] [[package]] name = "ruff_unicode_names2" -version = "0.0.21" +version = "0.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bc534053fd582ce4b3431d94f6e9f398bb214eb9baf497b06b5c8d6446f379d" +checksum = "e0093bf7d9c87185bbb954db78fb1ce7a03e0ede4d76241e957d17fb2dbbb3f3" dependencies = [ "phf 0.14.0", "ruff_unicode_names2_generator", @@ -1289,9 +1290,9 @@ dependencies = [ [[package]] name = "ruff_unicode_names2_generator" -version = "0.0.21" +version = "0.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3b540b2b312bde02dbfd5261013e06dda9d3ecd33cb6e62f962b019903ae56c" +checksum = "867f294853d3585ffedc6588db1b0ebc3dfe0acb2e63fa004034f196b8b82e55" dependencies = [ "phf_codegen 0.14.0", "rand 0.10.3", @@ -1447,6 +1448,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_spanned" version = "1.1.1" diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index 8040920f..8107c3d6 100644 --- a/THIRD-PARTY-LICENSES.txt +++ b/THIRD-PARTY-LICENSES.txt @@ -24,7 +24,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------ -** pydantic; version 2.14.3 -- https://pypi.org/project/pydantic/ +** pydantic; version 2.14.4 -- https://pypi.org/project/pydantic/ The MIT License (MIT) Copyright (c) 2017 to present Pydantic Services Inc. and individual contributors. @@ -48,7 +48,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------ -** pydantic_core; version 2.50.4 -- https://pypi.org/project/pydantic_core/ +** pydantic_core; version 2.50.5 -- https://pypi.org/project/pydantic_core/ The MIT License (MIT) Copyright (c) 2022 Samuel Colvin @@ -72,7 +72,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------ -** PyYAML; version 6.0.3 -- https://pypi.org/project/PyYAML/ +** PyYAML; version 6.0.4 -- https://pypi.org/project/PyYAML/ Copyright (c) 2017-2021 Ingy döt Net Copyright (c) 2006-2016 Kirill Simonov @@ -2110,7 +2110,7 @@ limitations under the License. ** regex-automata; version 0.4.18 -- https://crates.io/crates/regex-automata ** regex-syntax; version 0.8.11 -- https://crates.io/crates/regex-syntax ** regex; version 1.13.1 -- https://crates.io/crates/regex -** ruff_unicode_names2; version 0.0.21 -- https://crates.io/crates/ruff_unicode_names2 +** ruff_unicode_names2; version 0.0.22 -- https://crates.io/crates/ruff_unicode_names2 ** signal-hook-registry; version 1.4.8 -- https://crates.io/crates/signal-hook-registry ** smallvec; version 1.15.2 -- https://crates.io/crates/smallvec ** stacker; version 0.1.25 -- https://crates.io/crates/stacker @@ -2740,9 +2740,9 @@ limitations under the License. ** itoa; version 1.0.18 -- https://crates.io/crates/itoa ** libc; version 0.2.189 -- https://crates.io/crates/libc ** manyhow-macros; version 0.14.1 -- https://crates.io/crates/manyhow-macros -** openjd-expr; version 0.15.0 -- https://crates.io/crates/openjd-expr -** openjd-model; version 0.16.0 -- https://crates.io/crates/openjd-model -** openjd-sessions; version 0.10.0 -- https://crates.io/crates/openjd-sessions +** openjd-expr; version 0.18.1 -- https://crates.io/crates/openjd-expr +** openjd-model; version 0.18.0 -- https://crates.io/crates/openjd-model +** openjd-sessions; version 0.12.1 -- https://crates.io/crates/openjd-sessions ** pin-project-lite; version 0.2.17 -- https://crates.io/crates/pin-project-lite ** portable-atomic; version 1.15.0 -- https://crates.io/crates/portable-atomic ** proc-macro2; version 1.0.107 -- https://crates.io/crates/proc-macro2 @@ -2760,6 +2760,7 @@ limitations under the License. ** serde_core; version 1.0.229 -- https://crates.io/crates/serde_core ** serde_derive; version 1.0.229 -- https://crates.io/crates/serde_derive ** serde_json; version 1.0.151 -- https://crates.io/crates/serde_json +** serde_path_to_error; version 0.1.20 -- https://crates.io/crates/serde_path_to_error ** shlex; version 2.0.1 -- https://crates.io/crates/shlex ** siphasher; version 1.0.3 -- https://crates.io/crates/siphasher ** syn; version 2.0.119 -- https://crates.io/crates/syn @@ -3198,11 +3199,11 @@ SOFTWARE. ------ -** ruff_python_ast; version 0.0.21 -- https://crates.io/crates/ruff_python_ast -** ruff_python_parser; version 0.0.21 -- https://crates.io/crates/ruff_python_parser -** ruff_python_trivia; version 0.0.21 -- https://crates.io/crates/ruff_python_trivia -** ruff_source_file; version 0.0.21 -- https://crates.io/crates/ruff_source_file -** ruff_text_size; version 0.0.21 -- https://crates.io/crates/ruff_text_size +** ruff_python_ast; version 0.0.22 -- https://crates.io/crates/ruff_python_ast +** ruff_python_parser; version 0.0.22 -- https://crates.io/crates/ruff_python_parser +** ruff_python_trivia; version 0.0.22 -- https://crates.io/crates/ruff_python_trivia +** ruff_source_file; version 0.0.22 -- https://crates.io/crates/ruff_source_file +** ruff_text_size; version 0.0.22 -- https://crates.io/crates/ruff_text_size MIT License Copyright (c) @@ -3328,7 +3329,7 @@ THE SOFTWARE. ------ -** nix; version 0.31.3 -- https://crates.io/crates/nix +** nix; version 0.32.0 -- https://crates.io/crates/nix The MIT License (MIT) Copyright (c) 2015 Carl Lerche + nix-rust Authors @@ -3396,7 +3397,7 @@ authorization of the copyright holder. ------ -** ruff_unicode_names2; version 0.0.21 -- https://crates.io/crates/ruff_unicode_names2 +** ruff_unicode_names2; version 0.0.22 -- https://crates.io/crates/ruff_unicode_names2 UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE Unicode Data Files include all data files under the directories http://www.unicode.org/Public/, http://www.unicode.org/reports/, http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and http://www.unicode.org/utility/trac/browser/. diff --git a/rust-bindings/Cargo.toml b/rust-bindings/Cargo.toml index d248351d..7ea58c45 100644 --- a/rust-bindings/Cargo.toml +++ b/rust-bindings/Cargo.toml @@ -12,9 +12,9 @@ name = "_openjd_rs" crate-type = ["cdylib", "rlib"] [dependencies] -openjd-expr = "0.15.0" -openjd-model = "0.16.0" -openjd-sessions = "0.10.0" +openjd-expr = "0.18.1" +openjd-model = "0.18.0" +openjd-sessions = "0.12.1" tokio = { version = "1", features = ["rt-multi-thread"] } uuid = { version = "1", features = ["v4"] } serde_json = "1" diff --git a/rust-bindings/src/expr/expr_type.rs b/rust-bindings/src/expr/expr_type.rs index a0aba287..db3b0f55 100644 --- a/rust-bindings/src/expr/expr_type.rs +++ b/rust-bindings/src/expr/expr_type.rs @@ -9,6 +9,8 @@ use std::collections::HashMap; use openjd_expr::types::{ExprType, TypeCode}; +use super::errors::expr_err_to_py; + // ── PyTypeCode enum ── #[cfg_attr( @@ -248,7 +250,7 @@ impl PyExprType { .collect(); validate_typecode_arity(code, &rust_params)?; return Ok(PyExprType { - inner: ExprType::new(code, rust_params), + inner: ExprType::new(code, rust_params).map_err(expr_err_to_py)?, }); } // String form @@ -259,7 +261,7 @@ impl PyExprType { let rust_params: Vec = p.iter().map(|p| p.inner.clone()).collect(); validate_typecode_arity(code, &rust_params)?; return Ok(PyExprType { - inner: ExprType::new(code, rust_params), + inner: ExprType::new(code, rust_params).map_err(expr_err_to_py)?, }); } // Single-arg string form: ExprType("list[int]") @@ -273,23 +275,25 @@ impl PyExprType { } #[staticmethod] - fn list(elem: &PyExprType) -> Self { - PyExprType { - inner: ExprType::list(elem.inner.clone()), - } + fn list(elem: &PyExprType) -> PyResult { + Ok(PyExprType { + inner: ExprType::list(elem.inner.clone()).map_err(expr_err_to_py)?, + }) } #[staticmethod] - fn union(types: Vec) -> Self { - PyExprType { - inner: ExprType::union(types.into_iter().map(|t| t.inner).collect()), - } + fn union(types: Vec) -> PyResult { + Ok(PyExprType { + inner: ExprType::union(types.into_iter().map(|t| t.inner).collect()) + .map_err(expr_err_to_py)?, + }) } - fn nullable(&self) -> Self { - PyExprType { - inner: ExprType::union(vec![self.inner.clone(), ExprType::NULLTYPE]), - } + fn nullable(&self) -> PyResult { + Ok(PyExprType { + inner: ExprType::union(vec![self.inner.clone(), ExprType::NULLTYPE]) + .map_err(expr_err_to_py)?, + }) } fn is_nullable(&self) -> bool { @@ -351,7 +355,10 @@ impl PyExprType { rust_bindings.insert(tc.into(), et.inner); } Ok(PyExprType { - inner: self.inner.substitute(&rust_bindings), + inner: self + .inner + .substitute(&rust_bindings) + .map_err(expr_err_to_py)?, }) } diff --git a/rust-bindings/src/expr/symbol_table.rs b/rust-bindings/src/expr/symbol_table.rs index 521dd258..3733c7ad 100644 --- a/rust-bindings/src/expr/symbol_table.rs +++ b/rust-bindings/src/expr/symbol_table.rs @@ -23,7 +23,10 @@ pub(crate) struct PySymbolTable { pub(crate) fn dict_to_symtab(dict: &Bound<'_, PyDict>) -> PyResult { let mut st = SymbolTable::new(); - for (key, value) in dict.iter() { + // A snapshot: converting a value can run user code that changes the dict, + // and PyO3's live dict iterator panics on a size change. + for item in dict.items().iter() { + let (key, value): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; let k: String = key.extract()?; if let Ok(sub_dict) = value.cast::() { let sub = dict_to_symtab(sub_dict)?; @@ -425,7 +428,9 @@ pub(crate) fn build_symbol_table( .map(PathFormat::from) .unwrap_or_else(PathFormat::host); let mut st = SymbolTable::new(); - for (key, value) in values.iter() { + // A snapshot, as in `dict_to_symtab`. + for item in values.items().iter() { + let (key, value): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; let dotted: String = key.extract()?; let target: Option = match types { Some(t) => match t.get_item(dotted.as_str())? { diff --git a/rust-bindings/src/lib.rs b/rust-bindings/src/lib.rs index 8a118320..fc131d01 100644 --- a/rust-bindings/src/lib.rs +++ b/rust-bindings/src/lib.rs @@ -11,6 +11,7 @@ use pyo3::prelude::*; use pyo3::types::PyType; use openjd_expr::eval::{DEFAULT_MEMORY_LIMIT, DEFAULT_OPERATION_LIMIT}; +use openjd_expr::MAX_TYPE_DEPTH; #[cfg(feature = "stub-gen")] use pyo3_stub_gen::define_stub_info_gatherer; @@ -99,6 +100,7 @@ fn openjd_rs(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("DEFAULT_MEMORY_LIMIT", DEFAULT_MEMORY_LIMIT)?; m.add("DEFAULT_OPERATION_LIMIT", DEFAULT_OPERATION_LIMIT)?; + m.add("MAX_TYPE_DEPTH", MAX_TYPE_DEPTH)?; register_renamed_exception( m, @@ -188,6 +190,15 @@ fn openjd_rs(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + // ENV_PARAMS template-time types (unstable upstream; see env_params.rs) + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_function(wrap_pyfunction!( + _reconstruct_environment_parameter_definition, + m + )?)?; + m.add_function(wrap_pyfunction!(_reconstruct_job_parameter_definition, m)?)?; // JobParameterDefinition variants (template-time) m.add_class::()?; m.add_class::()?; diff --git a/rust-bindings/src/model/create_job_fns.rs b/rust-bindings/src/model/create_job_fns.rs index c354a685..9ddad20f 100644 --- a/rust-bindings/src/model/create_job_fns.rs +++ b/rust-bindings/src/model/create_job_fns.rs @@ -19,7 +19,10 @@ use super::template::{PyEnvironmentTemplate, PyJobTemplate}; fn extract_input_values(py_dict: &Bound<'_, PyDict>) -> PyResult { let mut result = JobParameterInputValues::new(); - for (key, val) in py_dict.iter() { + // A snapshot: reading a value can run user code that changes the dict, + // and PyO3's live dict iterator panics on a size change. + for item in py_dict.items().iter() { + let (key, val): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; let name: String = key.extract()?; if let Ok(inner_dict) = val.cast::() { // {"type": ..., "value": ...} — take the value field. @@ -397,12 +400,92 @@ pub(crate) fn py_deserialize_step(step_dict: &Bound<'_, PyDict>) -> PyResult PyEnvironment { - let env = openjd_model::convert_environment(&env_template.inner.environment); - PyEnvironment { inner: env } +#[pyo3(signature = (env_template, *, job_parameter_values=None))] +pub(crate) fn py_create_environment( + env_template: &PyEnvironmentTemplate, + job_parameter_values: Option<&Bound<'_, PyDict>>, +) -> PyResult { + let env = match job_parameter_values { + None => openjd_model::convert_environment(&env_template.inner.environment), + Some(values) => { + let mut values = crate::sessions::session::extract_job_parameter_values(values)?; + // The table replaces the session's values for every parameter + // other than PATH and LIST[PATH], so a declared parameter left out + // here would be undefined in the Environment even when the Session + // has a value for it. Refuse that, as `preprocess_job_parameters` + // refuses a missing value; its `dict` fills in defaults. + let mut missing: Vec<&str> = env_template + .inner + .parameter_definitions + .iter() + .flatten() + .map(|d| d.name()) + .filter(|name| !values.contains_key(*name)) + .collect(); + if !missing.is_empty() { + missing.sort_unstable(); + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "Values missing for required job parameters: {}", + missing.join(", ") + ))); + } + // A Session converts each non-PATH value to its declared type when + // it builds a table from job parameter values, but not the values + // of a table an Environment brings with it. Convert them here, as + // the Session would, so `{"type": "INT", "value": "05"}` is the + // int 5 and not the text "05". PATH and LIST[PATH] stay as given: + // openjd-model leaves their `Param.*` out of this table, and the + // Session maps them when the Environment is entered. + for (name, pv) in values.iter_mut() { + use openjd_model::JobParameterType; + if matches!( + pv.param_type, + JobParameterType::Path | JobParameterType::ListPath + ) { + continue; + } + pv.value = pv + .value + .clone() + .coerce( + &pv.param_type.expr_type(), + openjd_expr::path_mapping::PathFormat::host(), + ) + .map_err(|e| { + pyo3::exceptions::PyValueError::new_err(format!( + "Failed to coerce parameter 'Param.{name}': {e}" + )) + })?; + } + let symtab = openjd_model::build_symbol_table(&values).map_err(model_err_to_py)?; + openjd_model::convert_environment_with_symtab( + &env_template.inner.environment, + Some(&symtab), + ) + } + }; + Ok(PyEnvironment { inner: env }) } diff --git a/rust-bindings/src/model/env_params.rs b/rust-bindings/src/model/env_params.rs new file mode 100644 index 00000000..a168e424 --- /dev/null +++ b/rust-bindings/src/model/env_params.rs @@ -0,0 +1,530 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Template-time types of the `ENV_PARAMS` extension (RFC 0010). +//! +//! Mirror `openjd_model::template::{EnvironmentActivation, ExprField, +//! EnvironmentParameterDefinition, EnvironmentParameterValue, +//! EnvironmentParameterValueMap}`. openjd-model 0.18.0 decodes these +//! fields but does not yet act on them at job creation, and it marks the +//! extension unstable: decoding accepts a template that lists +//! `ENV_PARAMS` only with `CallerLimits(accept_unreleased_env_params=True)`. +//! +//! `EnvironmentParameterValue` and `EnvironmentParameterValueMap` have no +//! pyclass. A value is an `openjd.expr.FormatString` (a string containing +//! `{{`) or the literal as written (`str`, `int`, `float`, `bool`, `list`, +//! `dict` or `None`), and a map is a `dict[str, value]`. + +use std::collections::BTreeMap; + +use pyo3::prelude::*; +use pyo3::types::{PyDict, PyStringMethods, PyTuple, PyType}; +#[cfg(feature = "stub-gen")] +use pyo3_stub_gen::derive::*; + +use openjd_expr::FormatString; +use openjd_model::template::{ + EnvironmentActivation, EnvironmentParameterDefinition, EnvironmentParameterValue, + EnvironmentParameterValueMap, ExprField, +}; + +use super::job_param_defs::job_param_def_to_py; +use super::types::PyJobParameterType; +use crate::expr::PyFormatString; + +// ── JSON <-> Python ── + +/// Convert a Python object to a `serde_json::Value` through `json.dumps`, +/// so the conversion follows the same rules as `decode_job_template` on a +/// `dict`. An object `json.dumps` cannot write raises its `TypeError`; +/// a NaN or infinite float raises `ValueError`, since JSON has neither. +pub(crate) fn py_to_json(obj: &Bound<'_, PyAny>) -> PyResult { + let json_mod = obj.py().import("json")?; + let kwargs = PyDict::new(obj.py()); + kwargs.set_item("allow_nan", false)?; + let text: String = json_mod + .call_method("dumps", (obj,), Some(&kwargs))? + .extract()?; + serde_json::from_str(&text).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string())) +} + +/// Convert a `serde_json::Value` to the matching Python object: `None`, +/// `bool`, `int`, `float`, `str`, `list` or `dict`. +pub(crate) fn json_to_py<'py>( + py: Python<'py>, + value: &serde_json::Value, +) -> PyResult> { + use pyo3::IntoPyObject; + use serde_json::Value; + Ok(match value { + Value::Null => py.None().into_bound(py), + Value::Bool(b) => b.into_pyobject(py)?.to_owned().into_any(), + Value::Number(n) => { + if let Some(i) = n.as_i64() { + i.into_pyobject(py)?.into_any() + } else if let Some(u) = n.as_u64() { + u.into_pyobject(py)?.into_any() + } else { + // Without `arbitrary_precision`, every number that is not + // an i64 or u64 is an f64. + n.as_f64().unwrap_or(f64::NAN).into_pyobject(py)?.into_any() + } + } + Value::String(s) => s.into_pyobject(py)?.into_any(), + Value::Array(arr) => { + let list = pyo3::types::PyList::empty(py); + for v in arr { + list.append(json_to_py(py, v)?)?; + } + list.into_any() + } + Value::Object(obj) => { + let d = PyDict::new(py); + for (k, v) in obj { + d.set_item(k, json_to_py(py, v)?)?; + } + d.into_any() + } + }) +} + +// ── EnvironmentParameterValue ── + +/// The Python form of an `EnvironmentParameterValue`: the `FormatString`, +/// or the literal as written. +pub(crate) fn env_param_value_to_py<'py>( + py: Python<'py>, + v: &EnvironmentParameterValue, +) -> PyResult> { + match v { + EnvironmentParameterValue::FormatString(fs) => { + Bound::new(py, PyFormatString { inner: fs.clone() }).map(Bound::into_any) + } + EnvironmentParameterValue::Literal(value) => json_to_py(py, value), + // `EnvironmentParameterValue` is not `#[non_exhaustive]` today; the + // arm keeps the binding compiling if it becomes so. + #[allow(unreachable_patterns)] + _ => Err(pyo3::exceptions::PyNotImplementedError::new_err( + "internal error: unknown EnvironmentParameterValue variant", + )), + } +} + +/// Read an `EnvironmentParameterValue` from Python the way decoding reads +/// one from a template: a `str`, or a `FormatString`'s text, that contains +/// `{{` is a format string (a `str` that does not parse raises +/// `ExpressionError`, as `FormatString(...)` does), and a `str` without `{{` +/// is the literal string. Anything else is a literal, converted to JSON. +pub(crate) fn env_param_value_from_py( + obj: &Bound<'_, PyAny>, +) -> PyResult { + // A `FormatString` is read by its text, as decoding reads a string, so + // one without `{{` is the literal string. + let text = match obj.extract::() { + Ok(fs) => Some(fs.inner.raw().to_string()), + Err(_) => obj.extract::().ok(), + }; + if let Some(s) = text { + if s.contains("{{") { + return FormatString::new(&s) + .map(EnvironmentParameterValue::FormatString) + .map_err(crate::expr::errors::expr_err_to_py); + } + return Ok(EnvironmentParameterValue::Literal( + serde_json::Value::String(s), + )); + } + Ok(EnvironmentParameterValue::Literal(py_to_json(obj)?)) +} + +pub(crate) fn env_param_value_map_to_py<'py>( + py: Python<'py>, + m: &EnvironmentParameterValueMap, +) -> PyResult> { + let d = PyDict::new(py); + for (k, v) in &m.0 { + d.set_item(k, env_param_value_to_py(py, v)?)?; + } + Ok(d) +} + +pub(crate) fn env_param_value_map_from_py( + d: &Bound<'_, PyDict>, +) -> PyResult { + let mut map = BTreeMap::new(); + // Iterate over a snapshot: converting a value runs `json.dumps`, which + // can call user code (a dict subclass's `items()`) that changes `d`, and + // PyO3's live dict iterator panics when the size changes under it. + for item in d.items().iter() { + let (k, v): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; + let key: String = k.extract()?; + map.insert(key, env_param_value_from_py(&v)?); + } + Ok(EnvironmentParameterValueMap(map)) +} + +// ── EnvironmentActivation ── + +/// `ENV_PARAMS`: which Sessions of a Job enter an Environment (Template +/// Schemas §4 item 4). An Environment whose `activation` is absent acts as +/// `BY_DEFAULT` in a document that lists `ENV_PARAMS`. +#[cfg_attr( + feature = "stub-gen", + gen_stub_pyclass_enum(module = "openjd._openjd_rs") +)] +#[pyclass( + module = "openjd.model._v1.template", + name = "EnvironmentActivation", + eq, + hash, + frozen, + from_py_object +)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[allow(non_camel_case_types, clippy::upper_case_acronyms)] +pub(crate) enum PyEnvironmentActivation { + /// Every Session of the Job enters the Environment. + ALWAYS = 0, + /// Every Session enters it, except a Step's that declines it or for + /// which it is disabled. + BY_DEFAULT = 1, + /// Only the Sessions of a Step that requests it enter it. + ON_REQUEST = 2, +} + +#[cfg_attr(feature = "stub-gen", gen_stub_pymethods)] +#[pymethods] +impl PyEnvironmentActivation { + /// The value as a template writes it: `"ALWAYS"`, `"BY_DEFAULT"` or + /// `"ON_REQUEST"`. + fn as_str(&self) -> &'static str { + EnvironmentActivation::from(*self).as_str() + } + + /// Variant name, the same as `as_str()`. + #[getter] + fn name(&self) -> &'static str { + self.as_str() + } + + /// Parse the value as a template writes it (case-sensitive). Returns + /// `None` for any other string. + #[staticmethod] + fn from_str(s: &str) -> Option { + match s { + "ALWAYS" => Some(Self::ALWAYS), + "BY_DEFAULT" => Some(Self::BY_DEFAULT), + "ON_REQUEST" => Some(Self::ON_REQUEST), + _ => None, + } + } + + fn __repr__(&self) -> String { + format!("EnvironmentActivation.{}", self.as_str()) + } + + fn __str__(&self) -> &'static str { + self.as_str() + } + + #[allow(clippy::type_complexity)] + fn __reduce__<'py>( + &self, + py: Python<'py>, + ) -> PyResult<(Bound<'py, PyAny>, (Bound<'py, PyType>, &'static str))> { + let helper = py + .import("openjd._openjd_rs")? + .getattr("_reconstruct_enum")?; + Ok((helper, (py.get_type::(), self.name()))) + } +} + +impl From for EnvironmentActivation { + fn from(a: PyEnvironmentActivation) -> Self { + match a { + PyEnvironmentActivation::ALWAYS => Self::Always, + PyEnvironmentActivation::BY_DEFAULT => Self::ByDefault, + PyEnvironmentActivation::ON_REQUEST => Self::OnRequest, + } + } +} + +impl From for PyEnvironmentActivation { + fn from(a: EnvironmentActivation) -> Self { + match a { + EnvironmentActivation::Always => Self::ALWAYS, + EnvironmentActivation::ByDefault => Self::BY_DEFAULT, + EnvironmentActivation::OnRequest => Self::ON_REQUEST, + } + } +} + +// ── ExprField ── + +/// The value of an expression field (Template Schemas §7.6), as written, +/// such as an `enableIf`. +/// +/// `ExprField(value)` takes the value as a template writes it: a `bool`, +/// `int` or `float` scalar, a `str`, which is always the source of one +/// expression without `{{ }}` (`"true"` is the expression `true`, not the +/// boolean), or `None` for a present `null`. An absent field is `None` in +/// the getter that holds an `ExprField`, never `ExprField(None)`. +#[cfg_attr(feature = "stub-gen", gen_stub_pyclass(module = "openjd._openjd_rs"))] +#[pyclass( + module = "openjd.model._v1.template", + name = "ExprField", + frozen, + from_py_object +)] +#[derive(Clone)] +pub(crate) struct PyExprField { + pub(crate) inner: ExprField, +} + +#[cfg_attr(feature = "stub-gen", gen_stub_pymethods)] +#[pymethods] +impl PyExprField { + #[new] + fn new(value: &Bound<'_, PyAny>) -> PyResult { + use pyo3::types::{PyBool, PyFloat, PyInt, PyString}; + let inner = if value.is_none() { + ExprField::Null + } else if value.is_instance_of::() { + ExprField::Bool(value.extract()?) + } else if value.is_instance_of::() { + // As decoding reads a template number: an i64 is `Int`, one + // above i64::MAX that fits u64 is refused, and any other is read + // as the nearest float, as JSON number parsing reads it. + if let Ok(i) = value.extract::() { + ExprField::Int(i) + } else if value.extract::().is_ok() { + return Err(pyo3::exceptions::PyOverflowError::new_err( + "an ExprField integer from 2**63 to 2**64 - 1 is refused, as \ + decoding refuses it", + )); + } else { + // `int.__float__`, not the subclass's own `__float__`, so a + // subclass cannot turn the value into NaN or infinity. + let f: f64 = value + .py() + .get_type::() + .call_method1("__float__", (value,))? + .extract()?; + ExprField::Float(f) + } + } else if value.is_instance_of::() { + let f: f64 = value.extract()?; + if !f.is_finite() { + return Err(pyo3::exceptions::PyValueError::new_err( + "an ExprField float must be finite", + )); + } + ExprField::Float(f) + } else if value.is_instance_of::() { + ExprField::Expression(value.extract()?) + } else { + return Err(pyo3::exceptions::PyTypeError::new_err(format!( + "ExprField() takes a bool, int, float, str or None, not {}", + value.get_type().name()? + ))); + }; + Ok(Self { inner }) + } + + /// The value as written: a `bool`, `int` or `float` scalar, the + /// expression source as a `str`, or `None` for a present `null`. + #[getter] + fn value<'py>(&self, py: Python<'py>) -> PyResult> { + use pyo3::IntoPyObject; + Ok(match &self.inner { + ExprField::Bool(b) => b.into_pyobject(py)?.to_owned().into_any(), + ExprField::Int(i) => i.into_pyobject(py)?.into_any(), + ExprField::Float(f) => f.into_pyobject(py)?.into_any(), + ExprField::Expression(s) => s.into_pyobject(py)?.into_any(), + ExprField::Null => py.None().into_bound(py), + #[allow(unreachable_patterns)] + _ => { + return Err(pyo3::exceptions::PyNotImplementedError::new_err( + "internal error: unknown ExprField variant", + )) + } + }) + } + + /// Which form the value has: `"bool"`, `"int"`, `"float"`, + /// `"expression"` or `"null"`. + #[getter] + fn kind(&self) -> &'static str { + match &self.inner { + ExprField::Bool(_) => "bool", + ExprField::Int(_) => "int", + ExprField::Float(_) => "float", + ExprField::Expression(_) => "expression", + ExprField::Null => "null", + #[allow(unreachable_patterns)] + _ => "unknown", + } + } + + /// The boolean scalar, or `None` for any other value, an expression + /// included (even a constant one such as `"true"`). + fn as_bool(&self) -> Option { + self.inner.as_bool() + } + + fn __eq__(&self, other: PyRef<'_, Self>) -> bool { + other.inner == self.inner + } + + fn __hash__(&self) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + match &self.inner { + ExprField::Bool(b) => (0u8, *b).hash(&mut h), + ExprField::Int(i) => (1u8, *i).hash(&mut h), + ExprField::Float(f) => (2u8, f.to_bits()).hash(&mut h), + ExprField::Expression(s) => (3u8, s).hash(&mut h), + ExprField::Null => 4u8.hash(&mut h), + #[allow(unreachable_patterns)] + _ => 5u8.hash(&mut h), + } + h.finish() + } + + /// `ExprField()`, with the value as Python's `repr` writes it, + /// so the text evaluates back to an equal `ExprField`. + fn __repr__(&self, py: Python<'_>) -> PyResult { + let value = self.value(py)?; + Ok(format!("ExprField({})", value.repr()?.to_cow()?)) + } + + #[allow(clippy::type_complexity)] + fn __reduce__<'py>( + &self, + py: Python<'py>, + ) -> PyResult<(Bound<'py, PyType>, Bound<'py, PyTuple>)> { + Ok((py.get_type::(), PyTuple::new(py, [self.value(py)?])?)) + } +} + +// ── EnvironmentParameterDefinition ── + +/// One `ENV_PARAMS` Environment parameter definition (Template Schemas +/// §4.5): the shape of a Job Parameter definition of the same `type`, +/// except that `default` may be a format string. +/// +/// `EnvironmentParameterDefinition(definition)` decodes the template form +/// of one definition from a `dict`, as decoding a template does, and +/// raises `DecodeValidationError` for one that does not decode. It checks +/// only the decode; template validation checks the rest. +/// +/// It pickles through its template form. +#[cfg_attr(feature = "stub-gen", gen_stub_pyclass(module = "openjd._openjd_rs"))] +#[pyclass( + module = "openjd.model._v1.template", + name = "EnvironmentParameterDefinition", + frozen, + from_py_object +)] +#[derive(Clone)] +pub(crate) struct PyEnvironmentParameterDefinition { + pub(crate) inner: EnvironmentParameterDefinition, +} + +#[cfg_attr(feature = "stub-gen", gen_stub_pymethods)] +#[pymethods] +impl PyEnvironmentParameterDefinition { + #[new] + fn new(definition: &Bound<'_, PyDict>) -> PyResult { + // A `FormatString` default, as the `default` getter returns one, is + // read by its text. + let definition = definition.copy()?; + if let Some(d) = definition.get_item("default")? { + if let Ok(fs) = d.extract::() { + definition.set_item("default", fs.inner.raw())?; + } + } + let value = py_to_json(definition.as_any())?; + let inner: EnvironmentParameterDefinition = serde_json::from_value(value) + .map_err(|e| super::errors::PyDecodeValidationError::new_err(e.to_string()))?; + Ok(Self { inner }) + } + + /// The parameter's name. + #[getter] + fn name(&self) -> &str { + self.inner.name() + } + + /// The parameter's type. + #[getter] + fn r#type(&self) -> PyJobParameterType { + PyJobParameterType::from(self.inner.job_param_type()) + } + + /// The type as the specification spells it (`"STRING"`, + /// `"LIST[PATH]"`, ...). + #[getter] + fn type_name(&self) -> &str { + self.inner.type_name() + } + + /// The definition without its `default`, as the matching + /// `Job*ParameterDefinition`. Its own `default` is always `None`; the + /// default is `default` here. + #[getter] + fn definition<'py>(&self, py: Python<'py>) -> PyResult> { + job_param_def_to_py(py, &self.inner.definition) + } + + /// The `default` as written: a `FormatString` for a string containing + /// `{{`, otherwise the literal (`str`, `int`, `float`, `bool`, `list` + /// or `dict`), or `None` when there is no default. Template validation + /// does not check it. + #[getter] + fn default<'py>(&self, py: Python<'py>) -> PyResult>> { + self.inner + .default + .as_ref() + .map(|v| env_param_value_to_py(py, v)) + .transpose() + } + + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + let helper = py + .import("openjd._openjd_rs")? + .getattr("_reconstruct_environment_parameter_definition")?; + Ok(( + helper, + (super::param_def_json::env_param_def_to_json(&self.inner).to_string(),), + )) + } + + fn __repr__(&self) -> String { + format!( + "EnvironmentParameterDefinition(name={:?}, type={:?})", + self.inner.name(), + self.inner.type_name() + ) + } +} + +/// Pickle helper: decode an `EnvironmentParameterDefinition` from the +/// template form `__reduce__` wrote. +#[cfg_attr( + feature = "stub-gen", + gen_stub_pyfunction(module = "openjd._openjd_rs") +)] +#[pyfunction] +pub(crate) fn _reconstruct_environment_parameter_definition( + json: &str, +) -> PyResult { + let inner: EnvironmentParameterDefinition = serde_json::from_str(json).map_err(|e| { + pyo3::exceptions::PyValueError::new_err(format!( + "Failed to unpickle an EnvironmentParameterDefinition: {e}" + )) + })?; + Ok(PyEnvironmentParameterDefinition { inner }) +} diff --git a/rust-bindings/src/model/job.rs b/rust-bindings/src/model/job.rs index 0894754f..ff9fd335 100644 --- a/rust-bindings/src/model/job.rs +++ b/rust-bindings/src/model/job.rs @@ -57,13 +57,18 @@ impl PyJob { .collect() } - #[getter] - fn parameters(&self) -> HashMap { - self.inner - .parameters - .iter() - .map(|(k, v)| (k.clone(), PyJobParameter { inner: v.clone() })) - .collect() + /// The job's parameters as a new `dict`, in openjd-model's order: the + /// job template's parameters in definition order, then any other entry + /// (such as one an environment template contributes) in byte-wise name + /// order (openjd-rs#639). Built as a `dict` rather than collected into a + /// `HashMap`, which would lose that order. + #[getter] + fn parameters<'py>(&self, py: Python<'py>) -> PyResult> { + let d = pyo3::types::PyDict::new(py); + for (k, v) in &self.inner.parameters { + d.set_item(k, PyJobParameter { inner: v.clone() })?; + } + Ok(d) } #[getter] @@ -1006,7 +1011,10 @@ impl PyStepParameterSpace { ) -> PyResult { let mut defs = serde_json::Map::new(); if let Some(dict) = taskParameterDefinitions { - for (key, val) in dict.iter() { + // A snapshot: reading a definition can run user code that + // changes the dict, and PyO3's live dict iterator panics then. + for item in dict.items().iter() { + let (key, val): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; let name: String = key.extract()?; let value = task_param_def_from_dict(py, &val)?; defs.insert(name, value); diff --git a/rust-bindings/src/model/job_param_defs.rs b/rust-bindings/src/model/job_param_defs.rs index 3d995eb1..71c9886b 100644 --- a/rust-bindings/src/model/job_param_defs.rs +++ b/rust-bindings/src/model/job_param_defs.rs @@ -31,9 +31,10 @@ //! warrant a follow-up commit); calling `.user_interface` returns //! ``None`` for now. //! -//! Pickle is supported via `_reconstruct_kwargs`. The dispatch -//! helper at the bottom of this file produces the right pyclass -//! variant from a `JobParameterDefinition` enum. +//! Each pickles through its template form (`param_def_json`) and +//! `_reconstruct_job_parameter_definition`. The dispatch helper at the +//! bottom of this file produces the right pyclass variant from a +//! `JobParameterDefinition` enum. use pyo3::prelude::*; use pyo3::types::PyList; @@ -144,6 +145,12 @@ impl PyJobStringParameterDefinition { self.max_length() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::STRING(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobStringParameterDefinition(name={:?})", @@ -240,6 +247,12 @@ impl PyJobIntParameterDefinition { self.max_value() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::INT(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobIntParameterDefinition(name={:?})", @@ -334,6 +347,12 @@ impl PyJobFloatParameterDefinition { self.max_value() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::FLOAT(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobFloatParameterDefinition(name={:?})", @@ -447,6 +466,12 @@ impl PyJobPathParameterDefinition { self.data_flow() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::PATH(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobPathParameterDefinition(name={:?})", @@ -505,6 +530,12 @@ impl PyJobBoolParameterDefinition { self.inner.default.as_ref().map(|b| b.0) } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::BOOL(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobBoolParameterDefinition(name={:?})", @@ -585,6 +616,12 @@ impl PyJobRangeExprParameterDefinition { self.max_length() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::RANGE_EXPR(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobRangeExprParameterDefinition(name={:?})", @@ -665,6 +702,12 @@ impl PyJobListStringParameterDefinition { self.max_length() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::LIST_STRING(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobListStringParameterDefinition(name={:?})", @@ -767,6 +810,12 @@ impl PyJobListPathParameterDefinition { self.data_flow() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::LIST_PATH(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobListPathParameterDefinition(name={:?})", @@ -850,6 +899,12 @@ impl PyJobListIntParameterDefinition { self.max_length() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::LIST_INT(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobListIntParameterDefinition(name={:?})", @@ -933,6 +988,12 @@ impl PyJobListFloatParameterDefinition { self.max_length() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::LIST_FLOAT(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobListFloatParameterDefinition(name={:?})", @@ -1016,6 +1077,12 @@ impl PyJobListBoolParameterDefinition { self.max_length() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def(py, &JobParameterDefinition::LIST_BOOL(self.inner.clone())) + } + fn __repr__(&self) -> String { format!( "JobListBoolParameterDefinition(name={:?})", @@ -1100,6 +1167,15 @@ impl PyJobListListIntParameterDefinition { self.max_length() } + /// Pickle support, through the template form of the definition. + #[allow(clippy::type_complexity)] + fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>, (String,))> { + reduce_job_param_def( + py, + &JobParameterDefinition::LIST_LIST_INT(self.inner.clone()), + ) + } + fn __repr__(&self) -> String { format!( "JobListListIntParameterDefinition(name={:?})", @@ -1197,3 +1273,37 @@ pub(crate) fn job_param_defs_to_py<'py>( } } } + +/// `__reduce__` for every `Job*ParameterDefinition`: the reconstruct helper +/// and the definition's template form as JSON text. +fn reduce_job_param_def<'py>( + py: Python<'py>, + def: &JobParameterDefinition, +) -> PyResult<(Bound<'py, PyAny>, (String,))> { + let helper = py + .import("openjd._openjd_rs")? + .getattr("_reconstruct_job_parameter_definition")?; + Ok(( + helper, + (super::param_def_json::job_param_def_to_json(def).to_string(),), + )) +} + +/// Pickle helper: decode a `Job*ParameterDefinition` from the template +/// form `__reduce__` wrote. +#[cfg_attr( + feature = "stub-gen", + gen_stub_pyfunction(module = "openjd._openjd_rs") +)] +#[pyfunction] +pub(crate) fn _reconstruct_job_parameter_definition( + py: Python<'_>, + json: &str, +) -> PyResult> { + let def: JobParameterDefinition = serde_json::from_str(json).map_err(|e| { + pyo3::exceptions::PyValueError::new_err(format!( + "Failed to unpickle a job parameter definition: {e}" + )) + })?; + Ok(job_param_def_to_py(py, &def)?.unbind()) +} diff --git a/rust-bindings/src/model/mod.rs b/rust-bindings/src/model/mod.rs index e3aa4f30..e6479b65 100644 --- a/rust-bindings/src/model/mod.rs +++ b/rust-bindings/src/model/mod.rs @@ -4,9 +4,11 @@ pub(crate) mod capabilities; mod create_job_fns; pub(crate) mod decode; +pub(crate) mod env_params; pub(crate) mod errors; pub(crate) mod job; pub(crate) mod job_param_defs; +pub(crate) mod param_def_json; pub(crate) mod profile; pub(crate) mod step_dependency_graph; pub(crate) mod step_param_space; @@ -30,6 +32,10 @@ pub(crate) use decode::{ decode_environment_template, decode_environment_template_str, decode_job_template, decode_job_template_str, }; +pub(crate) use env_params::{ + _reconstruct_environment_parameter_definition, PyEnvironmentActivation, + PyEnvironmentParameterDefinition, PyExprField, +}; pub(crate) use errors::{PyDecodeValidationError, PyModelValidationError, PyUnsupportedSchema}; pub(crate) use job::{ PyAction, PyAmountRequirement, PyAttributeRequirement, PyCancelationMode, PyEmbeddedFile, @@ -37,12 +43,12 @@ pub(crate) use job::{ PyJobParameter, PyStep, PyStepActions, PyStepDependency, PyStepParameterSpace, PyStepScript, }; pub(crate) use job_param_defs::{ - PyJobBoolParameterDefinition, PyJobFloatParameterDefinition, PyJobIntParameterDefinition, - PyJobListBoolParameterDefinition, PyJobListFloatParameterDefinition, - PyJobListIntParameterDefinition, PyJobListListIntParameterDefinition, - PyJobListPathParameterDefinition, PyJobListStringParameterDefinition, - PyJobPathParameterDefinition, PyJobRangeExprParameterDefinition, - PyJobStringParameterDefinition, + _reconstruct_job_parameter_definition, PyJobBoolParameterDefinition, + PyJobFloatParameterDefinition, PyJobIntParameterDefinition, PyJobListBoolParameterDefinition, + PyJobListFloatParameterDefinition, PyJobListIntParameterDefinition, + PyJobListListIntParameterDefinition, PyJobListPathParameterDefinition, + PyJobListStringParameterDefinition, PyJobPathParameterDefinition, + PyJobRangeExprParameterDefinition, PyJobStringParameterDefinition, }; pub(crate) use profile::{ PyCallerLimits, PyModelExtension, PyModelProfile, PySpecificationRevision, PyValidationContext, diff --git a/rust-bindings/src/model/param_def_json.rs b/rust-bindings/src/model/param_def_json.rs new file mode 100644 index 00000000..4f0552ef --- /dev/null +++ b/rust-bindings/src/model/param_def_json.rs @@ -0,0 +1,368 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Write a decoded parameter definition back to its template form, for +//! pickle. +//! +//! openjd-model's `JobParameterDefinition` and +//! `EnvironmentParameterDefinition` deserialize from the template form but +//! do not serialize. These functions write the JSON that deserializes to an +//! equal definition: every field that is set, under its template name, with +//! a number that was written as a string (a `FLOAT` default of `"1.50"`) +//! written as that string, so the spelling survives the round trip. + +use openjd_model::template::{ + EnvironmentParameterDefinition, EnvironmentParameterValue, FileFilter, FlexFloat, FlexInt, + JobParameterDefinition, +}; +use openjd_model::types::{DataFlow, ObjectType}; +use serde_json::{json, Map, Value}; + +struct Obj(Map); + +impl Obj { + fn new() -> Self { + Self(Map::new()) + } + fn put(&mut self, key: &str, value: Option) -> &mut Self { + if let Some(v) = value { + self.0.insert(key.to_string(), v); + } + self + } + fn done(&mut self) -> Value { + Value::Object(std::mem::take(&mut self.0)) + } +} + +fn int(v: &FlexInt) -> Value { + json!(v.0) +} + +fn float(v: &FlexFloat) -> Value { + match &v.1 { + Some(text) => json!(text), + None => json!(v.0), + } +} + +fn opt(v: &Option, f: impl Fn(&T) -> Value) -> Option { + v.as_ref().map(f) +} + +fn list(v: &Option>, f: impl Fn(&T) -> Value) -> Option { + v.as_ref() + .map(|items| Value::Array(items.iter().map(f).collect())) +} + +fn strings(v: &Option>) -> Option { + list(v, |s| json!(s)) +} + +fn usize_(v: &Option) -> Option { + v.map(|n| json!(n)) +} + +fn text(v: &Option) -> Option { + v.as_ref().map(|s| json!(s)) +} + +fn object_type(t: &ObjectType) -> Value { + json!(match t { + ObjectType::File => "FILE", + ObjectType::Directory => "DIRECTORY", + }) +} + +fn data_flow(d: &DataFlow) -> Value { + json!(match d { + DataFlow::None => "NONE", + DataFlow::In => "IN", + DataFlow::Out => "OUT", + DataFlow::Inout => "INOUT", + }) +} + +fn file_filter(f: &FileFilter) -> Value { + json!({"label": f.label, "patterns": f.patterns}) +} + +/// The fields every `userInterface` has, plus the type's own. +fn ui( + control: &Option, + label: &Option, + group_label: &Option, + extra: &[(&str, Option)], +) -> Value { + let mut o = Obj::new(); + o.put("control", text(control)) + .put("label", text(label)) + .put("groupLabel", text(group_label)); + for (k, v) in extra { + o.put(k, v.clone()); + } + o.done() +} + +macro_rules! simple_ui { + ($u:expr) => { + opt($u, |u| ui(&u.control, &u.label, &u.group_label, &[])) + }; +} + +// openjd-model does not export the item-constraint and `BoolValue` +// types, so these read their fields through macros rather than functions +// that would have to name them. +macro_rules! boolean { + () => { + |v| json!(v.0) + }; +} + +macro_rules! string_items { + () => { + |c| { + Obj::new() + .put("allowedValues", strings(&c.allowed_values)) + .put("minLength", usize_(&c.min_length)) + .put("maxLength", usize_(&c.max_length)) + .done() + } + }; +} + +macro_rules! int_items { + () => { + |c| { + Obj::new() + .put("allowedValues", list(&c.allowed_values, int)) + .put("minValue", opt(&c.min_value, int)) + .put("maxValue", opt(&c.max_value, int)) + .done() + } + }; +} + +/// The template form of `def`, which deserializes to an equal definition. +pub(crate) fn job_param_def_to_json(def: &JobParameterDefinition) -> Value { + let mut o = Obj::new(); + o.put("name", Some(json!(def.name()))) + .put("type", Some(json!(def.type_name()))); + match def { + JobParameterDefinition::STRING(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", text(&p.default)) + .put("allowedValues", strings(&p.allowed_values)) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put("userInterface", simple_ui!(&p.user_interface)); + } + JobParameterDefinition::INT(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", opt(&p.default, int)) + .put("allowedValues", list(&p.allowed_values.0, int)) + .put("minValue", opt(&p.min_value, int)) + .put("maxValue", opt(&p.max_value, int)) + .put( + "userInterface", + opt(&p.user_interface, |u| { + ui( + &u.control, + &u.label, + &u.group_label, + &[("singleStepDelta", opt(&u.single_step_delta, int))], + ) + }), + ); + } + JobParameterDefinition::FLOAT(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", opt(&p.default, float)) + .put("allowedValues", list(&p.allowed_values.0, float)) + .put("minValue", opt(&p.min_value, float)) + .put("maxValue", opt(&p.max_value, float)) + .put( + "userInterface", + opt(&p.user_interface, |u| { + ui( + &u.control, + &u.label, + &u.group_label, + &[ + ("decimals", opt(&u.decimals, int)), + ("singleStepDelta", opt(&u.single_step_delta, float)), + ], + ) + }), + ); + } + JobParameterDefinition::PATH(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", text(&p.default)) + .put("allowedValues", strings(&p.allowed_values)) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put("objectType", opt(&p.object_type, object_type)) + .put("dataFlow", opt(&p.data_flow, data_flow)) + .put( + "userInterface", + opt(&p.user_interface, |u| { + ui( + &u.control, + &u.label, + &u.group_label, + &[ + ("fileFilters", list(&u.file_filters, file_filter)), + ( + "fileFilterDefault", + opt(&u.file_filter_default, file_filter), + ), + ], + ) + }), + ); + } + JobParameterDefinition::BOOL(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", opt(&p.default, boolean!())) + .put("userInterface", simple_ui!(&p.user_interface)); + } + JobParameterDefinition::RANGE_EXPR(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", text(&p.default)) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put("userInterface", simple_ui!(&p.user_interface)); + } + JobParameterDefinition::LIST_STRING(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", strings(&p.default)) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put("item", opt(&p.item, string_items!())) + .put("userInterface", simple_ui!(&p.user_interface)); + } + JobParameterDefinition::LIST_PATH(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("objectType", opt(&p.object_type, object_type)) + .put("dataFlow", opt(&p.data_flow, data_flow)) + .put("default", strings(&p.default)) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put("item", opt(&p.item, string_items!())) + .put( + "userInterface", + opt(&p.user_interface, |u| { + ui( + &u.control, + &u.label, + &u.group_label, + &[ + ("fileFilters", list(&u.file_filters, file_filter)), + ( + "fileFilterDefault", + opt(&u.file_filter_default, file_filter), + ), + ], + ) + }), + ); + } + JobParameterDefinition::LIST_INT(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", list(&p.default, int)) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put("item", opt(&p.item, int_items!())) + .put( + "userInterface", + opt(&p.user_interface, |u| { + ui( + &u.control, + &u.label, + &u.group_label, + &[("singleStepDelta", opt(&u.single_step_delta, int))], + ) + }), + ); + } + JobParameterDefinition::LIST_FLOAT(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", list(&p.default, float)) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put( + "item", + opt(&p.item, |c| { + Obj::new() + .put("allowedValues", list(&c.allowed_values, float)) + .put("minValue", opt(&c.min_value, float)) + .put("maxValue", opt(&c.max_value, float)) + .done() + }), + ) + .put( + "userInterface", + opt(&p.user_interface, |u| { + ui( + &u.control, + &u.label, + &u.group_label, + &[ + ("decimals", opt(&u.decimals, int)), + ("singleStepDelta", opt(&u.single_step_delta, float)), + ], + ) + }), + ); + } + JobParameterDefinition::LIST_BOOL(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put("default", list(&p.default, boolean!())) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put("userInterface", simple_ui!(&p.user_interface)); + } + JobParameterDefinition::LIST_LIST_INT(p) => { + o.put("description", opt(&p.description, |d| json!(d.0))) + .put( + "default", + list(&p.default, |row| { + Value::Array(row.iter().map(int).collect()) + }), + ) + .put("minLength", usize_(&p.min_length)) + .put("maxLength", usize_(&p.max_length)) + .put( + "item", + opt(&p.item, |c| { + Obj::new() + .put("minLength", usize_(&c.min_length)) + .put("maxLength", usize_(&c.max_length)) + .put("item", opt(&c.item, int_items!())) + .done() + }), + ) + .put("userInterface", simple_ui!(&p.user_interface)); + } + } + o.done() +} + +/// The template form of an `ENV_PARAMS` definition: its job-parameter +/// shape, with the `default` as written. +pub(crate) fn env_param_def_to_json(def: &EnvironmentParameterDefinition) -> Value { + let mut value = job_param_def_to_json(&def.definition); + if let (Some(default), Value::Object(obj)) = (&def.default, &mut value) { + let d = match default { + EnvironmentParameterValue::FormatString(fs) => json!(fs.raw()), + EnvironmentParameterValue::Literal(v) => v.clone(), + // Not `#[non_exhaustive]` today; the arm keeps the binding + // compiling if it becomes so. + #[allow(unreachable_patterns)] + _ => return value, + }; + obj.insert("default".to_string(), d); + } + value +} diff --git a/rust-bindings/src/model/profile.rs b/rust-bindings/src/model/profile.rs index 7cdd00d6..f3b614ac 100644 --- a/rust-bindings/src/model/profile.rs +++ b/rust-bindings/src/model/profile.rs @@ -185,6 +185,9 @@ pub(crate) enum PyModelExtension { FEATURE_BUNDLE_1 = 2, EXPR = 3, WRAP_ACTIONS = 4, + /// RFC 0010, unstable: decoding accepts a template that lists it only + /// with `CallerLimits(accept_unreleased_env_params=True)`. + ENV_PARAMS = 5, } #[cfg_attr(feature = "stub-gen", gen_stub_pymethods)] @@ -240,6 +243,7 @@ impl From for ModelExtension { PyModelExtension::FEATURE_BUNDLE_1 => ModelExtension::FeatureBundle1, PyModelExtension::EXPR => ModelExtension::Expr, PyModelExtension::WRAP_ACTIONS => ModelExtension::WrapActions, + PyModelExtension::ENV_PARAMS => ModelExtension::EnvParams, } } } @@ -252,6 +256,7 @@ impl From for PyModelExtension { ModelExtension::FeatureBundle1 => PyModelExtension::FEATURE_BUNDLE_1, ModelExtension::Expr => PyModelExtension::EXPR, ModelExtension::WrapActions => PyModelExtension::WRAP_ACTIONS, + ModelExtension::EnvParams => PyModelExtension::ENV_PARAMS, // `ModelExtension` is `#[non_exhaustive]`, so downstream // crates cannot write an exhaustive match. This arm is // mandatory, and the compiler will not warn when the Rust @@ -500,6 +505,8 @@ impl PyCallerLimits { max_resolved_data_len=None, max_eval_memory_bytes=None, max_eval_operations=None, + max_step_environment_entries=None, + accept_unreleased_env_params=false, ))] #[allow(clippy::too_many_arguments)] fn new( @@ -513,6 +520,8 @@ impl PyCallerLimits { max_resolved_data_len: Option, max_eval_memory_bytes: Option, max_eval_operations: Option, + max_step_environment_entries: Option, + accept_unreleased_env_params: bool, ) -> Self { Self { inner: CallerLimits { @@ -526,6 +535,8 @@ impl PyCallerLimits { max_resolved_data_len, max_eval_memory_bytes, max_eval_operations, + max_step_environment_entries, + accept_unreleased_env_params, }, } } @@ -575,27 +586,58 @@ impl PyCallerLimits { self.inner.max_eval_operations } + /// Cap on the `environment:` entries (`ENV_PARAMS`) in one Step's + /// `dependencies`, counted as written: disabled and `required: false` + /// entries count, `dependsOn` and `step` entries do not. Checked at + /// template validation only, so set it on the limits passed to + /// `decode_*`. Any value is accepted, including one below the 50 + /// entries Template Schemas §3 item 4 asks an implementation to allow. + #[getter] + fn max_step_environment_entries(&self) -> Option { + self.inner.max_step_environment_entries + } + + /// Not a limit: accept a template that lists `ENV_PARAMS`, whose + /// support in openjd-model is not complete. With the default + /// `False`, decoding reports `ENV_PARAMS` as an unsupported extension + /// name even when `supported_extensions` lists it. With `True`, it is + /// accepted when `supported_extensions` lists it. Unstable: it goes + /// away once openjd-model supports the extension fully. + #[getter] + fn accept_unreleased_env_params(&self) -> bool { + self.inner.accept_unreleased_env_params + } + fn __repr__(&self) -> String { + use crate::py_repr::py_opt_num; + let l = &self.inner; format!( - "CallerLimits(max_step_count={:?}, max_env_count={:?}, max_task_count={:?}, \ - max_step_script_size={:?}, max_environment_size={:?}, max_template_size={:?}, \ - max_resolved_arg_len={:?}, max_resolved_data_len={:?}, \ - max_eval_memory_bytes={:?}, max_eval_operations={:?})", - self.inner.max_step_count, - self.inner.max_env_count, - self.inner.max_task_count, - self.inner.max_step_script_size, - self.inner.max_environment_size, - self.inner.max_template_size, - self.inner.max_resolved_arg_len, - self.inner.max_resolved_data_len, - self.inner.max_eval_memory_bytes, - self.inner.max_eval_operations, + "CallerLimits(max_step_count={}, max_env_count={}, max_task_count={}, \ + max_step_script_size={}, max_environment_size={}, max_template_size={}, \ + max_resolved_arg_len={}, max_resolved_data_len={}, \ + max_eval_memory_bytes={}, max_eval_operations={}, \ + max_step_environment_entries={}, accept_unreleased_env_params={})", + py_opt_num(l.max_step_count), + py_opt_num(l.max_env_count), + py_opt_num(l.max_task_count), + py_opt_num(l.max_step_script_size), + py_opt_num(l.max_environment_size), + py_opt_num(l.max_template_size), + py_opt_num(l.max_resolved_arg_len), + py_opt_num(l.max_resolved_data_len), + py_opt_num(l.max_eval_memory_bytes), + py_opt_num(l.max_eval_operations), + py_opt_num(l.max_step_environment_entries), + if l.accept_unreleased_env_params { + "True" + } else { + "False" + }, ) } - /// Pickle support — round-trips through `__init__` with all ten - /// optional fields as keyword arguments. + /// Pickle support — round-trips through `__init__` with every field + /// as a keyword argument. fn __reduce__<'py>( &self, py: Python<'py>, @@ -616,12 +658,20 @@ impl PyCallerLimits { kwargs.set_item("max_resolved_data_len", self.inner.max_resolved_data_len)?; kwargs.set_item("max_eval_memory_bytes", self.inner.max_eval_memory_bytes)?; kwargs.set_item("max_eval_operations", self.inner.max_eval_operations)?; + kwargs.set_item( + "max_step_environment_entries", + self.inner.max_step_environment_entries, + )?; + kwargs.set_item( + "accept_unreleased_env_params", + self.inner.accept_unreleased_env_params, + )?; let args = PyTuple::new(py, [cls.into_any(), kwargs.into_any()])?; Ok((helper, args.into())) } /// Structural equality — required by the pickle round-trip - /// contract. Compares all ten fields; the underlying + /// contract. Compares every field; the underlying /// `CallerLimits` upstream doesn't derive `PartialEq`, so we /// implement equality field-by-field at the binding boundary. fn __eq__(&self, other: &Self) -> bool { @@ -635,6 +685,8 @@ impl PyCallerLimits { && self.inner.max_resolved_data_len == other.inner.max_resolved_data_len && self.inner.max_eval_memory_bytes == other.inner.max_eval_memory_bytes && self.inner.max_eval_operations == other.inner.max_eval_operations + && self.inner.max_step_environment_entries == other.inner.max_step_environment_entries + && self.inner.accept_unreleased_env_params == other.inner.accept_unreleased_env_params } } diff --git a/rust-bindings/src/model/step_param_space.rs b/rust-bindings/src/model/step_param_space.rs index f5618441..80998054 100644 --- a/rust-bindings/src/model/step_param_space.rs +++ b/rust-bindings/src/model/step_param_space.rs @@ -30,7 +30,10 @@ fn task_param_set_to_py(py: Python<'_>, params: &TaskParameterSet) -> PyResult

) -> PyResult { let mut result = TaskParameterSet::new(); - for (key, val) in dict.iter() { + // A snapshot: `getattr("type")` can run user code that changes the dict, + // and PyO3's live dict iterator panics on a size change. + for item in dict.items().iter() { + let (key, val): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; let name: String = key.extract()?; if let Ok(type_attr) = val.getattr("type") { // Resolve the parameter type's spec string. Try `as_str()` first diff --git a/rust-bindings/src/model/task_parameter.rs b/rust-bindings/src/model/task_parameter.rs index 54327c36..f4176440 100644 --- a/rust-bindings/src/model/task_parameter.rs +++ b/rust-bindings/src/model/task_parameter.rs @@ -29,12 +29,9 @@ //! | `PathTaskParameter` | `list[str]` | (absent) | //! | `ChunkIntTaskParameter` | `list[int] \| RangeExpr` | `TaskChunksDefinition` | //! -//! `IntTaskParameter` does *not* carry `chunks` even though the -//! underlying Rust struct has `chunks: Option`, -//! because no resolver path ever produces `Some(_)` on the `Int` -//! variant — chunks are exclusively a `ChunkInt` concern. Mirroring -//! the runtime *behaviour* is more useful than mirroring the -//! struct field declaration. +//! `IntTaskParameter` has no `chunks`: since openjd-model 0.17.0 +//! (openjd-rs#612) the Rust `TaskParameter::Int` variant has none either, +//! and a chunked parameter is `ChunkInt` and nothing else. use pyo3::prelude::*; use pyo3::types::{PyDict, PyList}; @@ -535,19 +532,12 @@ pub(crate) fn task_parameter_to_py<'py>( ) -> PyResult> { use pyo3::IntoPyObjectExt; match tp { - TaskParameter::Int { range, chunks: _ } => { - // The runtime crate carries `Option` on - // the `Int` variant, but no resolver path ever populates - // it (only `ChunkInt` does). The Python binding mirrors - // the runtime *behaviour*: `IntTaskParameter` has no - // chunks field at all. If a future code path produces - // `Some(_)` here it should construct `ChunkInt` instead; - // until then the field is silently ignored. - PyIntTaskParameter { - range: range.clone(), - } - .into_bound_py_any(py) + // Since openjd-model 0.17.0 (openjd-rs#612) a chunked parameter is + // `ChunkInt` and nothing else; `Int` has no chunk configuration. + TaskParameter::Int { range } => PyIntTaskParameter { + range: range.clone(), } + .into_bound_py_any(py), // `Float64` carries the spelling a `` range element was // written with (§7.5). It reaches a command line through // `TaskParameterValue`, which renders it verbatim; this getter is the diff --git a/rust-bindings/src/model/template.rs b/rust-bindings/src/model/template.rs index 1f16c440..65ed6586 100644 --- a/rust-bindings/src/model/template.rs +++ b/rust-bindings/src/model/template.rs @@ -173,6 +173,17 @@ impl PyEnvironmentTemplate { .map(|d| d.0.clone()) } + /// The [`ModelProfile`](crate::model::profile::PyModelProfile) this + /// template declares: the revision from `specificationVersion` and the + /// extensions its `extensions:` field lists, as `JobTemplate.profile` + /// gives a Job Template's. + #[getter] + fn profile(&self) -> PyModelProfile { + PyModelProfile { + inner: self.inner.profile(), + } + } + /// The `Environment` defined by this template — mirrors the /// `environment:` field in the YAML/JSON document. #[getter] diff --git a/rust-bindings/src/model/template_types.rs b/rust-bindings/src/model/template_types.rs index 63e9eb38..101ba24f 100644 --- a/rust-bindings/src/model/template_types.rs +++ b/rust-bindings/src/model/template_types.rs @@ -19,7 +19,7 @@ //! in the bindings. use pyo3::prelude::*; -use pyo3::types::{PyDict, PyList}; +use pyo3::types::PyDict; #[cfg(feature = "stub-gen")] use pyo3_stub_gen::derive::*; @@ -30,6 +30,13 @@ use openjd_model::template::{ }; use openjd_model::types::{EndOfLine, FileType}; +use openjd_model::template::Description; + +use super::env_params::{ + env_param_value_map_from_py, env_param_value_map_to_py, PyEnvironmentActivation, + PyEnvironmentParameterDefinition, PyExprField, +}; +use super::errors::model_err_to_py; use crate::expr::PyFormatString; // ── Action ── @@ -869,16 +876,40 @@ pub(crate) struct PyEnvironment { #[cfg_attr(feature = "stub-gen", gen_stub_pymethods)] #[pymethods] impl PyEnvironment { + /// Build a template Environment. `description` is checked as decoding + /// checks a `` (Template Schemas §7.2: 1 to 2048 + /// characters, no control character other than newline, carriage + /// return and tab) and raises `DecodeValidationError` otherwise. + /// + /// `env_parameter_definitions`, `activation`, `host_requirements`, + /// `enable_if` and `exclusive_group` are the `ENV_PARAMS` fields; see + /// their getters. Nothing here validates them: template validation + /// does, when the Environment is part of a decoded template. #[new] - #[pyo3(signature = (*, name, description=None, script=None, variables=None))] + #[pyo3(signature = ( + *, + name, + description=None, + script=None, + variables=None, + env_parameter_definitions=None, + activation=None, + host_requirements=None, + enable_if=None, + exclusive_group=None, + ))] + #[allow(clippy::too_many_arguments)] fn new( - py: Python<'_>, name: String, description: Option, script: Option, variables: Option<&Bound<'_, PyDict>>, + env_parameter_definitions: Option>, + activation: Option, + host_requirements: Option, + enable_if: Option, + exclusive_group: Option, ) -> PyResult { - let _ = py; let mut vars: Option> = None; if let Some(d) = variables { let mut map = std::collections::HashMap::new(); @@ -889,10 +920,20 @@ impl PyEnvironment { } vars = Some(map); } + let description = description + .map(|d| Description::new(&d)) + .transpose() + .map_err(model_err_to_py)?; Ok(PyEnvironment { inner: Environment { name, - description: description.map(openjd_model::template::Description), + description, + env_parameter_definitions: env_parameter_definitions + .map(|v| v.into_iter().map(|d| d.inner).collect()), + activation: activation.map(Into::into), + host_requirements: host_requirements.map(|h| h.inner), + enable_if: enable_if.map(|e| e.inner), + exclusive_group, script: script.map(|s| s.inner), variables: vars, }, @@ -931,10 +972,93 @@ impl PyEnvironment { } } + /// `ENV_PARAMS` `envParameterDefinitions`: the parameters a Step may + /// supply through an `environment:` entry of its `dependencies`, or + /// `None` when absent. An empty list stays an empty list. + #[getter] + fn env_parameter_definitions(&self) -> Option> { + self.inner.env_parameter_definitions.as_ref().map(|v| { + v.iter() + .map(|d| PyEnvironmentParameterDefinition { inner: d.clone() }) + .collect() + }) + } + + /// camelCase alias for `env_parameter_definitions`. + #[getter] + #[pyo3(name = "envParameterDefinitions")] + fn env_parameter_definitions_camel(&self) -> Option> { + self.env_parameter_definitions() + } + + /// `ENV_PARAMS` `activation` as written, or `None` when absent. See + /// `effective_activation` for the value with its default applied. + #[getter] + fn activation(&self) -> Option { + self.inner.activation.map(Into::into) + } + + /// `activation` with its default applied: `BY_DEFAULT` when absent, + /// as it applies in a document that lists `ENV_PARAMS`. + #[getter] + fn effective_activation(&self) -> PyEnvironmentActivation { + self.inner.activation().into() + } + + /// `ENV_PARAMS` `hostRequirements`: requirements on the Worker Host + /// that every Session entering this Environment must satisfy, or + /// `None` when absent. + #[getter] + fn host_requirements(&self) -> Option { + self.inner + .host_requirements + .as_ref() + .map(|h| PyHostRequirements { inner: h.clone() }) + } + + /// camelCase alias for `host_requirements`. + #[getter] + #[pyo3(name = "hostRequirements")] + fn host_requirements_camel(&self) -> Option { + self.host_requirements() + } + + /// `ENV_PARAMS` `enableIf` as written, or `None` when absent. A + /// present `null` is `ExprField(None)`. + #[getter] + fn enable_if(&self) -> Option { + self.inner + .enable_if + .as_ref() + .map(|e| PyExprField { inner: e.clone() }) + } + + /// camelCase alias for `enable_if`. + #[getter] + #[pyo3(name = "enableIf")] + fn enable_if_camel(&self) -> Option { + self.enable_if() + } + + /// `ENV_PARAMS` `exclusiveGroup`, or `None` when absent. + #[getter] + fn exclusive_group(&self) -> Option<&str> { + self.inner.exclusive_group.as_deref() + } + + /// camelCase alias for `exclusive_group`. + #[getter] + #[pyo3(name = "exclusiveGroup")] + fn exclusive_group_camel(&self) -> Option<&str> { + self.exclusive_group() + } + fn __repr__(&self) -> String { format!("Environment(name={:?})", self.inner.name) } + /// Pickle support. Every field round-trips, `env_parameter_definitions` + /// included. #[allow(clippy::type_complexity)] fn __reduce__<'py>( slf: PyRef<'py, Self>, @@ -955,6 +1079,22 @@ impl PyEnvironment { if let Some(v) = slf.variables(py)? { kwargs.set_item("variables", v)?; } + if let Some(defs) = slf.env_parameter_definitions() { + // An empty list stays distinct from absent. + kwargs.set_item("env_parameter_definitions", defs)?; + } + if let Some(a) = slf.activation() { + kwargs.set_item("activation", a)?; + } + if let Some(h) = slf.host_requirements() { + kwargs.set_item("host_requirements", h)?; + } + if let Some(e) = slf.enable_if() { + kwargs.set_item("enable_if", e)?; + } + if let Some(g) = slf.exclusive_group() { + kwargs.set_item("exclusive_group", g)?; + } let cls = py.get_type::(); let args = PyTuple::new(py, [cls.into_any(), kwargs.into_any()])?; Ok((helper, args.into())) @@ -1229,27 +1369,150 @@ pub(crate) struct PyStepDependency { #[cfg_attr(feature = "stub-gen", gen_stub_pymethods)] #[pymethods] impl PyStepDependency { + /// Build one entry of a Step's `dependencies`. The entry is + /// `dependsOn: ` or, with `ENV_PARAMS`, its synonym + /// `step: `, or `environment: ` with + /// optional `required`, `enable_if` and `parameters`. Every key is + /// optional, as in decoding, so an entry with more than one form or + /// none builds here and template validation reports it. #[new] - #[pyo3(signature = (*, depends_on))] - fn new(depends_on: String) -> Self { - PyStepDependency { - inner: StepDependency { depends_on }, - } + #[pyo3(signature = ( + *, + depends_on=None, + step=None, + environment=None, + required=None, + enable_if=None, + parameters=None, + ))] + fn new( + depends_on: Option, + step: Option, + environment: Option, + required: Option, + enable_if: Option, + parameters: Option<&Bound<'_, PyDict>>, + ) -> PyResult { + Ok(PyStepDependency { + inner: StepDependency { + depends_on, + step, + environment, + required, + enable_if: enable_if.map(|e| e.inner), + parameters: parameters.map(env_param_value_map_from_py).transpose()?, + }, + }) } + /// The `dependsOn` key as written, or `None` when absent. Use + /// `step_name()` for the Step a well-formed entry names, which also + /// reads the `step` synonym. #[getter] - fn depends_on(&self) -> &str { - &self.inner.depends_on + fn depends_on(&self) -> Option<&str> { + self.inner.depends_on.as_deref() } #[getter] #[pyo3(name = "dependsOn")] - fn depends_on_camel(&self) -> &str { + fn depends_on_camel(&self) -> Option<&str> { self.depends_on() } + /// `ENV_PARAMS`: the `step` key as written, or `None` when absent. + #[getter] + fn step(&self) -> Option<&str> { + self.inner.step.as_deref() + } + + /// `ENV_PARAMS`: the `environment` key as written, or `None` when + /// absent. + #[getter] + fn environment(&self) -> Option<&str> { + self.inner.environment.as_deref() + } + + /// `ENV_PARAMS`: `required` as written, or `None` when absent. See + /// `is_required()` for the value with its default applied. + #[getter] + fn required(&self) -> Option { + self.inner.required + } + + /// `ENV_PARAMS`: `enableIf` as written, or `None` when absent. A + /// present `null` is `ExprField(None)`. + #[getter] + fn enable_if(&self) -> Option { + self.inner + .enable_if + .as_ref() + .map(|e| PyExprField { inner: e.clone() }) + } + + #[getter] + #[pyo3(name = "enableIf")] + fn enable_if_camel(&self) -> Option { + self.enable_if() + } + + /// `ENV_PARAMS`: the `parameters` map as a new `dict`, or `None` when + /// absent. Each value is a `FormatString` (a string containing `{{`) + /// or the literal as written. Keys are in byte-wise order, since the + /// crate keeps the map sorted. + #[getter] + fn parameters<'py>(&self, py: Python<'py>) -> PyResult>> { + self.inner + .parameters + .as_ref() + .map(|m| env_param_value_map_to_py(py, m)) + .transpose() + } + + /// The Step a well-formed `dependsOn` or `step` entry names: exactly + /// one of `depends_on`, `step` and `environment` is set. `None` + /// otherwise. + fn step_name(&self) -> Option<&str> { + self.inner.step() + } + + /// The Environment a well-formed `environment` entry names. `None` + /// otherwise. + fn environment_name(&self) -> Option<&str> { + self.inner.environment() + } + + /// `required` with its default applied: `True` when absent. + fn is_required(&self) -> bool { + self.inner.is_required() + } + + /// Equal when every field is equal, as openjd-model's `StepDependency` + /// compares. Not hashable, since the class is not frozen. + fn __eq__(&self, other: PyRef<'_, Self>) -> bool { + other.inner == self.inner + } + fn __repr__(&self) -> String { - format!("StepDependency(dependsOn={:?})", self.inner.depends_on) + let mut parts = Vec::new(); + if let Some(v) = &self.inner.depends_on { + parts.push(format!("dependsOn={v:?}")); + } + if let Some(v) = &self.inner.step { + parts.push(format!("step={v:?}")); + } + if let Some(v) = &self.inner.environment { + parts.push(format!("environment={v:?}")); + } + if let Some(v) = self.inner.required { + parts.push(format!("required={}", if v { "True" } else { "False" })); + } + if self.inner.enable_if.is_some() { + parts.push("enableIf=...".to_string()); + } + if self.inner.parameters.is_some() { + parts.push("parameters=...".to_string()); + } + format!("StepDependency({})", parts.join(", ")) } #[allow(clippy::type_complexity)] @@ -1262,7 +1525,24 @@ impl PyStepDependency { .import("openjd._openjd_rs")? .getattr("_reconstruct_kwargs")?; let kwargs = PyDict::new(py); - kwargs.set_item("depends_on", slf.depends_on())?; + if let Some(v) = slf.depends_on() { + kwargs.set_item("depends_on", v)?; + } + if let Some(v) = slf.step() { + kwargs.set_item("step", v)?; + } + if let Some(v) = slf.environment() { + kwargs.set_item("environment", v)?; + } + if let Some(v) = slf.required() { + kwargs.set_item("required", v)?; + } + if let Some(v) = slf.enable_if() { + kwargs.set_item("enable_if", v)?; + } + if let Some(v) = slf.parameters(py)? { + kwargs.set_item("parameters", v)?; + } let cls = py.get_type::(); let args = PyTuple::new(py, [cls.into_any(), kwargs.into_any()])?; Ok((helper, args.into())) @@ -1538,42 +1818,3 @@ impl PyStepTemplate { format!("StepTemplate(name={:?})", self.inner.name) } } - -/// Convert a `serde_json::Value` to a Python object. (Reserved for -/// future use when a typed `StepParameterSpaceDefinition` pyclass is -/// added; currently unused.) -#[allow(dead_code)] -fn json_to_py<'py>(py: Python<'py>, value: &serde_json::Value) -> PyResult> { - use pyo3::IntoPyObject; - use serde_json::Value; - Ok(match value { - Value::Null => py.None().bind(py).clone(), - Value::Bool(b) => b.into_pyobject(py)?.to_owned().into_any(), - Value::Number(n) => { - if let Some(i) = n.as_i64() { - i.into_pyobject(py)?.into_any() - } else if let Some(u) = n.as_u64() { - u.into_pyobject(py)?.into_any() - } else if let Some(f) = n.as_f64() { - f.into_pyobject(py)?.into_any() - } else { - py.None().bind(py).clone() - } - } - Value::String(s) => s.into_pyobject(py)?.into_any(), - Value::Array(arr) => { - let py_list = PyList::empty(py); - for v in arr { - py_list.append(json_to_py(py, v)?)?; - } - py_list.into_any() - } - Value::Object(obj) => { - let d = PyDict::new(py); - for (k, v) in obj { - d.set_item(k, json_to_py(py, v)?)?; - } - d.into_any() - } - }) -} diff --git a/rust-bindings/src/model/types.rs b/rust-bindings/src/model/types.rs index 6a58cd75..55499718 100644 --- a/rust-bindings/src/model/types.rs +++ b/rust-bindings/src/model/types.rs @@ -400,6 +400,22 @@ impl PyTaskParameterType { format!("TaskParameterType.{}", self.name()) } + /// The expression type of `Task.Param.` for a parameter of this + /// type (Expression Language, "Task Parameter Types"). + fn expr_type(&self) -> crate::expr::PyExprType { + crate::expr::PyExprType { + inner: TaskParameterType::from(*self).expr_type(), + } + } + + /// The expression type of `Task.RawParam.`: the same as + /// `expr_type()`, except `string` for `PATH`. + fn raw_expr_type(&self) -> crate::expr::PyExprType { + crate::expr::PyExprType { + inner: TaskParameterType::from(*self).raw_expr_type(), + } + } + /// Variant name as a string (e.g. `"INT"`, `"CHUNK_INT"`). /// /// Distinct from `as_str()` for the `CHUNK_INT` variant, whose diff --git a/rust-bindings/src/py_repr.rs b/rust-bindings/src/py_repr.rs index e1c4148a..f7801acb 100644 --- a/rust-bindings/src/py_repr.rs +++ b/rust-bindings/src/py_repr.rs @@ -38,6 +38,15 @@ pub(crate) fn py_str(py: Python<'_>, value: &str) -> PyResult { Ok(PyString::new(py, value).repr()?.to_cow()?.into_owned()) } +/// An optional number as Python spells it: the number, or `None`. +/// `Debug` would emit `Some(0)`, which evaluates to a `NameError`. +pub(crate) fn py_opt_num(value: Option) -> String { + match value { + Some(v) => v.to_string(), + None => "None".to_string(), + } +} + /// An optional `int` as Python spells it. `Debug` would emit `Some(0)`, /// which evaluates to a `NameError`. pub(crate) fn py_opt_int(value: Option) -> String { diff --git a/rust-bindings/src/sessions/session.rs b/rust-bindings/src/sessions/session.rs index 9002cfc7..752b75f5 100644 --- a/rust-bindings/src/sessions/session.rs +++ b/rust-bindings/src/sessions/session.rs @@ -26,9 +26,15 @@ use crate::model::job::PyStepScript; use super::session_user::{PyPosixSessionUser, PyWindowsSessionUser}; -fn extract_job_parameter_values(py_dict: &Bound<'_, PyDict>) -> PyResult { +/// Read a `job_parameter_values` dict. It iterates over a snapshot, because +/// reading a value can run user code (`getattr`, a dict subclass) that +/// changes the dict, and PyO3's live dict iterator panics on a size change. +pub(crate) fn extract_job_parameter_values( + py_dict: &Bound<'_, PyDict>, +) -> PyResult { let mut result = JobParameterValues::new(); - for (key, val) in py_dict.iter() { + for item in py_dict.items().iter() { + let (key, val): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; let name: String = key.extract()?; // Direct passthrough when the Python caller already has a // typed ``JobParameterValue`` pyclass — unwrap to the @@ -70,7 +76,9 @@ fn extract_path_mapping_rules( fn extract_task_parameter_values(py_dict: &Bound<'_, PyDict>) -> PyResult { let mut result = TaskParameterSet::new(); - for (key, val) in py_dict.iter() { + // A snapshot, as in `extract_job_parameter_values`. + for item in py_dict.items().iter() { + let (key, val): (Bound<'_, PyAny>, Bound<'_, PyAny>) = item.extract()?; let name: String = key.extract()?; // Direct passthrough when the Python caller already has a // typed ``TaskParameterValue`` pyclass — unwrap to the @@ -754,10 +762,11 @@ impl PySession { // Clone the inner ``SerializedSymbolTable`` (a thin // ``serde_json::Value`` wrapper) so the background thread - // owns it. ``None`` means the runner sees an empty step-scope - // symtab — ``Param.*``, ``RawParam.*``, and step-level let - // bindings won't be visible during script-level let-binding - // evaluation or expression interpolation. + // owns it. With ``None``, openjd-sessions resolves the + // environment against its own ``resolved_symtab`` (an + // ``Environment`` from ``create_job`` has one), and otherwise + // builds the table from the session's job parameter values + // (openjd-rs#632). The exit then reuses the table the entry used. let resolved = resolved_symtab.map(|st| st.inner.clone()); self.dispatch(py, &[SessionState::Ready], move |rt, session| { diff --git a/scripts/check_third_party_licenses.sh b/scripts/check_third_party_licenses.sh index 19fb3f33..1689ea7c 100755 --- a/scripts/check_third_party_licenses.sh +++ b/scripts/check_third_party_licenses.sh @@ -85,7 +85,10 @@ python -m pip wheel --no-deps --quiet -w "$wheel_dir" . >/dev/null echo "Creating ephemeral venv..." python -m venv "$venv_dir" "$venv_dir/bin/pip" install --quiet --upgrade pip >/dev/null -"$venv_dir/bin/pip" install --quiet "$wheel_dir"/openjd_model-*.whl pip-licenses >/dev/null +# pip-licenses is pinned: 6.0.0 writes "UNKNOWN" for every license text, +# which would empty the Python section. Raise the pin only after checking +# that a newer release still fills in LicenseText. +"$venv_dir/bin/pip" install --quiet "$wheel_dir"/openjd_model-*.whl "pip-licenses==5.5.5" >/dev/null # Render Python deps in the same format cargo-about's about.hbs emits: # diff --git a/scripts/generate_stubs.sh b/scripts/generate_stubs.sh index f68bfe72..3bb24a55 100755 --- a/scripts/generate_stubs.sh +++ b/scripts/generate_stubs.sh @@ -48,6 +48,23 @@ sed -i '/"PyExprValueIter"/d; /"PyRangeExprIter"/d; /"PyStepParamSpaceIter"/d' s # as returning `T` directly. sed -i 's|def __next__(self) -> typing\.Optional\[dict\]: \.\.\.|def __next__(self) -> dict: ...|' src/openjd/_openjd_rs.pyi +# `Job.parameters` builds a `PyDict` to keep openjd-model's order, which +# pyo3-stub-gen can only type as a bare `dict`. Restore the value type. +python3 - <<'PYI_JOB_PARAMS' +from pathlib import Path + +p = Path("src/openjd/_openjd_rs.pyi") +text = p.read_text() +start = text.index("class Job:") +end = text.index("\nclass ", start + 1) +body = text[start:end].replace( + "def parameters(self) -> dict:", + "def parameters(self) -> builtins.dict[builtins.str, JobParameter]:", + 1, +) +p.write_text(text[:start] + body + text[end:]) +PYI_JOB_PARAMS + # Fill in iterator-protocol methods on the internal `Py*Iter` classes. # pyo3-stub-gen emits them as empty marker classes (`class Foo: ...`), # but they're returned from `__iter__` accessors elsewhere in the @@ -143,6 +160,7 @@ class UnsupportedSchema(builtins.ValueError): ... # level for callers that want to inspect or override the limits. DEFAULT_MEMORY_LIMIT: builtins.int DEFAULT_OPERATION_LIMIT: builtins.int +MAX_TYPE_DEPTH: builtins.int PYI # Run black on the final .pyi so the file matches the project's diff --git a/specs/python-expr-interface.md b/specs/python-expr-interface.md index ff634a14..e5f817ef 100644 --- a/specs/python-expr-interface.md +++ b/specs/python-expr-interface.md @@ -132,6 +132,18 @@ bindings = generic.match_type(concrete) # {TypeCode.TYPEVAR_T: ExprType("int") generic.substitute(bindings) # ExprType("list[int]") ``` +An `ExprType` is at most `MAX_TYPE_DEPTH` (64) levels deep: lists, unions and +signatures count a level each, and `unresolved[T]` is as deep as `T`. Since +openjd-expr 0.18.0 (openjd-rs#578), `ExprType(code, params)`, +`ExprType("list", params)`, `ExprType.list`, `ExprType.union`, `nullable()` and +`substitute()` raise `ExpressionError` (`Type nesting depth exceeded limit +(64)`) for a type deeper than that; before, such a type was built and `==`, +`hash` and `str` on it could overflow the stack. A type parsed from a string +stops at 10 levels of nesting (11 deep), and deeper text raises `ValueError`, +as any unparsable type string does. `ExprType` pickles through that string, so +a type deeper than 11 levels pickles but `pickle.loads` raises `ValueError` +(a strict xfail in `test/openjd/expr/test_known_gaps.py`). + ### `TypeCode` Enum identifying the kind of an `ExprType`. @@ -445,6 +457,12 @@ evaluate_expression("apply_path_mapping('/p')", profile=profile) # returns ExprValue.unresolved("path") ``` +Since openjd-expr 0.18.0 (openjd-rs#611), `HostContext.unresolved()` also makes +every `path(...)` overload and `with_number(string, int)` return +`unresolved[T]`, because the worker's path format is not known yet: +`path('/a/b').name` is `unresolved[string]`, where `HostContext.none()` gives +`'b'`. A call that matches no signature, such as `path(1)`, still raises. + **Equality and hashability.** Both `HostContext` and `ExprProfile` implement `__eq__` and `__hash__`. @@ -564,6 +582,17 @@ r2 = parsed.evaluate_with_metrics(values={"Param.N": 5}) r1.operation_count > r2.operation_count ``` +Since openjd-expr 0.18.1 (openjd-rs#368), each regex pattern cached during an +evaluation, at most 32 of them, counts 1 MiB plus its length toward +`memory_limit` and `peak_memory`, and a cache miss costs `len(pattern)` +operations. A pattern that does not fit the budget is compiled for that call +and not counted. `re_search('abc', 'b') != null` has a `peak_memory` above +1 MiB, and an expression that uses a regex can exceed a `memory_limit` it fit +in before. Because the choice to cache is made when the pattern is compiled, +a larger `memory_limit` can fail where a smaller one passes: a limit too small +for the pattern leaves it uncached, and one large enough to hold the pattern caches it and +leaves less for what follows (a strict xfail in `test_known_gaps.py`). + ### `EvalResult` The structured return type of @@ -767,8 +796,11 @@ A `RangeExpr` is kept in the canonical form of Template Schemas Two `RangeExpr`s are equal exactly when they have the same values. Every constructor raises `RangeExprError` when the canonical form would have more than 50,000 runs, and parsing accepts at most 50,000 -comma-separated elements. Values can be any 64-bit integer except the -most negative one. The pure-Python +comma-separated elements. A value or endpoint can be any 64-bit integer, +-2^63 included (openjd-expr 0.18.0, openjd-rs#633; before, -2^63 was +refused). A step of -2^63 is an integer overflow error, and a range with +more than 2^63 - 1 values raises `RangeExprError` (`Range expression has too +many values; the maximum is 9223372036854775807`). The pure-Python `openjd.model._range_expr.IntRangeExpr` follows the input's elements instead. @@ -848,6 +880,11 @@ result.item() # 43 result.type.type_code # TypeCode.INT ``` +`has_complex_expressions()` returns `False` only when every interpolation is +a bare dotted name. A name in parentheses, such as `{{ (Param.X) }}`, or one +with a comment or a line continuation in it, counts as complex (openjd-expr +0.18.0, openjd-rs#633; before, these returned `False`). + **Static validation.** ``validate_expressions(symtab, *, profile=None)`` walks every ``{{...}}`` segment and evaluates it against the supplied symbol table, raising @@ -989,6 +1026,30 @@ including a shortest-digit tie, which rounds to even: `string(1000000000000000.25 * 1.0)` is `"1000000000000000.2"` (openjd-expr 0.15.0, openjd-rs#539; before, ties rounded up). +`round(x, ndigits)` on a float returns `int` when `ndigits <= 0` and `float` +otherwise. It rounds the exact value half to even, as CPython does, so +`round(2.675, 2)` is `2.67`. An `int` result outside the 64-bit signed range +is an integer overflow error (openjd-expr 0.17.0, openjd-rs#567; before, it +returned a float, so `string(round(2.5, 0))` was `"2.0"` and is now `"2"`). + +Since openjd-expr 0.18.0 (openjd-rs#570), `re_sub` rejects a replacement that +contains a control character other than tab, newline or carriage return +(`Control characters in replacement strings are not supported (U+0001)`). A +non-raw `'\1'` is U+0001, so it gets this error. A `\u` or `\U` escape that +encodes a surrogate (U+D800 to U+DFFF) in a non-raw string is a syntax error +(`\ud800 is a surrogate code point, which a string can't hold`). Before, it +became U+FFFD. + +Since openjd-expr 0.18.1 (openjd-rs#626), a subscript is checked by its +receiver's type, resolved or not. Only `list`, `string` and `range_expr` can +be indexed, and any other type raises `Cannot subscript type `, as in +`5[0]` or a subscript of an unresolved `path`. A slice of an unresolved +`range_expr` is `unresolved[list[int] | range_expr]`. + +`path([])`, or `path(...)` of an empty comprehension, is +`path('.')` in every path format (openjd-expr 0.18.0, openjd-rs#576; before, +it raised `No matching signature for path(list[nulltype])`). + | Exception | Base | |---|---| @@ -1032,10 +1093,11 @@ err.message_with_expr_prefix("x = ") ## Constants ```python -from openjd.expr import DEFAULT_MEMORY_LIMIT, DEFAULT_OPERATION_LIMIT +from openjd.expr import DEFAULT_MEMORY_LIMIT, DEFAULT_OPERATION_LIMIT, MAX_TYPE_DEPTH DEFAULT_MEMORY_LIMIT # 100_000_000 (100 MB) DEFAULT_OPERATION_LIMIT # 10_000_000 (10 million) +MAX_TYPE_DEPTH # 64, the deepest an ExprType can be (openjd-expr 0.18.0) ``` ## Pickle Support diff --git a/specs/python-model-interface.md b/specs/python-model-interface.md index 55b7b15f..817ce519 100644 --- a/specs/python-model-interface.md +++ b/specs/python-model-interface.md @@ -161,6 +161,51 @@ The `ModelProfile` type is used as an *output* of decoding (via It is not an input to `decode_*_template` itself — that function takes a flat list of strings, mirroring the Rust crate. +Only a string is accepted in a format-string field. A number or boolean +raises `DecodeValidationError` (openjd-model 0.17.0, openjd-rs#633): +``'jobtemplate-2023-09' failed checks: steps[0] -> script -> actions -> onRun -> args[0]: invalid type: integer `5`, expected a string``. +v0 raises `String required`. +Before, v1 converted the value to text. A number in an amount or +attribute `name` or an attribute value was a `ModelValidationError` +before and is a `DecodeValidationError` now. `timeout`, +`notifyPeriodInSeconds` and amount `min`/`max` still accept numbers. + +Without EXPR, every format-string interpolation must be a bare dotted +name, in every field (openjd-model 0.17.0, openjd-rs#633). Anything else, +a parenthesized name included, raises `ModelValidationError` at the +field with `complex expressions require the EXPR extension.`, and a +range written as one expression raises `A range expression (format string) +requires the EXPR extension.` Before, only `variables`, `command`, +`args` and environment `data` were checked. v0 refuses the same +templates with a parse error, except that when the caller's +`supported_extensions` lists EXPR but the template does not, v0 accepts +the constants `{{ True }}`, `{{ False }}` and `{{ None }}`, and v1 refuses +them. + +An action `command` has no length limit of its own since openjd-model +0.17.0 (openjd-rs#561), as in v0. Before, a command over 1024 characters +was refused. `CallerLimits(max_resolved_arg_len=...)` still bounds it. + +These `openjd.expr` changes also affect decoding, in v0 and v1 alike. A +literal path in a host-scope field such as `args` is left +unresolved (openjd-expr 0.18.0, openjd-rs#611), so +`{{ int(path('C:\\a\\5').name) }}` decodes there. A TEMPLATE-scope field +(job `name`, a `timeout`, a range element, a step `let`) is checked +without a host context, so `{{ int(path('a/b').name) }}` there still +fails to decode with `Cannot convert 'b' to int`. That includes an expression +that reads a step `let` name: v0 checks it with the name as a value of type +`any`, so `{{ int(path('a/b').name) + n }}` in a `timeout` fails to decode in +both. A host-context function +such as `apply_path_mapping` in a TEMPLATE-scope field or step `let` fails +to decode in both. v0 finds the call by name, so it also refuses one in a +branch that a literal condition rules out, which v1 decodes. A subscript is checked +against its receiver's type (openjd-expr 0.18.1, openjd-rs#626): +`Param.P[0]` on a PATH parameter fails with `Cannot subscript type path`, +and on INT, FLOAT and BOOL the message is `Cannot subscript type int` +(`float`, `bool`). `round(x, n)` with `n <= 0` returns an int and rounds +the exact value (openjd-expr 0.17.0, openjd-rs#567), so a name +`J{{ round(2.5, 0) }}` gives `J2`, where it gave `J2.0`. + #### `decode_job_template_str` Decode directly from a YAML or JSON string — no intermediate dict. @@ -192,6 +237,13 @@ diagnostics on parse failures. ``decode_job_template_str`` accepts the same ``supported_extensions`` and ``caller_limits`` kwargs as :func:`decode_job_template`. +The YAML is read with the YAML 1.2 Core schema, where v0 reads YAML 1.1. +So `1e3`, `0o17` and `1_000` are numbers and refused in a format-string +field (openjd-model 0.17.0, openjd-rs#633), where v0 reads `1e3` and +`0o17` as strings. In the other direction, `yes`, `no`, `on`, `off`, +`.inf`, timestamps and base-60 integers such as `1:30` are strings here +and `String required` in v0. + #### `decode_environment_template` Decode and validate an environment template from a Python dict. @@ -286,6 +338,19 @@ absolute default is returned as written, and a relative one may escape value is joined to `current_working_dir`. Joined values are lexically normalized; an absolute submitted value is returned as written. A default's constraints are checked against the joined value. URI values are refused. Violations raise `DecodeValidationError` (openjd-rs#421). +A `..` that a relative working directory cannot cancel is kept, so +`rel/dir` and `../../../x` give `../x` (openjd-model 0.17.0, +openjd-rs#633). Before, it was dropped. v0 does not normalize. + +STRING and PATH `minLength`/`maxLength` count characters (Unicode scalar +values), not bytes, as v0 does (openjd-model 0.17.0, openjd-rs#615). +`-9223372036854775808` is a valid integer in a RANGE_EXPR value or +default, in an INT task parameter range and in a `range_expr()` argument +(openjd-model 0.17.0, openjd-rs#633), as in v0. + +The order of the returned `dict` is unspecified: openjd-model returns a +hash map, and the binding keeps its order. v0 returns the merge order. +`create_job` lists `Job.parameters` in a fixed order (see `Job`). A FLOAT given as a number, as a default, a `LIST[FLOAT]` item or a value, is written the way Python's `repr(float)` writes it, with zero @@ -603,6 +668,12 @@ job.job_environments # Optional[list[Environment]] job.jobEnvironments # same (camelCase alias) ``` +`job.parameters` lists the parameters of the job template in definition order, +then the other entries, from environment templates, in byte-wise name order +(openjd-model 0.18.0, openjd-rs#639). An environment parameter that the job +template also defines keeps the place it has in the job template. Before, the order changed from one +`create_job` call to the next. v0 gives definition order. + ### `Step` A step within a job. @@ -754,10 +825,10 @@ F.range # list[int] | RangeExpr (INT only) | `StringTaskParameter` | `TaskParameterType.STRING` | `list[str]` | | `PathTaskParameter` | `TaskParameterType.PATH` | `list[str]` | -None of these four carry a `chunks` field — only `ChunkIntTaskParameter` -does. (The underlying Rust struct has `chunks: Option` -on the `Int` variant for shape reasons, but no resolver path ever -populates it; the binding mirrors the runtime *behaviour*.) +None of these four carry a `chunks` field. Only `ChunkIntTaskParameter` +does, and since openjd-model 0.17.0 (openjd-rs#612) the Rust `Int` +variant has no `chunks` field either: a chunked parameter is `CHUNK[INT]` +and nothing else. `FloatTaskParameter.range` is numeric, so it does not show the decimal places a `` range element was written with. A range element @@ -864,6 +935,8 @@ env_template = decode_environment_template(template={...}) env_template.environment # Environment env_template.specification_version env_template.specificationVersion +env_template.profile # ModelProfile: revision + listed extensions, + # as JobTemplate.profile gives (openjd-model 0.18.0) ``` The structural pyclasses for template-time types live under @@ -877,6 +950,8 @@ from openjd.model._v1.template import ( StepScript, StepActions, EmbeddedFile, HostRequirements, AmountRequirement, AttributeRequirement, StepDependency, CancelationMode, SimpleAction, + # ENV_PARAMS (unstable, see "ENV_PARAMS" below) + EnvironmentActivation, EnvironmentParameterDefinition, ExprField, ) ``` @@ -925,8 +1000,34 @@ env.name # str env.description # Optional[str] env.script # Optional[EnvironmentScript] env.variables # Optional[dict[str, FormatString]] +# ENV_PARAMS fields; None when absent (see "ENV_PARAMS" below): +env.env_parameter_definitions # Optional[list[EnvironmentParameterDefinition]] + # (alias: envParameterDefinitions) +env.activation # Optional[EnvironmentActivation], as written +env.effective_activation # EnvironmentActivation; BY_DEFAULT when absent +env.host_requirements # Optional[HostRequirements] (alias: hostRequirements) +env.enable_if # Optional[ExprField] (alias: enableIf) +env.exclusive_group # Optional[str] (alias: exclusiveGroup) ``` +`Environment(*, name, description=None, script=None, variables=None, +env_parameter_definitions=None, activation=None, host_requirements=None, +enable_if=None, exclusive_group=None)` builds one. `description` is checked as +decoding checks a `` (Template Schemas §7.2: 1 to 2048 characters, +no control character other than newline, carriage return and tab) and raises +`DecodeValidationError` otherwise. Before openjd-model 0.18.0 the constructor +kept any string. The constructor checks no other field: template validation checks the +ENV_PARAMS fields when the Environment is part of a decoded template. Decoding checks every +`` the same way, at its path: +`environment -> description: Validation error: Description contains control characters`. +Decoding has refused an empty description in the job, a step, an +environment and a parameter definition since openjd-model 0.17.0 +(openjd-rs#633), with `Validation error: Description should have at +least 1 character`. Before, it decoded. + +An Environment pickles with every field, `env_parameter_definitions` +included. + ### `EnvironmentScript` / `StepScript` ```python @@ -968,7 +1069,7 @@ cm.notify_period_in_seconds # Optional[FormatString] (alias: notifyPeriodInS ef = step.script.embedded_files[0] ef.name # str ef.type # "TEXT" -ef.filename # Optional[FormatString] +ef.filename # Optional[str] ef.data # Optional[FormatString] ef.runnable # Optional[bool] ef.end_of_line # Optional["LF" | "CRLF" | "AUTO"] (alias: endOfLine) @@ -1018,9 +1119,134 @@ it was a `str` in both directions. The job-side `AmountRequirement.name` / ```python dep = step.dependencies[0] -dep.depends_on # str (alias: dependsOn) +dep.depends_on # Optional[str], the dependsOn key as written (alias: dependsOn) +# ENV_PARAMS forms; None when absent: +dep.step # Optional[str], the `step:` synonym of dependsOn +dep.environment # Optional[str] +dep.required # Optional[bool], as written +dep.enable_if # Optional[ExprField] (alias: enableIf) +dep.parameters # Optional[dict[str, FormatString | literal]] +dep.step_name() # the Step a well-formed dependsOn/step entry names, else None +dep.environment_name() # the Environment a well-formed environment entry names, else None +dep.is_required() # required with its default applied (True) +``` + +`StepDependency(*, depends_on=None, step=None, environment=None, required=None, +enable_if=None, parameters=None)` builds one. Every key is optional, as in +decoding, so an entry with more than one form or none builds, and template +validation reports it at its path; `step_name()` and `environment_name()` +return `None` for it. `depends_on` was a `str` and a required keyword before +openjd-model 0.18.0 (openjd-rs#641). A template without ENV_PARAMS still +validates only `dependsOn` entries, so a decoded one never has +`depends_on` of `None`. + +In a template without ENV_PARAMS, an ENV_PARAMS key on a dependency or an +Environment used to fail at decode with `DecodeValidationError`, as an +unknown field (and `dependencies: [{}]` as a missing `dependsOn`). Since +openjd-model 0.18.0 the entry decodes, and template validation raises +`ModelValidationError` at the key, which `except DecodeValidationError` +does not catch: `steps[1] -> dependencies[0]: the 'step' form of a +dependency requires the ENV_PARAMS extension.`, `jobEnvironments[0] -> +activation: activation on an Environment requires the ENV_PARAMS +extension.`, and `steps[1] -> dependencies[0]: must have 'dependsOn'.` An +unknown key is still a `DecodeValidationError`, and its message lists the +ENV_PARAMS keys among the expected ones. + +A `parameters` value is an `openjd.expr.FormatString` when it is a string +containing `{{`, and otherwise the literal as written (`str`, `int`, `float`, +`bool`, `list`, `dict` or `None`). The constructor reads a value by the same +rule, and raises `ExpressionError` for a `str` containing `{{` that does not +parse. +The getter returns a new `dict` with keys in byte-wise order, since the crate +keeps the map sorted. A `StepDependency` pickles with every field. + +The job-time `openjd.model._v1.job.StepDependency` is unchanged: `create_job` +keeps the `dependsOn` and `step` entries, as `depends_on`, and drops the +`environment:` entries, which openjd-model 0.18.0 does not act on. + +### ENV_PARAMS (unstable) + +openjd-model 0.18.0 decodes the RFC 0010 `ENV_PARAMS` fields (openjd-rs#641) +and marks the extension unstable: support is not complete, job creation does +not read the fields, and the names below may change in any release. + +Decoding accepts a template that lists `ENV_PARAMS` only when the caller +passes `CallerLimits(accept_unreleased_env_params=True)` **and** lists +`"ENV_PARAMS"` in `supported_extensions`. Without the opt-in, decoding reports +`extensions: Unsupported extension names: ENV_PARAMS`, as for an unknown name. +A document that lists `ENV_PARAMS` must also list `EXPR`. A field used without +`ENV_PARAMS` is rejected at its path. Template validation checks the counts, +names and constraints of `envParameterDefinitions` and the forms of each +``. It does not type-check or evaluate an expression field's +value or a parameter value, but decoding refuses a parameter value containing +`{{` that does not parse as a format string. + +```python +from openjd.model._v1 import CallerLimits, decode_job_template +from openjd.model._v1.template import EnvironmentActivation, ExprField + +template = decode_job_template( + template={...}, + supported_extensions=["EXPR", "ENV_PARAMS"], + caller_limits=CallerLimits(accept_unreleased_env_params=True), +) +template.profile.has_extension(ModelExtension.ENV_PARAMS) # True ``` +`EnvironmentActivation` is an enum: `ALWAYS`, `BY_DEFAULT`, `ON_REQUEST`. +`as_str()`, `name` and `str()` give the value as a template writes it, and +`EnvironmentActivation.from_str(s)` parses it case-sensitively, returning `None` +for any other string. It pickles. + +`ExprField(value)` is the value of an expression field (Template Schemas §7.6), +as written. `value` is a `bool`, an `int`, a finite `float` (else +`ValueError`), a `str`, which is always the source of one +expression without `{{ }}` (`"true"` is the expression `true`), or `None` for a +present `null`. Any other type raises `TypeError`. An absent field is `None` +in the getter, never `ExprField(None)`. An `int` is read as decoding reads a +template number: a signed 64-bit value is an `int` field, one from 2^63 to +2^64 - 1 raises `OverflowError`, and any other is read as the nearest float +(`ExprField(2**64).kind == "float"`). An int too large for any float, such +as `10**400`, raises `OverflowError`. + +```python +f = env.enable_if +f.value # bool | int | float | str | None +f.kind # "bool" | "int" | "float" | "expression" | "null" +f.as_bool() # the bool scalar, else None (an expression included) +``` + +`ExprField` compares by value, hashes, and pickles. `ExprField(True) != +ExprField(1)`, and floats compare by bit pattern, so `ExprField(0.0) != +ExprField(-0.0)`. + +`EnvironmentParameterDefinition` is one `envParameterDefinitions` entry +(Template Schemas §4.5). It has the fields of a Job Parameter definition of the +same `type`, except that `default` may be a format string. + +```python +d = env.env_parameter_definitions[0] +d.name # str +d.type # JobParameterType +d.type_name # "INT", "LIST[PATH]", ... +d.definition # the matching Job*ParameterDefinition; its default is None +d.default # FormatString for a string containing "{{", + # else the literal as written, or None +``` + +`EnvironmentParameterDefinition(definition: dict)` decodes the template form of +one definition, as decoding does, and raises `DecodeValidationError` for one +that does not decode. An explicit `default: None` means no default. It +pickles, as every `Job*ParameterDefinition` does, through its template form: +the `dict` it decodes from, with a number written as a string (a FLOAT +`default` of `"1.50"`) kept as that string. + +`ModelExtension.ENV_PARAMS` names the extension. `ModelExtension.from_str` and +`ModelProfile.from_strings` do not parse `"ENV_PARAMS"`, as openjd-model's +`FromStr` does not, so an allowlist built from names cannot enable it by +accident. A decoded template that lists it has it in `template.profile`, and +`ModelProfile(extensions=[ModelExtension.ENV_PARAMS, ...])` builds one. + ### `SimpleAction` (FEATURE_BUNDLE_1) ```python @@ -1293,6 +1519,19 @@ are told apart by the message rather than the type — the adaptive refusal says `Items cannot be retrieved by index because the parameter space uses adaptive chunking.` where a real overrun says `index out of range`. +Chunk order and sizes match the v0 reference since openjd-model 0.17.0 +(openjd-rs#633). An adaptive `CHUNK[INT]` parameter iterates innermost +in every product, where it used to iterate outermost when written first +in the combination. Static `NONCONTIGUOUS` chunking spreads leftover +values evenly, so `1-10` in chunks of 3 gives `1-3`, `4,5`, `6-8`, +`9,10`, where it gave `1-3`, `4-6`, `7,8`, `9,10`. + +Building an iterator over a directly built `StepParameterSpace` with two +`CHUNK[INT]` parameters raises `DecodeValidationError`: `Task parameters +'A' and 'B' are both CHUNK[INT]: only one CHUNK[INT] parameter is +allowed per step.` (openjd-model 0.17.0, openjd-rs#612). Before, it +iterated and used only the chunk settings of the first parameter. + ### `StepDependencyGraph` Step dependency graph for topological ordering. @@ -1356,8 +1595,15 @@ JobParameterType.LIST_INT # LIST_STRING, LIST_INT, LIST_FLOAT, LIST_PATH, LIST ```python from openjd.model._v1.types import TaskParameterType TaskParameterType.INT # INT, FLOAT, STRING, PATH, CHUNK_INT +TaskParameterType.PATH.expr_type() # ExprType("path"): the type of Task.Param. +TaskParameterType.PATH.raw_expr_type() # ExprType("string"): the type of Task.RawParam. ``` +`expr_type()` and `raw_expr_type()` differ only for `PATH`. `CHUNK_INT` is +`range_expr` for both. Template validation, job creation and the session give +each task parameter symbol the type these two methods return (openjd-model +0.18.0, openjd-rs#638). + ### `SpecificationRevision` (Rust pyclass, str-Enum-like) A Rust pyclass enum exposed at `openjd._openjd_rs` (re-exported from @@ -1493,6 +1739,16 @@ expr_profile = profile.to_expr_profile(HostContext.unresolved()) | `max_resolved_data_len` | each resolved embedded-file `data`, characters (§6.1.2) | decode, `create_job`, session | | `max_eval_memory_bytes` | memory per expression evaluation (default 100 MB) | decode, `create_job`, session | | `max_eval_operations` | operations per expression evaluation (default 10 million) | decode, `create_job`, session | +| `max_step_environment_entries` | `environment:` entries (ENV_PARAMS) in one step's `dependencies`, counted as written | decode | +| `accept_unreleased_env_params` | not a limit: `bool`, default `False`; accept a template that lists `ENV_PARAMS` (unstable) | decode | + +`max_step_environment_entries` counts every entry with an `environment` key, +disabled and `required: false` ones included; `dependsOn` and `step` entries do +not count. Any value is accepted, including one below the 50 entries Template +Schemas §3 item 4 asks an implementation to allow. It is checked only at +decode, so set it on the limits passed to `decode_*`: +`steps[1] -> dependencies: exceeds caller limit of 0 'environment' entries (1 entries).` +Both fields take part in `==`, `repr` and pickle, as the others do. `max_template_size` measures a document string, so it applies to `decode_job_template_str` and `decode_environment_template_str` and has @@ -1518,6 +1774,8 @@ through this process. | `REDACTED_ENV_VARS` | `"REDACTED_ENV_VARS"` | RFC 0003 | | `FEATURE_BUNDLE_1` | `"FEATURE_BUNDLE_1"` | RFC 0004 | | `EXPR` | `"EXPR"` | RFC 0005 | +| `WRAP_ACTIONS` | `"WRAP_ACTIONS"` | RFC 0008 | +| `ENV_PARAMS` | `"ENV_PARAMS"` | RFC 0010, unstable; `from_str` does not parse it (see "ENV_PARAMS" above) | ## Names removed from v0 @@ -1635,7 +1893,8 @@ union dispatch ran the field validators inside the decode call. The v1 binding splits the two phases: ``DecodeValidationError`` is raised strictly for schema-level failures the binding can detect before constructing the typed model (missing/unknown ``specificationVersion``, -unknown fields under strict mode, unparseable JSON/YAML, etc.), and +unknown fields under strict mode, a value of the wrong type such as a +number in a format-string field, unparseable JSON/YAML, etc.), and ``ModelValidationError`` is raised for everything caught by the model validator that runs once the decoded shape is in hand (the at-least-one- step rule, parameter-definition invariants, step-name uniqueness, etc.). @@ -1678,14 +1937,35 @@ more concise phrasing — correct singular/plural agreement phrasings like ``"Value (Y) for parameter X must be at most Z."``. Match by exception class and the field path inside the message -(both bindings emit the path-prefix shape -``steps[0] -> script -> actions -> onRun -> command:\\n\\tmust not be empty.``) -rather than by literal message bytes. Downstream tooling that +rather than by literal message bytes. A ``ModelValidationError``, and +every v0 error, puts each path on its own line +(``steps[0] -> script -> actions -> onRun -> command:\\n\\tmust not be empty.``). +A v1 ``DecodeValidationError`` is one line, +``'' failed checks: : `` (openjd-model 0.18.0, +openjd-rs#634). An unknown key's path ends at the key. A missing key's +path ends at its parent, where v0's ends at the key. A parameter +definition or a task parameter definition is located at its list entry, +and a missing top-level key has no path. Downstream tooling that greps the entire message for v0 wording will need to update its patterns; tooling that catches the exception class and reads ``e.field`` / ``e.location`` (where exposed) will continue to work. +openjd-model 0.18.0 (openjd-rs#634) also reports one error for one +mistake: a bad step `let`, an Environment Template with neither `script` +nor `variables`, and a script `let` that shadows a step `let` each give +one error, where they gave two to four. + +**Wrap hooks divergence from v0.** The rule that a Session enters at +most one Environment with wrap hooks (RFC 0008) is reported at the Step +since openjd-model 0.18.0 (openjd-rs#634), names the Environments, and +is reported once for Steps that share them: +``steps[0]:\\n\\tthe Sessions of Steps 'S' and 'S2' would enter 2 Environments that define wrap hooks (onWrapEnvEnter, onWrapTaskRun, onWrapEnvExit): 'Outer', 'Inner'. A Session may have at most one Environment defining wrap hooks (RFC 0008).`` +v0 keeps the old message at ``jobEnvironments`` (or +``steps[0] -> stepEnvironments``): ``only one environment in the session +stack may define any of onWrapEnvEnter, onWrapTaskRun, onWrapEnvExit +(RFC 0008).`` + ## Pickle Support The following value types are pickleable. Pickled state round-trips @@ -1711,6 +1991,8 @@ original. | ``TaskChunksDefinition`` | constructor arguments (three fields) | | ``SpecificationRevision`` | variant name (``v2023_09``) | | ``TemplateSpecificationVersion`` | variant name (``JOBTEMPLATE_v2023_09``, ``ENVIRONMENT_v2023_09``) | +| ``Job*ParameterDefinition`` (all twelve) | template form, as JSON text, through ``_reconstruct_job_parameter_definition`` | +| ``EnvironmentParameterDefinition`` | template form, as JSON text, through ``_reconstruct_environment_parameter_definition`` | | ``DecodeValidationError``, ``ModelValidationError``, ``UnsupportedSchema`` | standard exception pickle, under their canonical ``openjd.model._v1`` module path | ``SpecificationRevision`` and ``TemplateSpecificationVersion`` are Rust @@ -1756,8 +2038,35 @@ environment) to the job it's about to run. from openjd._openjd_rs import create_environment env = create_environment(env_template) # template-time → job-time +env = create_environment(env_template, job_parameter_values=values) ``` +Without `job_parameter_values`, the `Environment` has no table of its own, +and a `Session` resolves it against the session's job parameter values. +With them (the `dict` `preprocess_job_parameters` returns, or any form +`Session(job_parameter_values=...)` takes), it gets the filtered table that +`create_job` gives a Job Environment and `openjd run` gives an Environment +Template. A wrap hook (RFC 0008) reads its own `Param.*` from that table, so +an Environment Template with wrap hooks that wraps a Job Environment from +`create_job` needs it. Since openjd-sessions 0.12.0 (openjd-rs#632), the Job +Environment is entered with its own table, and the hook no longer sees the +session's job parameter values. + +Each value other than PATH and LIST[PATH] is converted to its declared type, +as a Session does with the values of its job parameters, so `{"type": "INT", "value": +"05"}` is the int `5`. A value that does not convert raises `ValueError` +(`Failed to coerce parameter 'Param.N': ...`). PATH and LIST[PATH] values are +left out of the table's `Param.*`, as openjd-model does, and the Session maps +them from its own job parameter values when the Environment is entered. For +every other parameter the table replaces the session's values, so each +parameter the template declares needs a value, and `ValueError` names the +missing ones (`Values missing for required job parameters: A, D`), as +`preprocess_job_parameters` does. A parameter with a default is not filled +in: pass the `dict` `preprocess_job_parameters` returns, which has the +defaults. Give the Session the same values. With different ones, a PATH +parameter's `Param.*` comes from the Session and its `RawParam.*` from the +table. + ### `_openjd_rs.deserialize_step` Reconstruct a job-side ``Step`` from the wire-protocol dict shape diff --git a/specs/python-sessions-interface.md b/specs/python-sessions-interface.md index 6898f54e..5a392998 100644 --- a/specs/python-sessions-interface.md +++ b/specs/python-sessions-interface.md @@ -223,7 +223,14 @@ Once the crate accepts a call, the method returns when its action is `action_status` describes that action. A `cancel_action` made as soon as it returns reaches the action, unless the action has already ended, as one that fails before its subprocess starts can: then it raises the -crate's `InvalidState`. A zero `time_limit` terminates at once. A second +crate's `InvalidState`. `cancel_action` uses the action's own cancel +method: a TERMINATE action, or one with no `cancelation`, is killed at +once, and a NOTIFY_THEN_TERMINATE action is notified and killed after +its declared period, capped at `time_limit`, so a zero `time_limit` +terminates at once (openjd-rs#563 in openjd-sessions 0.11.1, #575 in 0.12.0). A +cross-user session sends the grace in whole seconds, truncated, so a +grace under 1 s kills at once without the notify signal. The tests run +same-user only and don't exercise the cross-user part. A second `cancel_action` while the session is `CANCELING` raises the crate's `InvalidState`; the pure-Python reference accepts it and shortens the remaining grace period to at most its `time_limit`, which the crate @@ -261,11 +268,58 @@ pure-Python reference (openjd-rs#532). An environment whose enter fails this way still counts as entered, and one whose exit fails this way counts as exited. When `exit_environment` can't build its symbol table from `resolved_symtab`, it runs `onExit` with the table the environment -was entered with (openjd-rs#536). White space around a number in an INT -or FLOAT job or task parameter value is ignored, so `" 7 "` is `7` and -`" 1.50 "` is `1.50` (openjd-rs#530). On Windows, `cleanup` retries -removing a session directory that is still in use, for up to about 31 s, -with the GIL released (openjd-rs#485). +was entered with (openjd-rs#536). + +`exit_environment` with no `resolved_symtab` resolves `onExit` against +the table the environment was entered with: the `enter_environment` +argument, else the environment's own table, else one built from the job +parameter values (openjd-rs#632 in openjd-sessions 0.12.0). Before, it +always built one from the job parameter values. A Job Environment from +`create_job` (`job.job_environments`) has its own table, and `enter_environment` with no +`resolved_symtab` resolves against it, so `Job.Name` works in its +`variables`, `onEnter` and `onExit`. An `Environment` from +`create_environment` has none, so it resolves against the job parameter +values. So does a Step Environment from `create_job` +(`step.step_environments`), which has no table of its own: pass +`step.resolved_symtab` to resolve `Job.Name` in it. A wrap hook reads its +own `Param.*` from the wrap Environment's own table, not the session's job +parameter values, so an Environment Template with wrap hooks that wraps a +Job Environment needs one: build it with +`create_environment(env_template, job_parameter_values=...)`. + +A CHUNK[INT] task value must be a `RangeExpr` or a string in +range-expression form. The session binds `Task.Param.` and +`Task.RawParam.` to that range, written in canonical form except +that a string `-` already in canonical form is kept (`"01-05"` is +`1-5`), so `"6,5"` is `5,6` and `Task.Param.X[1]` and +`max(Task.Param.X)` work. A `RangeExpr` is written as `str(RangeExpr)`, so +`RangeExpr("1-2")` binds `1,2`. Any other value, such as `5`, `[1, 2]` or +`"abc"`, fails the task (openjd-rs#638 in openjd-sessions 0.12.1). A +`TaskParameterValue(type=TaskParameterType.CHUNK_INT, value=...)`, the form the +Deadline Cloud worker agent passes, is bound this way too. The pure-Python +`openjd.sessions.Session` binds the text unchanged, so a caller that runs both +writes a non-canonical chunk, such as `1,3,5` (`1-5:2` here), differently in +each. A +PATH task value given as a path `ExprValue` binds +`Task.RawParam.` as a string; the same value for a job parameter +still binds `RawParam.` as a path (a strict xfail in +`test/openjd/sessions/test_known_gaps.py`). A PATH value must be a +string or a path, and a LIST[PATH] value a list of them or a single path +(which binds `Param.` as a scalar path, a strict xfail in +`test_known_gaps.py`). Any other value that converts to an `ExprValue` +fails the action with `Failed to coerce parameter '': Cannot +coerce to path`, except for a PATH task parameter given a list or +`None`, which fails with `Failed to coerce parameter +'Task.RawParam.': Cannot coerce to string`, such as +`list[string]` or `nulltype` (openjd-rs#639 in openjd-sessions 0.12.1). +A Python value that does not convert to an `ExprValue`, such as a +`pathlib.Path`, raises `TypeError` from the call, and no action starts. Before, the action ran with an empty path or the value's text. + +White space around a number in an INT or FLOAT job or task parameter +value is ignored, so `" 7 "` is `7` and `" 1.50 "` is `1.50` +(openjd-rs#530). On Windows, `cleanup` retries removing a session +directory that is still in use, for up to about 31 s, with the GIL +released (openjd-rs#485). ### SessionUser (stays in Python, passed to Rust) @@ -288,6 +342,11 @@ class WindowsSessionUser: process user: ...")` if it can't look up the process user, as the pure-Python reference's `get_process_user()` raises. +A cross-user `Session` raises when it can't resolve the group of its +`user`, or can't give the session directory that group, and never widens +the directory's mode (openjd-rs#603 in openjd-sessions 0.12.0). The +tests run same-user only and don't exercise this. + ### Callback interface The Python callback `Callable[[str, ActionStatus], None]` is invoked from diff --git a/src/openjd/_openjd_rs.pyi b/src/openjd/_openjd_rs.pyi index 3f26b57b..49a9c16e 100644 --- a/src/openjd/_openjd_rs.pyi +++ b/src/openjd/_openjd_rs.pyi @@ -24,10 +24,13 @@ __all__ = [ "EmbeddedFile", "Environment", "EnvironmentActions", + "EnvironmentActivation", + "EnvironmentParameterDefinition", "EnvironmentScript", "EnvironmentTemplate", "EvalResult", "ExprExtension", + "ExprField", "ExprProfile", "ExprRevision", "ExprType", @@ -117,6 +120,7 @@ __all__ = [ "TypeCode", "ValidationContext", "WindowsSessionUser", + "build_symbol_table", "create_environment", "create_job", "decode_environment_template", @@ -127,6 +131,7 @@ __all__ = [ "escape_format_string", "evaluate_expression", "evaluate_let_bindings", + "job_parameter_type_expr_spec", "merge_job_parameter_definitions", "parse_expression", "preprocess_job_parameters", @@ -347,6 +352,28 @@ class CallerLimits: def max_eval_memory_bytes(self) -> typing.Optional[builtins.int]: ... @property def max_eval_operations(self) -> typing.Optional[builtins.int]: ... + @property + def max_step_environment_entries(self) -> typing.Optional[builtins.int]: + r""" + Cap on the `environment:` entries (`ENV_PARAMS`) in one Step's + `dependencies`, counted as written: disabled and `required: false` + entries count, `dependsOn` and `step` entries do not. Checked at + template validation only, so set it on the limits passed to + `decode_*`. Any value is accepted, including one below the 50 + entries Template Schemas §3 item 4 asks an implementation to allow. + """ + + @property + def accept_unreleased_env_params(self) -> builtins.bool: + r""" + Not a limit: accept a template that lists `ENV_PARAMS`, whose + support in openjd-model is not complete. With the default + `False`, decoding reports `ENV_PARAMS` as an unsupported extension + name even when `supported_extensions` lists it. With `True`, it is + accepted when `supported_extensions` lists it. Unstable: it goes + away once openjd-model supports the extension fully. + """ + def __new__( cls, *, @@ -360,18 +387,20 @@ class CallerLimits: max_resolved_data_len: typing.Optional[builtins.int] = None, max_eval_memory_bytes: typing.Optional[builtins.int] = None, max_eval_operations: typing.Optional[builtins.int] = None, + max_step_environment_entries: typing.Optional[builtins.int] = None, + accept_unreleased_env_params: builtins.bool = False, ) -> CallerLimits: ... def __repr__(self) -> builtins.str: ... def __reduce__(self) -> tuple[typing.Any, tuple]: r""" - Pickle support — round-trips through `__init__` with all six - optional fields as keyword arguments. + Pickle support — round-trips through `__init__` with every field + as a keyword argument. """ def __eq__(self, other: CallerLimits) -> builtins.bool: r""" Structural equality — required by the pickle round-trip - contract. Compares all six fields; the underlying + contract. Compares every field; the underlying `CallerLimits` upstream doesn't derive `PartialEq`, so we implement equality field-by-field at the binding boundary. """ @@ -485,7 +514,7 @@ class EmbeddedFile: *, name: builtins.str, type: builtins.str, - filename: typing.Optional[FormatString] = None, + filename: typing.Optional[builtins.str] = None, data: typing.Optional[FormatString] = None, runnable: typing.Optional[builtins.bool] = None, endOfLine: typing.Optional[builtins.str] = None, @@ -527,6 +556,65 @@ class EnvironmentActions: @property def onExit(self) -> typing.Optional[Action]: ... +@typing.final +class EnvironmentParameterDefinition: + r""" + One `ENV_PARAMS` Environment parameter definition (Template Schemas + §4.5): the shape of a Job Parameter definition of the same `type`, + except that `default` may be a format string. + + `EnvironmentParameterDefinition(definition)` decodes the template form + of one definition from a `dict`, as decoding a template does, and + raises `DecodeValidationError` for one that does not decode. It checks + only the decode; template validation checks the rest. + + It pickles through its template form. + """ + + @property + def name(self) -> builtins.str: + r""" + The parameter's name. + """ + + @property + def type(self) -> JobParameterType: + r""" + The parameter's type. + """ + + @property + def type_name(self) -> builtins.str: + r""" + The type as the specification spells it (`"STRING"`, + `"LIST[PATH]"`, ...). + """ + + @property + def definition(self) -> typing.Any: + r""" + The definition without its `default`, as the matching + `Job*ParameterDefinition`. Its own `default` is always `None`; the + default is `default` here. + """ + + @property + def default(self) -> typing.Optional[typing.Any]: + r""" + The `default` as written: a `FormatString` for a string containing + `{{`, otherwise the literal (`str`, `int`, `float`, `bool`, `list` + or `dict`), or `None` when there is no default. Template validation + does not check it. + """ + + def __new__(cls, definition: dict) -> EnvironmentParameterDefinition: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + + def __repr__(self) -> builtins.str: ... + @typing.final class EnvironmentScript: @property @@ -551,6 +639,15 @@ class EnvironmentTemplate: @property def description(self) -> typing.Optional[builtins.str]: ... + @property + def profile(self) -> ModelProfile: + r""" + The [`ModelProfile`](crate::model::profile::PyModelProfile) this + template declares: the revision from `specificationVersion` and the + extensions its `extensions:` field lists, as `JobTemplate.profile` + gives a Job Template's. + """ + @property def environment(self) -> TemplateEnvironment: r""" @@ -645,6 +742,50 @@ class ExprExtension: def __hash__(self) -> builtins.int: ... def __repr__(self) -> builtins.str: ... +@typing.final +class ExprField: + r""" + The value of an expression field (Template Schemas §7.6), as written, + such as an `enableIf`. + + `ExprField(value)` takes the value as a template writes it: a `bool`, + `int` or `float` scalar, a `str`, which is always the source of one + expression without `{{ }}` (`"true"` is the expression `true`, not the + boolean), or `None` for a present `null`. An absent field is `None` in + the getter that holds an `ExprField`, never `ExprField(None)`. + """ + + @property + def value(self) -> typing.Any: + r""" + The value as written: a `bool`, `int` or `float` scalar, the + expression source as a `str`, or `None` for a present `null`. + """ + + @property + def kind(self) -> builtins.str: + r""" + Which form the value has: `"bool"`, `"int"`, `"float"`, + `"expression"` or `"null"`. + """ + + def __new__(cls, value: typing.Any) -> ExprField: ... + def as_bool(self) -> typing.Optional[builtins.bool]: + r""" + The boolean scalar, or `None` for any other value, an expression + included (even a constant one such as `"true"`). + """ + + def __eq__(self, other: ExprField) -> builtins.bool: ... + def __hash__(self) -> builtins.int: ... + def __repr__(self) -> builtins.str: + r""" + `ExprField()`, with the value as Python's `repr` writes it, + so the text evaluates back to an equal `ExprField`. + """ + + def __reduce__(self) -> tuple[type, tuple]: ... + @typing.final class ExprProfile: r""" @@ -1216,7 +1357,15 @@ class Job: @property def steps(self) -> builtins.list[Step]: ... @property - def parameters(self) -> builtins.dict[builtins.str, JobParameter]: ... + def parameters(self) -> builtins.dict[builtins.str, JobParameter]: + r""" + The job's parameters as a new `dict`, in openjd-model's order: the + job template's parameters in definition order, then any other entry + (such as one an environment template contributes) in byte-wise name + order (openjd-rs#639). Built as a `dict` rather than collected into a + `HashMap`, which would lose that order. + """ + @property def job_environments(self) -> typing.Optional[builtins.list[Environment]]: ... @property @@ -1237,6 +1386,11 @@ class JobBoolParameterDefinition: def user_interface(self) -> typing.Optional[BoolUserInterface]: ... @property def userInterface(self) -> typing.Optional[BoolUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1265,6 +1419,11 @@ class JobFloatParameterDefinition: def user_interface(self) -> typing.Optional[FloatUserInterface]: ... @property def userInterface(self) -> typing.Optional[FloatUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1293,6 +1452,11 @@ class JobIntParameterDefinition: def user_interface(self) -> typing.Optional[IntUserInterface]: ... @property def userInterface(self) -> typing.Optional[IntUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1317,6 +1481,11 @@ class JobListBoolParameterDefinition: def user_interface(self) -> typing.Optional[ListSimpleUserInterface]: ... @property def userInterface(self) -> typing.Optional[ListSimpleUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1341,6 +1510,11 @@ class JobListFloatParameterDefinition: def user_interface(self) -> typing.Optional[ListFloatUserInterface]: ... @property def userInterface(self) -> typing.Optional[ListFloatUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1365,6 +1539,11 @@ class JobListIntParameterDefinition: def user_interface(self) -> typing.Optional[ListIntUserInterface]: ... @property def userInterface(self) -> typing.Optional[ListIntUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1389,6 +1568,11 @@ class JobListListIntParameterDefinition: def user_interface(self) -> typing.Optional[HiddenOnlyUserInterface]: ... @property def userInterface(self) -> typing.Optional[HiddenOnlyUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1421,6 +1605,11 @@ class JobListPathParameterDefinition: def user_interface(self) -> typing.Optional[ListPathUserInterface]: ... @property def userInterface(self) -> typing.Optional[ListPathUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1445,6 +1634,11 @@ class JobListStringParameterDefinition: def user_interface(self) -> typing.Optional[ListSimpleUserInterface]: ... @property def userInterface(self) -> typing.Optional[ListSimpleUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1549,6 +1743,11 @@ class JobPathParameterDefinition: def user_interface(self) -> typing.Optional[PathUserInterface]: ... @property def userInterface(self) -> typing.Optional[PathUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1573,6 +1772,11 @@ class JobRangeExprParameterDefinition: def user_interface(self) -> typing.Optional[RangeExprUserInterface]: ... @property def userInterface(self) -> typing.Optional[RangeExprUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1606,6 +1810,11 @@ class JobStringParameterDefinition: @property def userInterface(self) -> typing.Optional[StringUserInterface]: ... + def __reduce__(self) -> tuple[typing.Any, tuple[builtins.str]]: + r""" + Pickle support, through the template form of the definition. + """ + def __repr__(self) -> builtins.str: ... @typing.final @@ -1842,12 +2051,6 @@ class ParsedExpression: @property def expr(self) -> builtins.str: ... def __repr__(self) -> builtins.str: ... - def typecheck( - self, - *, - values: typing.Optional[typing.Any] = None, - profile: typing.Optional[ExprProfile] = None, - ) -> None: ... def evaluate( self, *, @@ -1865,6 +2068,25 @@ class ParsedExpression: resource-usage counters (peak memory, operation count). """ + def typecheck( + self, + *, + values: typing.Optional[typing.Any] = None, + profile: typing.Optional[ExprProfile] = None, + ) -> None: + r""" + Type-check the expression against a symbol table of (typically + unresolved) typed placeholders, without extracting a concrete value. + + Succeeds when the expression is well-typed for the given symbol types — + including when the result is an unresolved value that merely depends on + a runtime symbol — and raises only on a genuine type/evaluation error. + Unlike :meth:`evaluate`, it discards the result, so it never raises the + "cannot extract value from unresolved" boundary error; callers no longer + need to sniff the error message to tell a real type error from a + runtime-dependent one. + """ + def evaluate_with_metrics( self, *, @@ -2546,8 +2768,9 @@ class StepParameterSpaceIterator: `CHUNK[INT]` parameter and turns adaptive chunking off, so a chunked space can be walked at a caller-chosen granularity. Pass `1` to iterate individual tasks. Ignored when the space has no chunked parameter, matching the - pure-Python reference -- though a non-positive value is still rejected in - that case. + pure-Python reference — though a non-positive value is still rejected in + that case, since validating an argument is cheaper to reason about than + silently discarding a bad one. Without this, a statically chunked space could only be walked at the template's own chunk size: `chunks_default_task_count` is settable for @@ -2931,7 +3154,7 @@ class TemplateEmbeddedFile: @property def type(self) -> builtins.str: ... @property - def filename(self) -> typing.Optional[FormatString]: ... + def filename(self) -> typing.Optional[builtins.str]: ... @property def data(self) -> typing.Optional[FormatString]: ... @property @@ -2945,7 +3168,7 @@ class TemplateEmbeddedFile: *, name: builtins.str, type: builtins.str, - filename: typing.Optional[FormatString] = None, + filename: typing.Optional[builtins.str] = None, data: typing.Optional[FormatString] = None, runnable: typing.Optional[builtins.bool] = None, end_of_line: typing.Optional[builtins.str] = None, @@ -2963,6 +3186,77 @@ class TemplateEnvironment: def script(self) -> typing.Optional[TemplateEnvironmentScript]: ... @property def variables(self) -> typing.Optional[dict]: ... + @property + def env_parameter_definitions( + self, + ) -> typing.Optional[builtins.list[EnvironmentParameterDefinition]]: + r""" + `ENV_PARAMS` `envParameterDefinitions`: the parameters a Step may + supply through an `environment:` entry of its `dependencies`, or + `None` when absent. An empty list stays an empty list. + """ + + @property + def envParameterDefinitions( + self, + ) -> typing.Optional[builtins.list[EnvironmentParameterDefinition]]: + r""" + camelCase alias for `env_parameter_definitions`. + """ + + @property + def activation(self) -> typing.Optional[EnvironmentActivation]: + r""" + `ENV_PARAMS` `activation` as written, or `None` when absent. See + `effective_activation` for the value with its default applied. + """ + + @property + def effective_activation(self) -> EnvironmentActivation: + r""" + `activation` with its default applied: `BY_DEFAULT` when absent, + as it applies in a document that lists `ENV_PARAMS`. + """ + + @property + def host_requirements(self) -> typing.Optional[TemplateHostRequirements]: + r""" + `ENV_PARAMS` `hostRequirements`: requirements on the Worker Host + that every Session entering this Environment must satisfy, or + `None` when absent. + """ + + @property + def hostRequirements(self) -> typing.Optional[TemplateHostRequirements]: + r""" + camelCase alias for `host_requirements`. + """ + + @property + def enable_if(self) -> typing.Optional[ExprField]: + r""" + `ENV_PARAMS` `enableIf` as written, or `None` when absent. A + present `null` is `ExprField(None)`. + """ + + @property + def enableIf(self) -> typing.Optional[ExprField]: + r""" + camelCase alias for `enable_if`. + """ + + @property + def exclusive_group(self) -> typing.Optional[builtins.str]: + r""" + `ENV_PARAMS` `exclusiveGroup`, or `None` when absent. + """ + + @property + def exclusiveGroup(self) -> typing.Optional[builtins.str]: + r""" + camelCase alias for `exclusive_group`. + """ + def __new__( cls, *, @@ -2970,9 +3264,32 @@ class TemplateEnvironment: description: typing.Optional[builtins.str] = None, script: typing.Optional[TemplateEnvironmentScript] = None, variables: typing.Optional[dict] = None, - ) -> TemplateEnvironment: ... + env_parameter_definitions: typing.Optional[ + typing.Sequence[EnvironmentParameterDefinition] + ] = None, + activation: typing.Optional[EnvironmentActivation] = None, + host_requirements: typing.Optional[TemplateHostRequirements] = None, + enable_if: typing.Optional[ExprField] = None, + exclusive_group: typing.Optional[builtins.str] = None, + ) -> TemplateEnvironment: + r""" + Build a template Environment. `description` is checked as decoding + checks a `` (Template Schemas §7.2: 1 to 2048 + characters, no control character other than newline, carriage + return and tab) and raises `DecodeValidationError` otherwise. + + `env_parameter_definitions`, `activation`, `host_requirements`, + `enable_if` and `exclusive_group` are the `ENV_PARAMS` fields; see + their getters. Nothing here validates them: template validation + does, when the Environment is part of a decoded template. + """ + def __repr__(self) -> builtins.str: ... - def __reduce__(self) -> tuple[typing.Any, tuple]: ... + def __reduce__(self) -> tuple[typing.Any, tuple]: + r""" + Pickle support. Every field round-trips, `env_parameter_definitions` + included. + """ @typing.final class TemplateEnvironmentActions: @@ -2984,13 +3301,31 @@ class TemplateEnvironmentActions: def on_exit(self) -> typing.Optional[TemplateAction]: ... @property def onExit(self) -> typing.Optional[TemplateAction]: ... + @property + def on_wrap_env_enter(self) -> typing.Optional[TemplateAction]: ... + @property + def onWrapEnvEnter(self) -> typing.Optional[TemplateAction]: ... + @property + def on_wrap_task_run(self) -> typing.Optional[TemplateAction]: ... + @property + def onWrapTaskRun(self) -> typing.Optional[TemplateAction]: ... + @property + def on_wrap_env_exit(self) -> typing.Optional[TemplateAction]: ... + @property + def onWrapEnvExit(self) -> typing.Optional[TemplateAction]: ... def __new__( cls, *, on_enter: typing.Optional[TemplateAction] = None, on_exit: typing.Optional[TemplateAction] = None, + on_wrap_env_enter: typing.Optional[TemplateAction] = None, + on_wrap_task_run: typing.Optional[TemplateAction] = None, + on_wrap_env_exit: typing.Optional[TemplateAction] = None, onEnter: typing.Optional[TemplateAction] = None, onExit: typing.Optional[TemplateAction] = None, + onWrapEnvEnter: typing.Optional[TemplateAction] = None, + onWrapTaskRun: typing.Optional[TemplateAction] = None, + onWrapEnvExit: typing.Optional[TemplateAction] = None, ) -> TemplateEnvironmentActions: r""" Construct an ``EnvironmentActions``. Accepts either snake-case @@ -3074,10 +3409,96 @@ class TemplateStepActions: @typing.final class TemplateStepDependency: @property - def depends_on(self) -> builtins.str: ... + def depends_on(self) -> typing.Optional[builtins.str]: + r""" + The `dependsOn` key as written, or `None` when absent. Use + `step_name()` for the Step a well-formed entry names, which also + reads the `step` synonym. + """ + @property - def dependsOn(self) -> builtins.str: ... - def __new__(cls, *, depends_on: builtins.str) -> TemplateStepDependency: ... + def dependsOn(self) -> typing.Optional[builtins.str]: ... + @property + def step(self) -> typing.Optional[builtins.str]: + r""" + `ENV_PARAMS`: the `step` key as written, or `None` when absent. + """ + + @property + def environment(self) -> typing.Optional[builtins.str]: + r""" + `ENV_PARAMS`: the `environment` key as written, or `None` when + absent. + """ + + @property + def required(self) -> typing.Optional[builtins.bool]: + r""" + `ENV_PARAMS`: `required` as written, or `None` when absent. See + `is_required()` for the value with its default applied. + """ + + @property + def enable_if(self) -> typing.Optional[ExprField]: + r""" + `ENV_PARAMS`: `enableIf` as written, or `None` when absent. A + present `null` is `ExprField(None)`. + """ + + @property + def enableIf(self) -> typing.Optional[ExprField]: ... + @property + def parameters(self) -> typing.Optional[dict]: + r""" + `ENV_PARAMS`: the `parameters` map as a new `dict`, or `None` when + absent. Each value is a `FormatString` (a string containing `{{`) + or the literal as written. Keys are in byte-wise order, since the + crate keeps the map sorted. + """ + + def __new__( + cls, + *, + depends_on: typing.Optional[builtins.str] = None, + step: typing.Optional[builtins.str] = None, + environment: typing.Optional[builtins.str] = None, + required: typing.Optional[builtins.bool] = None, + enable_if: typing.Optional[ExprField] = None, + parameters: typing.Optional[dict] = None, + ) -> TemplateStepDependency: + r""" + Build one entry of a Step's `dependencies`. The entry is + `dependsOn: ` or, with `ENV_PARAMS`, its synonym + `step: `, or `environment: ` with + optional `required`, `enable_if` and `parameters`. Every key is + optional, as in decoding, so an entry with more than one form or + none builds here and template validation reports it. + """ + + def step_name(self) -> typing.Optional[builtins.str]: + r""" + The Step a well-formed `dependsOn` or `step` entry names: exactly + one of `depends_on`, `step` and `environment` is set. `None` + otherwise. + """ + + def environment_name(self) -> typing.Optional[builtins.str]: + r""" + The Environment a well-formed `environment` entry names. `None` + otherwise. + """ + + def is_required(self) -> builtins.bool: + r""" + `required` with its default applied: `True` when absent. + """ + + def __eq__(self, other: TemplateStepDependency) -> builtins.bool: + r""" + Equal when every field is equal, as openjd-model's `StepDependency` + compares. Not hashable, since the class is not frozen. + """ + def __repr__(self) -> builtins.str: ... def __reduce__(self) -> tuple[typing.Any, tuple]: ... @@ -3274,6 +3695,51 @@ class DocumentType(enum.Enum): Pickle support — round-trips through the variant name. """ +@typing.final +class EnvironmentActivation(enum.Enum): + r""" + `ENV_PARAMS`: which Sessions of a Job enter an Environment (Template + Schemas §4 item 4). An Environment whose `activation` is absent acts as + `BY_DEFAULT` in a document that lists `ENV_PARAMS`. + """ + + ALWAYS = ... + r""" + Every Session of the Job enters the Environment. + """ + BY_DEFAULT = ... + r""" + Every Session enters it, except a Step's that declines it or for + which it is disabled. + """ + ON_REQUEST = ... + r""" + Only the Sessions of a Step that requests it enter it. + """ + + @property + def name(self) -> builtins.str: + r""" + Variant name, the same as `as_str()`. + """ + + def as_str(self) -> builtins.str: + r""" + The value as a template writes it: `"ALWAYS"`, `"BY_DEFAULT"` or + `"ON_REQUEST"`. + """ + + @staticmethod + def from_str(s: builtins.str) -> typing.Optional[EnvironmentActivation]: + r""" + Parse the value as a template writes it (case-sensitive). Returns + `None` for any other string. + """ + + def __repr__(self) -> builtins.str: ... + def __str__(self) -> builtins.str: ... + def __reduce__(self) -> tuple[typing.Any, tuple[type, builtins.str]]: ... + @typing.final class ExprRevision(enum.Enum): r""" @@ -3355,6 +3821,11 @@ class ModelExtension(enum.Enum): FEATURE_BUNDLE_1 = ... EXPR = ... WRAP_ACTIONS = ... + ENV_PARAMS = ... + r""" + RFC 0010, unstable: decoding accepts a template that lists it only + with `CallerLimits(accept_unreleased_env_params=True)`. + """ @property def name(self) -> builtins.str: @@ -3517,6 +3988,18 @@ class TaskParameterType(enum.Enum): def as_str(self) -> builtins.str: ... def __repr__(self) -> builtins.str: ... + def expr_type(self) -> ExprType: + r""" + The expression type of `Task.Param.` for a parameter of this + type (Expression Language, "Task Parameter Types"). + """ + + def raw_expr_type(self) -> ExprType: + r""" + The expression type of `Task.RawParam.`: the same as + `expr_type()`, except `string` for `PATH`. + """ + def __reduce__(self) -> tuple[typing.Any, tuple[type, builtins.str]]: r""" Pickle support — round-trips through the variant name. @@ -3622,13 +4105,47 @@ class TypeCode(enum.Enum): Pickle support — round-trips through the variant name. """ +def _reconstruct_environment_parameter_definition( + json: builtins.str, +) -> EnvironmentParameterDefinition: + r""" + Pickle helper: decode an `EnvironmentParameterDefinition` from the + template form `__reduce__` wrote. + """ + +def _reconstruct_job_parameter_definition(json: builtins.str) -> typing.Any: + r""" + Pickle helper: decode a `Job*ParameterDefinition` from the template + form `__reduce__` wrote. + """ + def _reconstruct_serialized_symtab(json: builtins.str) -> SerializedSymbolTable: r""" Pickle helper — module-level free function so pickled bytes can be reconstructed across interpreter sessions. """ -def create_environment(env_template: EnvironmentTemplate) -> Environment: +def build_symbol_table( + values: dict, + types: typing.Optional[dict] = None, + *, + path_format: typing.Optional[PathFormat] = None, +) -> SymbolTable: + r""" + Build a typed :class:`SymbolTable` from a flat dotted-key value map and an + optional per-key EXPR type-spec map, coercing string values to their + declared type and nesting dotted keys (``"Param.Frame"``) into subtables. + + ``values`` maps dotted symbol names to their (typically string) values, as + the v0 model stores them. ``types`` maps the same dotted names to EXPR + type spec strings (``"int"``, ``"list[int]"``, ``"path"``, …); names absent + from ``types`` are inferred from the value. ``path_format`` controls how + PATH-typed values are interpreted (defaults to the host OS). + """ + +def create_environment( + env_template: EnvironmentTemplate, *, job_parameter_values: typing.Optional[dict] = None +) -> Environment: r""" Convert a template `EnvironmentTemplate` into a job-side `Environment` with the same contents. Analogous to how `create_job` instantiates a `JobTemplate` @@ -3638,6 +4155,24 @@ def create_environment(env_template: EnvironmentTemplate) -> Environment: Consumers like the Deadline Cloud worker agent need this to turn the `EnvironmentDetails` boto payload into an `Environment` they can pass to `Session.enter_environment`. + + Without `job_parameter_values` the `Environment` has no table of its own, + so a `Session` resolves it against the session's job parameter values. + With them (the `dict` that `preprocess_job_parameters` returns, or any + `Session(job_parameter_values=...)` form), it gets the filtered table that + openjd-model's `convert_environment_with_symtab` builds, as `create_job` + gives a Job Environment and `openjd run` gives an Environment Template. + That table is what an RFC 0008 wrap hook reads its own `Param.*` from: a + wrap hook in an Environment Template that wraps a Job Environment from + `create_job` needs it (openjd-sessions 0.12.0, openjd-rs#632). + + Values other than PATH and LIST[PATH] are converted to their declared + type, as a `Session` converts job parameter values; one that does not + convert raises `ValueError`. Every parameter the template declares needs + a value (the `preprocess_job_parameters` `dict` fills in defaults), or + `ValueError` names the missing ones. Give the `Session` the same values: + the Environment reads `Param.*` of a PATH parameter from the Session and + `RawParam.*` from this table. """ def create_job( @@ -3808,15 +4343,6 @@ def deserialize_step(step_dict: dict) -> Step: """ def escape_format_string(value: builtins.str) -> builtins.str: ... -def job_parameter_type_expr_spec( - type_name: builtins.str, -) -> typing.Optional[builtins.str]: ... -def build_symbol_table( - values: builtins.dict, - types: typing.Optional[builtins.dict] = None, - *, - path_format: typing.Optional[PathFormat] = None, -) -> SymbolTable: ... def evaluate_expression( expr: builtins.str, *, @@ -3847,6 +4373,17 @@ def evaluate_let_bindings( ignored. Omitting it uses the spec-recommended defaults. """ +def job_parameter_type_expr_spec(type_name: builtins.str) -> typing.Optional[builtins.str]: + r""" + Map an OpenJD job-parameter type spec name (e.g. ``"INT"``, ``"LIST[INT]"``, + ``"RANGE_EXPR"``; case-insensitive) to its EXPR type spec string + (``"int"``, ``"list[int]"``, ``"range_expr"``), or ``None`` when the name is + not a recognized job-parameter type. Single-sources both the + (case-insensitive) type-name parsing and the OpenJD-type -> EXPR-type + mapping in the Rust ``openjd-model`` crate so the Python model does not + hand-maintain a parallel table. + """ + def merge_job_parameter_definitions( *, job_template: JobTemplate, @@ -4012,3 +4549,4 @@ class UnsupportedSchema(builtins.ValueError): ... # level for callers that want to inspect or override the limits. DEFAULT_MEMORY_LIMIT: builtins.int DEFAULT_OPERATION_LIMIT: builtins.int +MAX_TYPE_DEPTH: builtins.int diff --git a/src/openjd/expr/__init__.py b/src/openjd/expr/__init__.py index d857e2f4..9f3fee1f 100644 --- a/src/openjd/expr/__init__.py +++ b/src/openjd/expr/__init__.py @@ -25,6 +25,7 @@ TypeCode, DEFAULT_MEMORY_LIMIT, DEFAULT_OPERATION_LIMIT, + MAX_TYPE_DEPTH, # Profile types — pass to entry points like # `evaluate_expression(..., profile=...)`, # `ParsedExpression.evaluate(..., profile=...)`, and @@ -77,4 +78,5 @@ # Constants "DEFAULT_MEMORY_LIMIT", "DEFAULT_OPERATION_LIMIT", + "MAX_TYPE_DEPTH", ] diff --git a/src/openjd/model/_format_strings/_expr_support.py b/src/openjd/model/_format_strings/_expr_support.py index a0222c70..efba4d33 100644 --- a/src/openjd/model/_format_strings/_expr_support.py +++ b/src/openjd/model/_format_strings/_expr_support.py @@ -164,17 +164,24 @@ def parse_expr_or_raise(expr: str) -> Any: raise _ModelExpressionError(str(exc)) -def _static_validation_profile() -> ExprProfile: +def _static_validation_profile(host_context: bool = True) -> ExprProfile: """Profile for static (parse-time) expression validation. - Uses ``HostContext.unresolved()`` so host-context-gated functions such as - ``apply_path_mapping`` resolve to unresolved values (valid) rather than - raising "Unknown function", while genuinely unknown functions still fail. + With ``host_context``, uses ``HostContext.unresolved()`` so + host-context-gated functions such as ``apply_path_mapping`` resolve to + unresolved values (valid) rather than raising "Unknown function", while + genuinely unknown functions still fail. That host context also leaves a + literal path unresolved (openjd-rs#611), since a worker's path format is + not known. Without it, the profile is the one a TEMPLATE-scope field is + resolved with at job creation: no host functions, and literal paths read + in the submitter's path format. """ + if not host_context: + return ExprProfile.current() return ExprProfile.current().with_host_context(HostContext.unresolved()) -def static_validate_symbol_free(expr: str) -> None: +def static_validate_symbol_free(expr: str, *, host_context: bool = True) -> None: """Statically validate an expression that references no free symbols. Catches literal/semantic errors that the Rust engine only raises at @@ -187,7 +194,7 @@ def static_validate_symbol_free(expr: str) -> None: """ try: _RustFormatString("{{ " + expr + " }}").validate_expressions( - {}, profile=_static_validation_profile() + {}, profile=_static_validation_profile(host_context) ) except _RUST_EXPR_ERRORS as exc: raise _ModelExpressionError(str(exc)) @@ -225,7 +232,9 @@ def longest_defined_prefix(name: str, defined: set) -> Optional[str]: return None -def validate_typed_expression(parsed: Any, *, typed_symbols: dict[str, str]) -> None: +def validate_typed_expression( + parsed: Any, *, typed_symbols: dict[str, str], host_context: bool = True +) -> None: """Statically validate a parsed expression against symbols of known EXPR type (provided as ``{dotted_name: expr_type_string}``). Catches type mismatches and invalid method/property access. Raises the model's @@ -248,7 +257,7 @@ def validate_typed_expression(parsed: Any, *, typed_symbols: dict[str, str]) -> # (no "cannot extract value from unresolved" boundary error to sniff for). parsed.typecheck( values=values, - profile=ExprProfile.current().with_host_context(HostContext.unresolved()), + profile=_static_validation_profile(host_context), ) except _RUST_EXPR_ERRORS as exc: raise _ModelExpressionError(str(exc)) diff --git a/src/openjd/model/_format_strings/_expression.py b/src/openjd/model/_format_strings/_expression.py index 844dc7c0..94082dd1 100644 --- a/src/openjd/model/_format_strings/_expression.py +++ b/src/openjd/model/_format_strings/_expression.py @@ -29,18 +29,24 @@ def __init__(self, expr: str, *, context: ModelParsingContextInterface) -> None: # Raises: ExpressionError, TokenError self._expresion_tree = parse_format_string_expr(expr, context=context) - def validate_symbol_refs(self, *, symbols: set[str], symbol_types: Any = None) -> None: + def validate_symbol_refs( + self, *, symbols: set[str], symbol_types: Any = None, template_scope: bool = False + ) -> None: """Check whether this expression can be evaluated correctly given a set of symbol names. Args: symbols (set[str]): The names of symbols visible to this expression. symbol_types: Optional mapping of symbol name -> EXPR type string, enabling type-aware validation when available. + template_scope: The expression is in a TEMPLATE-scope field, which + is validated with no host context. Raises: ValueError: If the expression cannot be evaluated with the given symbol names """ - self._expresion_tree.validate_symbol_refs(symbols=symbols, symbol_types=symbol_types) + self._expresion_tree.validate_symbol_refs( + symbols=symbols, symbol_types=symbol_types, template_scope=template_scope + ) @property def called_functions(self) -> set: diff --git a/src/openjd/model/_format_strings/_nodes.py b/src/openjd/model/_format_strings/_nodes.py index 750283b6..00c4b77e 100644 --- a/src/openjd/model/_format_strings/_nodes.py +++ b/src/openjd/model/_format_strings/_nodes.py @@ -10,6 +10,12 @@ from ._edit_distance import closest +# EXPR function-library functions that require a host context (path-mapping +# rules, host OS), so they are only available at runtime, not at +# submission/template-resolution (TEMPLATE) time (RFC 0005). +HOST_CONTEXT_FUNCTIONS = frozenset({"apply_path_mapping"}) + + class Node(ABC): """ Base expression tree node class. @@ -17,7 +23,7 @@ class Node(ABC): @abstractmethod def validate_symbol_refs( - self, *, symbols: set[str], symbol_types: Any = None + self, *, symbols: set[str], symbol_types: Any = None, template_scope: bool = False ) -> None: # pragma: no cover """Verifies that the expression rooted at this node is valid given the definitions of symbols in a symbol table. @@ -31,6 +37,8 @@ def validate_symbol_refs( Args: symbols (set[str]): The names of symbols visible to this expression. + template_scope (bool): The expression is in a TEMPLATE-scope field, + which is resolved at job creation with no host context. """ pass @@ -112,7 +120,9 @@ class FullNameNode(Node): name: str - def validate_symbol_refs(self, *, symbols: set[str], symbol_types: Any = None) -> None: + def validate_symbol_refs( + self, *, symbols: set[str], symbol_types: Any = None, template_scope: bool = False + ) -> None: if self.name not in symbols: raise _missing_symbol_error(self.name, symbols) @@ -163,16 +173,33 @@ def accessed_symbols(self) -> set: excluded by the engine.""" return set(self._parsed.accessed_symbols) - def validate_symbol_refs(self, *, symbols: set[str], symbol_types: Any = None) -> None: + def validate_symbol_refs( + self, *, symbols: set[str], symbol_types: Any = None, template_scope: bool = False + ) -> None: accessed = set(self._parsed.accessed_symbols) + # A TEMPLATE-scope field is resolved at job creation, where there is + # no host context and a literal path has the submitter's path format. + # Since openjd-expr 0.18.0 (openjd-rs#611), the unresolved host + # context leaves `path(...)` and `with_number` unresolved because the + # worker's path format is not known, so the check `__init__` ran + # misses their errors here. Check again without a host context, as + # openjd-model does for a TEMPLATE-scope field. An expression that + # calls a host-context function is reported for that by the caller. + no_host = template_scope and not (self.called_functions & HOST_CONTEXT_FUNCTIONS) + if no_host and not accessed: + from ._expr_support import static_validate_symbol_free + + static_validate_symbol_free(self.expr, host_context=False) + # Typed validation: if every accessed symbol resolves to a defined # symbol prefix whose EXPR type is known (e.g. job parameters), validate # the whole expression against those types. This catches type mismatches # and resolves method/property access (e.g. Param.File.name on a PATH). # Only attempted when ALL accessed prefixes are typed-known, so an # unknown-typed symbol (e.g. a `let` name) safely falls back to the - # name-only check below rather than risking a wrong-type rejection. + # name-only check below rather than risking a wrong-type rejection + # (in a TEMPLATE-scope field, after the `any`-typed check below). if symbol_types and accessed: from ._expr_support import ( longest_defined_prefix, @@ -189,10 +216,31 @@ def validate_symbol_refs(self, *, symbols: set[str], symbol_types: Any = None) - prefix_types[prefix] = symbol_types[prefix] if fully_typed: # Raises model ExpressionError on a type/method error. - validate_typed_expression(self._parsed, typed_symbols=prefix_types) + validate_typed_expression( + self._parsed, typed_symbols=prefix_types, host_context=not no_host + ) self._check_comprehension_shadowing(symbols) return + # A TEMPLATE-scope expression that reads a symbol of unknown type (a + # `let` name) is still checked without a host context, with each such + # symbol as an unresolved value of type `any`, so `int(path('a/b').name) + # + n` is refused here as openjd-model refuses it. An `any` value + # assumes nothing about the symbol, so only the rest of the expression + # can fail. A symbol that is not defined is left to the check below. + if no_host and accessed: + from ._expr_support import longest_defined_prefix, validate_typed_expression + + prefixes = {longest_defined_prefix(name, symbols) for name in accessed} + if None not in prefixes: + validate_typed_expression( + self._parsed, + typed_symbols={ + p: (symbol_types or {}).get(p, "any") for p in prefixes if p is not None + }, + host_context=False, + ) + # accessed_symbols are the free variable references in full dotted # spelling (e.g. "Param.X"); local let-bound names are excluded by the # engine. Compare against the set of symbols visible at this location. diff --git a/src/openjd/model/_internal/_variable_reference_validation.py b/src/openjd/model/_internal/_variable_reference_validation.py index caf14f1b..1ed9286c 100644 --- a/src/openjd/model/_internal/_variable_reference_validation.py +++ b/src/openjd/model/_internal/_variable_reference_validation.py @@ -18,6 +18,7 @@ from .._types import OpenJDModel, ResolutionScope, ModelParsingContextInterface from .._format_strings import FormatString, FormatStringError +from .._format_strings._nodes import HOST_CONTEXT_FUNCTIONS __all__ = ["prevalidate_model_template_variable_references"] @@ -201,7 +202,7 @@ def prevalidate_model_template_variable_references( if context is not None: context._prevalidation_expr_enabled = expr_enabled # type: ignore[attr-defined] - return _validate_model_template_variable_references( + errors = _validate_model_template_variable_references( cls, _internal_deepcopy(values), ResolutionScope.TEMPLATE, @@ -210,6 +211,25 @@ def prevalidate_model_template_variable_references( symbol_prefix="", context=context, ) + return _without_repeats(errors) + + +def _without_repeats(errors: list[InitErrorDetails]) -> list[InitErrorDetails]: + """Drop an error that repeats an earlier one at the same location. + + Some values are visited twice by the traversal (a ``cancelation`` value is + checked as each union member it could be), so one bad expression in + ``notifyPeriodInSeconds`` or a wrap-hook ``timeout`` was reported twice. + """ + seen: set[tuple[tuple, Any, str]] = set() + result: list[InitErrorDetails] = [] + for error in errors: + key = (tuple(error.get("loc", ())), error.get("type", ""), str(error.get("ctx", {}))) + if key in seen: + continue + seen.add(key) + result.append(error) + return result def _internal_deepcopy(value: Any) -> Any: @@ -499,10 +519,7 @@ def _validate_model_template_variable_references( return errors -# EXPR function-library functions that require host context (path-mapping -# rules / host OS), so they are only available at runtime — not at -# submission/template-resolution (TEMPLATE) time. -_HOST_CONTEXT_FUNCTIONS = {"apply_path_mapping"} +_HOST_CONTEXT_FUNCTIONS = HOST_CONTEXT_FUNCTIONS # EXPR types of the runtime-injected built-in symbols, mirroring the typed # symtabs openjd-rs validates against (format_strings.rs @@ -558,7 +575,9 @@ def _check_format_string( if expr.expression: try: expr.expression.validate_symbol_refs( - symbols=scoped_symbols, symbol_types=symbol_types + symbols=scoped_symbols, + symbol_types=symbol_types, + template_scope=current_scope == ResolutionScope.TEMPLATE, ) except ValueError as exc: errors.append( @@ -700,13 +719,35 @@ def _validate_let_bindings( accumulated.add(name) continue try: - node.validate_symbol_refs(symbols=accumulated, symbol_types=accumulated_types or None) + node.validate_symbol_refs( + symbols=accumulated, + symbol_types=accumulated_types or None, + template_scope=current_scope == ResolutionScope.TEMPLATE, + ) except ValueError as exc: errors.append( InitErrorDetails( type="value_error", loc=binding_loc, ctx={"error": exc}, input=binding ) ) + # A TEMPLATE-scope binding is evaluated at job creation, where no + # host context exists, as `_check_format_string` reports for a field. + if current_scope == ResolutionScope.TEMPLATE: + host_fns = node.called_functions & HOST_CONTEXT_FUNCTIONS + if host_fns: + errors.append( + InitErrorDetails( + type="value_error", + loc=binding_loc, + ctx={ + "error": ValueError( + f"The function {sorted(host_fns)[0]!r} is only available " + "at runtime (host context), not at submission time." + ) + }, + input=binding, + ) + ) accumulated.add(name) return errors diff --git a/src/openjd/model/_v1/template.py b/src/openjd/model/_v1/template.py index 1ce8eec8..bd2453d1 100644 --- a/src/openjd/model/_v1/template.py +++ b/src/openjd/model/_v1/template.py @@ -39,6 +39,12 @@ # Structural types with no name collision StepTemplate, SimpleAction, + # ENV_PARAMS extension types (unstable upstream: decoding accepts a + # template that lists ENV_PARAMS only with + # ``CallerLimits(accept_unreleased_env_params=True)``). + EnvironmentActivation, + EnvironmentParameterDefinition, + ExprField, # JobParameterDefinition — 12 typed variants returned by # ``JobTemplate.parameter_definitions`` and # ``EnvironmentTemplate.parameter_definitions``. @@ -116,6 +122,10 @@ "StepDependency", "StepScript", "StepTemplate", + # ENV_PARAMS extension types + "EnvironmentActivation", + "EnvironmentParameterDefinition", + "ExprField", # Disambiguating aliases (same classes; useful in pickle bytes # and where users want to be explicit about template vs job time) "TemplateAction", diff --git a/test/openjd/expr/test_arithmetic.py b/test/openjd/expr/test_arithmetic.py index 71b2714e..f2b9522e 100644 --- a/test/openjd/expr/test_arithmetic.py +++ b/test/openjd/expr/test_arithmetic.py @@ -238,20 +238,23 @@ def test_round_half_to_even(self, expr: str, expected: int) -> None: ("round(0.875, 2)", 0.88), # 0.875 is exact, rounds to even (0.88) ("round(0.25, 1)", 0.2), # 0.25 is exact, rounds to even (0.2) ("round(0.75, 1)", 0.8), # 0.75 is exact, rounds to even (0.8) - ("round(2.5, 0)", 2.0), # 2.5 is exact, rounds to even (2.0) - ("round(3.5, 0)", 4.0), # 3.5 is exact, rounds to even (4.0) + ("round(2.5, 0)", 2), # rounds to even; an int since openjd-rs#567 + ("round(3.5, 0)", 4), # rounds to even; an int since openjd-rs#567 # Negative values ("round(-0.125, 2)", -0.12), # -0.125 rounds to even (-0.12) ("round(-0.375, 2)", -0.38), # -0.375 rounds to even (-0.38) ("round(-0.25, 1)", -0.2), # -0.25 rounds to even (-0.2) ("round(-0.75, 1)", -0.8), # -0.75 rounds to even (-0.8) - ("round(-2.5, 0)", -2.0), # -2.5 rounds to even (-2.0) - ("round(-3.5, 0)", -4.0), # -3.5 rounds to even (-4.0) + ("round(-2.5, 0)", -2), # rounds to even; an int since openjd-rs#567 + ("round(-3.5, 0)", -4), # rounds to even; an int since openjd-rs#567 ], ) def test_round_ndigits_half_to_even(self, expr: str, expected: float) -> None: result = evaluate_expression(expr) assert result.item() == pytest.approx(expected) + # pytest.approx cannot tell an int from a float; the type is the point + # of the ndigits=0 rows (openjd-rs#567). + assert type(result.item()) is type(expected) @pytest.mark.parametrize( "expr,expected", @@ -273,6 +276,53 @@ def test_round_int_ndigits_returns_int(self, expr: str, expected: int) -> None: assert result.type.type_code == TypeCode.INT +class TestRoundFloatNdigits: + """openjd-expr 0.17.0 (openjd-rs#567) changed ``round(x: float, ndigits)``. + With ``ndigits <= 0`` it returns ``int``, rounded half-to-even on the exact + value, and an ``int`` outside the 64-bit signed range is an integer + overflow error. Before, it returned a ``float``, so ``string(round(2.5, 0))`` + was ``'2.0'``. With ``ndigits > 0`` it rounds the exact value once, as + CPython does, so ``round(2.675, 2)`` is 2.67, not 2.68. ``==`` and + ``pytest.approx`` cannot tell 2 from 2.0, so these tests check the type.""" + + @pytest.mark.parametrize( + "expr,expected", + [ + ("round(3.7, 0)", 4), + ("round(2.5, 0)", 2), + ("round(-2.5, 0)", -2), + ("round(1234.5, -1)", 1230), + ("round(3550693609029500000.0, -6)", 3550693609029000000), + ], + ) + def test_non_positive_ndigits_returns_int(self, expr: str, expected: int) -> None: + result = evaluate_expression(expr) + assert result.type.type_code == TypeCode.INT + assert type(result.item()) is int + assert result.item() == expected + + def test_interpolated_text_has_no_fraction(self) -> None: + assert evaluate_expression("string(round(2.5, 0))").item() == "2" + + def test_int_result_is_usable_as_an_int(self) -> None: + """``range(float)`` has no signature, so this raised before.""" + assert evaluate_expression("len(range(round(25.0, -1)))").item() == 20 + + def test_positive_ndigits_rounds_the_exact_value_once(self) -> None: + result = evaluate_expression("round(2.675, 2)") + assert result.type.type_code == TypeCode.FLOAT + assert result.item() == 2.67 + + def test_int_result_out_of_range_overflows(self) -> None: + with pytest.raises(ExpressionError) as excinfo: + evaluate_expression("round(1e300, -1)") + assert str(excinfo.value) == ( + "Integer overflow: result is outside the 64-bit signed range\n" + " round(1e300, -1)\n" + " ^~~~~~~~~~~~~~~~" + ) + + class TestFloorCeilReturnType: """Tests that floor and ceil always return int.""" diff --git a/test/openjd/expr/test_function_context.py b/test/openjd/expr/test_function_context.py index 0f3415a5..18265e6e 100644 --- a/test/openjd/expr/test_function_context.py +++ b/test/openjd/expr/test_function_context.py @@ -177,3 +177,42 @@ def test_not_available_without_any_context(self) -> None: returns a new one.""" with pytest.raises(ExpressionError, match="apply_path_mapping"): evaluate_expression("apply_path_mapping('/path')", profile=ExprProfile()) + + +class TestUnresolvedHostContextPathFunctions: + """Since openjd-expr 0.18.0 (openjd-rs#611), ``HostContext.unresolved()`` + also stubs every ``path(...)`` overload and ``with_number(string, int)``, + because the worker's path format is not known yet. Each returns + ``unresolved[T]`` even for a POSIX literal. Before, they folded to a + value, and ``int(path('C:\\\\a\\\\5').name)`` failed at validation.""" + + _profile = ExprProfile().with_host_context(HostContext.unresolved()) + + @pytest.mark.parametrize( + "expr,expected_type", + [ + ("path('/a/b')", "unresolved[path]"), + ("path('/a/b').name", "unresolved[string]"), + (r"int(path('C:\\a\\5').name)", "unresolved[int]"), + ("with_number('f_#.exr', 3)", "unresolved[string]"), + ], + ) + def test_path_and_with_number_are_unresolved(self, expr: str, expected_type: str) -> None: + from openjd.expr import ExprType + + result = evaluate_expression(expr, profile=self._profile) + assert result.type == ExprType(expected_type) + + def test_default_profile_still_folds(self) -> None: + assert evaluate_expression("path('/a/b').name").item() == "b" + assert evaluate_expression("with_number('f_#.exr', 3)").item() == "f_3.exr" + # A relative POSIX-style literal has the same name on every host, so + # this fails the same way on Windows, where the default profile reads + # a literal path in the host's format. + with pytest.raises(ExpressionError, match=r"Cannot convert 'b' to int"): + evaluate_expression("int(path('a/b').name)") + + def test_signature_errors_still_raise(self) -> None: + with pytest.raises(ExpressionError) as excinfo: + evaluate_expression("path(1)", profile=self._profile) + assert str(excinfo.value) == "No matching signature for path(int)\n path(1)\n ^~~~~~~" diff --git a/test/openjd/expr/test_int64_bounds.py b/test/openjd/expr/test_int64_bounds.py index c7fcb8ca..c57f8063 100644 --- a/test/openjd/expr/test_int64_bounds.py +++ b/test/openjd/expr/test_int64_bounds.py @@ -157,3 +157,58 @@ def test_large_negative_float(self) -> None: # Unary negation removes pass-through, so shortest repr result = evaluate_expression("-9223372036854775809.0") assert str(result) == "-9.223372036854776e+18" + + +class TestInt64MinInRanges: + """openjd-expr 0.18.0 (openjd-rs#633) accepts -2^63 as a range value and + endpoint in ``RangeExpr``, ``range_expr(...)`` and an ``ExprValue`` of type + ``range_expr``. Before, ``RangeExpr("-9223372036854775808")`` raised + ``Invalid integer '9223372036854775808'`` and ``range_expr([...])`` with + -2^63 raised ``Integer overflow``. A step of -2^63 is an integer overflow + error, and a range with more than 2^63 - 1 values reports that + limit.""" + + MIN = -9223372036854775808 + + def test_range_expr_class_accepts_int64_min(self) -> None: + from openjd.expr import RangeExpr + + r = RangeExpr("-9223372036854775808") + assert len(r) == 1 + assert list(RangeExpr("-9223372036854775808--9223372036854775806")) == [ + self.MIN, + self.MIN + 1, + self.MIN + 2, + ] + + def test_range_expr_function_accepts_int64_min(self) -> None: + result = evaluate_expression("range_expr('-9223372036854775808--9223372036854775806')[0]") + assert result.item() == self.MIN + result = evaluate_expression("range_expr([-9223372036854775807 - 1])") + assert str(result) == "-9223372036854775808" + + def test_expr_value_accepts_int64_min(self) -> None: + from openjd.expr import ExprType, ExprValue + + value = ExprValue("-9223372036854775808", ExprType("range_expr")) + assert str(value) == "-9223372036854775808" + + def test_too_many_values(self) -> None: + from openjd.expr import ExprType, ExprValue, RangeExpr, RangeExprError + + message = "Range expression has too many values; the maximum is 9223372036854775807" + with pytest.raises(RangeExprError) as range_info: + RangeExpr("-9223372036854775808-0") + assert str(range_info.value) == message + with pytest.raises(ValueError) as value_info: + ExprValue("-9223372036854775808-0", ExprType("range_expr")) + assert str(value_info.value) == ( + f"Cannot convert '-9223372036854775808-0' to range_expr: {message}" + ) + + def test_int64_min_step_overflows(self) -> None: + from openjd.expr import RangeExpr, RangeExprError + + with pytest.raises(RangeExprError) as exc_info: + RangeExpr("0-10:-9223372036854775808") + assert str(exc_info.value) == "Integer overflow: result is outside the 64-bit signed range" diff --git a/test/openjd/expr/test_known_gaps.py b/test/openjd/expr/test_known_gaps.py index 63ec635e..8b82a650 100644 --- a/test/openjd/expr/test_known_gaps.py +++ b/test/openjd/expr/test_known_gaps.py @@ -169,3 +169,54 @@ def test_message_with_expr_prefix_renders_cleanly_for_rust_error() -> None: # Reference shape: headline + " x = Param.X" + " " + " " * 6 + "^". expected = "Undefined variable: 'Param.X'.\n x = Param.X\n ^" assert rendered == expected + + +# ── ExprType deeper than 11 levels pickles but does not unpickle ── +# +# ``ExprType.__reduce__`` returns ``(ExprType, (str(self),))``, so +# unpickling parses the type string. Since openjd-expr 0.18.0 +# (openjd-rs#578) a type can be built up to ``MAX_TYPE_DEPTH`` (64) +# levels deep, but the type-string parser stops at 10 levels of nesting +# (11 deep). A type 12 to 64 levels deep therefore pickles, and +# ``pickle.loads`` raises ``ValueError: Type nesting depth exceeded``. +# +# Fix path: reduce through the type code and parameter list rather +# than the string, or raise the parser's nesting bound to match +# ``MAX_TYPE_DEPTH``. + + +@pytest.mark.xfail( + reason=( + "ExprType.__reduce__ goes through str(), and the type-string parser stops at " + "11 levels, so a 12-deep type pickles but pickle.loads raises ValueError" + ), + raises=ValueError, + strict=True, +) +def test_deep_expr_type_round_trips_through_pickle() -> None: + import pickle + + from openjd.expr import ExprType + + t = ExprType("int") + for _ in range(11): + t = ExprType.list(t) + # 11 lists around int is 12 levels, well inside MAX_TYPE_DEPTH. + assert pickle.loads(pickle.dumps(t)) == t + + +@pytest.mark.xfail( + strict=True, + raises=ExpressionError, + reason=( + "openjd-expr 0.18.1 (openjd-rs#368) decides whether to cache a regex when " + "it compiles it, so a limit just large enough to cache the pattern can " + "fail where a smaller limit, which leaves it uncached, passes" + ), +) +def test_a_larger_memory_limit_never_fails_where_a_smaller_one_passes() -> None: + from openjd.expr import parse_expression + + expr = parse_expression("re_search('abc', 'b') != null and len(string(round(1.0, 200000))) > 0") + assert expr.evaluate(memory_limit=300_000).item() is True + assert expr.evaluate(memory_limit=1_098_576).item() is True diff --git a/test/openjd/expr/test_memory.py b/test/openjd/expr/test_memory.py index 1325b29e..0e43349a 100644 --- a/test/openjd/expr/test_memory.py +++ b/test/openjd/expr/test_memory.py @@ -340,3 +340,58 @@ def test_an_attribute_value_error_is_still_rewritten(self) -> None: assert str(excinfo.value) == ( "'name' property is not available for string. Available for: path\n 'abc'.name\n ~~~~~~^~~~" ) + + +class TestRegexCacheMemory: + """openjd-expr 0.18.1 (openjd-rs#368) bounds the regex cache at 32 patterns + per evaluation and charges each cached pattern 1 MiB (the compiled-size + limit) plus its length to the memory budget. Before, the cache was not + counted, so an expression that also allocates can now exceed a + ``memory_limit`` it fit in. A pattern that would not fit the remaining + budget is compiled for one call and not cached or counted. The operation + side is pinned in ``test_string_operation_counting.py``.""" + + MIB = 1 << 20 + + def test_a_cached_pattern_counts_toward_peak_memory(self) -> None: + result = parse_expression("re_search('abc', 'b') != null").evaluate_with_metrics() + assert result.value.item() is True + assert result.peak_memory >= self.MIB + + def test_a_pattern_that_does_not_fit_is_not_cached(self) -> None: + """The same expression peaks at 1 MiB or more with no limit, so the low + peak under a 500 kB limit means the pattern was compiled for the call + and not cached, not that regexes are never charged.""" + expr = parse_expression("re_search('abc', 'b') != null") + assert expr.evaluate_with_metrics().peak_memory >= 1 << 20 + result = expr.evaluate_with_metrics(memory_limit=500_000) + assert result.value.item() is True + assert result.peak_memory < 1000 + + def test_cached_regex_counts_toward_memory_limit(self) -> None: + alone = "len([x for x in range(4000)]) > 0" + assert parse_expression(alone).evaluate(memory_limit=1_500_000).item() is True + + expr = "re_search('a', 'a') != null and len([x for x in range(4000)]) > 0" + with pytest.raises(ExpressionError) as excinfo: + parse_expression(expr).evaluate(memory_limit=1_500_000) + assert str(excinfo.value) == _memory_error( + 1572929, + 1500000, + expr, + " ^~~~~~~~~~~~~~~~~~~~~~~~", + ) + + @staticmethod + def _peak_with_patterns(count: int) -> int: + # Each re_sub pattern ('x', 'xx', ...) is distinct, so each is a miss. + expr = f"len([re_sub('a', 'x' * (i + 1), '') for i in range({count})])" + return parse_expression(expr).evaluate_with_metrics().peak_memory + + def test_the_cache_holds_at_most_32_patterns(self) -> None: + one = self._peak_with_patterns(1) + thirty_two = self._peak_with_patterns(32) + forty = self._peak_with_patterns(40) + assert thirty_two - one >= 31 * self.MIB + # Patterns past the 32nd do not raise the peak. + assert forty - thirty_two < self.MIB diff --git a/test/openjd/expr/test_parse_expression.py b/test/openjd/expr/test_parse_expression.py index b30c3a91..8c520bdd 100644 --- a/test/openjd/expr/test_parse_expression.py +++ b/test/openjd/expr/test_parse_expression.py @@ -218,6 +218,22 @@ def test_has_complex_expressions(self): assert not FormatString("{{Param.Name}}").has_complex_expressions() assert FormatString("{{Param.A + Param.B}}").has_complex_expressions() + @pytest.mark.parametrize( + "raw", + [ + pytest.param("{{ (Param.X) }}", id="parenthesized"), + pytest.param("{{ Param.X # c }}", id="comment"), + pytest.param("{{ Param.\\\nX }}", id="line-continuation"), + ], + ) + def test_has_complex_expressions_checks_how_the_name_is_written(self, raw: str): + """Since openjd-expr 0.18.0 (openjd-rs#633) only a bare dotted name is + simple. A name in parentheses, or one with a comment or a line + continuation in it, is complex. Before, each of these returned + ``False``.""" + assert FormatString(raw).has_complex_expressions() + assert not FormatString("{{ Param.X }}").has_complex_expressions() + @pytest.mark.parametrize( "raw, count", [ diff --git a/test/openjd/expr/test_parser_work_bound.py b/test/openjd/expr/test_parser_work_bound.py index 4e5dc1d9..fdb1af2d 100644 --- a/test/openjd/expr/test_parser_work_bound.py +++ b/test/openjd/expr/test_parser_work_bound.py @@ -121,8 +121,10 @@ def test_v1_decode_job_template(expr: str, headline: str) -> None: lambda: v1_decode_job_template(template=_template(expr), supported_extensions=["EXPR"]), V1DecodeValidationError, ) + # openjd-model 0.18.0 (openjd-rs#634) names the field that failed to parse. assert message.startswith( "'jobtemplate-2023-09' failed checks: " + "steps[0] -> script -> actions -> onRun -> args[0]: " f"Failed to parse interpolation expression at [0, {len(expr) + 6}]. " f"Reason: Syntax error: {headline}\n" ) diff --git a/test/openjd/expr/test_paths.py b/test/openjd/expr/test_paths.py index 0787d5e7..4026ae48 100644 --- a/test/openjd/expr/test_paths.py +++ b/test/openjd/expr/test_paths.py @@ -6,7 +6,7 @@ import pytest from pathlib import PurePath, PurePosixPath from openjd.expr import evaluate_expression, ExprValue, ExpressionError, SymbolTable -from openjd.expr import PathFormat +from openjd.expr import PathFormat, TypeCode HOST_PATH_FORMAT = PathFormat.WINDOWS if sys.platform == "win32" else PathFormat.POSIX @@ -597,3 +597,19 @@ def test_pathformat_usable_as_dict_key(self) -> None: assert d[PathFormat.POSIX] == "p" assert d[PathFormat.WINDOWS] == "w" assert d[PathFormat.URI] == "u" + + +class TestPathOfEmptyList: + """openjd-expr 0.18.0 (openjd-rs#576) adds a ``path(list[nulltype])`` + overload: ``path([])``, and a ``path(...)`` of a comprehension that keeps + nothing, is ``path('.')`` in every format. Before, it raised ``No matching + signature for path(list[nulltype])``.""" + + @pytest.mark.parametrize("path_format", [PathFormat.POSIX, PathFormat.WINDOWS]) + @pytest.mark.parametrize("expr", ["path([])", "path([s for s in ['a', 'b'] if False])"]) + def test_empty_parts_are_the_current_directory( + self, expr: str, path_format: PathFormat + ) -> None: + result = evaluate_expression(expr, path_format=path_format) + assert result.type.type_code == TypeCode.PATH + assert result.item() == "." diff --git a/test/openjd/expr/test_slicing.py b/test/openjd/expr/test_slicing.py index 1f5d3930..6a70842c 100644 --- a/test/openjd/expr/test_slicing.py +++ b/test/openjd/expr/test_slicing.py @@ -116,6 +116,26 @@ def test_path_slice_not_supported(self): evaluate_expression('path("/a/b/c")[1:3]') +class TestScalarSubscript: + """Since openjd-expr 0.18.1 (openjd-rs#626) only ``list``, ``string`` and + ``range_expr`` can be indexed, and an ``int``, ``float`` or ``bool`` + receiver raises ``Cannot subscript type ``. Before, the message was + ``No matching signature for __getitem__(int, int)``.""" + + @pytest.mark.parametrize( + "expr,type_name,caret", + [ + ("5[0]", "int", "~^~~"), + ("1.5[0:1]", "float", "~~~^~~~~"), + ("True[0]", "bool", "~~~~^~~"), + ], + ) + def test_scalar_cannot_be_subscripted(self, expr: str, type_name: str, caret: str) -> None: + with pytest.raises(ExpressionError) as exc_info: + evaluate_expression(expr) + assert str(exc_info.value) == f"Cannot subscript type {type_name}\n {expr}\n {caret}" + + class TestSlicingWithExpressions: """Tests for slicing with expression bounds.""" diff --git a/test/openjd/expr/test_string_operation_counting.py b/test/openjd/expr/test_string_operation_counting.py index 8714c190..464c8f9d 100644 --- a/test/openjd/expr/test_string_operation_counting.py +++ b/test/openjd/expr/test_string_operation_counting.py @@ -97,12 +97,35 @@ def test_string_contains(self) -> None: assert result.operation_count == 7 def test_regex_search(self) -> None: - """re_search() counts string ops on the input string and pattern.""" + """re_search() counts string ops on the input string and pattern, and + compiling the pattern charges one op per pattern byte (openjd-rs#368).""" result = parse_expression("re_search('a' * 500, r'b')").evaluate_with_metrics() # __mul__: 1 + ceil(500/256)=2 = 3 # re_search: 1 + ceil((500+1)/256)=2 = 3 - # total = 6 - assert result.operation_count == 6 + # compiling 'b': len('b') = 1 + # total = 7 + assert result.operation_count == 7 + + def test_regex_compile_charges_pattern_length(self) -> None: + """A cache miss charges ``len(pattern)`` ops (openjd-rs#368): one more + pattern byte is one more op, beyond the string ops on the pattern.""" + one = parse_expression("re_search('a', r'b')").evaluate_with_metrics() + two = parse_expression("re_search('a', r'bc')").evaluate_with_metrics() + assert two.operation_count == one.operation_count + 1 + + def test_regex_cache_hit_does_not_charge_compile(self) -> None: + """The second use of a pattern in one evaluation is a cache hit and + charges no compile ops (openjd-rs#368); a different pattern of the + same length is a miss and pays them again.""" + pattern = "b" * 300 + other = "b" * 299 + "c" + hit = parse_expression( + f"re_search('a', '{pattern}') == null and re_search('a', '{pattern}') == null" + ).evaluate_with_metrics() + miss = parse_expression( + f"re_search('a', '{pattern}') == null and re_search('a', '{other}') == null" + ).evaluate_with_metrics() + assert miss.operation_count - hit.operation_count == len(other) def test_repr_sh_string(self) -> None: """repr_sh() on a string counts string ops.""" diff --git a/test/openjd/expr/test_strings.py b/test/openjd/expr/test_strings.py index 9792f66b..15306534 100644 --- a/test/openjd/expr/test_strings.py +++ b/test/openjd/expr/test_strings.py @@ -1381,3 +1381,63 @@ def test_white_space_around_the_number_is_ignored( from openjd.expr import ExprType assert evaluate_expression(expr, target_type=ExprType(target)).item() == expected + + +class TestControlCharactersAndSurrogateEscapes: + """openjd-expr 0.18.0 (openjd-rs#570). ``re_sub`` rejects a replacement + that contains a control character (Unicode Cc) other than tab, newline + and carriage return, and a ``\\u`` or ``\\U`` escape that names a + surrogate (U+D800 to U+DFFF) in a non-raw string is a syntax error. + Before, the replacement was inserted as written, and a surrogate escape + became U+FFFD. The sources are raw Python strings so that the expression + parser, not Python, decodes the escapes.""" + + @pytest.mark.parametrize( + "expr,code_point", + [ + pytest.param(r"""re_sub('abc', 'b', '\x01')""", "U+0001", id="x01"), + # A non-raw '\1' is U+0001, not a group reference. + pytest.param(r"""re_sub('abc', '(b)', '\1')""", "U+0001", id="non-raw-backref"), + pytest.param(r"""re_sub('abc', 'b', '\x7f')""", "U+007F", id="delete"), + ], + ) + def test_re_sub_rejects_control_characters(self, expr: str, code_point: str) -> None: + with pytest.raises(ExpressionError) as excinfo: + evaluate_expression(expr) + assert str(excinfo.value) == ( + f"Control characters in replacement strings are not supported ({code_point})\n" + f" {expr}\n" + f" {'^' + '~' * (len(expr) - 1)}" + ) + + def test_re_sub_allows_tab_newline_and_carriage_return(self) -> None: + assert evaluate_expression(r"""re_sub('abc', 'b', '\t\n\r')""").item() == "a\t\n\rc" + + def test_raw_backref_is_still_a_group_reference_error(self) -> None: + with pytest.raises(ExpressionError, match="Group references in replacement strings"): + evaluate_expression(r"""re_sub('abc', '(b)', r'\1')""") + + @pytest.mark.parametrize( + "expr,escape,caret", + [ + pytest.param(r"""'\ud800'""", r"\ud800", " ^~~~~~", id="u"), + pytest.param(r"""'\U0000dfff'""", r"\U0000dfff", " ^~~~~~~~~~", id="U"), + pytest.param( + r"""'abc'[0:len('\ud800')]""", + r"\ud800", + " ^~~~~~", + id="in-slice-bound", + ), + ], + ) + def test_surrogate_escape_is_a_syntax_error(self, expr: str, escape: str, caret: str) -> None: + with pytest.raises(ExpressionError) as excinfo: + evaluate_expression(expr) + assert str(excinfo.value) == ( + f"Syntax error: {escape} is a surrogate code point, which a string can't hold\n" + f" {expr}\n" + f" {caret}" + ) + + def test_raw_surrogate_escape_is_six_characters(self) -> None: + assert evaluate_expression(r"""r'\ud800'""").item() == "\\ud800" diff --git a/test/openjd/expr/test_types.py b/test/openjd/expr/test_types.py index 9551a821..d9bbc9ec 100644 --- a/test/openjd/expr/test_types.py +++ b/test/openjd/expr/test_types.py @@ -804,3 +804,57 @@ def test_primitive_rejects_params(self) -> None: ): with pytest.raises(ValueError, match="does not accept type parameters"): ExprType(tc, [ExprType("int")]) + + +class TestTypeDepthLimit: + """openjd-expr 0.18.0 (openjd-rs#578) bounds how deep an ``ExprType`` can + be, and every constructor and ``substitute`` refuses a deeper one with + ``ExpressionError``. Before, such a type built and could overflow the + stack in ``==``, ``hash`` and ``str``.""" + + def test_the_limit_is_exported(self) -> None: + from openjd.expr import MAX_TYPE_DEPTH + + assert MAX_TYPE_DEPTH == 64 + + def _deepest_list(self) -> ExprType: + # `int` is one level and each `list[...]` adds one. + t = INT + for _ in range(63): + t = ExprType.list(t) + return t + + def test_list_refuses_one_level_past_the_limit(self) -> None: + from openjd.expr import ExpressionError + + t = self._deepest_list() + assert str(t).count("list[") == 63 + with pytest.raises(ExpressionError, match=r"Type nesting depth exceeded limit \(64\)"): + ExprType.list(t) + + def test_every_constructor_refuses(self) -> None: + from openjd.expr import ExpressionError + + t = self._deepest_list() + with pytest.raises(ExpressionError, match=r"^Type nesting depth exceeded limit \(64\)$"): + ExprType(TypeCode.LIST, [t]) + with pytest.raises(ExpressionError, match=r"^Type nesting depth exceeded limit \(64\)$"): + ExprType("list", [t]) + with pytest.raises(ExpressionError, match=r"^Type nesting depth exceeded limit \(64\)$"): + ExprType.union([t, STRING]) + with pytest.raises(ExpressionError, match=r"^Type nesting depth exceeded limit \(64\)$"): + t.nullable() + + def test_substitute_refuses(self) -> None: + from openjd.expr import ExpressionError + + generic = ExprType(TypeCode.LIST, [ExprType("T")]) + with pytest.raises(ExpressionError, match=r"^Type nesting depth exceeded limit \(64\)$"): + generic.substitute({TypeCode.TYPEVAR_T: self._deepest_list()}) + + def test_a_parsed_type_stops_at_ten_levels_of_nesting(self) -> None: + """Unchanged by the bump (control).""" + ExprType("list[" * 10 + "int" + "]" * 10) + with pytest.raises(ValueError) as excinfo: + ExprType("list[" * 11 + "int" + "]" * 11) + assert str(excinfo.value) == "Type nesting depth exceeded" diff --git a/test/openjd/expr/test_unresolved_eval.py b/test/openjd/expr/test_unresolved_eval.py index 03eca8ab..b7edd50f 100644 --- a/test/openjd/expr/test_unresolved_eval.py +++ b/test/openjd/expr/test_unresolved_eval.py @@ -549,12 +549,14 @@ def test_unknown_list_slice(self) -> None: assert result.type == ExprType("unresolved[list[int]]") def test_unknown_string_index_error(self) -> None: - """unresolved[string] as index is a type error.""" + """unresolved[string] as index is a type error. Since openjd-expr + 0.18.1 (openjd-rs#626) the receiver is checked by its type before the + index, and the message names both types.""" values = SymbolTable({"I": ExprValue.unresolved("string")}) with pytest.raises(ExpressionError) as exc_info: evaluate_expression("[1, 2][I]", values=values) expected = [ - "Index must be an integer\n", + "Cannot subscript type list[int] with index of type string\n", " [1, 2][I]\n", " ~~~~~~^~~", ] @@ -567,6 +569,40 @@ def test_unknown_slice_bounds(self) -> None: assert result.type == ExprType("unresolved[list[int]]") +class TestUnknownSubscriptReceiverType: + """Since openjd-expr 0.18.1 (openjd-rs#626) a subscript is checked by its + receiver's type, resolved or not. A subscript or slice of an unresolved + ``path``, ``int``, ``float`` or ``bool`` raises ``Cannot subscript type + ``. Before, it returned an unresolved value (``unresolved[bool]`` + raised ``No matching signature for __getitem__(bool, int)``), so + validation accepted what a run refused.""" + + @pytest.mark.parametrize("type_name", ["path", "int", "float", "bool"]) + @pytest.mark.parametrize( + "expr,caret", + [("X[0]", "~^~~"), ("X[0:1]", "~^~~~~"), ("X[::-1]", "~^~~~~~")], + ) + def test_unresolved_receiver_cannot_be_subscripted( + self, type_name: str, expr: str, caret: str + ) -> None: + values = SymbolTable({"X": ExprValue.unresolved(type_name)}) + with pytest.raises(ExpressionError) as exc_info: + evaluate_expression(expr, values=values) + assert str(exc_info.value) == f"Cannot subscript type {type_name}\n {expr}\n {caret}" + + def test_unresolved_range_expr_index(self) -> None: + values = SymbolTable({"X": ExprValue.unresolved("range_expr")}) + assert evaluate_expression("X[0]", values=values).type == ExprType("unresolved[int]") + + @pytest.mark.parametrize("expr", ["X[0:1]", "X[::-1]"]) + def test_unresolved_range_expr_slice_type(self, expr: str) -> None: + """A slice of a ``range_expr`` may not be a range, so the type is the + union. Before, ``X[::-1]`` was ``unresolved[range_expr]``.""" + values = SymbolTable({"X": ExprValue.unresolved("range_expr")}) + result = evaluate_expression(expr, values=values) + assert result.type == ExprType("unresolved[list[int] | range_expr]") + + class TestUnknownFail: """Test fail() behavior with unresolved values.""" diff --git a/test/openjd/model_v0/v2023_09/test_expr_literal_paths.py b/test/openjd/model_v0/v2023_09/test_expr_literal_paths.py new file mode 100644 index 00000000..11d685f5 --- /dev/null +++ b/test/openjd/model_v0/v2023_09/test_expr_literal_paths.py @@ -0,0 +1,370 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Template-time checks of EXPR expressions that the openjd-rs 0.18 bump changed, +in v0 (``openjd.model``) with the v1 binding's answer beside it. + +openjd-expr 0.18.0 (openjd-rs#611) leaves a literal path unresolved under a host +context, because a worker's path format is not known at submission. v0 checked +every symbol-free expression with ``HostContext.unresolved()``, so after that +change it stopped refusing a bad literal path in a TEMPLATE-scope field (job +``name``, a ``timeout``, a range element, a step ``let``): the template decoded and +the error appeared only at job creation, or for a ``timeout`` only at run time. v0 +now checks a TEMPLATE-scope field without a host context, as openjd-model does, +and keeps the host context for host-scope fields such as ``args``. +""" + +import sys +from typing import Any, Optional + +import pytest + +from openjd.model import DecodeValidationError, create_job, decode_job_template +from openjd.model._v1 import create_job as create_job_v1 +from openjd.model._v1 import decode_job_template as decode_job_template_v1 +from openjd.model._v1.errors import ModelValidationError + +_EXTS = ["EXPR", "FEATURE_BUNDLE_1"] +_BAD = "int(path('a/b').name)" +_WINDOWS_BAD = "int(path('C:\\\\a\\\\5').name)" + + +def _template( + *, + name: str = "J", + on_run: Optional[dict[str, Any]] = None, + parameter_definitions: Optional[list[dict[str, Any]]] = None, + **step_fields: Any, +) -> dict[str, Any]: + step: dict[str, Any] = { + "name": "S", + "script": {"actions": {"onRun": on_run or {"command": "echo"}}}, + } + step.update(step_fields) + return { + "specificationVersion": "jobtemplate-2023-09", + "extensions": _EXTS, + "name": name, + "parameterDefinitions": parameter_definitions + or [{"name": "X", "type": "INT", "default": 1}], + "steps": [step], + } + + +def _v0_error(template: dict[str, Any]) -> str: + with pytest.raises(DecodeValidationError) as excinfo: + decode_job_template(template=template, supported_extensions=_EXTS) + return str(excinfo.value) + + +def _v1_error(template: dict[str, Any]) -> str: + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template_v1(template=template, supported_extensions=_EXTS) + return str(excinfo.value) + + +def _caret(expr: str) -> str: + return f"\n {expr}\n ^{'~' * (len(expr) - 1)}" + + +class TestTemplateScopeLiteralPathsAreCheckedAtDecode: + """``{{ int(path('a/b').name) }}`` can never resolve. v0 refuses it at decode + again in every TEMPLATE-scope field, as it did with openjd-expr 0.17.0. With + openjd-expr 0.18.0 and the old check, the name row decoded and ``create_job`` + raised ``Failed to resolve the job's name: ...``, and the timeout row decoded + and ``create_job`` returned the timeout unresolved. v1 refused each throughout.""" + + @pytest.mark.parametrize( + "template, path, v0_detail, v1_detail", + [ + pytest.param( + _template(name="{{ " + _BAD + " }}"), + "name", + "Failed to parse interpolation expression at [0, 29]. Cannot convert 'b' to int" + + _caret(_BAD), + "Failed to parse interpolation expression at [0, 27]. Cannot convert 'b' to int" + + _caret(_BAD), + id="job name", + ), + pytest.param( + _template(on_run={"command": "echo", "timeout": "{{ " + _BAD + " }}"}), + "steps[0] -> script -> actions -> onRun -> timeout", + "Failed to parse interpolation expression at [0, 29]. Cannot convert 'b' to int" + + _caret(_BAD), + "Failed to parse interpolation expression at [0, 27]. Cannot convert 'b' to int" + + _caret(_BAD), + id="timeout", + ), + pytest.param( + _template(let=["y = " + _BAD]), + "steps[0] -> let[0]", + "Failed to parse interpolation expression at [0, 27]. Cannot convert 'b' to int" + + _caret(_BAD), + "Invalid expression in let binding 'y': Cannot convert 'b' to int\n" + " y = int(path('a/b').name)\n" + " ^~~~~~~~~~~~~~~~~~~~~", + id="step let", + ), + pytest.param( + _template(name="{{ " + _BAD + " + Param.X }}"), + "name", + "Cannot convert 'b' to int\n" + " int(path('a/b').name) + Param.X\n" + " ^~~~~~~~~~~~~~~~~~~~~", + "Failed to parse interpolation expression at [0, 37]. Cannot convert 'b' to int\n" + " int(path('a/b').name) + Param.X\n" + " ^~~~~~~~~~~~~~~~~~~~~", + id="job name with a typed symbol", + ), + ], + ) + def test_refused_in_v0_and_v1( + self, template: dict[str, Any], path: str, v0_detail: str, v1_detail: str + ) -> None: + assert _v0_error(template) == ( + f"1 validation errors for JobTemplate\n{path}:\n\t{v0_detail}" + ) + assert _v1_error(template) == f"1 validation error for JobTemplate\n{path}:\n\t{v1_detail}" + + def test_an_int_range_element_is_refused_in_v0_and_v1(self) -> None: + """v0 reports the element and the range, as it does for any bad element.""" + template = _template( + parameterSpace={ + "taskParameterDefinitions": [ + {"name": "T", "type": "INT", "range": ["{{ " + _BAD + " }}"]} + ] + } + ) + detail = "Cannot convert 'b' to int" + _caret(_BAD) + path = "steps[0] -> parameterSpace -> taskParameterDefinitions[0] -> range" + assert _v0_error(template) == ( + "2 validation errors for JobTemplate\n" + f"{path}[0]:\n\tFailed to parse interpolation expression at [0, 29]. {detail}\n" + f"{path}:\n\tFailed to parse interpolation expression at [0, 29]. {detail}" + ) + assert _v1_error(template) == ( + "1 validation error for JobTemplate\n" + f"{path}[0]:\n\tFailed to parse interpolation expression at [0, 27]. {detail}" + ) + + @pytest.mark.skipif( + sys.platform == "win32", + reason="TEMPLATE scope reads a literal path in the submitter's format; " + "on Windows this path's name is '5'.", + ) + def test_a_windows_literal_path_in_the_job_name_is_refused_on_posix(self) -> None: + template = _template(name="{{ " + _WINDOWS_BAD + " }}") + detail = "Cannot convert 'C:\\a\\5' to int" + _caret(_WINDOWS_BAD) + assert _v0_error(template) == ( + "1 validation errors for JobTemplate\nname:\n" + f"\tFailed to parse interpolation expression at [0, 34]. {detail}" + ) + assert _v1_error(template) == ( + "1 validation error for JobTemplate\nname:\n" + f"\tFailed to parse interpolation expression at [0, 32]. {detail}" + ) + + +class TestATemplateScopeExpressionThatReadsALetName: + """A ``let`` name has no declared type, so v0 used to check an expression that + reads one by name only, and skipped the TEMPLATE-scope check. The repros below + decoded in v0 and ``create_job`` left the timeout unresolved, so the error + came only on the worker. v1 evaluates the ``let`` values and refuses them at + decode. v0 now checks the expression without a host context, with each + untyped name as a value of unknown type.""" + + @pytest.mark.parametrize( + "expr, message", + [ + pytest.param(_BAD + " + n", "Cannot convert 'b' to int", id="int of a path name"), + pytest.param( + "path('a/b').parts[5] + n", + "Index 5 out of bounds for list of length 2", + id="path parts index", + ), + pytest.param( + "int(with_number('f_#',3)) + n", + "Cannot convert 'f_3' to int", + id="int of with_number", + ), + ], + ) + def test_a_timeout_is_refused_in_v0_and_v1(self, expr: str, message: str) -> None: + template = _template( + let=["n = 1"], on_run={"command": "echo", "timeout": "{{ " + expr + " }}"} + ) + v0 = _v0_error(template) + assert v0.startswith( + "1 validation errors for JobTemplate\n" + "steps[0] -> script -> actions -> onRun -> timeout:\n\t" + ) + assert message in v0 + assert message in _v1_error(template) + + @pytest.mark.parametrize( + "expr", ["n + 1", "len(n) if n else 0", "path(n).name", "[x for x in n]", "n.upper()"] + ) + def test_control_an_expression_of_unknown_type_decodes(self, expr: str) -> None: + """Nothing about an unknown-typed name is assumed, so these decode in a + TEMPLATE-scope step ``let`` that reads an earlier one.""" + decode_job_template( + template=_template(let=["n = 'abc'", "m = " + expr]), supported_extensions=_EXTS + ) + + +class TestATemplateScopeErrorIsReportedOnce: + """v0's reference check visits a ``cancelation`` value once per union member + it could be, so a failing expression in ``notifyPeriodInSeconds`` was + reported twice once this check ran there. It is reported once, as v1 does.""" + + def test_notify_period_in_seconds(self) -> None: + template = _template( + on_run={ + "command": "echo", + "cancelation": { + "mode": "NOTIFY_THEN_TERMINATE", + "notifyPeriodInSeconds": "{{ " + _BAD + " }}", + }, + } + ) + assert _v0_error(template) == ( + "1 validation errors for JobTemplate\n" + "steps[0] -> script -> actions -> onRun -> cancelation -> notifyPeriodInSeconds:\n" + "\tFailed to parse interpolation expression at [0, 29]. Cannot convert 'b' to int" + + _caret(_BAD) + ) + assert _v1_error(template).startswith("1 validation error for JobTemplate\n") + + def test_a_repeated_undefined_name_in_one_field_is_reported_once(self) -> None: + """The same error twice at one location is reported once, in a template + without EXPR too. Before, v0 reported ``{{Param.Y}} {{Param.Y}}`` twice; + v1 reports it once.""" + template = { + "specificationVersion": "jobtemplate-2023-09", + "name": "{{Param.Y}} {{Param.Y}}", + "steps": [{"name": "S", "script": {"actions": {"onRun": {"command": "echo"}}}}], + } + with pytest.raises(DecodeValidationError) as excinfo: + decode_job_template(template=template) + assert str(excinfo.value).startswith("1 validation errors for JobTemplate\nname:\n") + + +class TestHostFunctionsInATemplateScopeLet: + """A step ``let`` is evaluated at job creation, where no host context exists. + v0 refuses ``apply_path_mapping`` in one at decode, as it does in a + TEMPLATE-scope field, and as v1 does. Before, v0 decoded it and + ``create_job`` raised ``Unknown function: 'apply_path_mapping'``. A script + ``let`` is host scope, and both decode it (control).""" + + _LET = "z = string(apply_path_mapping('/a'))" + + def test_a_step_let_is_refused_in_v0_and_v1(self) -> None: + template = _template(let=[self._LET]) + assert _v0_error(template) == ( + "1 validation errors for JobTemplate\nsteps[0] -> let[0]:\n" + "\tThe function 'apply_path_mapping' is only available at runtime " + "(host context), not at submission time." + ) + assert _v1_error(template).startswith( + "1 validation error for JobTemplate\nsteps[0] -> let[0]:\n" + "\tInvalid expression in let binding 'z': Unknown function: 'apply_path_mapping'" + ) + + @pytest.mark.xfail( + strict=True, + raises=DecodeValidationError, + reason=( + "v0 refuses a host-context function in a TEMPLATE-scope let by name, " + "even in a branch a literal condition rules out; v1 folds the " + "condition first and decodes it. A job name already differed this way." + ), + ) + def test_a_dead_branch_decodes_as_in_v1(self) -> None: + template = _template(let=["z = 'a' if True else string(apply_path_mapping('/a'))"]) + decode_job_template_v1(template=template, supported_extensions=_EXTS) + decode_job_template(template=template, supported_extensions=_EXTS) + + def test_control_a_script_let_decodes_in_v0_and_v1(self) -> None: + template = _template() + template["steps"][0]["script"]["let"] = [self._LET] + decode_job_template(template=template, supported_extensions=_EXTS) + decode_job_template_v1(template=template, supported_extensions=_EXTS) + + +class TestHostScopeLiteralPathsAreLeftUnresolved: + """In a host-scope field a literal path stays unresolved at decode in v0 and v1 + since openjd-expr 0.18.0 (openjd-rs#611), so it is not read as a POSIX path. + Before, every row below failed to decode in v0 and v1, with ``Cannot convert + ... to int`` or ``Index 2 out of bounds``. The first row also shows that the + TEMPLATE-scope check above does not reach ``args``.""" + + @pytest.mark.parametrize( + "expr", + [_BAD, _WINDOWS_BAD, "path('C:\\\\a\\\\b').parts[2]"], + ) + def test_decodes_in_v0_and_v1(self, expr: str) -> None: + template = _template(on_run={"command": "echo", "args": ["{{ " + expr + " }}"]}) + assert decode_job_template(template=template, supported_extensions=_EXTS) + assert decode_job_template_v1(template=template, supported_extensions=_EXTS) + + +class TestSubscriptReceiverIsCheckedByType: + """Since openjd-expr 0.18.1 (openjd-rs#626) a subscript is checked against its + receiver's type at decode, in v0 and v1. ``Param.P[0]`` on a PATH parameter + used to decode in both. For INT, FLOAT and BOOL + the message was ``No matching signature for __getitem__(int, int)`` (``float``, + ``bool``).""" + + @pytest.mark.parametrize( + "ptype, default, type_name", + [ + pytest.param("INT", 1, "int", id="INT"), + pytest.param("FLOAT", 1.0, "float", id="FLOAT"), + pytest.param("BOOL", True, "bool", id="BOOL"), + pytest.param("PATH", "a", "path", id="PATH"), + ], + ) + def test_a_subscript_of_a_scalar_is_refused( + self, ptype: str, default: Any, type_name: str + ) -> None: + template = _template( + parameter_definitions=[{"name": "P", "type": ptype, "default": default}], + on_run={"command": "echo", "args": ["{{ Param.P[0] }}"]}, + ) + path = "steps[0] -> script -> actions -> onRun -> args[0]" + detail = f"Cannot subscript type {type_name}\n Param.P[0]\n ~~~~~~~^~~" + assert _v0_error(template) == f"1 validation errors for JobTemplate\n{path}:\n\t{detail}" + assert _v1_error(template) == ( + f"1 validation error for JobTemplate\n{path}:\n" + f"\tFailed to parse interpolation expression at [0, 16]. {detail}" + ) + + def test_control_a_string_subscript_decodes(self) -> None: + template = _template( + parameter_definitions=[{"name": "P", "type": "STRING", "default": "a"}], + on_run={"command": "echo", "args": ["{{ Param.P[0] }}"]}, + ) + assert decode_job_template(template=template, supported_extensions=_EXTS) + assert decode_job_template_v1(template=template, supported_extensions=_EXTS) + + +class TestRoundWithNonPositiveDigitsGivesAnInt: + """Since openjd-expr 0.17.0 (openjd-rs#567) ``round(x, n)`` with ``n <= 0`` + returns an int and every ``round`` rounds the exact value, so a job name built + from it changes in v0 and v1. Before, the rows below gave ``J2.0``, + ``J1200.0`` and ``J2.68``.""" + + @pytest.mark.parametrize( + "expr, name", + [ + pytest.param("round(2.5, 0)", "J2", id="ndigits 0"), + pytest.param("round(1234.5, -2)", "J1200", id="negative ndigits"), + pytest.param("repr_py(round(2.675, 2))", "J2.67", id="exact rounding"), + ], + ) + def test_the_job_name(self, expr: str, name: str) -> None: + template = _template(name="J{{ " + expr + " }}") + v0 = decode_job_template(template=template, supported_extensions=_EXTS) + assert create_job(job_template=v0, job_parameter_values={}).name == name + v1 = decode_job_template_v1(template=template, supported_extensions=_EXTS) + assert create_job_v1(job_template=v1, job_parameter_values={}).name == name diff --git a/test/openjd/model_v1/test_create_job.py b/test/openjd/model_v1/test_create_job.py index 4e825457..1ca60ca7 100644 --- a/test/openjd/model_v1/test_create_job.py +++ b/test/openjd/model_v1/test_create_job.py @@ -937,6 +937,33 @@ def test_uneven_parameter_space_association(self) -> None: ) +def test_job_parameter_values_changed_while_reading_does_not_panic() -> None: + """Reading a value's ``type`` attribute can run user code that changes the + dict. ``create_job`` used to raise PyO3's ``PanicException`` + ("dictionary changed size during iteration"); it reads a snapshot.""" + template = decode_job_template( + template={ + "specificationVersion": "jobtemplate-2023-09", + "name": "J", + "parameterDefinitions": [{"name": "A", "type": "INT"}], + "steps": [{"name": "S", "script": {"actions": {"onRun": {"command": "echo"}}}}], + } + ) + values: dict[str, Any] = {} + + class Value: + value = "1" + + @property + def type(self) -> str: + values["Added"] = 1 + return "INT" + + values["A"] = Value() + job = create_job(job_template=template, job_parameter_values=values) + assert {k: str(v.value) for k, v in job.parameters.items()} == {"A": "1"} + + class TestParametersDict: """``Job.parameters`` is the resolved parameter set: every parameter defined in the template (defaults plus explicit values) keyed by @@ -1098,6 +1125,44 @@ def test_constraint_check_runs_via_create_job(self) -> None: j = create_job(job_template=t, job_parameter_values={}) assert j.parameters["Frame"].value.item() == 5 + def test_job_parameters_are_in_definition_order(self) -> None: + """Since openjd-model 0.18.0 (openjd-rs#639) ``Job.parameters`` lists the + job template's parameters in definition order, then the other entries, + from environment templates, in byte-wise name order. An environment + parameter that the job template also defines keeps the job template's + place. Before, the order changed from one ``create_job`` call to the next; + v0 gives definition order. 32 calls are enough for a hash order to show.""" + names = ["Gamma", "Alpha", "Zeta", "Beta", "Mid", "Omega"] + t = decode_job_template( + template={ + "specificationVersion": "jobtemplate-2023-09", + "name": "T", + "parameterDefinitions": [ + {"name": n, "type": "STRING", "default": n} for n in names + ], + "steps": minimal_steps_v2023_09, + } + ) + env = decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "parameterDefinitions": [ + {"name": n, "type": "STRING", "default": n} + for n in ["Zulu", "alpha", "Bravo", "Mid"] + ], + "environment": minimal_environment_2023_09, + } + ) + orders = { + tuple( + create_job( + job_template=t, job_parameter_values={}, environment_templates=[env] + ).parameters + ) + for _ in range(32) + } + assert orders == {(*names, "Bravo", "Zulu", "alpha")} + class TestJobTimeFieldExposure: """Job-time pyclass field-coverage tests covering the P1 recommendations @@ -2773,6 +2838,27 @@ def test_relative_path_value_is_joined_and_normalized(self, value: str, expected out = _preprocess_posix([{"name": "P", "type": "PATH"}], {"P": value}) assert out["P"].value == expected + def test_a_leading_dot_dot_a_relative_directory_cannot_cancel_is_kept(self) -> None: + """Since openjd-model 0.17.0 (openjd-rs#633) a ``..`` that a relative + working directory cannot cancel is kept. Before, it was dropped, so + ``rel/dir`` + ``../../../x`` gave ``x``. v0 does not normalize, and gives + ``rel/dir/../../../x``.""" + template = decode_job_template( + template={ + "specificationVersion": "jobtemplate-2023-09", + "name": "T", + "parameterDefinitions": [{"name": "P", "type": "PATH"}], + "steps": minimal_steps_v2023_09, + } + ) + out = preprocess_job_parameters( + job_template=template, + job_parameter_values={"P": "../../../x"}, + job_template_dir=Path("/a/job1"), + current_working_dir="rel/dir", + ) + assert out["P"].value == "../x" + def test_list_path_elements_are_joined_and_normalized(self) -> None: out = _preprocess_posix( [{"name": "Paths", "type": "LIST[PATH]"}], @@ -3148,3 +3234,73 @@ def test_int(self, tmp_path: Path) -> None: def test_float_keeps_its_spelling(self, tmp_path: Path) -> None: defs = [{"name": "F", "type": "FLOAT"}] assert _preprocess(defs, {"F": " 1.50 "}, tmp_path) == {"F": "1.50"} + + +class TestLengthLimitsCountCharacters: + """Since openjd-model 0.17.0 (openjd-rs#615) ``preprocess_job_parameters`` counts + a STRING or PATH ``minLength``/``maxLength`` in characters (Unicode scalar + values), as v0 does. Before, it counted UTF-8 bytes, so ``"ééé"`` was refused + under ``maxLength: 3`` (``value length 6 exceeds maximum 3``) and ``"éé"`` was + accepted under ``minLength: 3``.""" + + def test_string_max_length(self, tmp_path: Path) -> None: + defs = [{"name": "P", "type": "STRING", "maxLength": 3, "default": "ééé"}] + assert _preprocess(defs, {}, tmp_path) == {"P": "ééé"} + + def test_string_min_length(self, tmp_path: Path) -> None: + with pytest.raises(DecodeValidationError) as excinfo: + _preprocess([{"name": "P", "type": "STRING", "minLength": 3}], {"P": "éé"}, tmp_path) + assert str(excinfo.value) == "Parameter 'P': value length 2 is less than minimum 3" + + @_POSIX_ONLY + def test_path_max_length(self, tmp_path: Path) -> None: + defs = [{"name": "P", "type": "PATH", "maxLength": 3}] + assert _preprocess(defs, {"P": "/é/"}, tmp_path) == {"P": "/é/"} + + +class TestTheSmallestInt64InParameters: + """Since openjd-model 0.17.0 (openjd-rs#633) ``-9223372036854775808`` (i64::MIN) + is a valid integer in a RANGE_EXPR value and default and in a ``range_expr()`` + argument, as in v0. Before, a value and a ``range_expr()`` argument failed with + ``Invalid integer '9223372036854775808'``, and the template with the default + failed to decode with ``default '-9223372036854775808' is not a valid range + expression.``""" + + _MIN = "-9223372036854775808" + + @pytest.mark.parametrize("value", [_MIN, _MIN + ",9223372036854775807"]) + def test_a_range_expr_value(self, value: str, tmp_path: Path) -> None: + assert _preprocess([{"name": "R", "type": "RANGE_EXPR"}], {"R": value}, tmp_path) == { + "R": value + } + + def test_a_range_expr_default(self, tmp_path: Path) -> None: + defs = [{"name": "R", "type": "RANGE_EXPR", "default": self._MIN}] + assert _preprocess(defs, {}, tmp_path) == {"R": self._MIN} + + def test_a_range_expr_call(self) -> None: + t = decode_job_template( + template={ + "specificationVersion": "jobtemplate-2023-09", + "extensions": ["EXPR"], + "name": "T", + "steps": [ + { + "name": "S", + "script": { + "actions": { + "onRun": { + "command": "echo", + "args": ["{{ len(range_expr('" + self._MIN + "')) }}"], + } + } + }, + } + ], + }, + supported_extensions=["EXPR"], + ) + assert t.steps[0].script is not None + on_run = t.steps[0].script.actions.on_run + assert on_run.args is not None + assert [str(a) for a in on_run.args] == ["{{ len(range_expr('" + self._MIN + "')) }}"] diff --git a/test/openjd/model_v1/test_env_params.py b/test/openjd/model_v1/test_env_params.py new file mode 100644 index 00000000..054d1697 --- /dev/null +++ b/test/openjd/model_v1/test_env_params.py @@ -0,0 +1,567 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The ``ENV_PARAMS`` template fields (RFC 0010, openjd-rs#641). + +openjd-model 0.18.0 decodes the new Environment fields +(``envParameterDefinitions``, ``activation``, ``hostRequirements``, +``enableIf``, ``exclusiveGroup``) and the new ```` forms +(``step:``, ``environment:`` with ``required``, ``enableIf`` and +``parameters``). It marks the extension unstable: decoding accepts a +template that lists ``ENV_PARAMS`` only with +``CallerLimits(accept_unreleased_env_params=True)``, and job creation does +not act on the fields yet. +""" + +from __future__ import annotations + +import copy +import pickle +from typing import Any +from unittest import mock + +import pytest + +from openjd.expr import ExpressionError, FormatString +from openjd.model._v1 import ( + CallerLimits, + create_job, + decode_environment_template, + decode_job_template, +) +from openjd.model._v1.errors import DecodeValidationError, ModelValidationError +from openjd.model._v1.template import ( + Action, + EnvironmentActions, + EnvironmentActivation, + EnvironmentParameterDefinition, + EnvironmentScript, + ExprField, + HostRequirements, + JobIntParameterDefinition, + JobStringParameterDefinition, + StepDependency, + TemplateEnvironment, +) +from openjd.model._v1.types import JobParameterType, ModelExtension + +_EXTS = ["EXPR", "ENV_PARAMS"] +_OPT_IN = CallerLimits(accept_unreleased_env_params=True) + +_ENV: dict[str, Any] = { + "name": "Lic", + "activation": "ON_REQUEST", + "exclusiveGroup": "licenses", + "enableIf": "Param.Seats > 0", + "envParameterDefinitions": [ + {"name": "Seats", "type": "INT", "default": "{{Param.Seats}}", "minValue": 1}, + {"name": "Mode", "type": "STRING", "default": "fast"}, + {"name": "Tags", "type": "LIST[STRING]", "default": ["a", "b"]}, + ], + "hostRequirements": {"amounts": [{"name": "amount.worker.vcpu", "min": 2}]}, + "variables": {"A": "b"}, +} + +_TEMPLATE: dict[str, Any] = { + "specificationVersion": "jobtemplate-2023-09", + "extensions": _EXTS, + "name": "T", + "parameterDefinitions": [{"name": "Seats", "type": "INT", "default": 3}], + "jobEnvironments": [_ENV], + "steps": [ + {"name": "A", "script": {"actions": {"onRun": {"command": "echo"}}}}, + { + "name": "S", + "dependencies": [ + { + "environment": "Lic", + "required": False, + "enableIf": True, + "parameters": {"Seats": "{{Param.Seats}}", "Mode": "slow"}, + }, + {"step": "A"}, + ], + "script": {"actions": {"onRun": {"command": "echo"}}}, + }, + ], +} + + +def _decode(template: dict[str, Any] = _TEMPLATE, **kwargs: Any) -> Any: + kwargs.setdefault("caller_limits", _OPT_IN) + return decode_job_template(template=template, supported_extensions=_EXTS, **kwargs) + + +class TestOptIn: + def test_without_the_opt_in_env_params_is_an_unsupported_extension(self) -> None: + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template(template=_TEMPLATE, supported_extensions=_EXTS) + assert str(excinfo.value) == ( + "1 validation error for JobTemplate\n" + "extensions:\n\tUnsupported extension names: ENV_PARAMS" + ) + + def test_the_opt_in_still_needs_the_allowlist(self) -> None: + with pytest.raises(ModelValidationError, match="Unsupported extension names: ENV_PARAMS"): + decode_job_template( + template=_TEMPLATE, supported_extensions=["EXPR"], caller_limits=_OPT_IN + ) + + def test_with_the_opt_in_the_profile_lists_env_params(self) -> None: + jt = _decode() + assert jt.profile.has_extension(ModelExtension.ENV_PARAMS) + assert jt.profile.has_extension(ModelExtension.EXPR) + + def test_a_field_without_env_params_is_rejected(self) -> None: + template = copy.deepcopy(_TEMPLATE) + template["extensions"] = ["EXPR"] + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template( + template=template, supported_extensions=["EXPR"], caller_limits=_OPT_IN + ) + message = str(excinfo.value) + assert "jobEnvironments[0] -> activation" in message + assert "steps[1] -> dependencies[0]" in message + + +class TestWithoutTheExtension: + """In a template that does not list ENV_PARAMS, an ENV_PARAMS key used to fail + at decode with ``DecodeValidationError`` (an unknown field, or for ``[{}]`` a + missing ``dependsOn``). Since openjd-model 0.18.0 (openjd-rs#641) the entry + decodes and template validation raises ``ModelValidationError`` at the key, + which ``except DecodeValidationError`` does not catch.""" + + @staticmethod + def _template(**fields: Any) -> dict[str, Any]: + echo = {"script": {"actions": {"onRun": {"command": "echo"}}}} + return { + "specificationVersion": "jobtemplate-2023-09", + "name": "T", + "steps": [dict(echo, name="A"), dict(echo, name="S", **fields.pop("step", {}))], + **fields, + } + + @pytest.mark.parametrize( + "dependencies, where, message", + [ + ([{}], "steps[1] -> dependencies[0]", "must have 'dependsOn'."), + ( + [{"dependsOn": "A", "required": True}], + "steps[1] -> dependencies[0] -> required", + "'required' is permitted only with 'environment', which requires the " + "ENV_PARAMS extension.", + ), + ( + [{"step": "A"}], + "steps[1] -> dependencies[0]", + "the 'step' form of a dependency requires the ENV_PARAMS extension.", + ), + ( + [{"environment": "E"}], + "steps[1] -> dependencies[0]", + "the 'environment' form of a dependency requires the ENV_PARAMS extension.", + ), + ], + ) + def test_a_dependency(self, dependencies: list, where: str, message: str) -> None: + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template(template=self._template(step={"dependencies": dependencies})) + assert str(excinfo.value) == (f"1 validation error for JobTemplate\n{where}:\n\t{message}") + + def test_an_environment_field(self) -> None: + template = self._template( + jobEnvironments=[{"name": "E", "activation": "ALWAYS", "variables": {"A": "b"}}] + ) + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template(template=template) + assert str(excinfo.value) == ( + "1 validation error for JobTemplate\njobEnvironments[0] -> activation:\n" + "\tactivation on an Environment requires the ENV_PARAMS extension." + ) + + def test_an_environment_template_field(self) -> None: + et = { + "specificationVersion": "environment-2023-09", + "environment": {"name": "E", "exclusiveGroup": "g", "variables": {"A": "b"}}, + } + with pytest.raises(ModelValidationError) as excinfo: + decode_environment_template(template=et) + assert str(excinfo.value) == ( + "1 validation error for EnvironmentTemplate\nenvironment -> exclusiveGroup:\n" + "\texclusiveGroup on an Environment requires the ENV_PARAMS extension." + ) + + def test_an_unknown_field_lists_the_env_params_keys(self) -> None: + template = self._template( + jobEnvironments=[{"name": "E", "bogus": 1, "variables": {"A": "b"}}] + ) + with pytest.raises(DecodeValidationError) as excinfo: + decode_job_template(template=template) + assert str(excinfo.value) == ( + "'jobtemplate-2023-09' failed checks: jobEnvironments[0] -> bogus: " + "unknown field `bogus`, expected one of `name`, `description`, " + "`envParameterDefinitions`, `activation`, `hostRequirements`, `enableIf`, " + "`exclusiveGroup`, `script`, `variables`" + ) + + +class TestEnvironmentFields: + def test_decoded_fields(self) -> None: + env = _decode().job_environments[0] + assert env.activation is EnvironmentActivation.ON_REQUEST + assert env.effective_activation is EnvironmentActivation.ON_REQUEST + assert env.exclusive_group == env.exclusiveGroup == "licenses" + assert env.enable_if == env.enableIf == ExprField("Param.Seats > 0") + assert env.enable_if.kind == "expression" + assert env.enable_if.as_bool() is None + amounts = env.host_requirements.amounts + assert [a.name.raw() for a in amounts] == ["amount.worker.vcpu"] + assert env.hostRequirements.amounts[0].min.raw() == "2" + + def test_definitions_keep_default_out_of_the_job_parameter(self) -> None: + seats, mode, tags = _decode().job_environments[0].env_parameter_definitions + assert (seats.name, seats.type, seats.type_name) == ("Seats", JobParameterType.INT, "INT") + assert isinstance(seats.definition, JobIntParameterDefinition) + assert seats.definition.default is None + assert seats.definition.min_value == 1 + assert isinstance(seats.default, FormatString) + assert seats.default.raw() == "{{Param.Seats}}" + assert isinstance(mode.definition, JobStringParameterDefinition) + assert mode.default == "fast" + assert tags.type_name == "LIST[STRING]" + assert tags.default == ["a", "b"] + + def test_absent_fields_are_none_and_activation_defaults_to_by_default(self) -> None: + template = copy.deepcopy(_TEMPLATE) + template["jobEnvironments"] = [{"name": "E", "variables": {"A": "b"}}] + template["steps"] = [_TEMPLATE["steps"][0]] + env = _decode(template).job_environments[0] + assert env.activation is None + assert env.effective_activation is EnvironmentActivation.BY_DEFAULT + assert env.env_parameter_definitions is None + assert env.host_requirements is None + assert env.enable_if is None + assert env.exclusive_group is None + + def test_a_present_null_enable_if_is_exprfield_none(self) -> None: + et = { + "specificationVersion": "environment-2023-09", + "extensions": _EXTS, + "environment": {"name": "E", "enableIf": None, "variables": {"A": "b"}}, + } + tpl = decode_environment_template( + template=et, supported_extensions=_EXTS, caller_limits=_OPT_IN + ) + enable_if = tpl.environment.enable_if + assert enable_if == ExprField(None) + assert enable_if is not None and enable_if.kind == "null" + assert tpl.profile.has_extension(ModelExtension.ENV_PARAMS) + + def test_job_creation_does_not_read_the_fields(self) -> None: + job = create_job(job_template=_decode(), job_parameter_values={}) + # The job-time step dependency keeps the Step entries only; the + # `environment:` entry is not acted on by openjd-model 0.18.0. + assert [(s.name, s.dependencies) for s in job.steps][0] == ("A", None) + deps = job.steps[1].dependencies + assert deps is not None and [d.depends_on for d in deps] == ["A"] + + +class TestStepDependency: + def test_decoded_environment_entry(self) -> None: + dep, step_dep = _decode().steps[1].dependencies + assert dep.environment == dep.environment_name() == "Lic" + assert dep.depends_on is None and dep.step is None and dep.step_name() is None + assert dep.required is False and dep.is_required() is False + assert dep.enable_if == ExprField(True) + params = dep.parameters + assert list(params) == ["Mode", "Seats"] # byte-wise key order + assert params["Mode"] == "slow" + assert isinstance(params["Seats"], FormatString) + assert params["Seats"].raw() == "{{Param.Seats}}" + assert step_dep.step == step_dep.step_name() == "A" + assert step_dep.depends_on is None and step_dep.environment_name() is None + assert step_dep.is_required() is True + + def test_construct_and_pickle(self) -> None: + dep = StepDependency( + environment="Lic", + required=True, + enable_if=ExprField("Param.X"), + parameters={"A": "{{Param.A}}", "B": 7, "C": [1, 2], "D": None}, + ) + loaded = pickle.loads(pickle.dumps(dep)) + assert loaded == dep + assert loaded.environment == "Lic" + assert loaded.required is True + assert loaded.enable_if == ExprField("Param.X") + p = loaded.parameters + assert p["A"].raw() == "{{Param.A}}" + assert (p["B"], p["C"], p["D"]) == (7, [1, 2], None) + assert repr(dep) == ( + 'StepDependency(environment="Lic", required=True, enableIf=..., parameters=...)' + ) + + def test_a_format_string_without_braces_is_the_literal_string(self) -> None: + """Read by its text, as decoding reads ``"plain"``.""" + dep = StepDependency(environment="E", parameters={"P": FormatString("plain")}) + params = dep.parameters + assert params is not None + assert params["P"] == "plain" and type(params["P"]) is str + with_braces = StepDependency(environment="E", parameters={"P": FormatString("{{X}}")}) + assert isinstance((with_braces.parameters or {})["P"], FormatString) + + def test_equality_compares_every_field_and_is_unhashable(self) -> None: + a = StepDependency(depends_on="A") + assert a == StepDependency(depends_on="A") + assert a != StepDependency(step="A") + assert StepDependency(environment="E", parameters={"P": 1}) != StepDependency( + environment="E", parameters={"P": 2} + ) + with pytest.raises(TypeError, match="unhashable"): + hash(a) + + @pytest.mark.parametrize( + "dep", + [ + StepDependency(step="A"), + StepDependency(depends_on="A"), + StepDependency(environment="E", required=False), + StepDependency(environment="E", enable_if=ExprField(None), parameters={}), + ], + ) + def test_every_form_pickles(self, dep: StepDependency) -> None: + assert pickle.loads(pickle.dumps(dep)) == dep + + def test_required_is_none_when_absent(self) -> None: + dep = StepDependency(environment="E") + assert dep.required is None and dep.is_required() is True + + def test_a_parameters_dict_changed_while_converting_does_not_panic(self) -> None: + """Converting a value runs ``json.dumps``, which calls a dict subclass's + ``items()``. One that changes the outer dict used to raise PyO3's + ``PanicException`` ("dictionary changed size during iteration"), and one + that swapped a key kept the new key and lost the old one. The binding + reads a snapshot of the dict, as decoding a template does.""" + outer: dict[str, Any] = {} + + class Mutating(dict): + def items(self): # type: ignore[override] + outer.pop("B", None) + outer["C"] = 3 + return super().items() + + outer["A"] = Mutating(x=1) + outer["B"] = 2 + dep = StepDependency(environment="E", parameters=outer) + assert dep.parameters == {"A": {"x": 1}, "B": 2} + + def test_a_str_with_braces_must_parse(self) -> None: + with pytest.raises(ExpressionError, match="Braces mismatch"): + StepDependency(environment="E", parameters={"A": "a{{b"}) + + def test_an_entry_with_two_forms_builds_and_names_neither(self) -> None: + dep = StepDependency(depends_on="A", environment="E") + assert dep.step_name() is None and dep.environment_name() is None + + def test_depends_on_keyword_still_works(self) -> None: + dep = StepDependency(depends_on="A") + assert dep.depends_on == dep.dependsOn == dep.step_name() == "A" + assert repr(dep) == 'StepDependency(dependsOn="A")' + + +class TestExprField: + @pytest.mark.parametrize( + "value, kind", + [(True, "bool"), (3, "int"), (1.5, "float"), ("true", "expression"), (None, "null")], + ) + def test_kinds_and_round_trip(self, value: Any, kind: str) -> None: + f = ExprField(value) + assert f.kind == kind + assert f.value == value and type(f.value) is type(value) + assert pickle.loads(pickle.dumps(f)) == f + assert hash(f) == hash(ExprField(value)) + + def test_a_string_is_never_a_scalar(self) -> None: + assert ExprField("true").as_bool() is None + assert ExprField(True).as_bool() is True + assert ExprField(True) != ExprField(1) + assert ExprField(0.0) != ExprField(-0.0) + + @pytest.mark.parametrize("value", [[1], {"a": 1}, b"x"]) + def test_other_types_are_refused(self, value: Any) -> None: + with pytest.raises(TypeError): + ExprField(value) + + @pytest.mark.parametrize("value", ["nan", "inf", "-inf"]) + def test_a_non_finite_float_is_refused(self, value: str) -> None: + with pytest.raises(ValueError) as excinfo: + ExprField(float(value)) + assert str(excinfo.value) == "an ExprField float must be finite" + + @pytest.mark.parametrize("value", [2**63, 2**64 - 1]) + def test_an_int_that_decoding_refuses_is_refused(self, value: int) -> None: + with pytest.raises(OverflowError, match="2\\*\\*63 to 2\\*\\*64 - 1"): + ExprField(value) + + @pytest.mark.parametrize("value", [2**64, 2**70, -(2**63) - 1]) + def test_an_int_outside_u64_and_i64_is_read_as_a_float(self, value: int) -> None: + """As decoding reads such a number: JSON number parsing gives a float.""" + assert ExprField(value) == ExprField(float(value)) + assert ExprField(value).kind == "float" + et = { + "specificationVersion": "environment-2023-09", + "extensions": _EXTS, + "environment": {"name": "E", "enableIf": value, "variables": {"A": "b"}}, + } + tpl = decode_environment_template( + template=et, supported_extensions=_EXTS, caller_limits=_OPT_IN + ) + assert tpl.environment.enable_if == ExprField(value) + + def test_an_int_subclass_cannot_make_a_non_finite_float(self) -> None: + """An int outside the i64 and u64 ranges is read as a float with + ``int.__float__``, so a subclass's own ``__float__`` cannot build an + ``ExprField(nan)`` that then fails to unpickle.""" + + class NanInt(int): + def __float__(self) -> float: + return float("nan") + + field = ExprField(NanInt(2**70)) + assert field == ExprField(float(2**70)) + assert pickle.loads(pickle.dumps(field)) == field + + def test_an_int_too_large_for_a_float_raises_overflow_error(self) -> None: + with pytest.raises(OverflowError) as excinfo: + ExprField(10**400) + assert str(excinfo.value) == "int too large to convert to float" + + def test_eq_defers_to_the_other_operand(self) -> None: + assert ExprField(1) == mock.ANY + assert [ExprField(1)] == [mock.ANY] + assert ExprField(1) != "1" + + @pytest.mark.parametrize("value", ["\x01", "\u2028", "a'b\"c", 1.5, -0.0, True, None]) + def test_repr_evaluates_back(self, value: Any) -> None: + f = ExprField(value) + assert eval(repr(f)) == f + + +class TestEnvironmentActivation: + @pytest.mark.parametrize("name", ["ALWAYS", "BY_DEFAULT", "ON_REQUEST"]) + def test_from_str_and_as_str(self, name: str) -> None: + a = EnvironmentActivation.from_str(name) + assert a is getattr(EnvironmentActivation, name) + assert a.as_str() == a.name == str(a) == name + + def test_from_str_is_case_sensitive(self) -> None: + assert EnvironmentActivation.from_str("always") is None + + def test_members_are_not_ints(self) -> None: + assert EnvironmentActivation.ALWAYS != 0 + assert len({EnvironmentActivation.ALWAYS, EnvironmentActivation.ALWAYS}) == 1 + + +class TestEnvironmentParameterDefinition: + def test_construct_from_a_dict(self) -> None: + d = EnvironmentParameterDefinition({"name": "P", "type": "PATH", "default": "/a"}) + assert (d.name, d.type_name, d.default) == ("P", "PATH", "/a") + assert d.definition.default is None + + def test_a_format_string_default_is_read_by_its_text(self) -> None: + """The ``default`` getter returns a FormatString; the constructor takes one.""" + d = EnvironmentParameterDefinition( + {"name": "P", "type": "INT", "default": FormatString("{{Param.X}}")} + ) + assert isinstance(d.default, FormatString) and d.default.raw() == "{{Param.X}}" + again = EnvironmentParameterDefinition({"name": "P", "type": "INT", "default": d.default}) + assert isinstance(again.default, FormatString) + + def test_an_explicit_null_default_is_no_default(self) -> None: + d = EnvironmentParameterDefinition({"name": "P", "type": "INT", "default": None}) + assert d.default is None + + def test_a_definition_that_does_not_decode_raises(self) -> None: + with pytest.raises(DecodeValidationError): + EnvironmentParameterDefinition({"name": "P", "type": "NOPE"}) + + def test_it_pickles(self) -> None: + d = EnvironmentParameterDefinition({"name": "P", "type": "INT", "default": 2}) + loaded = pickle.loads(pickle.dumps(d)) + assert (loaded.name, loaded.type_name, loaded.default) == ("P", "INT", 2) + + +class TestTemplateEnvironmentConstructor: + def test_every_field_and_pickle(self) -> None: + env = TemplateEnvironment( + name="E", + description="d", + activation=EnvironmentActivation.ALWAYS, + host_requirements=HostRequirements(), + enable_if=ExprField(False), + exclusive_group="g", + variables={"A": FormatString("b")}, + script=EnvironmentScript( + actions=EnvironmentActions(on_enter=Action(command=FormatString("echo"))) + ), + ) + loaded = pickle.loads(pickle.dumps(env)) + assert (loaded.name, loaded.description) == ("E", "d") + assert {k: v.raw() for k, v in (loaded.variables or {}).items()} == {"A": "b"} + assert loaded.script is not None + on_enter = loaded.script.actions.on_enter + assert on_enter is not None and on_enter.command.raw() == "echo" + assert loaded.activation is EnvironmentActivation.ALWAYS + assert loaded.enable_if == ExprField(False) + assert loaded.exclusive_group == "g" + assert loaded.host_requirements is not None + + def test_with_definitions_it_builds_and_pickles(self) -> None: + env = TemplateEnvironment( + name="E", + env_parameter_definitions=[ + EnvironmentParameterDefinition({"name": "P", "type": "INT", "default": 1}) + ], + ) + defs = env.env_parameter_definitions + assert defs is not None and defs[0].default == 1 + loaded = pickle.loads(pickle.dumps(env)).env_parameter_definitions + assert loaded is not None and [(d.name, d.default) for d in loaded] == [("P", 1)] + + def test_an_empty_definitions_list_pickles_as_an_empty_list(self) -> None: + env = pickle.loads( + pickle.dumps(TemplateEnvironment(name="E", env_parameter_definitions=[])) + ) + assert env.env_parameter_definitions == [] + + @pytest.mark.parametrize( + "description, message", + [ + ("", "Description should have at least 1 character"), + ("a\x01b", "Description contains control characters"), + ("x" * 2049, "Description exceeds 2048 characters"), + ], + ) + def test_description_is_checked(self, description: str, message: str) -> None: + with pytest.raises(DecodeValidationError) as excinfo: + TemplateEnvironment(name="E", description=description) + assert str(excinfo.value) == message + + def test_newline_tab_and_carriage_return_are_allowed(self) -> None: + assert TemplateEnvironment(name="E", description="a\n\t\rb").description == "a\n\t\rb" + + +class TestMaxStepEnvironmentEntries: + def test_cap_is_checked_at_decode(self) -> None: + limits = CallerLimits(accept_unreleased_env_params=True, max_step_environment_entries=0) + with pytest.raises(ModelValidationError) as excinfo: + _decode(caller_limits=limits) + assert str(excinfo.value) == ( + "1 validation error for JobTemplate\n" + "steps[1] -> dependencies:\n" + "\texceeds caller limit of 0 'environment' entries (1 entries)." + ) + + def test_step_entries_do_not_count(self) -> None: + limits = CallerLimits(accept_unreleased_env_params=True, max_step_environment_entries=1) + _decode(caller_limits=limits) diff --git a/test/openjd/model_v1/test_known_gaps.py b/test/openjd/model_v1/test_known_gaps.py index 9966817d..ff3ebf2e 100644 --- a/test/openjd/model_v1/test_known_gaps.py +++ b/test/openjd/model_v1/test_known_gaps.py @@ -137,3 +137,38 @@ def test_v0_range_string_renders_in_canonical_form(text: str, expected: str) -> from openjd.model._range_expr import IntRangeExpr assert str(IntRangeExpr.from_str(text)) == expected + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason=( + "openjd-model 0.18.0 does not check the text of a whole-field STRING or " + "PATH range expression at decode; create_job reports the undefined " + "variable instead. v0 refuses it at decode." + ), +) +def test_a_whole_field_string_range_expression_is_checked_at_decode() -> None: + from openjd.model._v1 import decode_job_template + + template = { + "specificationVersion": "jobtemplate-2023-09", + "extensions": ["EXPR"], + "name": "J", + "steps": [ + { + "name": "S", + "parameterSpace": { + "taskParameterDefinitions": [ + {"name": "T", "type": "STRING", "range": "{{ [y] }}"} + ] + }, + "script": {"actions": {"onRun": {"command": "echo"}}}, + } + ], + } + try: + decode_job_template(template=template, supported_extensions=["EXPR"]) + except ValueError: + return + raise AssertionError("decoded a range that reads an undefined variable") diff --git a/test/openjd/model_v1/test_parameter_definition_pickle.py b/test/openjd/model_v1/test_parameter_definition_pickle.py new file mode 100644 index 00000000..9ae9faba --- /dev/null +++ b/test/openjd/model_v1/test_parameter_definition_pickle.py @@ -0,0 +1,276 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Every ``Job*ParameterDefinition`` and ``EnvironmentParameterDefinition`` +pickles through its template form, and so does an Environment that holds +``env_parameter_definitions``.""" + +from __future__ import annotations + +import json +import pickle +from typing import Any + +import pytest + +from openjd._openjd_rs import ( + CallerLimits, + EnvironmentParameterDefinition, + FormatString, + TemplateEnvironment, + decode_job_template, +) + +_UI = {"label": "L", "groupLabel": "G"} + +# Each definition sets every field its type has, so a field that pickle +# drops makes the template form differ from the input. +_DEFINITIONS: list[dict[str, Any]] = [ + { + "name": "S", + "type": "STRING", + "description": "d", + "default": "a", + "allowedValues": ["a", "b"], + "minLength": 1, + "maxLength": 5, + "userInterface": {"control": "DROPDOWN_LIST", **_UI}, + }, + { + "name": "I", + "type": "INT", + "description": "d", + "default": 2, + "allowedValues": [1, 2], + "minValue": 1, + "maxValue": 5, + "userInterface": {"control": "DROPDOWN_LIST", **_UI}, + }, + { + "name": "I2", + "type": "INT", + "minValue": 1, + "userInterface": {"control": "SPIN_BOX", "singleStepDelta": 2, **_UI}, + }, + { + "name": "F", + "type": "FLOAT", + "description": "d", + "default": "1.50", + "minValue": "0.50", + "maxValue": 9.5, + "userInterface": {"control": "SPIN_BOX", "decimals": 2, "singleStepDelta": "0.25", **_UI}, + }, + {"name": "F2", "type": "FLOAT", "default": 1.0, "allowedValues": ["1.0", 2.5]}, + { + "name": "P", + "type": "PATH", + "description": "d", + "default": "a/b", + "minLength": 1, + "maxLength": 9, + "objectType": "FILE", + "dataFlow": "IN", + "userInterface": { + "control": "CHOOSE_INPUT_FILE", + "fileFilters": [{"label": "Images", "patterns": ["*.png"]}], + "fileFilterDefault": {"label": "All", "patterns": ["*"]}, + **_UI, + }, + }, + { + "name": "B", + "type": "BOOL", + "description": "d", + "default": True, + "userInterface": {"control": "CHECK_BOX", **_UI}, + }, + { + "name": "R", + "type": "RANGE_EXPR", + "description": "d", + "default": "1-5", + "minLength": 1, + "maxLength": 10, + "userInterface": {"control": "LINE_EDIT", **_UI}, + }, + { + "name": "LS", + "type": "LIST[STRING]", + "description": "d", + "default": ["a"], + "minLength": 1, + "maxLength": 3, + "item": {"allowedValues": ["a", "b"], "minLength": 1, "maxLength": 2}, + "userInterface": {"control": "LINE_EDIT_LIST", **_UI}, + }, + { + "name": "LP", + "type": "LIST[PATH]", + "description": "d", + "objectType": "DIRECTORY", + "dataFlow": "OUT", + "default": ["a"], + "minLength": 1, + "maxLength": 3, + "item": {"minLength": 1, "maxLength": 9}, + "userInterface": { + "control": "CHOOSE_DIRECTORY_LIST", + "fileFilters": [{"label": "All", "patterns": ["*"]}], + **_UI, + }, + }, + { + "name": "LI", + "type": "LIST[INT]", + "description": "d", + "default": [1, 2], + "minLength": 1, + "maxLength": 3, + "item": {"allowedValues": [1, 2, 3], "minValue": 1, "maxValue": 3}, + "userInterface": {"control": "SPIN_BOX_LIST", "singleStepDelta": 1, **_UI}, + }, + { + "name": "LF", + "type": "LIST[FLOAT]", + "description": "d", + "default": ["1.50", 2.0], + "minLength": 1, + "maxLength": 3, + "item": {"minValue": "0.5", "maxValue": 3.0}, + "userInterface": { + "control": "SPIN_BOX_LIST", + "decimals": 1, + "singleStepDelta": 0.5, + **_UI, + }, + }, + { + "name": "LF2", + "type": "LIST[FLOAT]", + "item": {"allowedValues": [1.5, "2.50"]}, + }, + { + "name": "LB", + "type": "LIST[BOOL]", + "description": "d", + "default": [True, False], + "minLength": 1, + "maxLength": 3, + "userInterface": {"control": "CHECK_BOX_LIST", **_UI}, + }, + { + "name": "LL", + "type": "LIST[LIST[INT]]", + "description": "d", + "default": [[1, 2]], + "minLength": 1, + "maxLength": 3, + "item": {"minLength": 1, "maxLength": 2, "item": {"minValue": 0, "maxValue": 9}}, + "userInterface": {"control": "HIDDEN", **_UI}, + }, +] + + +def _decoded() -> list[Any]: + template = { + "specificationVersion": "jobtemplate-2023-09", + "extensions": ["EXPR"], + "name": "J", + "parameterDefinitions": _DEFINITIONS, + "steps": [{"name": "S", "script": {"actions": {"onRun": {"command": "true"}}}}], + } + definitions = decode_job_template( + template=template, supported_extensions=["EXPR"] + ).parameterDefinitions + assert definitions is not None + return list(definitions) + + +def _template_form(obj: Any) -> Any: + return json.loads(obj.__reduce__()[1][0]) + + +@pytest.mark.parametrize("index", range(len(_DEFINITIONS)), ids=[d["name"] for d in _DEFINITIONS]) +def test_a_job_parameter_definition_pickles_with_every_field(index: int) -> None: + definition = _decoded()[index] + assert _template_form(definition) == _DEFINITIONS[index] + loaded = pickle.loads(pickle.dumps(definition)) + assert type(loaded) is type(definition) + assert _template_form(loaded) == _DEFINITIONS[index] + assert repr(loaded) == repr(definition) + + +def test_a_float_default_keeps_its_spelling() -> None: + loaded = pickle.loads(pickle.dumps(_decoded()[3])) + assert loaded.default == 1.5 + assert _template_form(loaded)["default"] == "1.50" + + +@pytest.mark.parametrize( + "definition", + [ + pytest.param( + {"name": "P", "type": "INT", "default": "{{Param.X}}", "minValue": 1}, id="fs" + ), + pytest.param({"name": "P", "type": "STRING", "default": "plain"}, id="literal"), + pytest.param({"name": "P", "type": "LIST[STRING]", "default": ["{{X}}"]}, id="list"), + pytest.param({"name": "P", "type": "PATH", "allowedValues": ["a", "b"]}, id="no default"), + ], +) +def test_an_environment_parameter_definition_pickles(definition: dict[str, Any]) -> None: + d = EnvironmentParameterDefinition(definition) + loaded = pickle.loads(pickle.dumps(d)) + assert _template_form(loaded) == definition + assert (loaded.name, loaded.type_name) == (d.name, d.type_name) + if isinstance(d.default, FormatString): + assert isinstance(loaded.default, FormatString) + assert loaded.default.raw() == d.default.raw() + else: + assert loaded.default == d.default + + +def test_an_environment_with_definitions_pickles() -> None: + env = TemplateEnvironment( + name="E", + env_parameter_definitions=[ + EnvironmentParameterDefinition({"name": "P", "type": "INT", "default": 1}), + EnvironmentParameterDefinition( + {"name": "Q", "type": "STRING", "default": "{{Param.X}}"} + ), + ], + ) + loaded = pickle.loads(pickle.dumps(env)) + defs = loaded.env_parameter_definitions + assert defs is not None + assert [_template_form(d) for d in defs] == [ + {"name": "P", "type": "INT", "default": 1}, + {"name": "Q", "type": "STRING", "default": "{{Param.X}}"}, + ] + + +def test_a_decoded_job_environment_with_definitions_pickles() -> None: + template = { + "specificationVersion": "jobtemplate-2023-09", + "extensions": ["EXPR", "ENV_PARAMS"], + "name": "J", + "jobEnvironments": [ + { + "name": "E", + "variables": {"A": "b"}, + "envParameterDefinitions": [{"name": "N", "type": "INT", "default": 2}], + } + ], + "steps": [{"name": "S", "script": {"actions": {"onRun": {"command": "true"}}}}], + } + jt = decode_job_template( + template=template, + supported_extensions=["EXPR", "ENV_PARAMS"], + caller_limits=CallerLimits(accept_unreleased_env_params=True), + ) + assert jt.jobEnvironments is not None + loaded = pickle.loads(pickle.dumps(jt.jobEnvironments[0])) + assert loaded.env_parameter_definitions is not None + assert [_template_form(d) for d in loaded.env_parameter_definitions] == [ + {"name": "N", "type": "INT", "default": 2} + ] diff --git a/test/openjd/model_v1/test_parse.py b/test/openjd/model_v1/test_parse.py index f0a1311e..8a4d2326 100644 --- a/test/openjd/model_v1/test_parse.py +++ b/test/openjd/model_v1/test_parse.py @@ -768,6 +768,24 @@ def test_command_under_cap_is_accepted(self) -> None: caller_limits=CallerLimits(max_resolved_arg_len=100), ) + def test_a_command_over_1024_characters_decodes(self) -> None: + """Since openjd-model 0.17.0 (openjd-rs#561) an action ``command`` has no + length limit of its own, as in v0. Before, a 2000-character command was + ``command:\\n\\texceeds 1024 characters.`` The caller cap still bounds it.""" + template = self._template({"command": "x" * 2000}) + assert decode_job_template(template=template, supported_extensions=[]) + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template( + template=template, + supported_extensions=[], + caller_limits=CallerLimits(max_resolved_arg_len=1500), + ) + assert str(excinfo.value) == ( + "1 validation error for JobTemplate\n" + "steps[0] -> script -> actions -> onRun -> command:\n" + "\tis 2000 characters, exceeding the maximum of 1500." + ) + def test_no_cap_accepts_any_length(self) -> None: """Negative control: omitting the cap imposes no limit, which is the only behaviour 0.8.0 had.""" @@ -1546,12 +1564,14 @@ def test_caller_limits_apply_at_the_authored_path( def test_a_malformed_script_fails_to_parse(self) -> None: """The script is now a ``FormatString``, so unbalanced braces fail while parsing - the document. On 0.10.0 the template decoded and ``create_job`` raised.""" + the document. On 0.10.0 the template decoded and ``create_job`` raised. + Since openjd-model 0.18.0 (openjd-rs#634) the message names the field.""" template = self._template([{"name": "S", "bash": {"script": "echo {{ "}}], _FB1) with pytest.raises(DecodeValidationError) as excinfo: decode_job_template(template=template, supported_extensions=_FB1_EXPR) assert str(excinfo.value) == ( - "'jobtemplate-2023-09' failed checks: Failed to parse interpolation expression " + "'jobtemplate-2023-09' failed checks: steps[0] -> bash -> script: " + "Failed to parse interpolation expression " "at [5, 8]. Reason: Braces mismatch.\n echo {{ \n ^~" ) @@ -1696,3 +1716,562 @@ def test_a_comprehension_over_a_fresh_name_in_data_decodes(self) -> None: } ) assert decoded.steps[0].name == "S" + + +def _echo_step(on_run: Optional[dict[str, Any]] = None, **fields: Any) -> dict[str, Any]: + """A step named ``S`` whose ``onRun`` is ``on_run`` (``echo a`` by default), + with ``fields`` added to the step.""" + step: dict[str, Any] = { + "name": "S", + "script": {"actions": {"onRun": on_run or {"command": "echo", "args": ["a"]}}}, + } + step.update(fields) + return step + + +_FAILED_CHECKS = "'jobtemplate-2023-09' failed checks: " + + +class TestFormatStringFieldsRefuseNumbers: + """Since openjd-model 0.17.0 (openjd-rs#633) a number or boolean in a field that + takes a format string is a decode error, as it is in v0 (``String required``). + Before, v1 converted it to text, so ``args: [5]`` decoded as ``"5"``. On + openjd-model 0.16.0 every row here decoded except the host requirements, which + changed exception class: an attribute value ``5`` was ``ModelValidationError + ... value '5' contains invalid characters.``, and an amount or attribute + ``name: 5`` was ``ModelValidationError ... name '5' does not match capability + name pattern.`` + + A STRING or PATH range list is located at its task parameter definition, not at + the element, because that definition is read as a whole.""" + + @pytest.mark.parametrize( + "template, message", + [ + pytest.param( + _one_step_template(name=123), + "name: invalid type: integer `123`, expected a string", + id="job name integer", + ), + pytest.param( + _one_step_template(name=True), + "name: invalid type: boolean `true`, expected a string", + id="job name boolean", + ), + pytest.param( + _one_step_template(steps=[_echo_step({"command": "echo", "args": [5]})]), + "steps[0] -> script -> actions -> onRun -> args[0]: " + "invalid type: integer `5`, expected a string", + id="args integer", + ), + pytest.param( + _one_step_template(steps=[_echo_step({"command": "echo", "args": [1.5]})]), + "steps[0] -> script -> actions -> onRun -> args[0]: " + "invalid type: floating point `1.5`, expected a string", + id="args float", + ), + pytest.param( + _one_step_template(steps=[_echo_step({"command": 5})]), + "steps[0] -> script -> actions -> onRun -> command: " + "invalid type: integer `5`, expected a string", + id="command", + ), + pytest.param( + _one_step_template(jobEnvironments=[{"name": "E", "variables": {"K": True}}]), + "jobEnvironments[0] -> variables -> K: " + "invalid type: boolean `true`, expected a string", + id="environment variable", + ), + pytest.param( + _one_step_template( + steps=[ + { + "name": "S", + "script": { + "actions": {"onRun": {"command": "echo"}}, + "embeddedFiles": [{"name": "f", "type": "TEXT", "data": 5}], + }, + } + ] + ), + "steps[0] -> script -> embeddedFiles[0] -> data: " + "invalid type: integer `5`, expected a string", + id="embedded file data", + ), + pytest.param( + _one_step_template( + steps=[ + _echo_step( + parameterSpace={ + "taskParameterDefinitions": [ + {"name": "P", "type": "STRING", "range": [1, 2]} + ] + } + ) + ] + ), + "steps[0] -> parameterSpace -> taskParameterDefinitions[0]: " + "invalid type: integer `1`, expected a string", + id="STRING range element", + ), + pytest.param( + _one_step_template( + steps=[ + _echo_step( + hostRequirements={ + "attributes": [{"name": "attr.custom.x", "anyOf": [5]}] + } + ) + ] + ), + "steps[0] -> hostRequirements -> attributes[0] -> anyOf[0]: " + "invalid type: integer `5`, expected a string", + id="attribute value", + ), + pytest.param( + _one_step_template( + steps=[ + _echo_step(hostRequirements={"attributes": [{"name": 5, "anyOf": ["a"]}]}) + ] + ), + "steps[0] -> hostRequirements -> attributes[0] -> name: " + "invalid type: integer `5`, expected a string", + id="attribute name", + ), + pytest.param( + _one_step_template( + steps=[_echo_step(hostRequirements={"amounts": [{"name": 5, "min": 1}]})] + ), + "steps[0] -> hostRequirements -> amounts[0] -> name: " + "invalid type: integer `5`, expected a string", + id="amount name", + ), + pytest.param( + _one_step_template( + extensions=["FEATURE_BUNDLE_1"], + steps=[{"name": "S", "bash": {"script": 5}}], + ), + "steps[0] -> bash -> script: invalid type: integer `5`, expected a string", + id="SimpleAction script", + ), + ], + ) + def test_a_number_or_boolean_is_refused(self, template: dict[str, Any], message: str) -> None: + with pytest.raises(DecodeValidationError) as excinfo: + decode_job_template(template=template, supported_extensions=["FEATURE_BUNDLE_1"]) + assert str(excinfo.value) == _FAILED_CHECKS + message + + def test_an_environment_template_variable_is_refused(self) -> None: + with pytest.raises(DecodeValidationError) as excinfo: + decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "environment": {"name": "E", "variables": {"K": 5}}, + } + ) + assert str(excinfo.value) == ( + "'environment-2023-09' failed checks: environment -> variables -> K: " + "invalid type: integer `5`, expected a string" + ) + + @pytest.mark.parametrize( + "step", + [ + pytest.param(_echo_step({"command": "echo", "timeout": 5}), id="timeout"), + pytest.param( + _echo_step(hostRequirements={"amounts": [{"name": "amount.custom.x", "min": 1}]}), + id="amount min", + ), + ], + ) + def test_control_numeric_fields_still_take_numbers(self, step: dict[str, Any]) -> None: + assert decode_job_template(template=_one_step_template(steps=[step])) + + +class TestYamlCoreSchemaInFormatStringFields: + """``decode_job_template_str`` reads YAML with the YAML 1.2 Core schema, and v0 + reads it as YAML 1.1. With openjd-model 0.17.0 (openjd-rs#633) refusing numbers in + format-string fields, ``1e3`` and ``0o17`` are numbers here and refused, where v0 + keeps them as the strings ``"1e3"`` and ``"0o17"``. Before, v1 converted them to + ``"1000"`` and ``"15"``. In the other direction, ``yes``, ``.inf``, a timestamp + and a base-60 integer are strings here and ``String required`` in v0, before and + after.""" + + @staticmethod + def _args(value: str) -> str: + return ( + "specificationVersion: jobtemplate-2023-09\n" + "name: J\n" + "steps:\n" + "- name: S\n" + " script:\n" + " actions:\n" + " onRun:\n" + " command: echo\n" + f" args: [{value}]\n" + ) + + @pytest.mark.parametrize( + "value, message", + [ + pytest.param("1e3", "invalid type: floating point `1000.0`, expected a string"), + pytest.param("0o17", "invalid type: integer `15`, expected a string"), + pytest.param("1_000", "invalid type: integer `1000`, expected a string"), + ], + ) + def test_a_yaml_1_2_number_is_refused(self, value: str, message: str) -> None: + with pytest.raises(DecodeValidationError) as excinfo: + decode_job_template_str(self._args(value)) + assert str(excinfo.value) == ( + _FAILED_CHECKS + "steps[0] -> script -> actions -> onRun -> args[0]: " + message + ) + + @pytest.mark.parametrize("value", ["yes", ".inf", "2001-12-14", "1:30"]) + def test_a_yaml_1_1_only_scalar_is_a_string(self, value: str) -> None: + t = decode_job_template_str(self._args(value)) + assert t.steps[0].script is not None + on_run = t.steps[0].script.actions.on_run + assert on_run.args is not None + assert [str(a) for a in on_run.args] == [value] + + +class TestComplexExpressionsNeedExprInEveryFormatString: + """Since openjd-model 0.17.0 (openjd-rs#633), without EXPR every format-string + interpolation must be a bare dotted name, in every field, as v0 requires. Before, + only ``variables``, ``command``/``args`` and environment ``data`` were checked, + so every row here decoded on openjd-model 0.16.0. A parenthesized name is + complex too.""" + + _P = [{"name": "P", "type": "STRING", "default": "x"}] + _COMPLEX = "\n\tcomplex expressions require the EXPR extension." + + @pytest.mark.parametrize( + "template, path", + [ + pytest.param( + _one_step_template(name="{{ Param.P + 'a' }}", parameterDefinitions=_P), + "name:", + id="job name operator", + ), + pytest.param( + _one_step_template(name="J{{ (Param.P) }}", parameterDefinitions=_P), + "name:", + id="job name parenthesized", + ), + pytest.param( + _one_step_template( + parameterDefinitions=_P, + steps=[ + _echo_step( + parameterSpace={ + "taskParameterDefinitions": [ + { + "name": "T", + "type": "STRING", + "range": ["{{ Param.P.upper() }}"], + } + ] + } + ) + ], + ), + "steps[0] -> parameterSpace -> taskParameterDefinitions[0] -> range[0]:", + id="range element", + ), + pytest.param( + _one_step_template( + parameterDefinitions=_P, + steps=[ + _echo_step( + hostRequirements={ + "attributes": [ + {"name": "attr.custom.x", "anyOf": ["{{ Param.P.upper() }}"]} + ] + } + ) + ], + ), + "steps[0] -> hostRequirements -> attributes[0] -> anyOf[0]:", + id="attribute value", + ), + pytest.param( + _one_step_template( + parameterDefinitions=_P, + steps=[ + _echo_step( + hostRequirements={ + "amounts": [{"name": "{{ 'amount.custom.a' }}", "min": 1}] + } + ) + ], + ), + "steps[0] -> hostRequirements -> amounts[0] -> name:", + id="amount name", + ), + pytest.param( + _one_step_template( + parameterDefinitions=_P, + steps=[ + _echo_step( + hostRequirements={ + "attributes": [{"name": "{{ 'attr.custom.a' }}", "anyOf": ["x"]}] + } + ) + ], + ), + "steps[0] -> hostRequirements -> attributes[0] -> name:", + id="attribute name", + ), + pytest.param( + _one_step_template( + parameterDefinitions=_P, + steps=[ + { + "name": "S", + "script": { + "actions": {"onRun": {"command": "echo"}}, + "embeddedFiles": [ + {"name": "f", "type": "TEXT", "data": "{{ Param.P * 2 }}"} + ], + }, + } + ], + ), + "steps[0] -> script -> embeddedFiles[0] -> data:", + id="step embedded file data", + ), + pytest.param( + _one_step_template( + extensions=["FEATURE_BUNDLE_1"], + parameterDefinitions=[{"name": "N", "type": "INT", "default": 5}], + steps=[_echo_step({"command": "echo", "timeout": "{{ Param.N + 1 }}"})], + ), + "steps[0] -> script -> actions -> onRun -> timeout:", + id="timeout", + ), + ], + ) + def test_a_complex_interpolation_is_refused(self, template: dict[str, Any], path: str) -> None: + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template(template=template, supported_extensions=["FEATURE_BUNDLE_1"]) + assert str(excinfo.value) == "1 validation error for JobTemplate\n" + path + self._COMPLEX + + @pytest.mark.parametrize("ptype", ["STRING", "PATH"]) + def test_a_whole_field_range_expression_is_refused(self, ptype: str) -> None: + template = _one_step_template( + parameterDefinitions=self._P, + steps=[ + _echo_step( + parameterSpace={ + "taskParameterDefinitions": [ + {"name": "T", "type": ptype, "range": "{{ [Param.P] }}"} + ] + } + ) + ], + ) + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template(template=template) + assert str(excinfo.value) == ( + "1 validation error for JobTemplate\n" + "steps[0] -> parameterSpace -> taskParameterDefinitions[0] -> range:\n" + "\tA range expression (format string) requires the EXPR extension." + ) + + def test_control_a_bare_name_decodes(self) -> None: + template = _one_step_template(name="J{{ Param.P }}", parameterDefinitions=self._P) + assert decode_job_template(template=template).name == "J{{ Param.P }}" + + +class TestDecodeErrorsNameTheirLocation: + """Since openjd-model 0.18.0 (openjd-rs#634) a ``DecodeValidationError`` names + where decoding failed, on one line: ``'' failed checks: : + ``. Before, these rows had no path. An unknown key's path ends at the + key. A missing key's path ends at its parent, where v0's ends at the key. A + parameter definition is located at its list entry, because it is read as a + whole. A missing top-level key has no path.""" + + @pytest.mark.parametrize( + "template, message", + [ + pytest.param( + _one_step_template(steps=[_echo_step({"command": "echo", "bogusKey": 1})]), + "steps[0] -> script -> actions -> onRun -> bogusKey: unknown field `bogusKey`, " + "expected one of `command`, `args`, `cancelation`, `timeout`", + id="unknown key", + ), + pytest.param( + _one_step_template(steps=[_echo_step({"args": ["a"]})]), + "steps[0] -> script -> actions -> onRun: missing field `command`", + id="missing key", + ), + pytest.param( + _one_step_template(parameterDefinitions=[{"name": "P", "type": "INT", "bogus": 1}]), + "parameterDefinitions[0]: unknown field `bogus`, expected one of `name`, " + "`description`, `default`, `allowedValues`, `minValue`, `maxValue`, " + "`userInterface`", + id="unknown key in a parameter definition", + ), + pytest.param( + {"specificationVersion": "jobtemplate-2023-09", "name": "J"}, + "missing field `steps`", + id="missing top-level key", + ), + ], + ) + def test_the_message_starts_with_the_path(self, template: dict[str, Any], message: str) -> None: + with pytest.raises(DecodeValidationError) as excinfo: + decode_job_template(template=template) + assert str(excinfo.value) == _FAILED_CHECKS + message + + +class TestOneEnvironmentWithWrapHooksPerSession: + """Since openjd-model 0.18.0 (openjd-rs#634) the rule that a Session enters at + most one Environment with wrap hooks (RFC 0008) is reported at the Step, names + the Environments, and is reported once for the Steps that share them. Before, + and in v0, it was ``jobEnvironments:\\n\\tonly one environment in the session + stack may define any of onWrapEnvEnter, onWrapTaskRun, onWrapEnvExit (RFC + 0008).`` (``steps[0] -> stepEnvironments`` for a Step Environment).""" + + _EXTS = ["WRAP_ACTIONS", "EXPR"] + + @staticmethod + def _wrap(name: str) -> dict[str, Any]: + return { + "name": name, + "script": { + "actions": { + "onWrapEnvEnter": {"command": "w"}, + "onWrapEnvExit": {"command": "w"}, + "onWrapTaskRun": {"command": "w", "args": ["{{ WrappedAction.Command }}"]}, + } + }, + } + + def _decode_error(self, template: dict[str, Any]) -> str: + template["extensions"] = self._EXTS + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template(template=template, supported_extensions=self._EXTS) + return str(excinfo.value) + + def test_two_job_environments_shared_by_two_steps(self) -> None: + message = self._decode_error( + _one_step_template( + jobEnvironments=[self._wrap("Outer"), self._wrap("Inner")], + steps=[_echo_step(), dict(_echo_step(), name="S2")], + ) + ) + assert message == ( + "1 validation error for JobTemplate\n" + "steps[0]:\n" + "\tthe Sessions of Steps 'S' and 'S2' would enter 2 Environments that define " + "wrap hooks (onWrapEnvEnter, onWrapTaskRun, onWrapEnvExit): 'Outer', 'Inner'. " + "A Session may have at most one Environment defining wrap hooks (RFC 0008)." + ) + + def test_with_no_steps_only_the_missing_steps_error_is_reported(self) -> None: + """The rule is checked per Step, so a template with no Steps gets only the + no-step error. Before, it also got the wrap-hooks error at + ``jobEnvironments``.""" + message = self._decode_error( + _one_step_template(jobEnvironments=[self._wrap("Outer"), self._wrap("Inner")], steps=[]) + ) + assert message == ( + "1 validation error for JobTemplate\nJobTemplate: must have at least one step." + ) + + def test_a_job_environment_and_a_step_environment(self) -> None: + message = self._decode_error( + _one_step_template( + jobEnvironments=[self._wrap("Outer")], + steps=[_echo_step(stepEnvironments=[self._wrap("Inner")])], + ) + ) + assert message == ( + "1 validation error for JobTemplate\n" + "steps[0]:\n" + "\tits Sessions would enter 2 Environments that define wrap hooks " + "(onWrapEnvEnter, onWrapTaskRun, onWrapEnvExit): 'Outer', 'Inner' " + "(stepEnvironments). A Session may have at most one Environment defining " + "wrap hooks (RFC 0008)." + ) + + +class TestOneErrorPerCause: + """Since openjd-model 0.18.0 (openjd-rs#634) one mistake gives one error. Each + test asserts the whole message, which pins the count. On openjd-model 0.16.0 a + bad step ``let`` gave 4 errors with ``hostRequirements`` and 3 without, an + Environment Template with neither ``script`` nor ``variables`` gave the same + error twice, and a script ``let`` shadowing a step ``let`` also reported a type + error in a Step Environment that read the outer binding.""" + + _RANGE_READS_X = { + "taskParameterDefinitions": [{"name": "T", "type": "INT", "range": "{{ x }}"}] + } + + def _decode_error(self, step: dict[str, Any]) -> str: + with pytest.raises(ModelValidationError) as excinfo: + decode_job_template( + template=_one_step_template(extensions=["EXPR"], steps=[step]), + supported_extensions=["EXPR"], + ) + return str(excinfo.value) + + def test_a_step_let_that_does_not_parse(self) -> None: + step = _echo_step( + {"command": "echo", "args": ["{{ x }}"]}, + let=["x = 1 +"], + hostRequirements={"amounts": [{"name": "amount.worker.vcpu", "min": 1}]}, + parameterSpace=self._RANGE_READS_X, + ) + assert self._decode_error(step) == ( + "1 validation error for JobTemplate\n" + "steps[0] -> let[0]:\n" + "\tInvalid expression in let binding 'x': Syntax error: Expected an expression\n" + " x = 1 +\n" + " ^~~" + ) + + def test_a_step_let_that_fails_to_evaluate(self) -> None: + step = _echo_step( + {"command": "echo", "args": ["{{ x }}"]}, + let=["x = 1 // 0"], + parameterSpace=self._RANGE_READS_X, + ) + assert self._decode_error(step) == ( + "1 validation error for JobTemplate\n" + "steps[0] -> let[0]:\n" + "\tInvalid expression in let binding 'x': Division by zero\n" + " x = 1 // 0\n" + " ~~^~~~" + ) + + def test_a_script_let_shadowing_a_step_let(self) -> None: + step = { + "name": "S", + "let": ["a = 1"], + "stepEnvironments": [{"name": "SE", "variables": {"V": "{{ a + 1 }}"}}], + "script": { + "let": ["a = 'x'"], + "actions": {"onRun": {"command": "echo", "args": ["{{ a }}"]}}, + }, + } + assert self._decode_error(step) == ( + "1 validation error for JobTemplate\n" + "steps[0] -> script -> let[0]:\n" + "\t'a' shadows enclosing scope." + ) + + def test_an_environment_template_with_neither_script_nor_variables(self) -> None: + with pytest.raises(ModelValidationError) as excinfo: + decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "environment": {"name": "E"}, + } + ) + assert str(excinfo.value) == ( + "1 validation error for EnvironmentTemplate\n" + "environment:\n" + "\tmust have at least one of 'script' or 'variables'." + ) diff --git a/test/openjd/model_v1/test_pickle.py b/test/openjd/model_v1/test_pickle.py index 059a51ea..5f576b6c 100644 --- a/test/openjd/model_v1/test_pickle.py +++ b/test/openjd/model_v1/test_pickle.py @@ -53,6 +53,10 @@ "openjd._openjd_rs.ModelExtension.FEATURE_BUNDLE_1", "openjd._openjd_rs.ModelExtension.EXPR", "openjd._openjd_rs.ModelExtension.WRAP_ACTIONS", + "openjd._openjd_rs.ModelExtension.ENV_PARAMS", + "openjd._openjd_rs.EnvironmentActivation.ALWAYS", + "openjd._openjd_rs.EnvironmentActivation.BY_DEFAULT", + "openjd._openjd_rs.EnvironmentActivation.ON_REQUEST", "openjd._openjd_rs.TemplateSpecificationVersion.JOBTEMPLATE_v2023_09", "openjd._openjd_rs.TemplateSpecificationVersion.ENVIRONMENT_v2023_09", ], @@ -133,6 +137,8 @@ def test_caller_limits_round_trip_default(): assert loaded.max_template_size is None assert loaded.max_resolved_arg_len is None assert loaded.max_eval_operations is None + assert loaded.max_step_environment_entries is None + assert loaded.accept_unreleased_env_params is False def test_caller_limits_round_trip_populated(): @@ -149,8 +155,13 @@ def test_caller_limits_round_trip_populated(): max_resolved_data_len=65536, max_eval_memory_bytes=1_048_576, max_eval_operations=100_000, + max_step_environment_entries=50, + accept_unreleased_env_params=True, ) loaded = pickle.loads(pickle.dumps(limits)) + assert loaded.max_step_environment_entries == 50 + assert loaded.accept_unreleased_env_params is True + assert loaded == limits assert loaded.max_step_count == 10 assert loaded.max_env_count == 5 assert loaded.max_task_count == 1_000_000 @@ -276,6 +287,17 @@ def test_caller_limits_equality_negative(): c = CallerLimits() assert a != b assert a != c + # repr writes Python, not Rust's ``Some(..)``. + assert repr(CallerLimits(max_step_count=5, accept_unreleased_env_params=True)) == ( + "CallerLimits(max_step_count=5, max_env_count=None, max_task_count=None, " + "max_step_script_size=None, max_environment_size=None, max_template_size=None, " + "max_resolved_arg_len=None, max_resolved_data_len=None, " + "max_eval_memory_bytes=None, max_eval_operations=None, " + "max_step_environment_entries=None, accept_unreleased_env_params=True)" + ) + # The two fields openjd-model 0.18.0 added take part in equality too. + assert CallerLimits(max_step_environment_entries=1) != c + assert CallerLimits(accept_unreleased_env_params=True) != c def test_validation_context_equality_after_pickle(): diff --git a/test/openjd/model_v1/test_pyclass_modules.py b/test/openjd/model_v1/test_pyclass_modules.py index 9816a16d..0901a88e 100644 --- a/test/openjd/model_v1/test_pyclass_modules.py +++ b/test/openjd/model_v1/test_pyclass_modules.py @@ -107,6 +107,10 @@ "TemplateStepActions": "openjd.model._v1.template", "TemplateStepDependency": "openjd.model._v1.template", "TemplateStepScript": "openjd.model._v1.template", + # ENV_PARAMS extension types (openjd-rs#641) + "EnvironmentActivation": "openjd.model._v1.template", + "EnvironmentParameterDefinition": "openjd.model._v1.template", + "ExprField": "openjd.model._v1.template", # openjd.model._v1.job "Action": "openjd.model._v1.job", "AmountRequirement": "openjd.model._v1.job", diff --git a/test/openjd/model_v1/test_step_param_space_iter.py b/test/openjd/model_v1/test_step_param_space_iter.py index b611c688..12212f64 100644 --- a/test/openjd/model_v1/test_step_param_space_iter.py +++ b/test/openjd/model_v1/test_step_param_space_iter.py @@ -23,6 +23,7 @@ create_job, decode_job_template, ) +from openjd.model._v1.errors import DecodeValidationError from openjd.model._v1.job import ( StepParameterSpace, StepParameterSpaceIterator, @@ -1118,3 +1119,136 @@ def _frames(range_values: list[str], default_task_count: int) -> list[str]: ) def test_chunk_renders_in_canonical_form(self, range_values: list[str], expected: str) -> None: assert self._frames(range_values, default_task_count=4) == [expected] + + +def _job_step_values( + task_parameter_definitions: list[dict[str, Any]], + *, + combination: Optional[str] = None, + extensions: Optional[list[str]] = None, +) -> list[dict[str, str]]: + """Decode a one-step template, create the job and return each yielded + task parameter set as ``{name: value}`` text, in iteration order.""" + space: dict[str, Any] = {"taskParameterDefinitions": task_parameter_definitions} + if combination is not None: + space["combination"] = combination + template: dict[str, Any] = { + "specificationVersion": "jobtemplate-2023-09", + "name": "T", + "steps": [ + { + "name": "S", + "parameterSpace": space, + "script": {"actions": {"onRun": {"command": "echo"}}}, + } + ], + } + if extensions: + template["extensions"] = extensions + t = decode_job_template(template=template, supported_extensions=extensions) + step = create_job(job_template=t, job_parameter_values={}).steps[0] + return [ + {name: value.value for name, value in params.items()} + for params in StepParameterSpaceIterator(step=step) + ] + + +class TestChunkOrderMatchesTheReference: + """openjd-model 0.17.0 (openjd-rs#633) orders and sizes chunks as the + pure-Python reference does. Before, an adaptive ``CHUNK[INT]`` written + first in ``C * P`` iterated outermost (``C 1-2, P 1``, ``C 1-2, P 2``, ...), + and static ``NONCONTIGUOUS`` chunking put the leftover values at the end + (``1-10`` by 3 gave ``1-3``, ``4-6``, ``7,8``, ``9,10``).""" + + _ADAPTIVE = { + "name": "C", + "type": "CHUNK[INT]", + "range": "1-4", + "chunks": { + "defaultTaskCount": 2, + "targetRuntimeSeconds": 10, + "rangeConstraint": "CONTIGUOUS", + }, + } + _P = {"name": "P", "type": "INT", "range": [1, 2]} + + @pytest.mark.parametrize( + "definitions, combination", + [ + pytest.param([_ADAPTIVE, _P], "C * P", id="chunk written first"), + pytest.param([_P, _ADAPTIVE], "P * C", id="control: chunk written last"), + pytest.param([_P, _ADAPTIVE], None, id="control: default combination"), + ], + ) + def test_an_adaptive_chunk_parameter_iterates_innermost( + self, definitions: list[dict[str, Any]], combination: Optional[str] + ) -> None: + values = _job_step_values( + definitions, combination=combination, extensions=["TASK_CHUNKING"] + ) + assert values == [ + {"P": "1", "C": "1-2"}, + {"P": "1", "C": "3-4"}, + {"P": "2", "C": "1-2"}, + {"P": "2", "C": "3-4"}, + ] + + @pytest.mark.parametrize( + "range_values, expected", + [ + pytest.param("1-10", ["1-3", "4,5", "6-8", "9,10"], id="contiguous values"), + pytest.param("1-3,5,7-12", ["1-3", "5,7", "8-10", "11,12"], id="values with gaps"), + ], + ) + def test_static_noncontiguous_chunks_spread_the_leftover_values( + self, range_values: str, expected: list[str] + ) -> None: + definition = { + "name": "C", + "type": "CHUNK[INT]", + "range": range_values, + "chunks": {"defaultTaskCount": 3, "rangeConstraint": "NONCONTIGUOUS"}, + } + values = _job_step_values([definition], extensions=["TASK_CHUNKING"]) + assert [v["C"] for v in values] == expected + + +class TestTwoChunkParametersInADirectlyBuiltSpace: + """Since openjd-model 0.17.0 (openjd-rs#612) a ``StepParameterSpace`` built + directly with two ``CHUNK[INT]`` parameters is refused when an iterator is + built over it. Before, it iterated and used only ``A``'s chunk metadata. A template with two + is refused at decode, before and after.""" + + def test_two_chunk_parameters_are_refused(self) -> None: + def chunk() -> dict[str, Any]: + return { + "type": "CHUNK[INT]", + "range": RangeExpr("1-4"), + "chunks": {"defaultTaskCount": 2, "rangeConstraint": "CONTIGUOUS"}, + } + + space = StepParameterSpace( + taskParameterDefinitions={"A": chunk(), "B": chunk()}, combination="A * B" + ) + with pytest.raises(DecodeValidationError) as excinfo: + StepParameterSpaceIterator(space=space) + assert str(excinfo.value) == ( + "Task parameters 'A' and 'B' are both CHUNK[INT]: " + "only one CHUNK[INT] parameter is allowed per step." + ) + + +class TestTheSmallestInt64: + """Since openjd-model 0.17.0 (openjd-rs#633) ``-9223372036854775808`` (i64::MIN) + is accepted in an INT range, as v0 accepts it. Before, it was ``INT parameter + 'T' range expression error: Invalid integer '9223372036854775808' in ...``.""" + + def test_an_int_range_starting_at_the_smallest_int64(self) -> None: + values = _job_step_values( + [{"name": "T", "type": "INT", "range": "-9223372036854775808--9223372036854775806"}] + ) + assert values == [ + {"T": "-9223372036854775808"}, + {"T": "-9223372036854775807"}, + {"T": "-9223372036854775806"}, + ] diff --git a/test/openjd/model_v1/test_task_parameter.py b/test/openjd/model_v1/test_task_parameter.py index 5467c852..b64a90d5 100644 --- a/test/openjd/model_v1/test_task_parameter.py +++ b/test/openjd/model_v1/test_task_parameter.py @@ -14,11 +14,9 @@ * ``ChunkIntTaskParameter`` — ``range: list[int] | RangeExpr``, ``chunks: TaskChunksDefinition`` -``IntTaskParameter`` deliberately does NOT carry a ``chunks`` field -even though the underlying Rust struct has -``chunks: Option`` — no resolver path ever produces -``Some(_)`` on the ``Int`` variant; chunks are exclusively a -``ChunkInt`` concern. +``IntTaskParameter`` has no ``chunks`` field. Since openjd-model 0.17.0 +(openjd-rs#612) the Rust ``Int`` variant has none either; chunks are +exclusively a ``ChunkInt`` concern. See ``reports/model-bindings-quality-evaluation-report.md`` Rec #6. """ diff --git a/test/openjd/model_v1/test_template_types.py b/test/openjd/model_v1/test_template_types.py index b47a9dd9..b83a5821 100644 --- a/test/openjd/model_v1/test_template_types.py +++ b/test/openjd/model_v1/test_template_types.py @@ -19,6 +19,7 @@ from openjd.expr import ExpressionError, FormatString from openjd.model._v1 import decode_environment_template, decode_job_template +from openjd.model._v1.errors import DecodeValidationError from openjd.model._v1.template import ( Action, AmountRequirement, @@ -150,6 +151,95 @@ def test_environment_accessor(self): assert isinstance(e, Environment) assert e.name == "EnvX" + def test_profile(self): + """``EnvironmentTemplate.profile`` gives the revision and the listed + extensions, as ``JobTemplate.profile`` does (openjd-model 0.18.0).""" + from openjd.model._v1.types import ModelExtension, SpecificationRevision + + et = decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "extensions": ["EXPR"], + "environment": {"name": "EnvX", "variables": {"K": "v"}}, + }, + supported_extensions=["EXPR"], + ) + assert et.profile.revision == SpecificationRevision.v2023_09 + assert et.profile.extensions == [ModelExtension.EXPR] + no_exts = decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "environment": {"name": "EnvX", "variables": {"K": "v"}}, + } + ) + assert no_exts.profile.extensions == [] + + @pytest.mark.parametrize( + "description, message", + [ + ("a\x01b", "Description contains control characters"), + ("x" * 2049, "2048"), + ("", "Description should have at least 1 character"), + ], + ) + def test_decoding_checks_the_description(self, description, message): + """Decoding checks every ```` (Template Schemas §7.2) + at its path (openjd-model 0.18.0). An empty one is refused since + openjd-model 0.17.0 (openjd-rs#633); before, it decoded.""" + with pytest.raises(DecodeValidationError) as excinfo: + decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "environment": { + "name": "EnvX", + "description": description, + "variables": {"K": "v"}, + }, + } + ) + assert "environment -> description" in str(excinfo.value) + assert message in str(excinfo.value) + + +class TestEmptyDescriptionIsRefused: + """Since openjd-model 0.17.0 (openjd-rs#633) decoding refuses ``description: ""`` + in every ```` field (Template Schemas §7.2: at least 1 character), + as v0 does (``String should have at least 1 character``). On openjd-model 0.16.0 + each row decoded. A parameter definition is located at its list entry, because + it is read as a whole.""" + + _STEP = {"name": "S", "script": {"actions": {"onRun": {"command": "echo"}}}} + + @pytest.mark.parametrize( + "overrides, path", + [ + pytest.param({"description": ""}, "description", id="job"), + pytest.param( + {"steps": [dict(_STEP, description="")]}, "steps[0] -> description", id="step" + ), + pytest.param( + {"parameterDefinitions": [{"name": "P", "type": "STRING", "description": ""}]}, + "parameterDefinitions[0]", + id="parameter definition", + ), + pytest.param( + {"jobEnvironments": [{"name": "E", "description": "", "variables": {"K": "v"}}]}, + "jobEnvironments[0] -> description", + id="job environment", + ), + ], + ) + def test_an_empty_description_is_refused(self, overrides, path): + with pytest.raises(DecodeValidationError) as excinfo: + _job_template(**overrides) + assert str(excinfo.value) == ( + f"'jobtemplate-2023-09' failed checks: {path}: " + "Validation error: Description should have at least 1 character" + ) + + def test_control_a_single_space_is_kept(self): + assert _job_template(description=" ").description == " " + class TestStepTemplate: def test_basic_fields(self): diff --git a/test/openjd/model_v1/test_version_enums.py b/test/openjd/model_v1/test_version_enums.py index 945c6415..2f7374dd 100644 --- a/test/openjd/model_v1/test_version_enums.py +++ b/test/openjd/model_v1/test_version_enums.py @@ -60,6 +60,9 @@ def test_template_specification_version_returned_from_decode(self) -> None: assert t.specification_version.value == "jobtemplate-2023-09" +_UNRELEASED_EXTENSION = "ENV_PARAMS" + + def _rust_extension_members() -> set[str]: # `ModelExtension` is a PyO3 pyclass enum, not a real `enum.Enum`, so # it is not iterable. Discover members by identity instead of relying @@ -92,7 +95,21 @@ def test_binding_members_match_python_extension_names(self) -> None: # set of 2023-09 extensions. Divergence in either direction is a # bug: a missing member means the catch-all aliases it to the # wrong extension; an extra member means Python cannot name it. - assert _rust_extension_members() == {e.value for e in ExtensionName} + # ENV_PARAMS (openjd-rs#641) is the one exception: openjd-model + # decodes it behind an unstable opt-in, and the pure-Python model + # does not know it. + assert _rust_extension_members() == {e.value for e in ExtensionName} | { + _UNRELEASED_EXTENSION + } + + def test_the_unreleased_extension_maps_to_itself(self) -> None: + # ENV_PARAMS has its own member, so a profile that lists it enables + # ENV_PARAMS and not, through the catch-all, EXPR. ``from_str`` + # does not parse it, as openjd-model's ``FromStr`` does not, so an + # allowlist built from names cannot enable it by accident. + ext = ModelExtension.ENV_PARAMS + assert ext.as_str() == ext.name == _UNRELEASED_EXTENSION + assert ModelExtension.from_str(_UNRELEASED_EXTENSION) is None @pytest.mark.parametrize("name", [e.value for e in ExtensionName]) def test_name_round_trips_to_its_own_member(self, name: str) -> None: @@ -103,3 +120,27 @@ def test_name_round_trips_to_its_own_member(self, name: str) -> None: assert parsed is not None, f"{name} is not recognized by the Rust binding" assert parsed.name == name assert parsed.as_str() == name + + +class TestTaskParameterTypeExprTypes: + """``expr_type`` types ``Task.Param.`` and ``raw_expr_type`` types + ``Task.RawParam.``; they differ only for PATH (openjd-model 0.18.0, + openjd-rs#638).""" + + @pytest.mark.parametrize( + "name, param, raw", + [ + ("INT", "int", "int"), + ("FLOAT", "float", "float"), + ("STRING", "string", "string"), + ("PATH", "path", "string"), + ("CHUNK_INT", "range_expr", "range_expr"), + ], + ) + def test_types(self, name: str, param: str, raw: str) -> None: + from openjd.expr import ExprType + from openjd.model._v1.types import TaskParameterType + + t = getattr(TaskParameterType, name) + assert t.expr_type() == ExprType(param) + assert t.raw_expr_type() == ExprType(raw) diff --git a/test/openjd/sessions/test_failed_actions.py b/test/openjd/sessions/test_failed_actions.py index a0303f93..1e7cb559 100644 --- a/test/openjd/sessions/test_failed_actions.py +++ b/test/openjd/sessions/test_failed_actions.py @@ -1,7 +1,7 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -"""How ``Session`` handles a failed action, through openjd-sessions 0.10.0. +"""How ``Session`` handles a failed action, through openjd-sessions 0.12.1. - openjd-rs#532: when ``run_task``, ``enter_environment`` or ``exit_environment`` fails before its subprocess starts, for example because a parameter value can't be coerced, @@ -18,6 +18,9 @@ - openjd-rs#530: white space around a number in an INT or FLOAT parameter value is ignored. Before, such a value failed before the action started, which the binding didn't report, so the task silently didn't run. +- openjd-rs#639: a PATH or LIST[PATH] job or task parameter value that isn't + a string or a path fails the action. Before, the action ran with an empty + path, or with the value's text for ``RawParam``. What a session does with a call it refuses is in ``test_refused_calls.py``. """ @@ -29,6 +32,8 @@ from pathlib import Path from typing import Any +import pytest + from openjd._openjd_rs import ( ActionState, Session, @@ -195,3 +200,98 @@ def test_white_space_around_a_numeric_parameter_value_is_ignored(tmp_path: Path) assert out.read_text() == "7|1.50" finally: session.cleanup() + + +@pytest.mark.parametrize( + "job_parameter_values, task_parameter_values, message", + [ + pytest.param( + {"P": {"type": "PATH", "value": 5}}, + None, + "Failed to coerce parameter 'Param.P': Cannot coerce int to path", + id="job int", + ), + pytest.param( + {}, + {"P": {"type": "PATH", "value": 5}}, + "Failed to coerce parameter 'Task.Param.P': Cannot coerce int to path", + id="task int", + ), + pytest.param( + {"P": {"type": "PATH", "value": None}}, + None, + "Failed to coerce parameter 'Param.P': Cannot coerce nulltype to path", + id="job None", + ), + pytest.param( + {"P": {"type": "PATH", "value": True}}, + None, + "Failed to coerce parameter 'Param.P': Cannot coerce bool to path", + id="job bool", + ), + pytest.param( + {"P": {"type": "PATH", "value": 1.5}}, + None, + "Failed to coerce parameter 'Param.P': Cannot coerce float to path", + id="job float", + ), + pytest.param( + {"P": {"type": "LIST[PATH]", "value": [1]}}, + None, + "Failed to coerce parameter 'Param.P': Cannot coerce int to path", + id="job LIST[PATH] of int", + ), + pytest.param( + {}, + {"P": {"type": "PATH", "value": ["/a"]}}, + "Failed to coerce parameter 'Task.RawParam.P': Cannot coerce list[string] to string", + id="task list", + ), + pytest.param( + {}, + {"P": {"type": "PATH", "value": None}}, + "Failed to coerce parameter 'Task.RawParam.P': Cannot coerce nulltype to string", + id="task None", + ), + ], +) +def test_a_path_parameter_value_that_is_not_a_path_fails_the_action( + tmp_path: Path, + job_parameter_values: dict[str, Any], + task_parameter_values: Any, + message: str, +) -> None: + session = Session( + session_id="s", + job_parameter_values=job_parameter_values, + session_root_directory=str(tmp_path), + ) + try: + session.run_task( + step_script=_step_script(_python("")), + task_parameter_values=task_parameter_values, + ) + _settle(session) + status = session.action_status + assert status is not None + assert (status.state, status.fail_message) == (ActionState.FAILED, message) + assert session.state == SessionState.READY_ENDING + finally: + session.cleanup() + + +def test_a_value_that_is_not_an_expr_value_raises_type_error(tmp_path: Path) -> None: + """A Python value with no ``ExprValue`` form raises from the call, and no + action starts, so the session stays ``READY``.""" + session = Session(session_id="s", job_parameter_values={}, session_root_directory=str(tmp_path)) + try: + with pytest.raises(TypeError) as excinfo: + session.run_task( + step_script=_step_script(_python("")), + task_parameter_values={"P": {"type": "PATH", "value": Path("/a")}}, + ) + # PosixPath or WindowsPath, depending on the host. + assert str(excinfo.value) == f"Cannot convert {type(Path('/a')).__name__} to ExprValue" + assert session.state == SessionState.READY + finally: + session.cleanup() diff --git a/test/openjd/sessions/test_known_gaps.py b/test/openjd/sessions/test_known_gaps.py new file mode 100644 index 00000000..93fcd4de --- /dev/null +++ b/test/openjd/sessions/test_known_gaps.py @@ -0,0 +1,94 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Known gaps in how the sessions binding resolves values. + +Each test is a strict xfail. When a gap is fixed, move its test next to the +surface it covers rather than leaving it here. +""" + +from __future__ import annotations + +import sys +import time +from pathlib import Path + +import pytest + +from openjd._openjd_rs import ActionState, ExprValue, Session, SessionState, deserialize_step + +# ── A PATH job parameter's RawParam is still a path ── +# +# openjd-rs#638 binds ``Task.RawParam.`` of a PATH task value given as +# a path ``ExprValue`` as a string, so ``Task.RawParam.P.upper()`` works +# (``test_parameter_values.py``). The same value for a job parameter still +# binds ``RawParam.`` as a path, so ``RawParam.P.upper()`` fails with +# ``Failed to resolve argument: upper() is not available for path. Available +# for: string``, as it did before openjd-rs#638. Upstream left the job +# parameter case out of scope (openjd-rs#638 audit item A4). A job parameter +# given as a ``str`` binds ``RawParam`` as a string and is not affected. + + +@pytest.mark.xfail( + reason="openjd-rs#638 A4: job RawParam of PATH keeps a path value", + strict=True, +) +def test_a_path_job_value_binds_raw_param_as_a_string(tmp_path: Path) -> None: + out = tmp_path / "out.txt" + code = "import sys; open(sys.argv[1], 'w').write('|'.join(sys.argv[2:]))" + action = { + "command": sys.executable, + "args": ["-c", code, str(out), "{{Param.P}}", "{{ RawParam.P.upper() }}"], + } + script = deserialize_step({"name": "S", "script": {"actions": {"onRun": action}}}).script + session = Session( + session_id="s", + job_parameter_values={"P": {"type": "PATH", "value": ExprValue("/a/b", type="path")}}, + session_root_directory=str(tmp_path), + ) + try: + session.run_task(step_script=script) + deadline = time.monotonic() + 30 + while session.state == SessionState.RUNNING and time.monotonic() < deadline: + time.sleep(0.05) + status = session.action_status + assert status is not None + assert (status.state, status.fail_message) == (ActionState.SUCCESS, None) + assert out.read_text() == "/a/b|/A/B" + finally: + session.cleanup() + + +# ── A single path is accepted for a LIST[PATH] job parameter ── +# +# A path ``ExprValue`` given for a LIST[PATH] job parameter binds ``Param.P`` +# as a scalar path, so ``{{ Param.P[0] }}`` fails later with ``Cannot +# subscript type path``. A string ``ExprValue`` for the same parameter is +# refused. Same with openjd-sessions 0.10.0. The coercion is upstream's. + + +@pytest.mark.xfail( + reason="openjd-sessions binds a single path for LIST[PATH] as a scalar path", + strict=True, +) +def test_a_single_path_for_a_list_path_parameter_is_a_one_item_list(tmp_path: Path) -> None: + out = tmp_path / "out.txt" + code = "import sys; open(sys.argv[1], 'w').write('|'.join(sys.argv[2:]))" + action = {"command": sys.executable, "args": ["-c", code, str(out), "{{ Param.P[0] }}"]} + script = deserialize_step({"name": "S", "script": {"actions": {"onRun": action}}}).script + session = Session( + session_id="s", + job_parameter_values={"P": {"type": "LIST[PATH]", "value": ExprValue("ab", type="path")}}, + session_root_directory=str(tmp_path), + ) + try: + session.run_task(step_script=script) + deadline = time.monotonic() + 30 + while session.state == SessionState.RUNNING and time.monotonic() < deadline: + time.sleep(0.05) + status = session.action_status + assert status is not None + assert (status.state, status.fail_message) == (ActionState.SUCCESS, None) + assert out.read_text() == "ab" + finally: + session.cleanup() diff --git a/test/openjd/sessions/test_parameter_values.py b/test/openjd/sessions/test_parameter_values.py new file mode 100644 index 00000000..cdd49813 --- /dev/null +++ b/test/openjd/sessions/test_parameter_values.py @@ -0,0 +1,163 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""How a session binds CHUNK[INT] and PATH task parameter values, through +openjd-sessions 0.12.1. + +- openjd-rs#638: a CHUNK[INT] task value is bound as a range expression for + both ``Task.Param`` and ``Task.RawParam``. A string is written in the range + expression's canonical form, except that ``-`` is kept, and indexing + and ``max()`` work on it. An int, a list or a string that isn't a range + fails the task. Before, the value was bound as the string it was given (an + int as its text), so ``"6,5"`` stayed ``6,5``, ``Task.Param.X[1]`` was + ``-`` and ``max()`` failed with ``No matching signature for max(string)``. +- openjd-rs#638: a PATH task value given as a path ``ExprValue`` binds + ``Task.RawParam`` as a string, so string methods such as ``upper()`` work + on it. Before, ``Task.RawParam`` held the path and ``upper()`` failed with + ``upper() is not available for path``. The same value for a job parameter + still binds ``RawParam`` as a path; that is in ``test_known_gaps.py``. + +A PATH value that isn't a string or a path is in ``test_failed_actions.py``. +""" + +from __future__ import annotations + +import sys +import time +from pathlib import Path +from typing import Any + +import pytest + +from openjd._openjd_rs import ( + ActionState, + ExprValue, + RangeExpr, + Session, + TaskParameterType, + TaskParameterValue, + SessionState, + deserialize_step, +) + + +def _run_task(tmp_path: Path, task_parameter_values: dict[str, Any], *fields: str) -> Any: + """Run a task that writes ``fields``, joined by ``|``, to a file. Returns + the action status and the file's text, or ``None`` if the task didn't + write it.""" + out = tmp_path / "out.txt" + code = "import sys; open(sys.argv[1], 'w').write('|'.join(sys.argv[2:]))" + action = {"command": sys.executable, "args": ["-c", code, str(out), *fields]} + script = deserialize_step({"name": "S", "script": {"actions": {"onRun": action}}}).script + session = Session(session_id="s", job_parameter_values={}, session_root_directory=str(tmp_path)) + try: + session.run_task(step_script=script, task_parameter_values=task_parameter_values) + deadline = time.monotonic() + 30 + while session.state == SessionState.RUNNING and time.monotonic() < deadline: + time.sleep(0.05) + assert session.state != SessionState.RUNNING, "action did not finish within 30s" + status = session.action_status + assert status is not None + return status, (out.read_text() if out.exists() else None) + finally: + session.cleanup() + + +def _chunk(value: Any) -> dict[str, Any]: + return {"X": {"type": "CHUNK[INT]", "value": value}} + + +@pytest.mark.parametrize( + "value, text", + [ + pytest.param("1-10", "1-10", id="N-M kept"), + pytest.param("1-3,5", "1-3,5", id="already canonical"), + pytest.param("6,5", "5,6", id="sorted"), + pytest.param("1,2,3", "1-3", id="run joined"), + pytest.param("1-10:2", "1-9:2", id="step end trimmed"), + pytest.param(" 5-6 ", "5-6", id="white space"), + pytest.param("5-6:1", "5,6", id="step one"), + pytest.param("7", "7", id="single"), + pytest.param(RangeExpr("1-10"), "1-10", id="RangeExpr"), + pytest.param("1-2", "1-2", id="string N-M kept"), + pytest.param(RangeExpr("1-2"), "1,2", id="RangeExpr written as str(RangeExpr)"), + ], +) +def test_chunk_int_task_value_is_a_range_expr(tmp_path: Path, value: Any, text: str) -> None: + status, out = _run_task(tmp_path, _chunk(value), "{{Task.Param.X}}", "{{Task.RawParam.X}}") + assert (status.state, status.fail_message) == (ActionState.SUCCESS, None) + assert out == f"{text}|{text}" + + +def test_chunk_int_task_value_can_be_indexed(tmp_path: Path) -> None: + status, out = _run_task( + tmp_path, + _chunk("1-10"), + "{{ Task.Param.X[1] }}", + "{{ max(Task.Param.X) }}", + "{{ len(Task.Param.X) }}", + ) + assert (status.state, status.fail_message) == (ActionState.SUCCESS, None) + assert out == "2|10|10" + + +@pytest.mark.parametrize( + "value, message", + [ + pytest.param( + 5, + "Failed to coerce parameter 'Task.RawParam.X': Cannot coerce int to range_expr", + id="int", + ), + pytest.param( + [1, 2], + "Failed to coerce parameter 'Task.RawParam.X': Cannot coerce list[int] to range_expr", + id="list", + ), + pytest.param( + "abc", + "Failed to coerce parameter 'Task.RawParam.X': Expected integer in 'abc'", + id="not a range", + ), + ], +) +def test_chunk_int_task_value_must_be_a_range(tmp_path: Path, value: Any, message: str) -> None: + """Before openjd-rs#638 each of these ran the task.""" + status, out = _run_task(tmp_path, _chunk(value), "{{Task.Param.X}}") + assert (status.state, status.fail_message) == (ActionState.FAILED, message) + assert out is None + + +def test_a_path_task_value_binds_raw_param_as_a_string(tmp_path: Path) -> None: + status, out = _run_task( + tmp_path, + # A one-component relative path renders the same in every path format. + {"P": {"type": "PATH", "value": ExprValue("ab", type="path")}}, + "{{Task.Param.P}}", + "{{ Task.RawParam.P.upper() }}", + ) + assert (status.state, status.fail_message) == (ActionState.SUCCESS, None) + assert out == "ab|AB" + + +@pytest.mark.parametrize( + "text, written", + [ + pytest.param("1,3,5", "1-5:2", id="stepped run"), + pytest.param("1-10:2", "1-9:2", id="end trimmed"), + pytest.param("01-05", "1-5", id="leading zeros"), + pytest.param("1-5", "1-5", id="N-M kept"), + ], +) +def test_a_task_parameter_value_for_chunk_int_is_written_in_canonical_form( + tmp_path: Path, text: str, written: str +) -> None: + """The form the Deadline Cloud worker agent passes, a ``TaskParameterValue`` + holding the service's text, is bound the same way as the dict form: in + canonical range form, with a canonical ``-`` kept (openjd-rs#638). + openjd-sessions 0.10.0 bound the text unchanged, as the pure-Python + ``openjd.sessions.Session`` still does.""" + value = TaskParameterValue(type=TaskParameterType.CHUNK_INT, value=text) + status, out = _run_task(tmp_path, {"X": value}, "{{Task.Param.X}}", "{{Task.RawParam.X}}") + assert (status.state, status.fail_message) == (ActionState.SUCCESS, None) + assert out == f"{written}|{written}" diff --git a/test/openjd/sessions/test_refused_calls.py b/test/openjd/sessions/test_refused_calls.py index ef3b9488..c782891f 100644 --- a/test/openjd/sessions/test_refused_calls.py +++ b/test/openjd/sessions/test_refused_calls.py @@ -433,6 +433,77 @@ def test_straight_after_the_call_that_started_the_action( assert session.state == SessionState.READY_ENDING session.clear_ending_only() + @pytest.mark.parametrize( + "cancelation, time_limit, at_least, under", + [ + pytest.param(None, 5.0, 0.0, 1.5, id="no cancelation"), + pytest.param({"mode": "TERMINATE"}, 5.0, 0.0, 1.5, id="TERMINATE"), + pytest.param( + {"mode": "NOTIFY_THEN_TERMINATE", "notifyPeriodInSeconds": 30}, + 1.0, + 0.8, + 5.0, + id="period capped at time_limit", + ), + pytest.param( + {"mode": "NOTIFY_THEN_TERMINATE", "notifyPeriodInSeconds": 2}, + None, + 1.8, + 6.0, + id="period, no time_limit", + ), + pytest.param( + {"mode": "NOTIFY_THEN_TERMINATE", "notifyPeriodInSeconds": 2}, + 10.0, + 1.8, + 6.0, + id="period under time_limit", + ), + ], + ) + def test_cancel_grace_is_the_declared_period_capped_by_time_limit( + self, + session: Session, + tmp_path: Path, + cancelation: Optional[dict[str, Any]], + time_limit: Optional[float], + at_least: float, + under: float, + ) -> None: + """A same-user ``cancel_action`` uses the action's own cancel method: + an action with no ``cancelation``, or a TERMINATE one, is killed at + once whatever the ``time_limit``; a NOTIFY_THEN_TERMINATE one is killed + after its declared period, or after ``time_limit`` if that is shorter. + openjd-rs#563 and #575 document this rule; the same-user behavior + didn't change. The action ignores the notify signal, so only the kill + ends it. The upper bounds are loose so that a slow host passes, but + each is below the grace the case must not use.""" + marker = tmp_path / "started" + ignore_notify = ( + "import signal, time\n" + "for name in ('SIGTERM', 'SIGBREAK'):\n" + " if hasattr(signal, name):\n" + " signal.signal(getattr(signal, name), signal.SIG_IGN)\n" + f"open({str(marker)!r}, 'w').close()\n" + "time.sleep(60)" + ) + action: dict[str, Any] = _python(ignore_notify) + if cancelation is not None: + action["cancelation"] = cancelation + script = deserialize_step({"name": "S", "script": {"actions": {"onRun": action}}}).script + session.run_task(step_script=script) + deadline = time.monotonic() + 10 + while not marker.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert marker.exists() + began = time.monotonic() + session.cancel_action(time_limit=time_limit) + _settle(session) + took = time.monotonic() - began + status = session.action_status + assert status is not None and status.state == ActionState.CANCELED + assert at_least <= took < under, f"cancel took {took:.2f}s" + class TestAcceptedCalls: """An accepted call returns once its action is running, with diff --git a/test/openjd/sessions/test_resolved_symtab.py b/test/openjd/sessions/test_resolved_symtab.py new file mode 100644 index 00000000..7323cf90 --- /dev/null +++ b/test/openjd/sessions/test_resolved_symtab.py @@ -0,0 +1,394 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Which symbol table an environment's actions resolve against when the caller +gives no ``resolved_symtab``, through openjd-sessions 0.12.1. + +openjd-rs#632 changed both calls: + +- ``exit_environment`` with no ``resolved_symtab`` resolves ``onExit`` against + the table the environment was entered with. Before, it built a table from + the session's job parameter values, so an exit after an enter with an + explicit table saw different values, or failed when the session had no + value for the parameter. +- ``enter_environment`` with no ``resolved_symtab`` resolves an ``Environment`` + from ``create_job`` against the environment's own table, so ``Job.Name`` + works in its ``variables``, ``onEnter`` and ``onExit``. Before, the enter + failed with ``Undefined variable: 'Job.Name'``. An ``Environment`` from + ``create_environment`` has no table of its own, so it still resolves + against the job parameter values. + +What ``exit_environment`` does with a ``resolved_symtab`` it can't use is in +``test_failed_actions.py``. +""" + +from __future__ import annotations + +import sys +import time +from pathlib import Path +from typing import Any + +import pytest + +from openjd._openjd_rs import ( + ActionState, + SerializedSymbolTable, + Session, + SessionState, + SymbolTable, + create_environment, + create_job, + decode_environment_template, + decode_job_template, + preprocess_job_parameters, +) + + +def _writer(out: Path, *fields: str) -> dict[str, Any]: + """An action that appends ``fields``, joined by ``|``, as a line of ``out``.""" + code = "import sys; open(sys.argv[1], 'a').write('|'.join(sys.argv[2:]) + '\\n')" + return {"command": sys.executable, "args": ["-c", code, str(out), *fields]} + + +def _settle(session: Session) -> None: + deadline = time.monotonic() + 30 + while session.state == SessionState.RUNNING and time.monotonic() < deadline: + time.sleep(0.05) + assert session.state != SessionState.RUNNING, "action did not finish within 30s" + + +def _assert_succeeded(session: Session) -> None: + status = session.action_status + assert status is not None + assert (status.state, status.fail_message) == (ActionState.SUCCESS, None) + + +def _param_x_environment(out: Path) -> Any: + return create_environment( + decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "parameterDefinitions": [{"name": "X", "type": "STRING"}], + "environment": { + "name": "E", + "script": { + "actions": { + "onEnter": _writer(out, "enter", "{{Param.X}}"), + "onExit": _writer(out, "exit", "{{Param.X}}"), + } + }, + }, + } + ) + ) + + +@pytest.mark.parametrize( + "job_parameter_values", + [ + pytest.param({"X": {"type": "STRING", "value": "from-session"}}, id="session has X"), + pytest.param({}, id="session lacks X"), + ], +) +def test_exit_without_a_table_uses_the_enter_time_table( + tmp_path: Path, job_parameter_values: dict[str, Any] +) -> None: + """Before openjd-rs#632 the exit read ``from-session`` when the session + had a value for ``X``, and failed with ``Failed to resolve argument: + Undefined variable: 'Param.X'.`` when it had none.""" + out = tmp_path / "out.txt" + table = SymbolTable() + table["Param.X"] = "from-table" + session = Session( + session_id="s", + job_parameter_values=job_parameter_values, + session_root_directory=str(tmp_path), + ) + try: + identifier = session.enter_environment( + environment=_param_x_environment(out), + resolved_symtab=SerializedSymbolTable.from_symtab(table), + ) + _settle(session) + _assert_succeeded(session) + session.exit_environment(identifier=identifier) + _settle(session) + _assert_succeeded(session) + assert out.read_text() == "enter|from-table\nexit|from-table\n" + finally: + session.cleanup() + + +def test_a_job_environment_entered_without_a_table_resolves_job_name(tmp_path: Path) -> None: + out = tmp_path / "out.txt" + job_template = decode_job_template( + supported_extensions=["EXPR"], + template={ + "specificationVersion": "jobtemplate-2023-09", + "name": "TJ", + "extensions": ["EXPR"], + "parameterDefinitions": [{"name": "P", "type": "STRING", "default": "pv"}], + "jobEnvironments": [ + { + "name": "JE", + "variables": {"V": "{{Job.Name}}"}, + "script": { + "actions": { + "onEnter": _writer(out, "enter", "{{Job.Name}}", "{{Param.P}}"), + "onExit": _writer(out, "exit", "{{Job.Name}}", "{{Param.P}}"), + } + }, + } + ], + "steps": [{"name": "S", "script": {"actions": {"onRun": {"command": "true"}}}}], + }, + ) + job_environments = create_job( + job_template=job_template, job_parameter_values={} + ).job_environments + assert job_environments is not None + environment = job_environments[0] + session = Session( + session_id="s", + job_parameter_values={"P": {"type": "STRING", "value": "pv"}}, + session_root_directory=str(tmp_path), + ) + try: + identifier = session.enter_environment(environment=environment) + _settle(session) + _assert_succeeded(session) + session.exit_environment(identifier=identifier) + _settle(session) + _assert_succeeded(session) + assert out.read_text() == "enter|TJ|pv\nexit|TJ|pv\n" + finally: + session.cleanup() + + +def test_a_step_environment_needs_the_step_table_for_job_name(tmp_path: Path) -> None: + """A Step Environment from ``create_job`` has no table of its own (unchanged + by openjd-rs#632), so entered without one ``Job.Name`` is undefined. + ``step.resolved_symtab`` resolves it.""" + out = tmp_path / "out.txt" + job_template = decode_job_template( + supported_extensions=["EXPR"], + template={ + "specificationVersion": "jobtemplate-2023-09", + "name": "TJ", + "extensions": ["EXPR"], + "steps": [ + { + "name": "S", + "stepEnvironments": [ + { + "name": "SE", + "script": { + "actions": {"onEnter": _writer(out, "enter", "{{Job.Name}}")} + }, + } + ], + "script": {"actions": {"onRun": {"command": "true"}}}, + } + ], + }, + ) + step = create_job(job_template=job_template, job_parameter_values={}).steps[0] + assert step.step_environments is not None + environment = step.step_environments[0] + session = Session(session_id="s", job_parameter_values={}, session_root_directory=str(tmp_path)) + try: + session.enter_environment(environment=environment) + _settle(session) + status = session.action_status + assert status is not None + assert (status.state, status.fail_message) == ( + ActionState.FAILED, + "Failed to resolve argument: Undefined variable: 'Job.Name'.\n Job.Name\n ~~~~^~~~", + ) + finally: + session.cleanup() + session = Session( + session_id="s2", job_parameter_values={}, session_root_directory=str(tmp_path) + ) + try: + session.enter_environment(environment=environment, resolved_symtab=step.resolved_symtab) + _settle(session) + _assert_succeeded(session) + assert out.read_text() == "enter|TJ\n" + finally: + session.cleanup() + + +def test_a_standalone_environment_entered_without_a_table_uses_the_job_parameters( + tmp_path: Path, +) -> None: + """``create_environment`` builds no table, so the session's job parameter + values are what the environment sees, on enter and on exit.""" + out = tmp_path / "out.txt" + session = Session( + session_id="s", + job_parameter_values={"X": {"type": "STRING", "value": "from-session"}}, + session_root_directory=str(tmp_path), + ) + try: + identifier = session.enter_environment(environment=_param_x_environment(out)) + _settle(session) + _assert_succeeded(session) + session.exit_environment(identifier=identifier) + _settle(session) + _assert_succeeded(session) + assert out.read_text() == "enter|from-session\nexit|from-session\n" + finally: + session.cleanup() + + +def test_an_environment_template_wrap_hook_sees_its_own_parameters(tmp_path: Path) -> None: + """A wrap hook reads its own ``Param.*`` from the wrap Environment's table. + Since openjd-rs#632 a Job Environment from ``create_job`` is entered with + its own filtered table, so a wrap Environment with no table of its own + lost ``Param.Prefix`` and the enter failed with ``Undefined variable: + 'Param.Prefix'``. ``create_environment(..., job_parameter_values=...)`` + gives the wrap Environment the table ``openjd run`` gives it.""" + out = tmp_path / "out.txt" + env_template = decode_environment_template( + supported_extensions=["WRAP_ACTIONS", "EXPR"], + template={ + "specificationVersion": "environment-2023-09", + "extensions": ["WRAP_ACTIONS", "EXPR"], + "parameterDefinitions": [{"name": "Prefix", "type": "STRING", "default": "pv"}], + "environment": { + "name": "Wrap", + "script": { + "actions": { + "onWrapEnvEnter": _writer(out, "wrap", "{{ Param.Prefix }}"), + "onWrapTaskRun": {"command": "{{ WrappedAction.Command }}"}, + "onWrapEnvExit": {"command": "true"}, + } + }, + }, + }, + ) + job_template = decode_job_template( + template={ + "specificationVersion": "jobtemplate-2023-09", + "name": "J", + "jobEnvironments": [ + {"name": "Inner", "script": {"actions": {"onEnter": _writer(out, "inner")}}} + ], + "steps": [{"name": "S", "script": {"actions": {"onRun": {"command": "true"}}}}], + } + ) + values = preprocess_job_parameters( + job_template=job_template, + job_parameter_values={}, + environment_templates=[env_template], + job_template_dir=str(tmp_path), + current_working_dir=str(tmp_path), + ) + job = create_job( + job_template=job_template, + job_parameter_values=values, + environment_templates=[env_template], + ) + assert job.job_environments is not None + wrap = create_environment(env_template, job_parameter_values=values) + session = Session( + session_id="s", job_parameter_values=values, session_root_directory=str(tmp_path) + ) + try: + for environment in (wrap, job.job_environments[0]): + session.enter_environment(environment=environment) + _settle(session) + _assert_succeeded(session) + assert out.read_text() == "wrap|pv\n" + finally: + session.cleanup() + + +@pytest.mark.parametrize( + "value, expected", + [ + pytest.param({"type": "INT", "value": "05"}, "5|6", id="INT string"), + pytest.param({"type": "BOOL", "value": "false"}, "false|off", id="BOOL string"), + ], +) +def test_create_environment_converts_values_to_their_types( + tmp_path: Path, value: dict[str, Any], expected: str +) -> None: + """``create_environment(job_parameter_values=...)`` converts each value to + its declared type, as a Session does for job parameter values. A Session + does not convert the values of a table an Environment brings, so ``"05"`` + for an INT used to reach the action as the text ``05``, and arithmetic on + it failed.""" + out = tmp_path / "out.txt" + ptype = value["type"] + second = "{{ Param.N + 1 }}" if ptype == "INT" else "{{ 'on' if Param.N else 'off' }}" + env_template = decode_environment_template( + supported_extensions=["EXPR"], + template={ + "specificationVersion": "environment-2023-09", + "extensions": ["EXPR"], + "parameterDefinitions": [{"name": "N", "type": ptype}], + "environment": { + "name": "E", + "script": {"actions": {"onEnter": _writer(out, "{{ Param.N }}", second)}}, + }, + }, + ) + environment = create_environment(env_template, job_parameter_values={"N": value}) + # The Session has no job parameter values, so `Param.N` can only come from + # the table `create_environment` built. Without the keyword this fails + # with "Undefined variable: 'Param.N'"; without the conversion it writes + # `05` or fails on the arithmetic or the condition. + session = Session(session_id="s", job_parameter_values={}, session_root_directory=str(tmp_path)) + try: + session.enter_environment(environment=environment) + _settle(session) + _assert_succeeded(session) + assert out.read_text() == expected + "\n" + finally: + session.cleanup() + + +def test_create_environment_refuses_a_value_that_does_not_convert() -> None: + env_template = decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "parameterDefinitions": [{"name": "N", "type": "INT"}], + "environment": {"name": "E", "variables": {"V": "{{Param.N}}"}}, + }, + ) + with pytest.raises(ValueError) as excinfo: + create_environment( + env_template, job_parameter_values={"N": {"type": "INT", "value": "abc"}} + ) + assert str(excinfo.value).startswith("Failed to coerce parameter 'Param.N': ") + + +def test_create_environment_refuses_a_declared_parameter_without_a_value() -> None: + """The table replaces the session's values, so a declared parameter left + out of ``job_parameter_values`` would be undefined in the Environment even + when the Session has it. ``create_environment`` refuses it instead, as + ``preprocess_job_parameters`` does, defaults included: that ``dict`` + fills them in.""" + env_template = decode_environment_template( + template={ + "specificationVersion": "environment-2023-09", + "parameterDefinitions": [ + {"name": "N", "type": "INT"}, + {"name": "D", "type": "STRING", "default": "d"}, + {"name": "A", "type": "PATH"}, + ], + "environment": {"name": "E", "variables": {"V": "{{Param.N}}"}}, + }, + ) + with pytest.raises(ValueError) as excinfo: + create_environment( + env_template, + job_parameter_values={ + "N": {"type": "INT", "value": "1"}, + "Other": {"type": "INT", "value": "1"}, + }, + ) + assert str(excinfo.value) == "Values missing for required job parameters: A, D" diff --git a/test/openjd/test_dict_snapshots.py b/test/openjd/test_dict_snapshots.py new file mode 100644 index 00000000..d8f4d668 --- /dev/null +++ b/test/openjd/test_dict_snapshots.py @@ -0,0 +1,106 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Bindings that read a caller's ``dict`` read a snapshot of it. + +Converting a value can run user code: a ``Decimal`` subclass's ``__float__``, +a ``type`` property, a type object's ``as_str``. When that code changed the +dict, PyO3's live dict iterator raised ``PanicException`` ("dictionary changed +size during iteration"). Each binding now iterates over ``dict.items()``, so +the call sees the dict as it was when the call started. +""" + +from __future__ import annotations + +import decimal +import tempfile +from typing import Any, Callable + +import pytest + +from openjd._openjd_rs import ( + FormatString, + Session, + StepParameterSpace, + StepParameterSpaceIterator, + SymbolTable, + TaskParameterType, + build_symbol_table, +) + + +def _decimal_that_adds(target: dict[str, Any], key: str, value: Any) -> decimal.Decimal: + class Adds(decimal.Decimal): + def __float__(self) -> float: + target[key] = value + return 1.5 + + return Adds("1.5") + + +def _value_whose_type_adds(target: dict[str, Any]) -> Any: + class Value: + value = "1" + + @property + def type(self) -> Any: + target["Added"] = 1 + return TaskParameterType.INT + + return Value() + + +def _symbol_table_cases() -> list[Any]: + def build(call: Callable[[dict[str, Any]], Any], key: str) -> Callable[[], Any]: + def run() -> Any: + values: dict[str, Any] = {} + values[key] = _decimal_that_adds(values, "Added", 1) + return call(values) + + return run + + return [ + pytest.param(build(build_symbol_table, "Param.X"), id="build_symbol_table"), + pytest.param(build(SymbolTable, "X"), id="SymbolTable"), + pytest.param( + build(lambda d: FormatString("{{X}}").resolve(symtab=d), "X"), + id="FormatString.resolve", + ), + ] + + +@pytest.mark.parametrize("call", _symbol_table_cases()) +def test_symbol_table_conversions(call: Callable[[], Any]) -> None: + call() + + +def test_step_parameter_space() -> None: + definitions: dict[str, Any] = {} + + class Type: + def as_str(self) -> str: + definitions["Added"] = {"type": "INT", "range": ["1"]} + return "INT" + + definitions["F"] = {"type": Type(), "range": ["1", "2"]} + space = StepParameterSpace(taskParameterDefinitions=definitions) + assert [t["F"].value for t in StepParameterSpaceIterator(space=space)] == ["1", "2"] + + +def test_step_parameter_space_iterator_containment() -> None: + space = StepParameterSpace(taskParameterDefinitions={"F": {"type": "INT", "range": ["1", "2"]}}) + iterator = StepParameterSpaceIterator(space=space) + values: dict[str, Any] = {} + values["F"] = _value_whose_type_adds(values) + assert values in iterator + + +def test_session_job_parameter_values() -> None: + values: dict[str, Any] = {} + values["X"] = { + "type": "FLOAT", + "value": _decimal_that_adds(values, "Added", {"type": "INT", "value": 1}), + } + Session( + session_id="s", job_parameter_values=values, session_root_directory=tempfile.mkdtemp() + ).cleanup()