Skip to content

Commit e02c7f7

Browse files
rsareddy0329jam-jeeRoja Reddy Sareddy
authored
fix(processing): Fix V3 shape regressions + KMS/requirements gaps in processors (#6364)
* fix(processing): Fix V3 shape regressions in processors PySparkProcessor still built ProcessingInput/ProcessingOutput with the V2 source/destination keyword signature, so spark_event_logs_s3_uri and the configuration channel failed on V3. Build them with the V3 shapes (ProcessingS3Input/ProcessingS3Output) instead. Validate that submit_py_files, submit_jars and submit_files are lists and raise a clear ValueError otherwise. FrameworkProcessor.run(requirements=...) now threads the file name into the generated runproc.sh instead of hardcoding requirements.txt. Processor.run defaults kms_key to the configured output_kms_key so uploaded code is encrypted with the same key as job outputs. The requirements file is also honored on the custom entry_point (S3 source_dir) path, and a relative path such as reqs/cpu.txt is kept as-is because the source bundle preserves the source_dir layout. Integration tests (real jobs, submit-then-stop where the fix is in the request path) cover the code-upload KMS fallback, the FrameworkProcessor requirements file, and a V3 PySparkProcessor job ported from V2 that asserts the event-log output and the conf/py-files input shape; V3 had no Spark integ coverage before. Fixes #3809 Fixes #6253 Fixes #6252 Fixes #5805 Fixes #4874 --- X-AI-Prompt: Fix S-effort PySDK V3 bugs, processing-spark theme X-AI-Tool: Kiro * fix(processing): encrypt sourcedir.tar.gz with resolved kms_key FrameworkProcessor._pack_and_upload_code computed the output_kms_key fallback (evaluated_kms_key) only after calling _package_code, and passed the raw kms_key to _package_code. FrameworkProcessor.run does not apply the fallback before delegating here, so with output_kms_key set and no explicit kms_key, sourcedir.tar.gz -- the largest, most sensitive artifact -- was uploaded unencrypted, while install_requirements.py and runproc.sh were encrypted. This left #4874 unfixed for FrameworkProcessor. Resolve the key once, before packaging, and pass it into _package_code so all three artifacts share the same key. An explicitly passed kms_key still wins; behaviour when both are unset is unchanged. Add unit tests asserting _package_code and the helper-script uploads all receive the resolved key on the fallback path (regression for #4874) and that an explicit key overrides output_kms_key. Relates-to #4874 * fix(processing): reject pipeline variable for requirements argument FrameworkProcessor.run bakes the requirements path into the generated runproc.sh script, so it cannot be a pipeline variable. Passing a ParameterString previously surfaced as an opaque "TypeError: expected str, bytes or os.PathLike object, not ParameterString" from os.path.isabs deep in script generation. Add an explicit is_pipeline_variable guard at the top of FrameworkProcessor.run, raising a clear ValueError, matching the existing code and submit_app guards. Add a unit test. Relates-to #5805 * test(workflow): raise wait_duration for 3-job step-decorator test test_passing_different_pipeline_variables_to_function chains a ScriptProcessor ProcessingStep with two @step function steps (3 jobs). The 600s wait budget was too low once instance provisioning is included, so func_2 was still "Executing" at the deadline and the test failed fleet-wide (same failure on main and on unrelated PRs #6154/#6261/#6400/ #5722), not just here. Raise it to 1500s, consistent with the other multi-step tests in this file (800-1000s). Formatting-only otherwise; no product code change. * chore(codestyle): black-format test_processing.py Apply black to tests/unit/test_processing.py (added two blank lines before TestProcessorLocalModeRole), fixing the failing codestyle-doc-tests (sagemaker-core) black-check and flake8 E302. Formatting-only. --------- Co-authored-by: Amarjeet LNU <jamjee@amazon.com> Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>
1 parent 0495265 commit e02c7f7

12 files changed

Lines changed: 1937 additions & 22 deletions

File tree

‎sagemaker-core/src/sagemaker/core/processing.py‎

Lines changed: 58 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,8 @@ def run(
333333
is built with :class:`~sagemaker.workflow.pipeline_context.PipelineSession`.
334334
However, the value of `TrialComponentDisplayName` is honored for display in Studio.
335335
kms_key (str): The ARN of the KMS key that is used to encrypt the
336-
user code file (default: None).
336+
user code file. If not provided, the processor's configured
337+
``output_kms_key`` is used (default: None).
337338
Returns:
338339
None or pipeline step arguments in case the Processor instance is built with
339340
:class:`~sagemaker.workflow.pipeline_context.PipelineSession`
@@ -344,6 +345,12 @@ def run(
344345
raise ValueError("""Logs can only be shown if wait is set to True.
345346
Please either set wait to True or set logs to False.""")
346347

348+
# When no explicit code-encryption key is given, fall back to the
349+
# configured output KMS key so the uploaded code and job outputs are
350+
# encrypted with the same key.
351+
if kms_key is None:
352+
kms_key = self.output_kms_key
353+
347354
normalized_inputs, normalized_outputs = self._normalize_args(
348355
job_name=job_name,
349356
arguments=arguments,
@@ -915,7 +922,8 @@ def run(
915922
is built with :class:`~sagemaker.workflow.pipeline_context.PipelineSession`.
916923
However, the value of `TrialComponentDisplayName` is honored for display in Studio.
917924
kms_key (str): The ARN of the KMS key that is used to encrypt the
918-
user code file (default: None).
925+
user code file. If not provided, the processor's configured
926+
``output_kms_key`` is used (default: None).
919927
Returns:
920928
None or pipeline step arguments in case the Processor instance is built with
921929
:class:`~sagemaker.workflow.pipeline_context.PipelineSession`
@@ -926,7 +934,7 @@ def run(
926934
inputs=inputs,
927935
outputs=outputs,
928936
code=code,
929-
kms_key=kms_key,
937+
kms_key=kms_key if kms_key is not None else self.output_kms_key,
930938
)
931939

932940
experiment_config = check_and_get_run_experiment_config(experiment_config)
@@ -1406,6 +1414,13 @@ def run(
14061414
None or pipeline step arguments in case the Processor instance is built with
14071415
:class:`~sagemaker.workflow.pipeline_context.PipelineSession`
14081416
"""
1417+
if requirements and is_pipeline_variable(requirements):
1418+
raise ValueError(
1419+
"requirements argument has to be a path relative to source_dir "
1420+
+ "rather than a pipeline variable, because it is baked into the "
1421+
+ "generated runproc.sh script"
1422+
)
1423+
14091424
s3_runproc_sh, inputs, job_name = self._pack_and_upload_code(
14101425
code,
14111426
source_dir,
@@ -1448,14 +1463,22 @@ def _pack_and_upload_code(
14481463
if job_name is None:
14491464
job_name = self._generate_current_job_name(job_name)
14501465

1466+
# Resolve the KMS key once, before any upload, so every artifact this method
1467+
# produces -- the source bundle, install_requirements.py and runproc.sh -- is
1468+
# encrypted with the same key. An explicitly passed kms_key always wins; when it
1469+
# is not set we fall back to the configured output_kms_key. This must happen
1470+
# before _package_code so sourcedir.tar.gz (the largest, most sensitive artifact)
1471+
# is not left unencrypted (issue #4874).
1472+
evaluated_kms_key = kms_key if kms_key else self.output_kms_key
1473+
14511474
# Package and upload code
14521475
s3_payload = self._package_code(
14531476
entry_point=code,
14541477
source_dir=source_dir,
14551478
dependencies=dependencies,
14561479
requirements=requirements,
14571480
job_name=job_name,
1458-
kms_key=kms_key,
1481+
kms_key=evaluated_kms_key,
14591482
)
14601483

14611484
inputs = self._patch_inputs_with_payload(inputs, s3_payload)
@@ -1491,7 +1514,6 @@ def _pack_and_upload_code(
14911514
# Upload install_requirements helper
14921515
import sagemaker.core.utils.install_requirements as _ir_mod
14931516

1494-
evaluated_kms_key = kms_key if kms_key else self.output_kms_key
14951517
with open(_ir_mod.__file__, "r") as _ir_file:
14961518
_ir_body = _ir_file.read()
14971519
s3.S3Uploader.upload_string_as_file_body(
@@ -1509,6 +1531,7 @@ def _pack_and_upload_code(
15091531
entry_point,
15101532
source_dir,
15111533
install_requirements_dir,
1534+
requirements=requirements,
15121535
)
15131536

15141537
return s3_runproc_sh, inputs, job_name
@@ -1554,13 +1577,14 @@ def _create_and_upload_runproc(
15541577
entry_point=None,
15551578
source_dir=None,
15561579
install_requirements_dir=None,
1580+
requirements=None,
15571581
):
15581582
"""Create runproc shell script and upload to S3 bucket."""
15591583
from sagemaker.core.workflow.utilities import _pipeline_config, hash_object
15601584

15611585
if _pipeline_config and _pipeline_config.pipeline_name:
15621586
runproc_file_str = self._generate_framework_script(
1563-
user_script, entry_point, source_dir, install_requirements_dir
1587+
user_script, entry_point, source_dir, install_requirements_dir, requirements
15641588
)
15651589
runproc_file_hash = hash_object(runproc_file_str)
15661590
s3_uri = s3.s3_path_join(
@@ -1579,7 +1603,7 @@ def _create_and_upload_runproc(
15791603
else:
15801604
s3_runproc_sh = s3.S3Uploader.upload_string_as_file_body(
15811605
self._generate_framework_script(
1582-
user_script, entry_point, source_dir, install_requirements_dir
1606+
user_script, entry_point, source_dir, install_requirements_dir, requirements
15831607
),
15841608
desired_s3_uri=entrypoint_s3_uri,
15851609
kms_key=kms_key,
@@ -1588,20 +1612,36 @@ def _create_and_upload_runproc(
15881612

15891613
return s3_runproc_sh
15901614

1615+
@staticmethod
1616+
def _requirements_file_in_container(requirements: Optional[str]) -> str:
1617+
"""Return the requirements path as it appears inside the extracted source bundle.
1618+
1619+
``requirements`` is documented as relative to ``source_dir`` and ``_package_code``
1620+
preserves the directory layout, so a relative path (``reqs/cpu.txt``) is kept. An
1621+
absolute path cannot be located inside the bundle, so only its basename is used.
1622+
"""
1623+
if not requirements:
1624+
return "requirements.txt"
1625+
if os.path.isabs(requirements):
1626+
return os.path.basename(requirements)
1627+
return os.path.normpath(requirements).replace(os.sep, "/")
1628+
15911629
def _generate_framework_script(
15921630
self,
15931631
user_script: str,
15941632
entry_point: str = None,
15951633
source_dir: str = None,
15961634
install_requirements_dir: str = None,
1635+
requirements: str = None,
15971636
) -> str:
15981637
"""Generate the framework entrypoint file (as text) for a processing job."""
15991638
if entry_point:
16001639
return self._generate_custom_framework_script(
1601-
user_script, entry_point, source_dir, install_requirements_dir
1640+
user_script, entry_point, source_dir, install_requirements_dir, requirements
16021641
)
16031642

16041643
install_requirements_dir = install_requirements_dir or self._SOURCE_CODE_CONTAINER_DIR
1644+
requirements_file = self._requirements_file_in_container(requirements)
16051645

16061646
return dedent("""\
16071647
#!/bin/bash
@@ -1625,16 +1665,17 @@ def _generate_framework_script(
16251665
exit 1
16261666
fi
16271667
1628-
if [[ -f 'requirements.txt' ]]; then
1668+
if [[ -f '{requirements_file}' ]]; then
16291669
# Some py3 containers has typing, which may breaks pip install
16301670
pip uninstall --yes typing
16311671
1632-
python3 {install_requirements_dir}/install_requirements.py requirements.txt
1672+
python3 {install_requirements_dir}/install_requirements.py {requirements_file}
16331673
fi
16341674
16351675
{entry_point_command} {entry_point} "$@"
16361676
""").format(
16371677
install_requirements_dir=install_requirements_dir,
1678+
requirements_file=requirements_file,
16381679
entry_point_command=" ".join(self.command),
16391680
entry_point=user_script,
16401681
)
@@ -1645,6 +1686,7 @@ def _generate_custom_framework_script(
16451686
entry_point: str,
16461687
source_dir: str = None,
16471688
install_requirements_dir: str = None,
1689+
requirements: str = None,
16481690
) -> str:
16491691
"""Generate a custom framework script with a user-provided entrypoint embedded.
16501692
@@ -1658,6 +1700,8 @@ def _generate_custom_framework_script(
16581700
is relative, it will be combined with source_dir.
16591701
install_requirements_dir (str): Container directory that holds
16601702
``install_requirements.py`` (default: the extracted source code dir).
1703+
requirements (str): Path to the requirements file relative to source_dir
1704+
(default: ``requirements.txt``).
16611705
16621706
Returns:
16631707
str: The generated script content
@@ -1667,6 +1711,7 @@ def _generate_custom_framework_script(
16671711
# source bundle on the container.
16681712
if self._is_s3_uri(source_dir):
16691713
install_requirements_dir = install_requirements_dir or self._SOURCE_CODE_CONTAINER_DIR
1714+
requirements_file = self._requirements_file_in_container(requirements)
16701715
return dedent("""\
16711716
#!/bin/bash
16721717
@@ -1683,9 +1728,9 @@ def _generate_custom_framework_script(
16831728
exit 1
16841729
fi
16851730
1686-
if [[ -f 'requirements.txt' ]]; then
1731+
if [[ -f '{requirements_file}' ]]; then
16871732
pip uninstall --yes typing
1688-
python3 {install_requirements_dir}/install_requirements.py requirements.txt
1733+
python3 {install_requirements_dir}/install_requirements.py {requirements_file}
16891734
fi
16901735
16911736
# Execute custom entrypoint
@@ -1695,6 +1740,7 @@ def _generate_custom_framework_script(
16951740
{entry_point_command} {user_script} "$@"
16961741
""").format(
16971742
install_requirements_dir=install_requirements_dir,
1743+
requirements_file=requirements_file,
16981744
entry_point=entry_point,
16991745
entry_point_command=" ".join(self.command),
17001746
user_script=user_script,

‎sagemaker-core/src/sagemaker/core/spark/processing.py‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
from sagemaker.core import s3
4040
from sagemaker.core.local.image import _ecr_login_if_needed, _pull_image
4141
from sagemaker.core.processing import ProcessingInput, ProcessingOutput, ScriptProcessor
42+
from sagemaker.core.shapes import ProcessingS3Input, ProcessingS3Output
4243
from sagemaker.core.s3 import S3Uploader
4344
from sagemaker.core.helper.session_helper import Session
4445
from sagemaker.core.network import NetworkConfig
@@ -330,9 +331,12 @@ def _extend_processing_args(self, inputs, outputs, **kwargs):
330331
)
331332

332333
output = ProcessingOutput(
333-
source=_SparkProcessorBase._spark_event_log_default_local_path,
334-
destination=spark_event_logs_s3_uri,
335-
s3_upload_mode="Continuous",
334+
output_name="spark-event-logs",
335+
s3_output=ProcessingS3Output(
336+
s3_uri=spark_event_logs_s3_uri,
337+
local_path=_SparkProcessorBase._spark_event_log_default_local_path,
338+
s3_upload_mode="Continuous",
339+
),
336340
)
337341

338342
extended_outputs.append(output)
@@ -444,9 +448,13 @@ def _stage_configuration(self, configuration):
444448
)
445449

446450
conf_input = ProcessingInput(
447-
source=s3_uri,
448-
destination=f"{self._conf_container_base_path}{self._conf_container_input_name}",
449451
input_name=_SparkProcessorBase._conf_container_input_name,
452+
s3_input=ProcessingS3Input(
453+
s3_uri=s3_uri,
454+
local_path=f"{self._conf_container_base_path}{self._conf_container_input_name}",
455+
s3_data_type="S3Prefix",
456+
s3_input_mode="File",
457+
),
450458
)
451459
return conf_input
452460

@@ -473,6 +481,11 @@ def _stage_submit_deps(self, submit_deps, input_channel_name):
473481
)
474482
if not input_channel_name:
475483
raise ValueError("input_channel_name value may not be empty.")
484+
if not isinstance(submit_deps, (list, tuple)):
485+
raise ValueError(
486+
f"submit_deps must be a list of one or more paths, but got "
487+
f"{type(submit_deps).__name__}. {self._submit_deps_error_message}"
488+
)
476489

477490
use_input_channel = False
478491
spark_opt_s3_uris = []
@@ -544,15 +557,20 @@ def _stage_submit_deps(self, submit_deps, input_channel_name):
544557
# them to the Spark container and form the spark-submit option from a
545558
# combination of S3 URIs and container's local input path
546559
if use_input_channel:
560+
input_channel_local_path = f"{self._conf_container_base_path}{input_channel_name}"
547561
input_channel = ProcessingInput(
548-
source=input_channel_s3_uri,
549-
destination=f"{self._conf_container_base_path}{input_channel_name}",
550562
input_name=input_channel_name,
563+
s3_input=ProcessingS3Input(
564+
s3_uri=input_channel_s3_uri,
565+
local_path=input_channel_local_path,
566+
s3_data_type="S3Prefix",
567+
s3_input_mode="File",
568+
),
551569
)
552570
spark_opt = (
553-
Join(on=",", values=spark_opt_s3_uris + [input_channel.destination])
571+
Join(on=",", values=spark_opt_s3_uris + [input_channel_local_path])
554572
if spark_opt_s3_uris_has_pipeline_var
555-
else ",".join(spark_opt_s3_uris + [input_channel.destination])
573+
else ",".join(spark_opt_s3_uris + [input_channel_local_path])
556574
)
557575
# If no local files were uploaded, form the spark-submit option from a list of S3 URIs
558576
else:
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License"). You
4+
# may not use this file except in compliance with the License. A copy of
5+
# the License is located at
6+
#
7+
# http://aws.amazon.com/apache2.0/
8+
#
9+
# or in the "license" file accompanying this file. This file is
10+
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11+
# ANY KIND, either express or implied. See the License for the specific
12+
# language governing permissions and limitations under the License.
13+
import argparse
14+
import time
15+
16+
from pyspark.sql import SparkSession, SQLContext
17+
from pyspark.sql.functions import udf
18+
from pyspark.sql.types import IntegerType
19+
20+
# Import local module to test spark-submit--py-files dependencies
21+
import hello_py_spark_udfs as udfs
22+
23+
if __name__ == "__main__":
24+
parser = argparse.ArgumentParser(description="inputs and outputs")
25+
parser.add_argument("--input", type=str, help="path to input data")
26+
parser.add_argument("--output", required=False, type=str, help="path to output data")
27+
args = parser.parse_args()
28+
spark = SparkSession.builder.appName("SparkContainerTestApp").getOrCreate()
29+
sqlContext = SQLContext(spark.sparkContext)
30+
31+
# Load test data set
32+
inputPath = args.input
33+
salesDF = spark.read.json(inputPath)
34+
salesDF.printSchema()
35+
36+
salesDF.createOrReplaceTempView("sales")
37+
topDF = spark.sql("SELECT date, sale FROM sales WHERE sale > 750")
38+
# Show the first 20 rows of the dataframe
39+
topDF.show()
40+
time.sleep(60)
41+
42+
# Calculate average sales by date
43+
averageSalesPerDay = salesDF.groupBy("date").avg().collect()
44+
print(averageSalesPerDay)
45+
46+
outputPath = args.output
47+
48+
# Define a UDF that doubles an integer column
49+
# The UDF function is imported from local module to test spark-submit--py-files dependencies
50+
double_udf_int = udf(udfs.double_x, IntegerType())
51+
52+
# Save transformed data set to disk
53+
salesDF.select("date", "sale", double_udf_int("sale").alias("sale_double")).write.json(
54+
outputPath
55+
)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
def double_x(x):
2+
return x + x

0 commit comments

Comments
 (0)