From 03b3ba7c837a19e089352110c12b1b032378a4f2 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Sat, 3 Oct 2026 06:13:07 -0700 Subject: [PATCH 01/52] Add PipelineJob submission and read support to beta.jobs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 1 + sdk/ai/azure-ai-projects/README.md | 2 +- .../azure-ai-projects/apiview-properties.json | 3 +- .../ai/projects/aio/operations/_operations.py | 7 +- .../aio/operations/_patch_jobs_async.py | 67 +++--- .../azure/ai/projects/models/__init__.py | 2 + .../azure/ai/projects/models/_enums.py | 2 + .../azure/ai/projects/models/_models.py | 112 ++++++++- .../azure/ai/projects/models/_patch.py | 2 + .../azure/ai/projects/models/_patch_jobs.py | 54 +++++ .../ai/projects/operations/_operations.py | 27 +-- .../azure/ai/projects/operations/_patch.py | 2 +- .../ai/projects/operations/_patch_jobs.py | 69 +++--- .../tests/jobs/test_pipeline_jobs.py | 218 ++++++++++++++++++ sdk/ai/azure-ai-projects/tsp-location.yaml | 2 +- 15 files changed, 488 insertions(+), 82 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index cfdf5ed729e4..31ddd4ce30a4 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -24,6 +24,7 @@ * New optional `force` parameter on `agents.delete` and `agents.delete_version` methods. * New optional `blueprint_reference` parameters on `agents.create_version` method. * New `.beta.jobs` sub-client with CommandJob operations: `create_or_update`, `get`, `list`, `begin_delete`, `begin_cancel`, `validate`, `show_services`, `stream`, `download`. +* Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Pipeline graph nodes, inputs, outputs, and settings are sent as provided; local asset handling and validation remain specific to Command jobs. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index 8c68f2045389..8378270e3b3a 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -37,7 +37,7 @@ resources in your Microsoft Foundry Project. Use it to: * **Upload documents and create Datasets** to reference them using `.datasets` operations. * **Register and manage local model weights** as Foundry `ModelVersion` resources using `.beta.models` operations, including the `create` end-to-end helper. * **Create and enumerate Search Indexes** using `.indexes` operations. -* **Submit and manage Jobs (preview)** to run Training Jobs on compute using `.beta.jobs` operations. +* **Submit and manage Command and Pipeline Jobs (preview)** on compute using `.beta.jobs` operations. The client library uses version `v1` of the Microsoft Foundry [data plane REST APIs](https://aka.ms/azsdk/azure-ai-projects-v2/api-reference-v1). diff --git a/sdk/ai/azure-ai-projects/apiview-properties.json b/sdk/ai/azure-ai-projects/apiview-properties.json index 24b65ff3df37..3fbcdf169639 100644 --- a/sdk/ai/azure-ai-projects/apiview-properties.json +++ b/sdk/ai/azure-ai-projects/apiview-properties.json @@ -267,6 +267,7 @@ "azure.ai.projects.models.Output": "Azure.AI.Projects.Output", "azure.ai.projects.models.PendingUploadRequest": "Azure.AI.Projects.PendingUploadRequest", "azure.ai.projects.models.PendingUploadResponse": "Azure.AI.Projects.PendingUploadResponse", + "azure.ai.projects.models.PipelineJob": "Azure.AI.Projects.PipelineJob", "azure.ai.projects.models.ProceduralMemoryItem": "Azure.AI.Projects.ProceduralMemoryItem", "azure.ai.projects.models.PromoteCandidateRequest": "Azure.AI.Projects.PromoteCandidateRequest", "azure.ai.projects.models.PromoteCandidateResponse": "Azure.AI.Projects.PromoteCandidateResponse", @@ -503,5 +504,5 @@ "azure.ai.projects.operations.IndexesOperations.create_or_update": "Azure.AI.Projects.Indexes.createOrUpdateVersion", "azure.ai.projects.aio.operations.IndexesOperations.create_or_update": "Azure.AI.Projects.Indexes.createOrUpdateVersion" }, - "CrossLanguageVersion": "454439a0b62a" + "CrossLanguageVersion": "33bdc2e1e817" } \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py index 6640da2c8c6c..ec7cc20374f0 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py @@ -9312,7 +9312,7 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): - if body is _Unset: # pyright: ignore[reportUnboundVariable] + if body is _Unset: if scope is _Unset: raise TypeError("missing required argument: scope") body = {"scope": scope} @@ -14236,7 +14236,8 @@ def list( ) -> AsyncItemPaged["_models.Job"]: """List Jobs. - :keyword job_type: Filter by job type (e.g. 'Command'). "Command" Default value is None. + :keyword job_type: Filter by job type (e.g. 'Command' or 'Pipeline'). Known values are: + "Command" and "Pipeline". Default value is None. :paramtype job_type: str or ~azure.ai.projects.models.JobType :keyword tag: Filter jobs by tag in the format 'key=value' (e.g., 'framework=pytorch'). Default value is None. @@ -14292,7 +14293,7 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = "2026-01-15-preview" + _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 67d0c773d43f..ba2a0719aeef 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -3,9 +3,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -"""Async customized jobs operations — flat CommandJob UX, no envelope required.""" +"""Async customized jobs operations — flat CommandJob and PipelineJob UX, no envelope required.""" import asyncio # pylint: disable=do-not-import-asyncio +from copy import copy import json import logging import sys @@ -62,7 +63,7 @@ from ...models._models import Output as _Output from ...models._models import ModelCredentialRequest as _ModelCredentialRequest from ...models._enums import AssetTypes -from ...models._patch_jobs import CommandJob, ServiceInstance, ValidationResult +from ...models._patch_jobs import CommandJob, PipelineJob, ServiceInstance, ValidationResult, _from_rest_job from ...models._patch import _FOUNDRY_FEATURES_HEADER_NAME, _has_header_case_insensitive from ...models._enums import _FoundryFeaturesOptInKeys @@ -70,8 +71,8 @@ class JobsOperations(_GeneratedJobsOps): - """Async patched Jobs operations that expose a flat :class:`~azure.ai.projects.models.CommandJob` - interface — no ``Job`` envelope wrapping required by callers. + """Async patched Jobs operations that expose flat :class:`~azure.ai.projects.models.CommandJob` + and :class:`~azure.ai.projects.models.PipelineJob` objects without a ``Job`` envelope. Also automatically injects the ``Foundry-Features: Jobs=V1Preview`` preview opt-in header into every request so callers do not need to supply it manually. @@ -86,8 +87,13 @@ class JobsOperations(_GeneratedJobsOps): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self._datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) - self._models = _GeneratedModelsOps(self._client, self._config, self._serialize, self._deserialize) + original_config = self._config + # Generated Jobs operations use config.api_version; keep the existing preview route + # without changing the shared v1 config used by datasets and models. + self._config = copy(original_config) + self._config.api_version = "2026-01-15-preview" + self._datasets = DatasetsOperations(self._client, original_config, self._serialize, self._deserialize) + self._models = _GeneratedModelsOps(self._client, original_config, self._serialize, self._deserialize) @distributed_trace_async async def validate( @@ -276,11 +282,10 @@ def list( # type: ignore[override] list_view_type: Optional[Union[str, Any]] = None, properties: Optional[str] = None, **kwargs: Any, - ) -> AsyncItemPaged[CommandJob]: - """List all training jobs as flat :class:`~azure.ai.projects.models.CommandJob` - objects with ``name`` and ``id`` promoted from the Job resource envelope. + ) -> AsyncItemPaged[Union[CommandJob, PipelineJob]]: + """List Command and Pipeline jobs with ``name`` and ``id`` promoted from the Job envelope. - :keyword job_type: Filter by job type (e.g. ``'Command'``). Default value is None. + :keyword job_type: Filter by job type (``'Command'`` or ``'Pipeline'``). Default value is None. :paramtype job_type: str or ~azure.ai.projects.models.JobType :keyword tag: Filter by tag in the format ``'key=value'``. Default value is None. :paramtype tag: str @@ -288,14 +293,14 @@ def list( # type: ignore[override] :paramtype list_view_type: str or ~azure.ai.projects.models.ListViewType :keyword properties: Comma-separated user properties filter. Default value is None. :paramtype properties: str - :return: An iterator like instance of :class:`~azure.ai.projects.models.CommandJob`. - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.CommandJob] + :return: An iterator of CommandJob or PipelineJob objects. + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob] :raises ~azure.core.exceptions.HttpResponseError: """ self._inject_preview_header(kwargs) - def _convert_page(page: List) -> List[CommandJob]: - return [CommandJob._from_rest_object(item) for item in page] + def _convert_page(page: List[_RestJob]) -> List[Union[CommandJob, PipelineJob]]: + return [_from_rest_job(item) for item in page] return super().list( job_type=job_type, @@ -307,50 +312,52 @@ def _convert_page(page: List) -> List[CommandJob]: ) # type: ignore[return-value] @distributed_trace_async - async def get(self, name: str, **kwargs: Any) -> CommandJob: # type: ignore[override] + async def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: # type: ignore[override] """Get a training job by name. :param name: The name of the job. Required. :type name: str - :return: The job as a flat :class:`~azure.ai.projects.models.CommandJob` with - ``name`` and ``id`` promoted from the Job resource envelope. - :rtype: ~azure.ai.projects.models.CommandJob + :return: The CommandJob or PipelineJob with ``name`` and ``id`` from the Job envelope. + :rtype: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob :raises ~azure.core.exceptions.HttpResponseError: """ self._inject_preview_header(kwargs) rest_result = await super().get(name=name, **kwargs) - return CommandJob._from_rest_object(rest_result) + return _from_rest_job(rest_result) @distributed_trace_async async def create_or_update( # type: ignore[override] self, name: str, - job: CommandJob, + job: Union[CommandJob, PipelineJob], *, skip_validation: bool = False, **kwargs: Any, - ) -> CommandJob: + ) -> Union[CommandJob, PipelineJob]: """Create or update a training job. :param name: The name of the job. Required. :type name: str - :param job: The command job to create or update. Required. - :type job: ~azure.ai.projects.models.CommandJob - :keyword skip_validation: If ``True``, skip the local validation step. - Defaults to ``False``. + :param job: The Command or Pipeline job to create or update. Required. + :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob + :keyword skip_validation: If ``True``, skip local CommandJob validation. + PipelineJob is submitted as-is. Defaults to ``False``. :paramtype skip_validation: bool :return: The created/updated job. - :rtype: ~azure.ai.projects.models.CommandJob + :rtype: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob :raises ~azure.core.exceptions.HttpResponseError: :raises ValueError: If required fields are missing or empty. """ - if not skip_validation: - _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) - await self._resolve_local_paths(name, job) + if isinstance(job, CommandJob): + if not skip_validation: + _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) + await self._resolve_local_paths(name, job) + elif not isinstance(job, PipelineJob): + raise TypeError("job must be a CommandJob or PipelineJob") self._inject_preview_header(kwargs) rest_body = _RestJob(properties=job) rest_result = await super().create_or_update(name=name, job=rest_body, **kwargs) - return CommandJob._from_rest_object(rest_result) + return _from_rest_job(rest_result) @distributed_trace_async async def begin_delete(self, name: str, **kwargs: Any) -> AsyncLROPoller[None]: # type: ignore[override] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py index 8f32166e17a5..c658b7dea95b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py @@ -269,6 +269,7 @@ Output, PendingUploadRequest, PendingUploadResponse, + PipelineJob, ProceduralMemoryItem, PromoteCandidateRequest, PromoteCandidateResponse, @@ -725,6 +726,7 @@ "Output", "PendingUploadRequest", "PendingUploadResponse", + "PipelineJob", "ProceduralMemoryItem", "PromoteCandidateRequest", "PromoteCandidateResponse", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py index ae15adcd7033..5d06fb74f749 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py @@ -750,6 +750,8 @@ class JobType(str, Enum, metaclass=CaseInsensitiveEnumMeta): COMMAND = "Command" """Command job.""" + PIPELINE = "Pipeline" + """Pipeline job.""" class ListViewType(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py index 50630f3f2f8e..831bfb0bcf48 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py @@ -3762,7 +3762,7 @@ class JobProperties(_Model): """Base properties of a Job. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CommandJob + CommandJob, PipelineJob :ivar job_type: Job type. Required. Default value is None. :vartype job_type: str @@ -12517,6 +12517,116 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class PipelineJob(JobProperties, discriminator="Pipeline"): + """Properties of a Pipeline Job. + + :ivar job_type: Job type. Required. Default value is "Pipeline". + :vartype job_type: str + :ivar display_name: Display name of the job. + :vartype display_name: str + :ivar description: The asset description text. + :vartype description: str + :ivar tags: Tag dictionary. Tags can be added, removed, and updated. + :vartype tags: dict[str, str] + :ivar properties: The asset property dictionary. + :vartype properties: dict[str, str] + :ivar experiment_name: Name of the experiment the job belongs to. If omitted, the service uses + "Default". + :vartype experiment_name: str + :ivar services: Services exposed by the job. + :vartype services: dict[str, ~azure.ai.projects.models.JobService] + :ivar compute_id: Compute resource ID. + :vartype compute_id: str + :ivar settings: Pipeline settings. + :vartype settings: dict[str, any] + :ivar jobs: Pipeline nodes keyed by name. Node objects preserve their original field names. + :vartype jobs: dict[str, dict[str, any]] + :ivar inputs: Graph inputs keyed by name. + :vartype inputs: dict[str, dict[str, any]] + :ivar outputs: Graph outputs keyed by name. + :vartype outputs: dict[str, dict[str, any]] + :ivar source_job_id: ARM resource ID of the source job. + :vartype source_job_id: str + :ivar is_archived: Is the job archived?. + :vartype is_archived: bool + :ivar status: Status of the job. + :vartype status: str + """ + + job_type: Literal["Pipeline"] = rest_discriminator(name="jobType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Job type. Required. Default value is \"Pipeline\".""" + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """Display name of the job.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The asset description text.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tag dictionary. Tags can be added, removed, and updated.""" + properties: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The asset property dictionary.""" + experiment_name: Optional[str] = rest_field( + name="experimentName", visibility=["read", "create", "update", "delete", "query"] + ) + """Name of the experiment the job belongs to. If omitted, the service uses \"Default\".""" + services: Optional[dict[str, "_models.JobService"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Services exposed by the job.""" + compute_id: Optional[str] = rest_field(name="computeId", visibility=["read", "create", "update", "delete", "query"]) + """Compute resource ID.""" + settings: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Pipeline settings.""" + jobs: Optional[dict[str, dict[str, Any]]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Pipeline nodes keyed by name. Node objects preserve their original field names.""" + inputs: Optional[dict[str, dict[str, Any]]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Graph inputs keyed by name.""" + outputs: Optional[dict[str, dict[str, Any]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Graph outputs keyed by name.""" + source_job_id: Optional[str] = rest_field( + name="sourceJobId", visibility=["read", "create", "update", "delete", "query"] + ) + """ARM resource ID of the source job.""" + is_archived: Optional[bool] = rest_field( + name="isArchived", visibility=["read", "create", "update", "delete", "query"] + ) + """Is the job archived?.""" + status: Optional[str] = rest_field(visibility=["read"]) + """Status of the job.""" + + @overload + def __init__( + self, + *, + display_name: Optional[str] = None, + description: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + properties: Optional[dict[str, str]] = None, + experiment_name: Optional[str] = None, + services: Optional[dict[str, "_models.JobService"]] = None, + compute_id: Optional[str] = None, + settings: Optional[dict[str, Any]] = None, + jobs: Optional[dict[str, dict[str, Any]]] = None, + inputs: Optional[dict[str, dict[str, Any]]] = None, + outputs: Optional[dict[str, dict[str, Any]]] = None, + source_job_id: Optional[str] = None, + is_archived: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.job_type = "Pipeline" # type: ignore + + class ProceduralMemoryItem(MemoryItem, discriminator="procedural"): """A memory item containing a procedure extracted from conversations. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py index e5e6f5bc3277..776f673323cf 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py @@ -21,6 +21,7 @@ CommandJob, CommandJobLimits, Diagnostic, + PipelineJob, ServiceInstance, ValidationResult, load_job, @@ -428,6 +429,7 @@ def from_continuation_token( "EvalCsvFileIdSource", "EvalCsvRunDataSource", "ModelSamplingConfigParam", + "PipelineJob", "RedTeamEvalRunDataSource", "ResponseRetrievalItemGenerationParams", "ServiceInstance", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index 0c50eaf1685b..bea57e4713ef 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -19,6 +19,7 @@ JobResourceConfiguration, MpiDistribution, Output, + PipelineJob as _RestPipelineJob, PyTorchDistribution, QueueSettings, ServiceInstance as _RestServiceInstance, @@ -103,6 +104,59 @@ def _from_rest_object(cls, rest_obj: Union[_RestJob, Any]) -> "CommandJob": return obj +class PipelineJob(_RestPipelineJob): + """A pipeline job with graph nodes, inputs, and outputs. + + :ivar name: The name of the job. Read-only; populated after the job is created. + :vartype name: str or None + :ivar id: The resource ID of the job. Read-only; populated after the job is created. + :vartype id: str or None + :ivar system_data: Metadata pertaining to creation and last modification of the job. + :vartype system_data: ~azure.ai.projects.models.SystemData or None + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._name: Optional[str] = None + self._id: Optional[str] = None + self._system_data: Optional[SystemData] = None + + @property + def name(self) -> Optional[str]: + """The name of the job.""" + return self._name + + @property + def id(self) -> Optional[str]: + """The resource ID of the job.""" + return self._id + + @property + def system_data(self) -> Optional[SystemData]: + """Metadata pertaining to creation and last modification of the job.""" + return self._system_data + + @classmethod + def _from_rest_object(cls, rest_obj: _RestJob) -> "PipelineJob": + props = rest_obj.properties + if not isinstance(props, _RestPipelineJob): + raise TypeError( + f"Cannot convert REST Job to PipelineJob: expected properties of type " + f"PipelineJob, but got {type(props).__name__}." + ) + obj = cls(props) + obj._name = rest_obj.name + obj._id = rest_obj.id + obj._system_data = rest_obj.system_data + return obj + + +def _from_rest_job(rest_obj: _RestJob) -> Union[CommandJob, PipelineJob]: + if isinstance(rest_obj.properties, _RestPipelineJob): + return PipelineJob._from_rest_object(rest_obj) + return CommandJob._from_rest_object(rest_obj) + + class CommandJobLimits(_RestCommandJobLimits): def __init__( # type: ignore[override] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py index 68e25954b038..2297f661553d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py @@ -3805,7 +3805,7 @@ def build_beta_jobs_list_request( _url = "/jobs" # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if job_type is not None: _params["jobType"] = _SERIALIZER.query("job_type", job_type, "str") if tag is not None: @@ -3837,7 +3837,7 @@ def build_beta_jobs_get_request(name: str, **kwargs: Any) -> HttpRequest: _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -3863,7 +3863,7 @@ def build_beta_jobs_show_services_request(name: str, run_id: str, node_id: int, _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -3888,7 +3888,7 @@ def build_beta_jobs_get_run_details_request(name: str, run_id: str, **kwargs: An _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -3913,7 +3913,7 @@ def build_beta_jobs_get_run_request(name: str, run_id: str, **kwargs: Any) -> Ht _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -3948,7 +3948,7 @@ def build_beta_jobs_list_artifacts_request( _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if path is not None: _params["path"] = _SERIALIZER.query("path", path, "str") if continuation_token_parameter is not None: @@ -3990,7 +3990,7 @@ def build_beta_jobs_get_artifact_content_information_request( # pylint: disable _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if path is not None: _params["path"] = _SERIALIZER.query("path", path, "str") if continuation_token_parameter is not None: @@ -4021,7 +4021,7 @@ def build_beta_jobs_create_or_update_request(name: str, **kwargs: Any) -> HttpRe _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: @@ -4044,7 +4044,7 @@ def build_beta_jobs_begin_delete_request(name: str, **kwargs: Any) -> HttpReques _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) @@ -4062,7 +4062,7 @@ def build_beta_jobs_begin_cancel_request(name: str, **kwargs: Any) -> HttpReques _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", "2026-01-15-preview", "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") return HttpRequest(method="POST", url=_url, params=_params, **kwargs) @@ -13177,7 +13177,7 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): - if body is _Unset: # pyright: ignore[reportUnboundVariable] + if body is _Unset: if scope is _Unset: raise TypeError("missing required argument: scope") body = {"scope": scope} @@ -18103,7 +18103,8 @@ def list( ) -> ItemPaged["_models.Job"]: """List Jobs. - :keyword job_type: Filter by job type (e.g. 'Command'). "Command" Default value is None. + :keyword job_type: Filter by job type (e.g. 'Command' or 'Pipeline'). Known values are: + "Command" and "Pipeline". Default value is None. :paramtype job_type: str or ~azure.ai.projects.models.JobType :keyword tag: Filter jobs by tag in the format 'key=value' (e.g., 'framework=pytorch'). Default value is None. @@ -18159,7 +18160,7 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = "2026-01-15-preview" + _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py index 6b9fded50f95..9b788c68ba8d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py @@ -135,7 +135,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.memory_stores = BetaMemoryStoresOperations(self._client, self._config, self._serialize, self._deserialize) # Replace with patched class that includes create (3-step upload helper) self.models = BetaModelsOperations(self._client, self._config, self._serialize, self._deserialize) - # Replace with patched class that exposes flat CommandJob UX + # Replace with patched class that exposes flat CommandJob and PipelineJob UX self.jobs = BetaJobsOperations(self._client, self._config, self._serialize, self._deserialize) for property_name, foundry_features_value in _BETA_OPERATION_FEATURE_HEADERS.items(): diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index c7e6f6a61e8d..d618b1671056 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -3,8 +3,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -"""Customized jobs operations — flat CommandJob UX, no envelope required.""" +"""Customized jobs operations — flat CommandJob and PipelineJob UX, no envelope required.""" +from copy import copy import json import logging import sys @@ -65,7 +66,7 @@ from ..models._models import Output as _Output from ..models._models import ModelCredentialRequest as _ModelCredentialRequest from ..models._enums import AssetTypes -from ..models._patch_jobs import CommandJob, ServiceInstance, ValidationResult +from ..models._patch_jobs import CommandJob, PipelineJob, ServiceInstance, ValidationResult, _from_rest_job from ..models._patch import _FOUNDRY_FEATURES_HEADER_NAME, _has_header_case_insensitive from ..models._enums import _FoundryFeaturesOptInKeys @@ -73,8 +74,8 @@ class JobsOperations(_GeneratedJobsOps): - """Patched Jobs operations that expose a flat :class:`~azure.ai.projects.models.CommandJob` - interface — no ``Job`` envelope wrapping required by callers. + """Patched Jobs operations that expose flat :class:`~azure.ai.projects.models.CommandJob` + and :class:`~azure.ai.projects.models.PipelineJob` objects without a ``Job`` envelope. Also automatically injects the ``Foundry-Features: Jobs=V1Preview`` preview opt-in header into every request so callers do not need to supply it manually. @@ -89,8 +90,13 @@ class JobsOperations(_GeneratedJobsOps): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self._datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) - self._models = _GeneratedModelsOps(self._client, self._config, self._serialize, self._deserialize) + original_config = self._config + # Generated Jobs operations use config.api_version; keep the existing preview route + # without changing the shared v1 config used by datasets and models. + self._config = copy(original_config) + self._config.api_version = "2026-01-15-preview" + self._datasets = DatasetsOperations(self._client, original_config, self._serialize, self._deserialize) + self._models = _GeneratedModelsOps(self._client, original_config, self._serialize, self._deserialize) @distributed_trace def validate( @@ -284,11 +290,10 @@ def list( # type: ignore[override] list_view_type: Optional[Union[str, Any]] = None, properties: Optional[str] = None, **kwargs: Any, - ) -> ItemPaged[CommandJob]: - """List all training jobs as flat :class:`~azure.ai.projects.models.CommandJob` - objects with ``name`` and ``id`` promoted from the Job resource envelope. + ) -> ItemPaged[Union[CommandJob, PipelineJob]]: + """List Command and Pipeline jobs with ``name`` and ``id`` promoted from the Job envelope. - :keyword job_type: Filter by job type (e.g. ``'Command'``). Default value is None. + :keyword job_type: Filter by job type (``'Command'`` or ``'Pipeline'``). Default value is None. :paramtype job_type: str or ~azure.ai.projects.models.JobType :keyword tag: Filter by tag in the format ``'key=value'``. Default value is None. :paramtype tag: str @@ -296,14 +301,14 @@ def list( # type: ignore[override] :paramtype list_view_type: str or ~azure.ai.projects.models.ListViewType :keyword properties: Comma-separated user properties filter. Default value is None. :paramtype properties: str - :return: An iterator like instance of :class:`~azure.ai.projects.models.CommandJob`. - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.CommandJob] + :return: An iterator of CommandJob or PipelineJob objects. + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob] :raises ~azure.core.exceptions.HttpResponseError: """ self._inject_preview_header(kwargs) - def _convert_page(page: List) -> List[CommandJob]: - return [CommandJob._from_rest_object(item) for item in page] + def _convert_page(page: List[_RestJob]) -> List[Union[CommandJob, PipelineJob]]: + return [_from_rest_job(item) for item in page] return super().list( job_type=job_type, @@ -315,51 +320,53 @@ def _convert_page(page: List) -> List[CommandJob]: ) # type: ignore[return-value] @distributed_trace - def get(self, name: str, **kwargs: Any) -> CommandJob: # type: ignore[override] + def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: # type: ignore[override] """Get a training job by name. :param name: The name of the job. Required. :type name: str - :return: The job as a flat :class:`~azure.ai.projects.models.CommandJob` with - ``name`` and ``id`` promoted from the Job resource envelope. - :rtype: ~azure.ai.projects.models.CommandJob + :return: The CommandJob or PipelineJob with ``name`` and ``id`` from the Job envelope. + :rtype: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob :raises ~azure.core.exceptions.HttpResponseError: """ self._inject_preview_header(kwargs) rest_result = super().get(name=name, **kwargs) - return CommandJob._from_rest_object(rest_result) + return _from_rest_job(rest_result) @distributed_trace def create_or_update( # type: ignore[override] self, name: str, - job: CommandJob, + job: Union[CommandJob, PipelineJob], *, skip_validation: bool = False, **kwargs: Any, - ) -> CommandJob: + ) -> Union[CommandJob, PipelineJob]: """Create or update a training job. :param name: The name of the job. Required. :type name: str - :param job: The command job to create or update. Required. - :type job: ~azure.ai.projects.models.CommandJob - :keyword skip_validation: If ``True``, skip the local validation step. - Defaults to ``False``. + :param job: The Command or Pipeline job to create or update. Required. + :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob + :keyword skip_validation: If ``True``, skip local CommandJob validation. + PipelineJob is submitted as-is. Defaults to ``False``. :paramtype skip_validation: bool :return: The created/updated job. - :rtype: ~azure.ai.projects.models.CommandJob + :rtype: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob :raises ~azure.core.exceptions.HttpResponseError: :raises ValueError: If required fields are missing or empty. """ - if not skip_validation: - _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) - self._resolve_local_paths(name, job) + if isinstance(job, CommandJob): + if not skip_validation: + _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) + self._resolve_local_paths(name, job) + elif not isinstance(job, PipelineJob): + raise TypeError("job must be a CommandJob or PipelineJob") self._inject_preview_header(kwargs) - # Wrap the flat CommandJob inside the Job envelope required by the wire format + # Wrap the flat job inside the Job envelope required by the wire format. rest_body = _RestJob(properties=job) rest_result = super().create_or_update(name=name, job=rest_body, **kwargs) - return CommandJob._from_rest_object(rest_result) + return _from_rest_job(rest_result) # LRO is implemented here rather than via TypeSpec @pollingOperation because the backend # uses pure HTTP-status-code Location polling (202=in-progress, 200/204=done) with no diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py new file mode 100644 index 000000000000..08b3a1515ac1 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -0,0 +1,218 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Offline wire and response tests for Command and Pipeline jobs.""" + +import json +from typing import Any, Union +from urllib.parse import parse_qs, urlparse + +import pytest +from azure.core.credentials import AccessToken +from azure.core.pipeline.transport import ( + AsyncHttpResponse, + AsyncHttpTransport, + HttpRequest, + HttpResponse, + HttpTransport, +) + +from azure.ai.projects import AIProjectClient +from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient +from azure.ai.projects.models import CommandJob, JobType, PipelineJob + +_ENDPOINT = "https://fake-account.services.ai.azure.com/api/projects/fake-project" +_COMPUTE = "/subscriptions/test/resourceGroups/test/providers/Microsoft.CognitiveServices/accounts/test/computes/cpu" +_PIPELINE_PROPERTIES = { + "jobType": "Pipeline", + "displayName": "example pipeline", + "computeId": _COMPUTE, + "settings": {"continueOnStepFailure": False}, + "jobs": { + "train": { + "jobType": "Command", + "command": "python train.py --data ${{parent.inputs.training_data}}", + "environmentImageReference": "example.azurecr.io/train:latest", + "inputs": {"training_data": {"path": "${{parent.inputs.training_data}}", "mode": "ro_mount"}}, + } + }, + "inputs": {"training_data": {"type": "uri_folder", "path": "azureml://datastores/test/paths/training/"}}, + "outputs": {"model": {"type": "uri_folder", "mode": "rw_mount"}}, +} +_COMMAND_PROPERTIES = { + "jobType": "Command", + "command": "echo hello", + "environmentImageReference": "example.azurecr.io/train:latest", + "computeId": _COMPUTE, +} + + +class _Credential: + def get_token(self, *args: Any, **kwargs: Any) -> AccessToken: + return AccessToken("fake-token", 9_999_999_999) + + +class _AsyncCredential: + async def get_token(self, *args: Any, **kwargs: Any) -> AccessToken: + return AccessToken("fake-token", 9_999_999_999) + + +class _JsonResponse(HttpResponse): + def __init__(self, request: HttpRequest, payload: dict[str, Any]) -> None: + super().__init__(request, None) + self.status_code = 200 + self.headers["Content-Type"] = "application/json" + self._content = json.dumps(payload).encode() + + def body(self) -> bytes: + return self._content + + def json(self) -> Any: + return json.loads(self._content) + + +class _AsyncJsonResponse(AsyncHttpResponse): + def __init__(self, request: HttpRequest, payload: dict[str, Any]) -> None: + super().__init__(request, None) + self.status_code = 200 + self.headers["Content-Type"] = "application/json" + self._content = json.dumps(payload).encode() + + def body(self) -> bytes: + return self._content + + async def read(self) -> bytes: + return self._content + + def json(self) -> Any: + return json.loads(self._content) + + +class _Transport(HttpTransport): + def __init__(self, responses: list[dict[str, Any]]) -> None: + self._responses = iter(responses) + self.requests: list[HttpRequest] = [] + + def send(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + self.requests.append(request) + return _JsonResponse(request, next(self._responses)) + + def open(self) -> None: + pass + + def close(self) -> None: + pass + + def __exit__(self, *args: Any) -> None: + pass + + +class _AsyncTransport(AsyncHttpTransport): + def __init__(self, responses: list[dict[str, Any]]) -> None: + self._responses = iter(responses) + self.requests: list[HttpRequest] = [] + + async def send(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + self.requests.append(request) + return _AsyncJsonResponse(request, next(self._responses)) + + async def open(self) -> None: + pass + + async def close(self) -> None: + pass + + async def __aexit__(self, *args: Any) -> None: + pass + + +def _job(kind: str) -> tuple[Union[CommandJob, PipelineJob], dict[str, Any]]: + if kind == "Pipeline": + return ( + PipelineJob( + display_name="example pipeline", + compute_id=_COMPUTE, + settings=_PIPELINE_PROPERTIES["settings"], + jobs=_PIPELINE_PROPERTIES["jobs"], + inputs=_PIPELINE_PROPERTIES["inputs"], + outputs=_PIPELINE_PROPERTIES["outputs"], + ), + _PIPELINE_PROPERTIES, + ) + return ( + CommandJob( + command="echo hello", + environment_image_reference="example.azurecr.io/train:latest", + compute=_COMPUTE, + ), + _COMMAND_PROPERTIES, + ) + + +def _response(kind: str) -> dict[str, Any]: + return { + "name": kind.lower(), + "id": f"/jobs/{kind.lower()}", + "properties": _PIPELINE_PROPERTIES if kind == "Pipeline" else _COMMAND_PROPERTIES, + } + + +def _assert_job(result: Union[CommandJob, PipelineJob], kind: str) -> None: + assert isinstance(result, PipelineJob if kind == "Pipeline" else CommandJob) + assert result.job_type == kind + assert result.name == kind.lower() + assert result.id == f"/jobs/{kind.lower()}" + if kind == "Pipeline": + assert result.jobs == _PIPELINE_PROPERTIES["jobs"] + assert result.inputs == _PIPELINE_PROPERTIES["inputs"] + assert result.outputs == _PIPELINE_PROPERTIES["outputs"] + assert result.settings == _PIPELINE_PROPERTIES["settings"] + + +def _assert_requests(requests: list[HttpRequest], kind: str, expected: dict[str, Any]) -> None: + assert len(requests) == 3 + assert [request.method for request in requests] == ["PUT", "GET", "GET"] + for request in requests: + assert request.headers["Foundry-Features"] == "Jobs=V1Preview" + assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] + assert urlparse(requests[0].url).path.endswith(f"/jobs/{kind.lower()}") + assert json.loads(requests[0].body) == {"properties": expected} + assert JobType.PIPELINE == "Pipeline" + + +@pytest.mark.parametrize("kind", ["Command", "Pipeline"]) +def test_jobs_sync_create_get_and_list(kind: str) -> None: + job, expected = _job(kind) + transport = _Transport([_response(kind), _response(kind), {"value": [_response("Command"), _response("Pipeline")]}]) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + _assert_job(client.beta.jobs.create_or_update(kind.lower(), job), kind) + _assert_job(client.beta.jobs.get(kind.lower()), kind) + listed = list(client.beta.jobs.list()) + assert len(listed) == 2 + _assert_job(listed[0], "Command") + _assert_job(listed[1], "Pipeline") + + _assert_requests(transport.requests, kind, expected) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["Command", "Pipeline"]) +async def test_jobs_async_create_get_and_list(kind: str) -> None: + job, expected = _job(kind) + transport = _AsyncTransport( + [_response(kind), _response(kind), {"value": [_response("Command"), _response("Pipeline")]}] + ) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + _assert_job(await client.beta.jobs.create_or_update(kind.lower(), job), kind) + _assert_job(await client.beta.jobs.get(kind.lower()), kind) + listed = [item async for item in client.beta.jobs.list()] + assert len(listed) == 2 + _assert_job(listed[0], "Command") + _assert_job(listed[1], "Pipeline") + + _assert_requests(transport.requests, kind, expected) diff --git a/sdk/ai/azure-ai-projects/tsp-location.yaml b/sdk/ai/azure-ai-projects/tsp-location.yaml index ac0d403d2563..de893a73e51b 100644 --- a/sdk/ai/azure-ai-projects/tsp-location.yaml +++ b/sdk/ai/azure-ai-projects/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/ai-foundry/data-plane/Foundry -commit: 0992bcf9661b67ce60bc836e48630ee1aeab3b51 +commit: ba4d0e3c01618a703851b2e2dd1b6c829ec7d6e4 repo: Azure/azure-rest-api-specs additionalDirectories: From a3070d426ba8d2b13e4eaa3a99751b260e0aac15 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Sat, 3 Oct 2026 06:15:44 -0700 Subject: [PATCH 02/52] Narrow PipelineJob assertion type in offline tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure-ai-projects/tests/jobs/test_pipeline_jobs.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 08b3a1515ac1..bb78ac89b15f 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -159,15 +159,17 @@ def _response(kind: str) -> dict[str, Any]: def _assert_job(result: Union[CommandJob, PipelineJob], kind: str) -> None: - assert isinstance(result, PipelineJob if kind == "Pipeline" else CommandJob) - assert result.job_type == kind - assert result.name == kind.lower() - assert result.id == f"/jobs/{kind.lower()}" if kind == "Pipeline": + assert isinstance(result, PipelineJob) assert result.jobs == _PIPELINE_PROPERTIES["jobs"] assert result.inputs == _PIPELINE_PROPERTIES["inputs"] assert result.outputs == _PIPELINE_PROPERTIES["outputs"] assert result.settings == _PIPELINE_PROPERTIES["settings"] + else: + assert isinstance(result, CommandJob) + assert result.job_type == kind + assert result.name == kind.lower() + assert result.id == f"/jobs/{kind.lower()}" def _assert_requests(requests: list[HttpRequest], kind: str, expected: dict[str, Any]) -> None: From 751518e30d36f38f0825877483e3981c3eac2521 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Sat, 3 Oct 2026 07:21:39 -0700 Subject: [PATCH 03/52] Accept CommandJob nodes in PipelineJob graphs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/tools/azure-sdk-tools/azpysdk/samples.py | 1 + sdk/ai/azure-ai-projects/CHANGELOG.md | 1 + .../azure/ai/projects/models/_patch_jobs.py | 85 ++++++++++++ .../jobs/sample_pipeline_hello_world.py | 67 +++++++++ .../tests/jobs/test_pipeline_jobs.py | 131 +++++++++++++++++- 5 files changed, 284 insertions(+), 1 deletion(-) create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py diff --git a/eng/tools/azure-sdk-tools/azpysdk/samples.py b/eng/tools/azure-sdk-tools/azpysdk/samples.py index a7f7b83e229e..5e288157f2f2 100644 --- a/eng/tools/azure-sdk-tools/azpysdk/samples.py +++ b/eng/tools/azure-sdk-tools/azpysdk/samples.py @@ -75,6 +75,7 @@ # Add your library + sample file if you do not want a particular sample to be run IGNORED_SAMPLES = { + "azure-ai-projects": ["sample_pipeline_hello_world.py"], "azure-appconfiguration-provider": [ "key_vault_reference_customized_clients_sample.py", "aad_sample.py", diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 31ddd4ce30a4..859371a6ef27 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -25,6 +25,7 @@ * New optional `blueprint_reference` parameters on `agents.create_version` method. * New `.beta.jobs` sub-client with CommandJob operations: `create_or_update`, `get`, `list`, `begin_delete`, `begin_cancel`, `validate`, `show_services`, `stream`, `download`. * Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Pipeline graph nodes, inputs, outputs, and settings are sent as provided; local asset handling and validation remain specific to Command jobs. +* `PipelineJob.jobs` also accepts `CommandJob` instances with literal inputs, converting them to inline command nodes. Raw graph dictionaries remain supported for other node features. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index bea57e4713ef..ea27d79636b3 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -107,6 +107,10 @@ def _from_rest_object(cls, rest_obj: Union[_RestJob, Any]) -> "CommandJob": class PipelineJob(_RestPipelineJob): """A pipeline job with graph nodes, inputs, and outputs. + ``jobs`` accepts raw graph node dictionaries or :class:`CommandJob` instances + with literal inputs. Command jobs are converted to inline command nodes; + use raw graph dictionaries for other node features. + :ivar name: The name of the job. Read-only; populated after the job is created. :vartype name: str or None :ivar id: The resource ID of the job. Read-only; populated after the job is created. @@ -116,11 +120,92 @@ class PipelineJob(_RestPipelineJob): """ def __init__(self, *args: Any, **kwargs: Any) -> None: + jobs = kwargs.get("jobs") + if isinstance(jobs, dict) and any(isinstance(node, CommandJob) for node in jobs.values()): + settings = kwargs.get("settings") + default_compute = settings.get("default_compute") if isinstance(settings, dict) else None + default_compute = default_compute or kwargs.get("compute_id") + kwargs["jobs"] = { + name: self._command_node(name, node, default_compute) if isinstance(node, CommandJob) else node + for name, node in jobs.items() + } super().__init__(*args, **kwargs) self._name: Optional[str] = None self._id: Optional[str] = None self._system_data: Optional[SystemData] = None + @staticmethod + def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> Dict[str, Any]: + unsupported = set(job.as_dict(exclude_readonly=True)) - { + "jobType", + "command", + "environmentImageReference", + "computeId", + "inputs", + "resources", + "userAssignedIdentityId", + } + if unsupported: + raise ValueError( + f"Pipeline node '{name}' cannot convert CommandJob fields {sorted(unsupported)}; " + "use a raw graph node for these fields." + ) + if not job.command or not job.environment_image_reference: + raise ValueError(f"Pipeline node '{name}' requires a command and environment image.") + if not default_compute or job.compute != default_compute: + raise ValueError( + f"Pipeline node '{name}' must use the pipeline's default compute; " + "use a raw graph node for another compute." + ) + + inputs: Dict[str, Any] = {} + for input_name, job_input in (job.inputs or {}).items(): + if ( + not isinstance(job_input, Input) + or job_input.type != "literal" + or job_input.value is None + or set(job_input.as_dict()) - {"jobInputType", "value"} + ): + raise ValueError( + f"Pipeline node '{name}' cannot convert input '{input_name}'; " + "only literal CommandJob inputs are supported. Use a raw graph node for other inputs." + ) + inputs[input_name] = {"job_input_type": "literal", "value": job_input.value} + + node: Dict[str, Any] = { + "type": "command", + "component": { + "name": name, + "version": "1", + "type": "command", + "command": job.command, + "environment": {"image": job.environment_image_reference}, + "inputs": {input_name: {"type": "string"} for input_name in inputs}, + "outputs": {}, + }, + "inputs": inputs, + "outputs": {}, + } + if job.user_assigned_identity_id is not None: + node["identity"] = {"type": "managed", "msi_resource_id": job.user_assigned_identity_id} + + if job.resources is not None: + unsupported_resources = set(job.resources.as_dict()) - {"instanceCount", "instanceType", "properties"} + if unsupported_resources: + raise ValueError( + f"Pipeline node '{name}' cannot convert resource fields {sorted(unsupported_resources)}; " + "use a raw graph node for these fields." + ) + resources = {} + if job.resources.instance_count is not None: + resources["instance_count"] = job.resources.instance_count + if job.resources.instance_type is not None: + resources["instance_type"] = job.resources.instance_type + if job.resources.properties is not None: + resources["properties"] = job.resources.properties + node["resources"] = resources + return node + @property def name(self) -> Optional[str]: """The name of the job.""" diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py new file mode 100644 index 000000000000..80671bf38562 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py @@ -0,0 +1,67 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""One-step PipelineJob sample. Review the request before running it against a project. + +Set FOUNDRY_PROJECT_ENDPOINT, JOB_NAME, JOB_COMPUTE_ID (full compute resource ID), +JOB_ENVIRONMENT_IMAGE (direct container image), JOB_NODE_UAI_RESOURCE_ID (full +user-assigned identity resource ID), and JOB_INSTANCE_TYPE for the target compute. +DefaultAzureCredential must have permission to submit jobs to the project. +""" + +import os + +from azure.ai.projects import AIProjectClient +from azure.ai.projects.models import CommandJob, Input, JobResourceConfiguration, PipelineJob +from azure.identity import DefaultAzureCredential + + +def build_job(compute_id: str, image: str, node_uai_id: str, instance_type: str) -> PipelineJob: + command = CommandJob( + command="echo hello ${{inputs.name}}", + environment_image_reference=image, + compute=compute_id, + inputs={"name": Input(type="literal", value="${{parent.inputs.name}}")}, + user_assigned_identity_id=node_uai_id, + resources=JobResourceConfiguration( + { + "instanceCount": 1, + "instanceType": instance_type, + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + } + ), + ) + return PipelineJob( + display_name="Pipeline hello world", + compute_id=compute_id, + settings={"default_compute": compute_id, "force_rerun": True}, + inputs={"name": Input(type="literal", value="world")}, + outputs={}, + jobs={"hello": command}, + ) + + +def main() -> None: + endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"] + job_name = os.environ["JOB_NAME"] + job = build_job( + compute_id=os.environ["JOB_COMPUTE_ID"], + image=os.environ["JOB_ENVIRONMENT_IMAGE"], + node_uai_id=os.environ["JOB_NODE_UAI_RESOURCE_ID"], + instance_type=os.environ["JOB_INSTANCE_TYPE"], + ) + with ( + DefaultAzureCredential() as credential, + AIProjectClient(endpoint=endpoint, credential=credential) as client, + ): + created = client.beta.jobs.create_or_update( + name=job_name, + job=job, + headers={"x-ms-foundry-job-route": "execution"}, + ) + print(f"Submitted {created.name}: {created.id} (status: {created.status})") + + +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index bb78ac89b15f..efecfc4a0625 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -20,7 +20,7 @@ from azure.ai.projects import AIProjectClient from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient -from azure.ai.projects.models import CommandJob, JobType, PipelineJob +from azure.ai.projects.models import AssetTypes, CommandJob, Input, JobResourceConfiguration, JobType, PipelineJob _ENDPOINT = "https://fake-account.services.ai.azure.com/api/projects/fake-project" _COMPUTE = "/subscriptions/test/resourceGroups/test/providers/Microsoft.CognitiveServices/accounts/test/computes/cpu" @@ -46,6 +46,35 @@ "environmentImageReference": "example.azurecr.io/train:latest", "computeId": _COMPUTE, } +_INLINE_PIPELINE_PROPERTIES = { + "jobType": "Pipeline", + "computeId": _COMPUTE, + "settings": {"default_compute": _COMPUTE, "force_rerun": True}, + "inputs": {"name": {"jobInputType": "literal", "value": "world"}}, + "outputs": {}, + "jobs": { + "hello": { + "type": "command", + "identity": {"type": "managed", "msi_resource_id": "/subscriptions/test/identities/hello"}, + "component": { + "name": "hello", + "version": "1", + "type": "command", + "command": "echo hello ${{inputs.name}}", + "environment": {"image": "example.azurecr.io/train:latest"}, + "inputs": {"name": {"type": "string"}}, + "outputs": {}, + }, + "resources": { + "instance_count": 1, + "instance_type": "Standard_D4_v3", + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + }, + "inputs": {"name": {"job_input_type": "literal", "value": "${{parent.inputs.name}}"}}, + "outputs": {}, + } + }, +} class _Credential: @@ -183,6 +212,106 @@ def _assert_requests(requests: list[HttpRequest], kind: str, expected: dict[str, assert JobType.PIPELINE == "Pipeline" +def _inline_pipeline() -> tuple[PipelineJob, CommandJob]: + command = CommandJob( + command="echo hello ${{inputs.name}}", + environment_image_reference="example.azurecr.io/train:latest", + compute=_COMPUTE, + inputs={"name": Input(type=AssetTypes.LITERAL, value="${{parent.inputs.name}}")}, + user_assigned_identity_id="/subscriptions/test/identities/hello", + resources=JobResourceConfiguration( + { + "instanceCount": 1, + "instanceType": "Standard_D4_v3", + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + } + ), + ) + pipeline = PipelineJob( + compute_id=_COMPUTE, + settings={"default_compute": _COMPUTE, "force_rerun": True}, + inputs={"name": Input(type=AssetTypes.LITERAL, value="world")}, + outputs={}, + jobs={"hello": command}, + ) + return pipeline, command + + +def _assert_inline_request(request: HttpRequest) -> None: + assert request.method == "PUT" + assert request.headers["Foundry-Features"] == "Jobs=V1Preview" + assert json.loads(request.body) == {"properties": _INLINE_PIPELINE_PROPERTIES} + + +def test_jobs_sync_create_from_command_node() -> None: + pipeline, command = _inline_pipeline() + transport = _Transport([_response("Pipeline")]) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + _assert_job(client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") + + assert len(transport.requests) == 1 + _assert_inline_request(transport.requests[0]) + assert command.inputs["name"].value == "${{parent.inputs.name}}" + assert command.resources.instance_type == "Standard_D4_v3" + + +@pytest.mark.asyncio +async def test_jobs_async_create_from_command_node() -> None: + pipeline, _ = _inline_pipeline() + transport = _AsyncTransport([_response("Pipeline")]) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + _assert_job(await client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") + + assert len(transport.requests) == 1 + _assert_inline_request(transport.requests[0]) + + +def test_pipeline_composes_commands_and_preserves_raw_graph_nodes() -> None: + first, _ = _inline_pipeline() + raw_node = {"type": "command", "component": {"name": "raw", "version": "1"}} + pipeline = PipelineJob( + compute_id=_COMPUTE, + jobs={ + "hello": CommandJob( + command="echo hello", environment_image_reference="example.azurecr.io/train:latest", compute=_COMPUTE + ), + "second": CommandJob( + command="echo again", environment_image_reference="example.azurecr.io/train:latest", compute=_COMPUTE + ), + "raw": raw_node, + }, + ) + + assert pipeline.jobs["hello"]["component"]["command"] == "echo hello" + assert pipeline.jobs["second"]["component"]["command"] == "echo again" + assert pipeline.jobs["raw"] == raw_node + assert first.jobs["hello"] == _INLINE_PIPELINE_PROPERTIES["jobs"]["hello"] + + +@pytest.mark.parametrize( + ("extra", "message"), + [ + ({"code": "azureai:code:1"}, "codeId"), + ({"inputs": {"data": Input(type=AssetTypes.URI_FILE, path="azureai:data:1")}}, "input 'data'"), + ({"compute": "/subscriptions/test/computes/other"}, "default compute"), + ({"resources": JobResourceConfiguration({"shmSize": "1g"})}, "shmSize"), + ], +) +def test_pipeline_rejects_unmapped_command_fields(extra: dict[str, Any], message: str) -> None: + fields: dict[str, Any] = { + "command": "echo hello", + "environment_image_reference": "example.azurecr.io/train:latest", + "compute": _COMPUTE, + } + fields.update(extra) + with pytest.raises(ValueError, match=message): + PipelineJob(compute_id=_COMPUTE, jobs={"hello": CommandJob(**fields)}) + + @pytest.mark.parametrize("kind", ["Command", "Pipeline"]) def test_jobs_sync_create_get_and_list(kind: str) -> None: job, expected = _job(kind) From deb7a04cdf67bdd4046673ec58d6d9652deb96c9 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Sat, 3 Oct 2026 07:23:03 -0700 Subject: [PATCH 04/52] Narrow optional Job fields in Pipeline tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index efecfc4a0625..c368542955f9 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -252,7 +252,9 @@ def test_jobs_sync_create_from_command_node() -> None: assert len(transport.requests) == 1 _assert_inline_request(transport.requests[0]) + assert command.inputs is not None assert command.inputs["name"].value == "${{parent.inputs.name}}" + assert command.resources is not None assert command.resources.instance_type == "Standard_D4_v3" @@ -286,9 +288,11 @@ def test_pipeline_composes_commands_and_preserves_raw_graph_nodes() -> None: }, ) + assert pipeline.jobs is not None assert pipeline.jobs["hello"]["component"]["command"] == "echo hello" assert pipeline.jobs["second"]["component"]["command"] == "echo again" assert pipeline.jobs["raw"] == raw_node + assert first.jobs is not None assert first.jobs["hello"] == _INLINE_PIPELINE_PROPERTIES["jobs"]["hello"] From 9424d842ec24917b3a6de088f2c11ead1fba7b90 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Sat, 3 Oct 2026 07:27:24 -0700 Subject: [PATCH 05/52] Convert Command nodes across PipelineJob model entry points Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../aio/operations/_patch_jobs_async.py | 2 + .../azure/ai/projects/models/_patch_jobs.py | 37 ++++++++++++--- .../ai/projects/operations/_patch_jobs.py | 2 + .../tests/jobs/test_pipeline_jobs.py | 46 +++++++++++++++++++ 4 files changed, 80 insertions(+), 7 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index ba2a0719aeef..89c3ed18f301 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -354,6 +354,8 @@ async def create_or_update( # type: ignore[override] await self._resolve_local_paths(name, job) elif not isinstance(job, PipelineJob): raise TypeError("job must be a CommandJob or PipelineJob") + else: + job._convert_pending_jobs() self._inject_preview_header(kwargs) rest_body = _RestJob(properties=job) rest_result = await super().create_or_update(name=name, job=rest_body, **kwargs) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index ea27d79636b3..b812795d7c40 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -7,6 +7,7 @@ import datetime import json +from collections.abc import Mapping from os import PathLike from pathlib import Path from typing import IO, Any, AnyStr, Dict, List, Optional, Union @@ -120,20 +121,42 @@ class PipelineJob(_RestPipelineJob): """ def __init__(self, *args: Any, **kwargs: Any) -> None: - jobs = kwargs.get("jobs") + fields = args[0] if args and isinstance(args[0], Mapping) else kwargs + jobs = fields.get("jobs") if isinstance(jobs, dict) and any(isinstance(node, CommandJob) for node in jobs.values()): - settings = kwargs.get("settings") + settings = fields.get("settings") default_compute = settings.get("default_compute") if isinstance(settings, dict) else None - default_compute = default_compute or kwargs.get("compute_id") - kwargs["jobs"] = { - name: self._command_node(name, node, default_compute) if isinstance(node, CommandJob) else node - for name, node in jobs.items() - } + default_compute = default_compute or fields.get("computeId" if args else "compute_id") + converted = dict(fields) + converted["jobs"] = self._convert_jobs(jobs, default_compute) + if args: + args = (converted,) + args[1:] + else: + kwargs = converted super().__init__(*args, **kwargs) self._name: Optional[str] = None self._id: Optional[str] = None self._system_data: Optional[SystemData] = None + @classmethod + def _convert_jobs(cls, jobs: Dict[str, Any], default_compute: Optional[str]) -> Dict[str, Any]: + return { + name: cls._command_node(name, node, default_compute) if isinstance(node, CommandJob) else node + for name, node in jobs.items() + } + + def __setattr__(self, name: str, value: Any) -> None: + if name == "jobs" and isinstance(value, dict) and any(isinstance(node, CommandJob) for node in value.values()): + settings = self.settings + default_compute = settings.get("default_compute") if isinstance(settings, dict) else None + value = self._convert_jobs(value, default_compute or self.compute_id) + super().__setattr__(name, value) + + def _convert_pending_jobs(self) -> None: + jobs = self._data.get("jobs") + if isinstance(jobs, dict) and any(isinstance(node, CommandJob) for node in jobs.values()): + self.jobs = jobs + @staticmethod def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> Dict[str, Any]: unsupported = set(job.as_dict(exclude_readonly=True)) - { diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index d618b1671056..cc8c309e15c5 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -362,6 +362,8 @@ def create_or_update( # type: ignore[override] self._resolve_local_paths(name, job) elif not isinstance(job, PipelineJob): raise TypeError("job must be a CommandJob or PipelineJob") + else: + job._convert_pending_jobs() self._inject_preview_header(kwargs) # Wrap the flat job inside the Job envelope required by the wire format. rest_body = _RestJob(properties=job) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index c368542955f9..c56bc8a8196b 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -272,6 +272,52 @@ async def test_jobs_async_create_from_command_node() -> None: _assert_inline_request(transport.requests[0]) +@pytest.mark.parametrize("form", ["mapping", "assignment", "mutation"]) +def test_jobs_sync_create_from_updated_command_node(form: str) -> None: + _, command = _inline_pipeline() + if form == "mapping": + pipeline = PipelineJob( + { + "computeId": _COMPUTE, + "settings": {"default_compute": _COMPUTE, "force_rerun": True}, + "inputs": {"name": Input(type=AssetTypes.LITERAL, value="world")}, + "outputs": {}, + "jobs": {"hello": command}, + } + ) + pipeline.display_name = "Pipeline hello world" + else: + pipeline, _ = _inline_pipeline() + if form == "assignment": + pipeline.jobs = {"hello": command} + else: + assert pipeline.jobs is not None + pipeline.jobs["hello"] = command + + transport = _Transport([_response("Pipeline")]) + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + _assert_job(client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") + + assert len(transport.requests) == 1 + _assert_inline_request(transport.requests[0]) + + +@pytest.mark.asyncio +async def test_jobs_async_create_from_mutated_command_node() -> None: + pipeline, command = _inline_pipeline() + assert pipeline.jobs is not None + pipeline.jobs["hello"] = command + transport = _AsyncTransport([_response("Pipeline")]) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + _assert_job(await client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") + + assert len(transport.requests) == 1 + _assert_inline_request(transport.requests[0]) + + def test_pipeline_composes_commands_and_preserves_raw_graph_nodes() -> None: first, _ = _inline_pipeline() raw_node = {"type": "command", "component": {"name": "raw", "version": "1"}} From da5210aa52500f6d9403d06cb6516b8256c0ad89 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Sat, 3 Oct 2026 07:28:33 -0700 Subject: [PATCH 06/52] Keep Pipeline command composition constructor scoped Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 2 +- .../aio/operations/_patch_jobs_async.py | 2 - .../azure/ai/projects/models/_patch_jobs.py | 18 ++------ .../ai/projects/operations/_patch_jobs.py | 2 - .../tests/jobs/test_pipeline_jobs.py | 46 ++++--------------- 5 files changed, 14 insertions(+), 56 deletions(-) diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 859371a6ef27..cb65813237bd 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -25,7 +25,7 @@ * New optional `blueprint_reference` parameters on `agents.create_version` method. * New `.beta.jobs` sub-client with CommandJob operations: `create_or_update`, `get`, `list`, `begin_delete`, `begin_cancel`, `validate`, `show_services`, `stream`, `download`. * Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Pipeline graph nodes, inputs, outputs, and settings are sent as provided; local asset handling and validation remain specific to Command jobs. -* `PipelineJob.jobs` also accepts `CommandJob` instances with literal inputs, converting them to inline command nodes. Raw graph dictionaries remain supported for other node features. +* When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with literal inputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 89c3ed18f301..ba2a0719aeef 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -354,8 +354,6 @@ async def create_or_update( # type: ignore[override] await self._resolve_local_paths(name, job) elif not isinstance(job, PipelineJob): raise TypeError("job must be a CommandJob or PipelineJob") - else: - job._convert_pending_jobs() self._inject_preview_header(kwargs) rest_body = _RestJob(properties=job) rest_result = await super().create_or_update(name=name, job=rest_body, **kwargs) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index b812795d7c40..77fe77daa81e 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -108,9 +108,9 @@ def _from_rest_object(cls, rest_obj: Union[_RestJob, Any]) -> "CommandJob": class PipelineJob(_RestPipelineJob): """A pipeline job with graph nodes, inputs, and outputs. - ``jobs`` accepts raw graph node dictionaries or :class:`CommandJob` instances - with literal inputs. Command jobs are converted to inline command nodes; - use raw graph dictionaries for other node features. + When constructing a pipeline, ``jobs`` accepts raw graph node dictionaries + or :class:`CommandJob` instances with literal inputs. Command jobs are + converted to inline command nodes; use raw dictionaries for other features. :ivar name: The name of the job. Read-only; populated after the job is created. :vartype name: str or None @@ -145,18 +145,6 @@ def _convert_jobs(cls, jobs: Dict[str, Any], default_compute: Optional[str]) -> for name, node in jobs.items() } - def __setattr__(self, name: str, value: Any) -> None: - if name == "jobs" and isinstance(value, dict) and any(isinstance(node, CommandJob) for node in value.values()): - settings = self.settings - default_compute = settings.get("default_compute") if isinstance(settings, dict) else None - value = self._convert_jobs(value, default_compute or self.compute_id) - super().__setattr__(name, value) - - def _convert_pending_jobs(self) -> None: - jobs = self._data.get("jobs") - if isinstance(jobs, dict) and any(isinstance(node, CommandJob) for node in jobs.values()): - self.jobs = jobs - @staticmethod def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> Dict[str, Any]: unsupported = set(job.as_dict(exclude_readonly=True)) - { diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index cc8c309e15c5..d618b1671056 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -362,8 +362,6 @@ def create_or_update( # type: ignore[override] self._resolve_local_paths(name, job) elif not isinstance(job, PipelineJob): raise TypeError("job must be a CommandJob or PipelineJob") - else: - job._convert_pending_jobs() self._inject_preview_header(kwargs) # Wrap the flat job inside the Job envelope required by the wire format. rest_body = _RestJob(properties=job) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index c56bc8a8196b..8a6dfc7c0320 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -272,27 +272,17 @@ async def test_jobs_async_create_from_command_node() -> None: _assert_inline_request(transport.requests[0]) -@pytest.mark.parametrize("form", ["mapping", "assignment", "mutation"]) -def test_jobs_sync_create_from_updated_command_node(form: str) -> None: +def test_jobs_sync_create_from_mapping_with_command_node() -> None: _, command = _inline_pipeline() - if form == "mapping": - pipeline = PipelineJob( - { - "computeId": _COMPUTE, - "settings": {"default_compute": _COMPUTE, "force_rerun": True}, - "inputs": {"name": Input(type=AssetTypes.LITERAL, value="world")}, - "outputs": {}, - "jobs": {"hello": command}, - } - ) - pipeline.display_name = "Pipeline hello world" - else: - pipeline, _ = _inline_pipeline() - if form == "assignment": - pipeline.jobs = {"hello": command} - else: - assert pipeline.jobs is not None - pipeline.jobs["hello"] = command + pipeline = PipelineJob( + { + "computeId": _COMPUTE, + "settings": {"default_compute": _COMPUTE, "force_rerun": True}, + "inputs": {"name": Input(type=AssetTypes.LITERAL, value="world")}, + "outputs": {}, + "jobs": {"hello": command}, + } + ) transport = _Transport([_response("Pipeline")]) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] @@ -302,22 +292,6 @@ def test_jobs_sync_create_from_updated_command_node(form: str) -> None: _assert_inline_request(transport.requests[0]) -@pytest.mark.asyncio -async def test_jobs_async_create_from_mutated_command_node() -> None: - pipeline, command = _inline_pipeline() - assert pipeline.jobs is not None - pipeline.jobs["hello"] = command - transport = _AsyncTransport([_response("Pipeline")]) - - async with AsyncAIProjectClient( - endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] - ) as client: - _assert_job(await client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") - - assert len(transport.requests) == 1 - _assert_inline_request(transport.requests[0]) - - def test_pipeline_composes_commands_and_preserves_raw_graph_nodes() -> None: first, _ = _inline_pipeline() raw_node = {"type": "command", "component": {"name": "raw", "version": "1"}} From 02e4493892f8da4ddd31aad75a9a9fe4fed3d29d Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 15:55:57 -0700 Subject: [PATCH 07/52] Support local code in PipelineJob command nodes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 5 +- .../aio/operations/_patch_jobs_async.py | 16 +- .../azure/ai/projects/models/_patch_jobs.py | 39 +++- .../ai/projects/operations/_patch_jobs.py | 16 +- .../samples/jobs/sample_pipeline_two_code.py | 115 ++++++++++ .../tests/jobs/test_pipeline_jobs.py | 214 +++++++++++++++++- 6 files changed, 390 insertions(+), 15 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index cb65813237bd..8c7aac612401 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -24,8 +24,8 @@ * New optional `force` parameter on `agents.delete` and `agents.delete_version` methods. * New optional `blueprint_reference` parameters on `agents.create_version` method. * New `.beta.jobs` sub-client with CommandJob operations: `create_or_update`, `get`, `list`, `begin_delete`, `begin_cancel`, `validate`, `show_services`, `stream`, `download`. -* Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Pipeline graph nodes, inputs, outputs, and settings are sent as provided; local asset handling and validation remain specific to Command jobs. -* When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with literal inputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. +* Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Local code folders on inline command nodes are registered as Code datasets before submission; local input handling and validation remain specific to standalone Command jobs. +* When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. @@ -88,6 +88,7 @@ Breaking changes in beta classes: * Refreshed evaluation samples under `samples/evaluations/` and `samples/evaluations/agentic_evaluators/` (including `sample_agent_evaluation`, `sample_agent_response_evaluation`, `sample_eval_catalog_prompt_based_evaluators`, `sample_evaluations_ai_assisted`, `sample_evaluations_builtin_with_csv`, `sample_evaluations_builtin_with_dataset_id`, `sample_evaluations_builtin_with_inline_data`, `sample_evaluations_builtin_with_inline_data_oai`, `sample_scheduled_evaluations`, `sample_coherence`, `sample_fluency`, `sample_intent_resolution`, `sample_relevance`, `sample_response_completeness`, `sample_tool_call_accuracy`, `sample_tool_call_success`, `sample_tool_input_accuracy`, `sample_tool_output_utilization`, `sample_tool_selection`, and `sample_generic_agentic_evaluator`). * New sample `sample_dataset_generation_job_simpleqna_with_prompt_source.py` showing an end-to-end flow that generates a QnA dataset via `.beta.datasets.create_generation_job` and runs an OpenAI evaluation. * Updated job samples `sample_jobs.py` and `sample_jobs_async.py` to show requesting GPUs with `gpu_count` on a GPU cluster versus whole nodes with `instance_count` on a CPU cluster, and to set the new `priority` property. +* Added `sample_pipeline_two_code.py` to demonstrate a producer and consumer using separate local code folders and a mounted file output. ## 2.1.0 (2026-04-20) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index ba2a0719aeef..5311d897d383 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -241,6 +241,16 @@ async def _resolve_local_paths(self, name: str, job: CommandJob) -> None: await self._resolve_code(name, job) await self._resolve_input_paths(name, job) + async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: + """Resolve local code folders on inline command nodes to dataset asset URIs.""" + for node_name, node in (job.jobs or {}).items(): + if not isinstance(node, dict) or node.get("type") != "command": + continue + component = node.get("component") + if not isinstance(component, dict) or not isinstance(component.get("code"), str): + continue + component["code"] = await self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -341,7 +351,7 @@ async def create_or_update( # type: ignore[override] :param job: The Command or Pipeline job to create or update. Required. :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob :keyword skip_validation: If ``True``, skip local CommandJob validation. - PipelineJob is submitted as-is. Defaults to ``False``. + PipelineJob nodes are not locally validated. Defaults to ``False``. :paramtype skip_validation: bool :return: The created/updated job. :rtype: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob @@ -352,7 +362,9 @@ async def create_or_update( # type: ignore[override] if not skip_validation: _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) await self._resolve_local_paths(name, job) - elif not isinstance(job, PipelineJob): + elif isinstance(job, PipelineJob): + await self._resolve_pipeline_code(name, job) + else: raise TypeError("job must be a CommandJob or PipelineJob") self._inject_preview_header(kwargs) rest_body = _RestJob(properties=job) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index 77fe77daa81e..bbed3eaa4f98 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -109,8 +109,9 @@ class PipelineJob(_RestPipelineJob): """A pipeline job with graph nodes, inputs, and outputs. When constructing a pipeline, ``jobs`` accepts raw graph node dictionaries - or :class:`CommandJob` instances with literal inputs. Command jobs are - converted to inline command nodes; use raw dictionaries for other features. + or :class:`CommandJob` instances with value-bound inputs, code, and outputs. + Command jobs are converted to inline command nodes; use raw dictionaries + for other features. :ivar name: The name of the job. Read-only; populated after the job is created. :vartype name: str or None @@ -152,7 +153,9 @@ def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> "command", "environmentImageReference", "computeId", + "codeId", "inputs", + "outputs", "resources", "userAssignedIdentityId", } @@ -170,18 +173,38 @@ def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> ) inputs: Dict[str, Any] = {} + component_inputs: Dict[str, Any] = {} for input_name, job_input in (job.inputs or {}).items(): if ( not isinstance(job_input, Input) - or job_input.type != "literal" + or job_input.type not in ("literal", "uri_file") or job_input.value is None or set(job_input.as_dict()) - {"jobInputType", "value"} ): raise ValueError( f"Pipeline node '{name}' cannot convert input '{input_name}'; " - "only literal CommandJob inputs are supported. Use a raw graph node for other inputs." + "only value-bound literal and uri_file CommandJob inputs are supported. " + "Use a raw graph node for other inputs." ) inputs[input_name] = {"job_input_type": "literal", "value": job_input.value} + component_inputs[input_name] = {"type": "string" if job_input.type == "literal" else job_input.type} + + outputs: Dict[str, Any] = {} + component_outputs: Dict[str, Any] = {} + for output_name, job_output in (job.outputs or {}).items(): + if not isinstance(job_output, Output) or set(job_output.as_dict()) - { + "jobOutputType", + "assetName", + "mode", + }: + raise ValueError( + f"Pipeline node '{name}' cannot convert output '{output_name}'; " + "use a raw graph node for other output fields." + ) + component_outputs[output_name] = {"type": job_output.type} + outputs[output_name] = {"job_output_type": job_output.type} + if job_output.mode is not None: + outputs[output_name]["mode"] = job_output.mode node: Dict[str, Any] = { "type": "command", @@ -191,12 +214,14 @@ def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> "type": "command", "command": job.command, "environment": {"image": job.environment_image_reference}, - "inputs": {input_name: {"type": "string"} for input_name in inputs}, - "outputs": {}, + "inputs": component_inputs, + "outputs": component_outputs, }, "inputs": inputs, - "outputs": {}, + "outputs": outputs, } + if job.code is not None: + node["component"]["code"] = job.code if job.user_assigned_identity_id is not None: node["identity"] = {"type": "managed", "msi_resource_id": job.user_assigned_identity_id} diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index d618b1671056..3aded07e7fc0 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -244,6 +244,16 @@ def _resolve_local_paths(self, name: str, job: CommandJob) -> None: self._resolve_code(name, job) self._resolve_input_paths(name, job) + def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: + """Resolve local code folders on inline command nodes to dataset asset URIs.""" + for node_name, node in (job.jobs or {}).items(): + if not isinstance(node, dict) or node.get("type") != "command": + continue + component = node.get("component") + if not isinstance(component, dict) or not isinstance(component.get("code"), str): + continue + component["code"] = self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -349,7 +359,7 @@ def create_or_update( # type: ignore[override] :param job: The Command or Pipeline job to create or update. Required. :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob :keyword skip_validation: If ``True``, skip local CommandJob validation. - PipelineJob is submitted as-is. Defaults to ``False``. + PipelineJob nodes are not locally validated. Defaults to ``False``. :paramtype skip_validation: bool :return: The created/updated job. :rtype: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob @@ -360,7 +370,9 @@ def create_or_update( # type: ignore[override] if not skip_validation: _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) self._resolve_local_paths(name, job) - elif not isinstance(job, PipelineJob): + elif isinstance(job, PipelineJob): + self._resolve_pipeline_code(name, job) + else: raise TypeError("job must be a CommandJob or PipelineJob") self._inject_preview_header(kwargs) # Wrap the flat job inside the Job envelope required by the wire format. diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py new file mode 100644 index 000000000000..37d6fb695030 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py @@ -0,0 +1,115 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Submit a two-step PipelineJob with a separate local Python code folder per step. + +Set FOUNDRY_PROJECT_ENDPOINT, JOB_NAME, JOB_COMPUTE_ID (full compute resource ID), +JOB_ENVIRONMENT_IMAGE, JOB_NODE_UAI_RESOURCE_ID (full identity resource ID), +JOB_INSTANCE_TYPE, JOB_PRODUCER_CODE_DIR, and JOB_CONSUMER_CODE_DIR. Use absolute +paths for the code directories. The producer directory must contain produce.py, +which writes its first argument; the consumer directory must contain consume.py, +which reads its first argument. + +Running this sample uploads both local code folders and submits a job. +""" + +import os + +from azure.ai.projects import AIProjectClient +from azure.ai.projects.models import ( + AssetTypes, + CommandJob, + Input, + InputOutputModes, + JobResourceConfiguration, + Output, + PipelineJob, +) +from azure.identity import AzureCliCredential + + +def build_job( + compute_id: str, + image: str, + node_uai_id: str, + instance_type: str, + producer_code_dir: str, + consumer_code_dir: str, +) -> PipelineJob: + resources = JobResourceConfiguration( + { + "instanceCount": 1, + "instanceType": instance_type, + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + } + ) + producer = CommandJob( + command="python produce.py ${{outputs.message}}", + code=producer_code_dir, + environment_image_reference=image, + compute=compute_id, + user_assigned_identity_id=node_uai_id, + resources=resources, + outputs={ + # Inline nodes serialize the output type and mount mode, not this model's asset name. + "message": Output( + type=AssetTypes.URI_FILE, + asset_name="message", + mode=InputOutputModes.READ_WRITE_MOUNT, + ) + }, + ) + consumer = CommandJob( + command="python consume.py ${{inputs.message}}", + code=consumer_code_dir, + environment_image_reference=image, + compute=compute_id, + user_assigned_identity_id=node_uai_id, + resources=resources, + inputs={ + "message": Input( + type=AssetTypes.URI_FILE, + value="${{parent.jobs.produce.outputs.message}}", + ) + }, + ) + return PipelineJob( + display_name="Two-step code SDK test", + compute_id=compute_id, + settings={"default_compute": compute_id, "force_rerun": True}, + inputs={}, + outputs={}, + jobs={"produce": producer, "consume": consumer}, + ) + + +def main() -> None: + job_name = os.environ["JOB_NAME"] + job = build_job( + compute_id=os.environ["JOB_COMPUTE_ID"], + image=os.environ["JOB_ENVIRONMENT_IMAGE"], + node_uai_id=os.environ["JOB_NODE_UAI_RESOURCE_ID"], + instance_type=os.environ["JOB_INSTANCE_TYPE"], + producer_code_dir=os.environ["JOB_PRODUCER_CODE_DIR"], + consumer_code_dir=os.environ["JOB_CONSUMER_CODE_DIR"], + ) + with ( + AzureCliCredential() as credential, + AIProjectClient( + endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"], + credential=credential, + allow_preview=True, + retry_total=0, + ) as client, + ): + created = client.beta.jobs.create_or_update( + name=job_name, + job=job, + headers={"x-ms-foundry-job-route": "execution"}, + ) + print(f"Submitted {created.name}: {created.id} (status: {created.status})") + + +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 8a6dfc7c0320..8ee991d6a53c 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -5,11 +5,14 @@ """Offline wire and response tests for Command and Pipeline jobs.""" import json +import runpy +from pathlib import Path from typing import Any, Union from urllib.parse import parse_qs, urlparse import pytest from azure.core.credentials import AccessToken +from azure.core.exceptions import ResourceNotFoundError from azure.core.pipeline.transport import ( AsyncHttpResponse, AsyncHttpTransport, @@ -20,10 +23,21 @@ from azure.ai.projects import AIProjectClient from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient -from azure.ai.projects.models import AssetTypes, CommandJob, Input, JobResourceConfiguration, JobType, PipelineJob +from azure.ai.projects.models import ( + AssetTypes, + CommandJob, + DatasetVersion, + Input, + JobResourceConfiguration, + JobType, + PipelineJob, +) _ENDPOINT = "https://fake-account.services.ai.azure.com/api/projects/fake-project" _COMPUTE = "/subscriptions/test/resourceGroups/test/providers/Microsoft.CognitiveServices/accounts/test/computes/cpu" +_TWO_CODE_BUILDER = runpy.run_path( + str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / "sample_pipeline_two_code.py") +)["build_job"] _PIPELINE_PROPERTIES = { "jobType": "Pipeline", "displayName": "example pipeline", @@ -243,6 +257,103 @@ def _assert_inline_request(request: HttpRequest) -> None: assert json.loads(request.body) == {"properties": _INLINE_PIPELINE_PROPERTIES} +def _two_code_job(tmp_path: Path) -> tuple[PipelineJob, dict[str, Path]]: + code_dirs = {node: tmp_path / node for node in ("produce", "consume")} + for node, code_dir in code_dirs.items(): + code_dir.mkdir() + (code_dir / f"{node}.py").write_text(f"print({node!r})", encoding="utf-8") + job = _TWO_CODE_BUILDER( + compute_id=_COMPUTE, + image="example.azurecr.io/train:latest", + node_uai_id="/subscriptions/test/identities/hello", + instance_type="Singularity.D4_v3", + producer_code_dir=str(code_dirs["produce"]), + consumer_code_dir=str(code_dirs["consume"]), + ) + return job, code_dirs + + +def _code_uri(name: str, version: str) -> str: + return f"azureai://accounts/fake-account/projects/fake-project/data/{name}/versions/{version}" + + +def _uploaded_code(name: str, version: str) -> DatasetVersion: + return DatasetVersion( + { + "id": _code_uri(name, version), + "name": name, + "version": version, + "type": "uri_folder", + "dataUri": "azureml://datastores/test/paths/code/", + } + ) + + +def _assert_two_code_request(request: HttpRequest, code_uris: dict[str, str]) -> None: + assert request.method == "PUT" + assert request.headers["Foundry-Features"] == "Jobs=V1Preview" + assert request.headers["x-ms-foundry-job-route"] == "execution" + assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] + resources = { + "instance_count": 1, + "instance_type": "Singularity.D4_v3", + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + } + identity = {"type": "managed", "msi_resource_id": "/subscriptions/test/identities/hello"} + expected = { + "properties": { + "jobType": "Pipeline", + "displayName": "Two-step code SDK test", + "computeId": _COMPUTE, + "settings": {"default_compute": _COMPUTE, "force_rerun": True}, + "inputs": {}, + "outputs": {}, + "jobs": { + "produce": { + "type": "command", + "component": { + "name": "produce", + "version": "1", + "type": "command", + "command": "python produce.py ${{outputs.message}}", + "environment": {"image": "example.azurecr.io/train:latest"}, + "inputs": {}, + "outputs": {"message": {"type": "uri_file"}}, + "code": code_uris["produce"], + }, + "identity": identity, + "resources": resources, + "inputs": {}, + "outputs": {"message": {"job_output_type": "uri_file", "mode": "ReadWriteMount"}}, + }, + "consume": { + "type": "command", + "component": { + "name": "consume", + "version": "1", + "type": "command", + "command": "python consume.py ${{inputs.message}}", + "environment": {"image": "example.azurecr.io/train:latest"}, + "inputs": {"message": {"type": "uri_file"}}, + "outputs": {}, + "code": code_uris["consume"], + }, + "inputs": { + "message": { + "job_input_type": "literal", + "value": "${{parent.jobs.produce.outputs.message}}", + } + }, + "outputs": {}, + "identity": identity, + "resources": resources, + }, + }, + } + } + assert json.loads(request.body) == expected + + def test_jobs_sync_create_from_command_node() -> None: pipeline, command = _inline_pipeline() transport = _Transport([_response("Pipeline")]) @@ -316,11 +427,110 @@ def test_pipeline_composes_commands_and_preserves_raw_graph_nodes() -> None: assert first.jobs["hello"] == _INLINE_PIPELINE_PROPERTIES["jobs"]["hello"] +def test_pipeline_uploads_both_local_code_folders(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + pipeline, code_dirs = _two_code_job(tmp_path) + transport = _Transport([_response("Pipeline")]) + uploads: list[tuple[str, str, str]] = [] + + def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + uploads.append((name, version, folder)) + return _uploaded_code(name, version) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + _assert_job( + client.beta.jobs.create_or_update( + "two-code", + pipeline, + headers={"x-ms-foundry-job-route": "execution"}, + ), + "Pipeline", + ) + + assert [(name, folder) for name, _, folder in uploads] == [ + ("two-code-produce-code", str(code_dirs["produce"])), + ("two-code-consume-code", str(code_dirs["consume"])), + ] + assert uploads[0][1] != uploads[1][1] + assert len(transport.requests) == 1 + _assert_two_code_request( + transport.requests[0], + {name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) for name, version, _ in uploads}, + ) + + +@pytest.mark.asyncio +async def test_pipeline_uploads_both_local_code_folders_async( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + pipeline, code_dirs = _two_code_job(tmp_path) + transport = _AsyncTransport([_response("Pipeline")]) + uploads: list[tuple[str, str, str]] = [] + + async def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + uploads.append((name, version, folder)) + return _uploaded_code(name, version) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + _assert_job( + await client.beta.jobs.create_or_update( + "two-code", + pipeline, + headers={"x-ms-foundry-job-route": "execution"}, + ), + "Pipeline", + ) + + assert [(name, folder) for name, _, folder in uploads] == [ + ("two-code-produce-code", str(code_dirs["produce"])), + ("two-code-consume-code", str(code_dirs["consume"])), + ] + assert len(transport.requests) == 1 + _assert_two_code_request( + transport.requests[0], + {name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) for name, version, _ in uploads}, + ) + + +def test_pipeline_does_not_submit_when_code_upload_fails(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + pipeline, _ = _two_code_job(tmp_path) + transport = _Transport([]) + + def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + raise RuntimeError("upload failed") + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + with pytest.raises(RuntimeError, match="upload failed"): + client.beta.jobs.create_or_update("two-code", pipeline) + + assert transport.requests == [] + + @pytest.mark.parametrize( ("extra", "message"), [ - ({"code": "azureai:code:1"}, "codeId"), + ({"priority": "High"}, "priority"), ({"inputs": {"data": Input(type=AssetTypes.URI_FILE, path="azureai:data:1")}}, "input 'data'"), + ( + {"outputs": {"message": {"job_output_type": "uri_file", "mode": "ReadWriteMount"}}}, + "output 'message'", + ), ({"compute": "/subscriptions/test/computes/other"}, "default compute"), ({"resources": JobResourceConfiguration({"shmSize": "1g"})}, "shmSize"), ], From f786ab407c2973f2cc71960b0c1f7053a7e8ca25 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 16:00:03 -0700 Subject: [PATCH 08/52] Format two-code PipelineJob tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/jobs/test_pipeline_jobs.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 8ee991d6a53c..d69a478b75ef 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -459,14 +459,15 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat assert len(transport.requests) == 1 _assert_two_code_request( transport.requests[0], - {name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) for name, version, _ in uploads}, + { + name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) + for name, version, _ in uploads + }, ) @pytest.mark.asyncio -async def test_pipeline_uploads_both_local_code_folders_async( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: +async def test_pipeline_uploads_both_local_code_folders_async(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: pipeline, code_dirs = _two_code_job(tmp_path) transport = _AsyncTransport([_response("Pipeline")]) uploads: list[tuple[str, str, str]] = [] @@ -499,7 +500,10 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) assert len(transport.requests) == 1 _assert_two_code_request( transport.requests[0], - {name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) for name, version, _ in uploads}, + { + name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) + for name, version, _ in uploads + }, ) From 1cc87656db44af6eae84f68b00afa8ee97b667bd Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:32:44 -0700 Subject: [PATCH 09/52] Author Foundry pipeline jobs from Python functions Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 2 + sdk/ai/azure-ai-projects/README.md | 21 ++ .../aio/operations/_patch_jobs_async.py | 72 +++- .../azure/ai/projects/dsl.py | 342 ++++++++++++++++++ .../ai/projects/operations/_patch_jobs.py | 72 +++- .../samples/jobs/sample_pipeline_dsl.py | 61 ++++ .../tests/jobs/test_pipeline_jobs.py | 328 ++++++++++++++++- 7 files changed, 869 insertions(+), 29 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 8c7aac612401..8fbb23f9389d 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -26,6 +26,7 @@ * New `.beta.jobs` sub-client with CommandJob operations: `create_or_update`, `get`, `list`, `begin_delete`, `begin_cancel`, `validate`, `show_services`, `stream`, `download`. * Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Local code folders on inline command nodes are registered as Code datasets before submission; local input handling and validation remain specific to standalone Command jobs. * When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. +* Added `azure.ai.projects.dsl` function-body `@component` and `@pipeline` authoring for native two-step PipelineJobs. Calling the pipeline function builds its graph, packages each Python component body as its own executable Code folder, binds typed inputs and file outputs, and supports repeated component calls. `.beta.jobs.create_or_update(pipeline_job)` now generates a unique name (sync and async), while the existing explicit-name form remains available. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. @@ -89,6 +90,7 @@ Breaking changes in beta classes: * New sample `sample_dataset_generation_job_simpleqna_with_prompt_source.py` showing an end-to-end flow that generates a QnA dataset via `.beta.datasets.create_generation_job` and runs an OpenAI evaluation. * Updated job samples `sample_jobs.py` and `sample_jobs_async.py` to show requesting GPUs with `gpu_count` on a GPU cluster versus whole nodes with `instance_count` on a CPU cluster, and to set the new `priority` property. * Added `sample_pipeline_two_code.py` to demonstrate a producer and consumer using separate local code folders and a mounted file output. +* Added `sample_pipeline_dsl.py` to show Python function components and direct pipeline-function job construction. ## 2.1.0 (2026-04-20) diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index 8378270e3b3a..9a5709b3f053 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -173,6 +173,27 @@ Full descriptions and working code for all of the above are available in: | Files (upload, retrieve, list, delete) | [OpenAI Files API](https://platform.openai.com/docs/api-reference/files) | `samples/files/` | | Fine-tuning | [Fine-Tuning in AI Foundry](https://github.com/microsoft-foundry/fine-tuning) | `samples/finetuning/` | +### Author Python function pipeline jobs (preview) + +Use `from azure.ai.projects import dsl` to define a Python function body with `@dsl.component` and +call that component inside an `@dsl.pipeline` function. `dsl.Input(type="uri_file")` and +`dsl.Output(type="uri_file")` declare file ports; output names are inferred from parameter names +and file outputs use read-write mounts by default. The pipeline decorator supplies the compute +resource ID, container image, user-assigned identity ID, and instance type inherited by its nodes. +Calling the decorated pipeline function constructs a native Foundry `PipelineJob` without an outer +builder. Submit it with `client.beta.jobs.create_or_update(job)` for an autogenerated job name, +optionally passing `experiment_name="pipeline_samples"`, or use the existing +`create_or_update(name=..., job=...)` form. + +See the [two-component Python sample](samples/jobs/sample_pipeline_dsl.py) for a producer and +consumer connected through a mounted file. Each function body is packaged into a separate Code +folder and runs on the selected compute, not when the graph is built. Component functions must be +defined in a readable `.py` file; referenced module-level imports are copied into the generated +entrypoint, but non-import globals, closures, and sibling source files are not bundled. Required +third-party modules must already exist in the container image. This native Foundry authoring API +does not accept an unmodified `azure.ai.ml.dsl` PipelineJob or provide full Azure ML component +registration and environment features; local pipeline file inputs are not supported. + ### Hosted agents (preview) Hosted agents let you run your own containerized agent runtime while using Microsoft Foundry for managed hosting and scaling. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 5311d897d383..88ab600817f8 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -14,8 +14,9 @@ from concurrent.futures import ThreadPoolExecutor, as_completed from os import PathLike from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Union, cast +from typing import Any, Dict, List, Optional, Tuple, Union, cast, overload from urllib.parse import urlparse +from uuid import uuid4 from azure.core.async_paging import AsyncItemPaged from azure.core.exceptions import ResourceNotFoundError @@ -243,13 +244,20 @@ async def _resolve_local_paths(self, name: str, job: CommandJob) -> None: async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: """Resolve local code folders on inline command nodes to dataset asset URIs.""" - for node_name, node in (job.jobs or {}).items(): - if not isinstance(node, dict) or node.get("type") != "command": - continue - component = node.get("component") - if not isinstance(component, dict) or not isinstance(component.get("code"), str): - continue - component["code"] = await self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + try: + for node_name, node in (job.jobs or {}).items(): + if not isinstance(node, dict) or node.get("type") != "command": + continue + component = node.get("component") + if not isinstance(component, dict) or not isinstance(component.get("code"), str): + continue + component["code"] = await self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + finally: + code_dirs = getattr(job, "_component_code_dirs", None) + if code_dirs is not None: + for directory in code_dirs: + directory.cleanup() + code_dirs.clear() def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -335,21 +343,45 @@ async def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: rest_result = await super().get(name=name, **kwargs) return _from_rest_job(rest_result) - @distributed_trace_async - async def create_or_update( # type: ignore[override] + @overload + async def create_or_update( + self, + name: PipelineJob, + job: None = None, + *, + experiment_name: Optional[str] = None, + skip_validation: bool = False, + **kwargs: Any, + ) -> PipelineJob: ... + + @overload + async def create_or_update( self, name: str, job: Union[CommandJob, PipelineJob], *, skip_validation: bool = False, **kwargs: Any, + ) -> Union[CommandJob, PipelineJob]: ... + + @distributed_trace_async + async def create_or_update( # type: ignore[override] + self, + name: Union[str, PipelineJob], + job: Optional[Union[CommandJob, PipelineJob]] = None, + *, + experiment_name: Optional[str] = None, + skip_validation: bool = False, + **kwargs: Any, ) -> Union[CommandJob, PipelineJob]: """Create or update a training job. - :param name: The name of the job. Required. - :type name: str - :param job: The Command or Pipeline job to create or update. Required. - :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob + :param name: The job name, or a PipelineJob for a unique autogenerated name. + :type name: str or ~azure.ai.projects.models.PipelineJob + :param job: The Command or Pipeline job. Required when ``name`` is a string. + :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob or None + :keyword experiment_name: Experiment name for a job-only PipelineJob submission. + :paramtype experiment_name: str or None :keyword skip_validation: If ``True``, skip local CommandJob validation. PipelineJob nodes are not locally validated. Defaults to ``False``. :paramtype skip_validation: bool @@ -358,6 +390,18 @@ async def create_or_update( # type: ignore[override] :raises ~azure.core.exceptions.HttpResponseError: :raises ValueError: If required fields are missing or empty. """ + if isinstance(name, PipelineJob): + if job is not None: + raise TypeError("A job cannot be supplied when the first argument is a PipelineJob.") + job = name + name = f"pipeline-{uuid4().hex}" + if experiment_name is not None: + job.experiment_name = experiment_name + elif not isinstance(name, str) or job is None: + raise TypeError("create_or_update requires a job name and job, or one PipelineJob.") + elif experiment_name is not None: + raise TypeError("Set job.experiment_name when submitting a job with an explicit name.") + if isinstance(job, CommandJob): if not skip_validation: _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py new file mode 100644 index 000000000000..b5f1eb07d5cd --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -0,0 +1,342 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Python function authoring for Foundry command components and pipeline jobs.""" + +import ast +import inspect +import textwrap +from contextvars import ContextVar +from dataclasses import dataclass +from functools import wraps +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from typing import Any, Callable, Dict, List, Optional, Tuple, Union, get_type_hints + +from .models import AssetTypes, CommandJob, Input, InputOutputModes, JobResourceConfiguration, PipelineJob +from .models import Output as _JobOutput + +__all__ = ["Input", "Output", "component", "pipeline"] + + +@dataclass(frozen=True) +class Output: + """A writable file output in a Python component signature. + + The parameter name becomes the output asset name. Outputs are read-write mounted + unless ``mode`` is specified. + """ + + type: Union[str, AssetTypes] + mode: Optional[Union[str, InputOutputModes]] = None + + +@dataclass(frozen=True) +class _Port: + name: str + type: str + conversion: str + mode: Optional[Union[str, InputOutputModes]] = None + + +@dataclass(frozen=True) +class _InputRef: + owner: object + name: str + type: str + + +@dataclass(frozen=True) +class _OutputRef: + owner: object + node: str + name: str + type: str + mode: Union[str, InputOutputModes] + + +_ACTIVE_PIPELINE: ContextVar[Optional["_PipelineContext"]] = ContextVar("foundry_pipeline", default=None) +_PRIMITIVES: Dict[Any, Tuple[str, str]] = { + str: ("string", "str"), + int: ("integer", "int"), + float: ("number", "float"), + bool: ("boolean", "bool"), +} + + +def _component_ports(func: Callable[..., Any]) -> Tuple[List[_Port], List[_Port]]: + inputs: List[_Port] = [] + outputs: List[_Port] = [] + annotations = get_type_hints(func) + for parameter in inspect.signature(func).parameters.values(): + if parameter.kind not in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY): + raise TypeError(f"Component '{func.__name__}' supports only named parameters.") + annotation = annotations.get(parameter.name, parameter.annotation) + if isinstance(annotation, Output): + if annotation.type != AssetTypes.URI_FILE: + raise ValueError(f"Component output '{parameter.name}' must be a uri_file.") + if parameter.default is not inspect.Parameter.empty: + raise TypeError(f"Component output '{parameter.name}' cannot have a default.") + outputs.append( + _Port( + parameter.name, + AssetTypes.URI_FILE, + "str", + annotation.mode if annotation.mode is not None else InputOutputModes.READ_WRITE_MOUNT, + ) + ) + elif isinstance(annotation, Input): + if annotation.type != AssetTypes.URI_FILE or annotation.path or annotation.value or annotation.mode: + raise ValueError(f"Component input '{parameter.name}' supports only Input(type='uri_file').") + inputs.append(_Port(parameter.name, AssetTypes.URI_FILE, "str")) + elif annotation in _PRIMITIVES: + component_type, conversion = _PRIMITIVES[annotation] + inputs.append(_Port(parameter.name, component_type, conversion)) + else: + raise TypeError(f"Component parameter '{parameter.name}' needs a primitive, Input, or Output annotation.") + return inputs, outputs + + +def _function_script(func: Callable[..., Any], inputs: List[_Port], outputs: List[_Port]) -> str: + try: + source_file = inspect.getsourcefile(func) + if source_file is None: + raise OSError("no source file") + function_tree = ast.parse(textwrap.dedent(inspect.getsource(func))) + module_tree = ast.parse(Path(source_file).read_text(encoding="utf-8")) + except (OSError, TypeError, SyntaxError) as error: + raise ValueError(f"Component '{func.__name__}' must be defined in a readable Python source file.") from error + + if len(function_tree.body) != 1 or not isinstance(function_tree.body[0], ast.FunctionDef): + raise TypeError(f"Component '{func.__name__}' must be a synchronous Python function.") + definition = function_tree.body[0] + if definition.name != func.__name__: + raise ValueError(f"Component '{func.__name__}' must be defined by its original function name.") + + free_vars = inspect.getclosurevars(func) + if free_vars.nonlocals: + raise ValueError(f"Component '{func.__name__}' cannot capture enclosing variables: {sorted(free_vars.nonlocals)}.") + globals_needed = set(free_vars.globals) + imports: List[str] = [] + for statement in module_tree.body: + if isinstance(statement, ast.Import): + names = {alias.asname or alias.name.split(".")[0] for alias in statement.names} + elif isinstance(statement, ast.ImportFrom): + names = {alias.asname or alias.name for alias in statement.names} + else: + continue + if names & globals_needed: + imports.append(ast.unparse(statement)) + globals_needed -= names + if globals_needed: + raise ValueError( + f"Component '{func.__name__}' uses unsupported module globals: {sorted(globals_needed)}. " + "Import dependencies at module scope or inside the function." + ) + + definition.decorator_list = [] + definition.returns = None + for parameter in ( + definition.args.posonlyargs + definition.args.args + definition.args.kwonlyargs + ): + parameter.annotation = None + definition.args.defaults = [] + definition.args.kw_defaults = [None] * len(definition.args.kwonlyargs) + + arguments: List[str] = [] + for index, port in enumerate(inputs + outputs, start=1): + value = f"sys.argv[{index}]" + if port.conversion == "bool": + value = f"({value} == 'True')" + elif port.conversion != "str": + value = f"{port.conversion}({value})" + arguments.append(f"{port.name}={value}") + + return "\n".join( + ["import sys", *imports, "", ast.unparse(definition), "", "if __name__ == '__main__':"] + + [f" {definition.name}({', '.join(arguments)})", ""] + ) + + +class _PipelineContext: + def __init__(self, compute_id: str, image: str, identity: str, instance_type: str) -> None: + self.compute_id = compute_id + self.image = image + self.identity = identity + self.instance_type = instance_type + self.jobs: Dict[str, Dict[str, Any]] = {} + self.code_dirs: List[TemporaryDirectory] = [] + + def add( + self, func: Callable[..., Any], inputs: List[_Port], outputs: List[_Port], arguments: Dict[str, Any] + ) -> SimpleNamespace: + name = func.__name__ + suffix = 2 + while name in self.jobs: + name = f"{func.__name__}_{suffix}" + suffix += 1 + + bound_inputs: Dict[str, Input] = {} + for port in inputs: + value = arguments[port.name] + if isinstance(value, _InputRef): + if value.owner is not self or value.type != port.type: + raise ValueError(f"Component input '{port.name}' has an incompatible pipeline input.") + serialized = f"${{{{parent.inputs.{value.name}}}}}" + elif isinstance(value, _OutputRef): + if value.owner is not self or value.type != port.type: + raise ValueError(f"Component input '{port.name}' has an incompatible node output.") + serialized = f"${{{{parent.jobs.{value.node}.outputs.{value.name}}}}}" + elif port.type == AssetTypes.URI_FILE: + raise TypeError(f"Component input '{port.name}' needs a pipeline input or node file output.") + elif (port.conversion == "int" and type(value) is int) or ( + port.conversion == "float" and type(value) is float + ) or (port.conversion == "bool" and type(value) is bool) or ( + port.conversion == "str" and type(value) is str + ): + serialized = str(value) + else: + raise TypeError(f"Component input '{port.name}' has an incompatible primitive value.") + input_type = AssetTypes.URI_FILE if port.type == AssetTypes.URI_FILE else AssetTypes.LITERAL + bound_inputs[port.name] = Input(type=input_type, value=serialized) + + code_dir = TemporaryDirectory(prefix="foundry-component-") + self.code_dirs.append(code_dir) + (Path(code_dir.name) / "component.py").write_text(_function_script(func, inputs, outputs), encoding="utf-8") + job = CommandJob( + command="python component.py " + + " ".join( + [f'"${{{{inputs.{port.name}}}}}"' for port in inputs] + + [f'"${{{{outputs.{port.name}}}}}"' for port in outputs] + ), + code=code_dir.name, + environment_image_reference=self.image, + compute=self.compute_id, + user_assigned_identity_id=self.identity, + resources=JobResourceConfiguration( + { + "instanceCount": 1, + "instanceType": self.instance_type, + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + } + ), + inputs=bound_inputs, + outputs={ + port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs + }, + ) + node = PipelineJob._command_node(name, job, self.compute_id) + for port in inputs: + if port.type != AssetTypes.URI_FILE: + node["component"]["inputs"][port.name]["type"] = port.type + self.jobs[name] = node + return SimpleNamespace( + outputs=SimpleNamespace( + **{ + port.name: _OutputRef(self, name, port.name, port.type, port.mode or InputOutputModes.READ_WRITE_MOUNT) + for port in outputs + } + ) + ) + + +def component(func: Callable[..., Any]) -> Callable[..., SimpleNamespace]: + """Decorate a Python function to create a command node when invoked inside a pipeline. + + The function body is packaged as code and runs remotely, not during graph creation. + """ + inputs, outputs = _component_ports(func) + input_names = {port.name for port in inputs} + input_signature = inspect.Signature( + parameter for parameter in inspect.signature(func).parameters.values() if parameter.name in input_names + ) + + @wraps(func) + def invoke(**kwargs: Any) -> SimpleNamespace: + context = _ACTIVE_PIPELINE.get() + if context is None: + raise RuntimeError(f"Component '{func.__name__}' must be called inside a @pipeline function.") + bound = input_signature.bind(**kwargs) + bound.apply_defaults() + return context.add(func, inputs, outputs, dict(bound.arguments)) + + return invoke + + +command_component = component + + +def pipeline( + *, + compute_id: str, + environment_image_reference: str, + user_assigned_identity_id: str, + instance_type: str, +) -> Callable[[Callable[..., Any]], Callable[..., PipelineJob]]: + """Decorate a pipeline builder; calling it returns a native Foundry PipelineJob. + + Compute, image, identity, and instance type are inherited by each command node. + """ + + def decorate(func: Callable[..., Any]) -> Callable[..., PipelineJob]: + signature = inspect.signature(func) + annotations = get_type_hints(func) + + @wraps(func) + def build(*args: Any, **kwargs: Any) -> PipelineJob: + bound = signature.bind(*args, **kwargs) + bound.apply_defaults() + context = _PipelineContext(compute_id, environment_image_reference, user_assigned_identity_id, instance_type) + job_inputs: Dict[str, Input] = {} + references: Dict[str, _InputRef] = {} + for name, value in bound.arguments.items(): + annotation = annotations.get(name, signature.parameters[name].annotation) + if isinstance(annotation, Input): + if annotation.type != AssetTypes.URI_FILE or not isinstance(value, Input) or value.type != AssetTypes.URI_FILE: + raise TypeError(f"Pipeline input '{name}' requires Input(type='uri_file', path=...).") + if not value.path or "://" not in value.path: + raise ValueError(f"Pipeline input '{name}' requires a remote URI; local files are not supported.") + job_inputs[name] = value + port_type = AssetTypes.URI_FILE + elif annotation in _PRIMITIVES and type(value) is annotation: + job_inputs[name] = Input(type=AssetTypes.LITERAL, value=str(value)) + port_type = _PRIMITIVES[annotation][0] + else: + raise TypeError(f"Pipeline input '{name}' needs a matching primitive or uri_file Input value.") + references[name] = _InputRef(context, name, port_type) + + token = _ACTIVE_PIPELINE.set(context) + try: + result = func(**references) + finally: + _ACTIVE_PIPELINE.reset(token) + + job_outputs: Dict[str, Dict[str, Any]] = {} + if result is not None: + if not isinstance(result, dict): + raise TypeError("Pipeline outputs must be returned as a dictionary of node outputs.") + for name, value in result.items(): + if not isinstance(value, _OutputRef) or value.owner is not context: + raise TypeError(f"Pipeline output '{name}' must reference an output from this pipeline.") + node_output = context.jobs[value.node]["outputs"][value.name] + if "path" in node_output: + raise ValueError(f"Node output '{value.node}.{value.name}' cannot bind to multiple pipeline outputs.") + node_output["path"] = f"${{{{parent.outputs.{name}}}}}" + job_outputs[name] = {"type": value.type, "mode": value.mode} + + job = PipelineJob( + display_name=func.__name__, + compute_id=compute_id, + settings={"default_compute": compute_id, "force_rerun": True}, + inputs=job_inputs, + outputs=job_outputs, + jobs=context.jobs, + ) + job._component_code_dirs = context.code_dirs + return job + + return build + + return decorate diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index 3aded07e7fc0..2b6cfb06be97 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -13,8 +13,9 @@ from concurrent.futures import ThreadPoolExecutor, as_completed from os import PathLike from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Union +from typing import Any, Dict, List, Optional, Tuple, Union, overload from urllib.parse import urlparse +from uuid import uuid4 from azure.core.exceptions import ResourceNotFoundError @@ -246,13 +247,20 @@ def _resolve_local_paths(self, name: str, job: CommandJob) -> None: def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: """Resolve local code folders on inline command nodes to dataset asset URIs.""" - for node_name, node in (job.jobs or {}).items(): - if not isinstance(node, dict) or node.get("type") != "command": - continue - component = node.get("component") - if not isinstance(component, dict) or not isinstance(component.get("code"), str): - continue - component["code"] = self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + try: + for node_name, node in (job.jobs or {}).items(): + if not isinstance(node, dict) or node.get("type") != "command": + continue + component = node.get("component") + if not isinstance(component, dict) or not isinstance(component.get("code"), str): + continue + component["code"] = self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + finally: + code_dirs = getattr(job, "_component_code_dirs", None) + if code_dirs is not None: + for directory in code_dirs: + directory.cleanup() + code_dirs.clear() def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -343,21 +351,45 @@ def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: # ty rest_result = super().get(name=name, **kwargs) return _from_rest_job(rest_result) - @distributed_trace - def create_or_update( # type: ignore[override] + @overload + def create_or_update( + self, + name: PipelineJob, + job: None = None, + *, + experiment_name: Optional[str] = None, + skip_validation: bool = False, + **kwargs: Any, + ) -> PipelineJob: ... + + @overload + def create_or_update( self, name: str, job: Union[CommandJob, PipelineJob], *, skip_validation: bool = False, **kwargs: Any, + ) -> Union[CommandJob, PipelineJob]: ... + + @distributed_trace + def create_or_update( # type: ignore[override] + self, + name: Union[str, PipelineJob], + job: Optional[Union[CommandJob, PipelineJob]] = None, + *, + experiment_name: Optional[str] = None, + skip_validation: bool = False, + **kwargs: Any, ) -> Union[CommandJob, PipelineJob]: """Create or update a training job. - :param name: The name of the job. Required. - :type name: str - :param job: The Command or Pipeline job to create or update. Required. - :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob + :param name: The job name, or a PipelineJob for a unique autogenerated name. + :type name: str or ~azure.ai.projects.models.PipelineJob + :param job: The Command or Pipeline job. Required when ``name`` is a string. + :type job: ~azure.ai.projects.models.CommandJob or ~azure.ai.projects.models.PipelineJob or None + :keyword experiment_name: Experiment name for a job-only PipelineJob submission. + :paramtype experiment_name: str or None :keyword skip_validation: If ``True``, skip local CommandJob validation. PipelineJob nodes are not locally validated. Defaults to ``False``. :paramtype skip_validation: bool @@ -366,6 +398,18 @@ def create_or_update( # type: ignore[override] :raises ~azure.core.exceptions.HttpResponseError: :raises ValueError: If required fields are missing or empty. """ + if isinstance(name, PipelineJob): + if job is not None: + raise TypeError("A job cannot be supplied when the first argument is a PipelineJob.") + job = name + name = f"pipeline-{uuid4().hex}" + if experiment_name is not None: + job.experiment_name = experiment_name + elif not isinstance(name, str) or job is None: + raise TypeError("create_or_update requires a job name and job, or one PipelineJob.") + elif experiment_name is not None: + raise TypeError("Set job.experiment_name when submitting a job with an explicit name.") + if isinstance(job, CommandJob): if not skip_validation: _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py new file mode 100644 index 000000000000..d488ca4173b3 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py @@ -0,0 +1,61 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Author a two-step PipelineJob from Python function bodies. + +Set FOUNDRY_PROJECT_ENDPOINT, JOB_COMPUTE_ID, JOB_ENVIRONMENT_IMAGE, +JOB_NODE_UAI_RESOURCE_ID, and JOB_INSTANCE_TYPE before running. Each function +gets its own generated Code folder, which is uploaded when the job is submitted. +Running this sample uploads both folders and submits a job. +""" + +import os +from pathlib import Path + +from azure.ai.projects import AIProjectClient, dsl +from azure.ai.projects.dsl import Input, Output +from azure.identity import AzureCliCredential + + +@dsl.component +def produce(text: str, message: Output(type="uri_file")) -> None: + Path(message).write_text(text, encoding="utf-8") + + +@dsl.component +def consume(message: Input(type="uri_file"), receipt: Output(type="uri_file")) -> None: + Path(receipt).write_text(Path(message).read_text(encoding="utf-8").upper(), encoding="utf-8") + + +@dsl.pipeline( + compute_id=os.environ["JOB_COMPUTE_ID"], + environment_image_reference=os.environ["JOB_ENVIRONMENT_IMAGE"], + user_assigned_identity_id=os.environ["JOB_NODE_UAI_RESOURCE_ID"], + instance_type=os.environ["JOB_INSTANCE_TYPE"], +) +def workflow(text: str): + first = produce(text=text) + second = consume(message=first.outputs.message) + return {"receipt": second.outputs.receipt} + + +def main() -> None: + job = workflow(text="hello") + with ( + AzureCliCredential() as credential, + AIProjectClient( + endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"], + credential=credential, + allow_preview=True, + retry_total=0, + ) as client, + ): + created = client.beta.jobs.create_or_update( + job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} + ) + print(f"Submitted {created.name}: {created.id} (status: {created.status})") + + +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index d69a478b75ef..8cc52ea2a2d3 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -5,7 +5,10 @@ """Offline wire and response tests for Command and Pipeline jobs.""" import json +import re import runpy +import subprocess +import sys from pathlib import Path from typing import Any, Union from urllib.parse import parse_qs, urlparse @@ -21,7 +24,7 @@ HttpTransport, ) -from azure.ai.projects import AIProjectClient +from azure.ai.projects import AIProjectClient, dsl from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient from azure.ai.projects.models import ( AssetTypes, @@ -585,3 +588,326 @@ async def test_jobs_async_create_get_and_list(kind: str) -> None: _assert_job(listed[1], "Pipeline") _assert_requests(transport.requests, kind, expected) + + +def _dsl_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: + monkeypatch.setenv("JOB_COMPUTE_ID", _COMPUTE) + monkeypatch.setenv("JOB_ENVIRONMENT_IMAGE", "example.azurecr.io/train:latest") + monkeypatch.setenv("JOB_NODE_UAI_RESOURCE_ID", "/subscriptions/test/identities/hello") + monkeypatch.setenv("JOB_INSTANCE_TYPE", "Singularity.D4_v3") + sample = runpy.run_path( + str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / "sample_pipeline_dsl.py") + ) + return sample["workflow"](text="hello") + + +def _dsl_code_paths(job: PipelineJob) -> dict[str, Path]: + assert job.jobs is not None + return {name: Path(node["component"]["code"]) for name, node in job.jobs.items()} + + +def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: + assert request.method == "PUT" + assert request.headers["Foundry-Features"] == "Jobs=V1Preview" + assert request.headers["x-ms-foundry-job-route"] == "execution" + assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] + assert re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", urlparse(request.url).path) + resources = { + "instance_count": 1, + "instance_type": "Singularity.D4_v3", + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + } + identity = {"type": "managed", "msi_resource_id": "/subscriptions/test/identities/hello"} + assert json.loads(request.body) == { + "properties": { + "jobType": "Pipeline", + "displayName": "workflow", + "experimentName": "pipeline_samples", + "computeId": _COMPUTE, + "settings": {"default_compute": _COMPUTE, "force_rerun": True}, + "inputs": {"text": {"jobInputType": "literal", "value": "hello"}}, + "outputs": {"receipt": {"type": "uri_file", "mode": "ReadWriteMount"}}, + "jobs": { + "produce": { + "type": "command", + "component": { + "name": "produce", + "version": "1", + "type": "command", + "command": 'python component.py "${{inputs.text}}" "${{outputs.message}}"', + "environment": {"image": "example.azurecr.io/train:latest"}, + "inputs": {"text": {"type": "string"}}, + "outputs": {"message": {"type": "uri_file"}}, + "code": uploaded["produce"], + }, + "identity": identity, + "resources": resources, + "inputs": {"text": {"job_input_type": "literal", "value": "${{parent.inputs.text}}"}}, + "outputs": {"message": {"job_output_type": "uri_file", "mode": "ReadWriteMount"}}, + }, + "consume": { + "type": "command", + "component": { + "name": "consume", + "version": "1", + "type": "command", + "command": 'python component.py "${{inputs.message}}" "${{outputs.receipt}}"', + "environment": {"image": "example.azurecr.io/train:latest"}, + "inputs": {"message": {"type": "uri_file"}}, + "outputs": {"receipt": {"type": "uri_file"}}, + "code": uploaded["consume"], + }, + "identity": identity, + "resources": resources, + "inputs": { + "message": { + "job_input_type": "literal", + "value": "${{parent.jobs.produce.outputs.message}}", + } + }, + "outputs": { + "receipt": { + "job_output_type": "uri_file", + "mode": "ReadWriteMount", + "path": "${{parent.outputs.receipt}}", + } + }, + }, + }, + } + } + + +def test_dsl_component_bodies_execute_with_module_level_imports( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + job = _dsl_job(monkeypatch) + code = _dsl_code_paths(job) + try: + assert code["produce"] != code["consume"] + assert all(path.is_dir() for path in code.values()) + for path in code.values(): + script = (path / "component.py").read_text(encoding="utf-8") + assert "from pathlib import Path" in script + assert "azure.ai.projects" not in script + + message = tmp_path / "message.txt" + receipt = tmp_path / "receipt.txt" + subprocess.run( + [sys.executable, str(code["produce"] / "component.py"), "hello", str(message)], + check=True, + capture_output=True, + text=True, + ) + subprocess.run( + [sys.executable, str(code["consume"] / "component.py"), str(message), str(receipt)], + check=True, + capture_output=True, + text=True, + ) + assert receipt.read_text(encoding="utf-8") == "HELLO" + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + +def test_dsl_sync_uploads_code_and_cleans_after_submission(monkeypatch: pytest.MonkeyPatch) -> None: + job = _dsl_job(monkeypatch) + paths = _dsl_code_paths(job) + transport = _Transport([_response("Pipeline")]) + uploads: list[tuple[str, str]] = [] + + def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + assert Path(folder).is_dir() + uploads.append((name, folder)) + return _uploaded_code(name, version) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + created = client.beta.jobs.create_or_update( + job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} + ) + + assert isinstance(created, PipelineJob) + assert job.experiment_name == "pipeline_samples" + assert len(uploads) == 2 + assert [name.rsplit("-", 2)[-2] for name, _ in uploads] == ["produce", "consume"] + assert [folder for _, folder in uploads] == [str(paths["produce"]), str(paths["consume"])] + assert all(not path.exists() for path in paths.values()) + assert len(transport.requests) == 1 + code_uris = { + name.rsplit("-", 2)[-2]: job.jobs[name.rsplit("-", 2)[-2]]["component"]["code"] + for name, _ in uploads + } + _assert_dsl_request(transport.requests[0], code_uris) + + +@pytest.mark.asyncio +async def test_dsl_async_uploads_code_and_cleans_after_submission(monkeypatch: pytest.MonkeyPatch) -> None: + job = _dsl_job(monkeypatch) + paths = _dsl_code_paths(job) + transport = _AsyncTransport([_response("Pipeline")]) + uploads: list[tuple[str, str]] = [] + + async def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + assert Path(folder).is_dir() + uploads.append((name, folder)) + return _uploaded_code(name, version) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + created = await client.beta.jobs.create_or_update( + job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} + ) + + assert isinstance(created, PipelineJob) + assert len(uploads) == 2 + assert [folder for _, folder in uploads] == [str(paths["produce"]), str(paths["consume"])] + assert all(not path.exists() for path in paths.values()) + assert len(transport.requests) == 1 + assert json.loads(transport.requests[0].body)["properties"]["experimentName"] == "pipeline_samples" + + +def test_dsl_upload_failure_cleans_code_without_put(monkeypatch: pytest.MonkeyPatch) -> None: + job = _dsl_job(monkeypatch) + paths = _dsl_code_paths(job) + transport = _Transport([]) + uploads: list[str] = [] + + def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + uploads.append(folder) + if len(uploads) == 2: + raise RuntimeError("upload failed") + return _uploaded_code(name, version) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + with pytest.raises(RuntimeError, match="upload failed"): + client.beta.jobs.create_or_update(job) + + assert len(uploads) == 2 + assert transport.requests == [] + assert all(not path.exists() for path in paths.values()) + + +@pytest.mark.asyncio +async def test_dsl_async_upload_failure_cleans_code_without_put(monkeypatch: pytest.MonkeyPatch) -> None: + job = _dsl_job(monkeypatch) + paths = _dsl_code_paths(job) + transport = _AsyncTransport([]) + uploads: list[str] = [] + + async def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + uploads.append(folder) + if len(uploads) == 2: + raise RuntimeError("upload failed") + return _uploaded_code(name, version) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + with pytest.raises(RuntimeError, match="upload failed"): + await client.beta.jobs.create_or_update(job) + + assert len(uploads) == 2 + assert transport.requests == [] + assert all(not path.exists() for path in paths.values()) + + +def test_dsl_repeated_component_calls_get_distinct_nodes() -> None: + @dsl.component + def write(text: str, result: dsl.Output(type="uri_file", mode="Upload")) -> None: + from pathlib import Path + Path(result).write_text(text, encoding="utf-8") + + @dsl.pipeline( + compute_id=_COMPUTE, + environment_image_reference="example.azurecr.io/train:latest", + user_assigned_identity_id="/subscriptions/test/identities/hello", + instance_type="Singularity.D4_v3", + ) + def workflow(text: str): + first = write(text=text) + second = write(text=text) + return {"first": first.outputs.result, "second": second.outputs.result} + + job = workflow(text="hello") + try: + assert list(job.jobs) == ["write", "write_2"] + assert job.jobs["write"]["outputs"]["result"]["path"] == "${{parent.outputs.first}}" + assert job.jobs["write_2"]["outputs"]["result"]["path"] == "${{parent.outputs.second}}" + assert job.jobs["write"]["outputs"]["result"]["mode"] == "Upload" + assert _dsl_code_paths(job)["write"] != _dsl_code_paths(job)["write_2"] + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + +def test_dsl_rejects_unsupported_module_globals_and_outside_calls() -> None: + @dsl.component + def write(result: dsl.Output(type="uri_file")) -> None: + Path(result).write_text(_COMPUTE, encoding="utf-8") + + @dsl.pipeline( + compute_id=_COMPUTE, + environment_image_reference="example.azurecr.io/train:latest", + user_assigned_identity_id="/subscriptions/test/identities/hello", + instance_type="Singularity.D4_v3", + ) + def workflow() -> None: + write() + + with pytest.raises(RuntimeError, match="inside a @pipeline"): + write() + with pytest.raises(ValueError, match="unsupported module globals"): + workflow() + + +def test_jobs_sync_job_only_names_are_unique() -> None: + job = PipelineJob(compute_id=_COMPUTE, jobs={}) + transport = _Transport([_response("Pipeline"), _response("Pipeline")]) + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + client.beta.jobs.create_or_update(job) + client.beta.jobs.create_or_update(job) + with pytest.raises(TypeError, match="one PipelineJob"): + client.beta.jobs.create_or_update("missing-job") + with pytest.raises(TypeError, match="A job cannot be supplied"): + client.beta.jobs.create_or_update(job, job) + + paths = [urlparse(request.url).path for request in transport.requests] + assert len(paths) == len(set(paths)) == 2 + assert all(re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", path) for path in paths) + + +@pytest.mark.asyncio +async def test_jobs_async_job_only_names_are_unique() -> None: + job = PipelineJob(compute_id=_COMPUTE, jobs={}) + transport = _AsyncTransport([_response("Pipeline"), _response("Pipeline")]) + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + await client.beta.jobs.create_or_update(job) + await client.beta.jobs.create_or_update(job) + + paths = [urlparse(request.url).path for request in transport.requests] + assert len(paths) == len(set(paths)) == 2 + assert all(re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", path) for path in paths) From 2aa28e211a8af33378b945c7e93cec7fc0931bd9 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:36:48 -0700 Subject: [PATCH 10/52] Format Foundry DSL and pipeline tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/dsl.py | 43 ++++++++++++------- .../tests/jobs/test_pipeline_jobs.py | 10 ++--- 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index b5f1eb07d5cd..ca4c23ef2d7b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -117,7 +117,9 @@ def _function_script(func: Callable[..., Any], inputs: List[_Port], outputs: Lis free_vars = inspect.getclosurevars(func) if free_vars.nonlocals: - raise ValueError(f"Component '{func.__name__}' cannot capture enclosing variables: {sorted(free_vars.nonlocals)}.") + raise ValueError( + f"Component '{func.__name__}' cannot capture enclosing variables: {sorted(free_vars.nonlocals)}." + ) globals_needed = set(free_vars.globals) imports: List[str] = [] for statement in module_tree.body: @@ -138,9 +140,7 @@ def _function_script(func: Callable[..., Any], inputs: List[_Port], outputs: Lis definition.decorator_list = [] definition.returns = None - for parameter in ( - definition.args.posonlyargs + definition.args.args + definition.args.kwonlyargs - ): + for parameter in definition.args.posonlyargs + definition.args.args + definition.args.kwonlyargs: parameter.annotation = None definition.args.defaults = [] definition.args.kw_defaults = [None] * len(definition.args.kwonlyargs) @@ -191,10 +191,11 @@ def add( serialized = f"${{{{parent.jobs.{value.node}.outputs.{value.name}}}}}" elif port.type == AssetTypes.URI_FILE: raise TypeError(f"Component input '{port.name}' needs a pipeline input or node file output.") - elif (port.conversion == "int" and type(value) is int) or ( - port.conversion == "float" and type(value) is float - ) or (port.conversion == "bool" and type(value) is bool) or ( - port.conversion == "str" and type(value) is str + elif ( + (port.conversion == "int" and type(value) is int) + or (port.conversion == "float" and type(value) is float) + or (port.conversion == "bool" and type(value) is bool) + or (port.conversion == "str" and type(value) is str) ): serialized = str(value) else: @@ -223,9 +224,7 @@ def add( } ), inputs=bound_inputs, - outputs={ - port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs - }, + outputs={port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs}, ) node = PipelineJob._command_node(name, job, self.compute_id) for port in inputs: @@ -235,7 +234,9 @@ def add( return SimpleNamespace( outputs=SimpleNamespace( **{ - port.name: _OutputRef(self, name, port.name, port.type, port.mode or InputOutputModes.READ_WRITE_MOUNT) + port.name: _OutputRef( + self, name, port.name, port.type, port.mode or InputOutputModes.READ_WRITE_MOUNT + ) for port in outputs } ) @@ -288,16 +289,24 @@ def decorate(func: Callable[..., Any]) -> Callable[..., PipelineJob]: def build(*args: Any, **kwargs: Any) -> PipelineJob: bound = signature.bind(*args, **kwargs) bound.apply_defaults() - context = _PipelineContext(compute_id, environment_image_reference, user_assigned_identity_id, instance_type) + context = _PipelineContext( + compute_id, environment_image_reference, user_assigned_identity_id, instance_type + ) job_inputs: Dict[str, Input] = {} references: Dict[str, _InputRef] = {} for name, value in bound.arguments.items(): annotation = annotations.get(name, signature.parameters[name].annotation) if isinstance(annotation, Input): - if annotation.type != AssetTypes.URI_FILE or not isinstance(value, Input) or value.type != AssetTypes.URI_FILE: + if ( + annotation.type != AssetTypes.URI_FILE + or not isinstance(value, Input) + or value.type != AssetTypes.URI_FILE + ): raise TypeError(f"Pipeline input '{name}' requires Input(type='uri_file', path=...).") if not value.path or "://" not in value.path: - raise ValueError(f"Pipeline input '{name}' requires a remote URI; local files are not supported.") + raise ValueError( + f"Pipeline input '{name}' requires a remote URI; local files are not supported." + ) job_inputs[name] = value port_type = AssetTypes.URI_FILE elif annotation in _PRIMITIVES and type(value) is annotation: @@ -322,7 +331,9 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: raise TypeError(f"Pipeline output '{name}' must reference an output from this pipeline.") node_output = context.jobs[value.node]["outputs"][value.name] if "path" in node_output: - raise ValueError(f"Node output '{value.node}.{value.name}' cannot bind to multiple pipeline outputs.") + raise ValueError( + f"Node output '{value.node}.{value.name}' cannot bind to multiple pipeline outputs." + ) node_output["path"] = f"${{{{parent.outputs.{name}}}}}" job_outputs[name] = {"type": value.type, "mode": value.mode} diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 8cc52ea2a2d3..4add1fc6c383 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -595,9 +595,7 @@ def _dsl_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: monkeypatch.setenv("JOB_ENVIRONMENT_IMAGE", "example.azurecr.io/train:latest") monkeypatch.setenv("JOB_NODE_UAI_RESOURCE_ID", "/subscriptions/test/identities/hello") monkeypatch.setenv("JOB_INSTANCE_TYPE", "Singularity.D4_v3") - sample = runpy.run_path( - str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / "sample_pipeline_dsl.py") - ) + sample = runpy.run_path(str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / "sample_pipeline_dsl.py")) return sample["workflow"](text="hello") @@ -739,10 +737,7 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat assert [folder for _, folder in uploads] == [str(paths["produce"]), str(paths["consume"])] assert all(not path.exists() for path in paths.values()) assert len(transport.requests) == 1 - code_uris = { - name.rsplit("-", 2)[-2]: job.jobs[name.rsplit("-", 2)[-2]]["component"]["code"] - for name, _ in uploads - } + code_uris = {name.rsplit("-", 2)[-2]: job.jobs[name.rsplit("-", 2)[-2]]["component"]["code"] for name, _ in uploads} _assert_dsl_request(transport.requests[0], code_uris) @@ -837,6 +832,7 @@ def test_dsl_repeated_component_calls_get_distinct_nodes() -> None: @dsl.component def write(text: str, result: dsl.Output(type="uri_file", mode="Upload")) -> None: from pathlib import Path + Path(result).write_text(text, encoding="utf-8") @dsl.pipeline( From 1426c92922c3005a8d5ed6fae5263ec650468d5b Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:39:52 -0700 Subject: [PATCH 11/52] Keep generated pipeline code snapshots typed Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../ai/projects/aio/operations/_patch_jobs_async.py | 10 ++++------ sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py | 4 ++-- .../azure/ai/projects/models/_patch_jobs.py | 2 ++ .../azure/ai/projects/operations/_patch_jobs.py | 10 ++++------ 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 88ab600817f8..8e8fbfbb2e5f 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -253,11 +253,9 @@ async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: continue component["code"] = await self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") finally: - code_dirs = getattr(job, "_component_code_dirs", None) - if code_dirs is not None: - for directory in code_dirs: - directory.cleanup() - code_dirs.clear() + for directory in job._component_code_dirs: + directory.cleanup() + job._component_code_dirs.clear() def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -344,7 +342,7 @@ async def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: return _from_rest_job(rest_result) @overload - async def create_or_update( + async def create_or_update( # type: ignore[override] self, name: PipelineJob, job: None = None, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index ca4c23ef2d7b..5a7dec873b69 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -251,7 +251,7 @@ def component(func: Callable[..., Any]) -> Callable[..., SimpleNamespace]: inputs, outputs = _component_ports(func) input_names = {port.name for port in inputs} input_signature = inspect.Signature( - parameter for parameter in inspect.signature(func).parameters.values() if parameter.name in input_names + [parameter for parameter in inspect.signature(func).parameters.values() if parameter.name in input_names] ) @wraps(func) @@ -308,7 +308,7 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: f"Pipeline input '{name}' requires a remote URI; local files are not supported." ) job_inputs[name] = value - port_type = AssetTypes.URI_FILE + port_type: str = AssetTypes.URI_FILE elif annotation in _PRIMITIVES and type(value) is annotation: job_inputs[name] = Input(type=AssetTypes.LITERAL, value=str(value)) port_type = _PRIMITIVES[annotation][0] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index bbed3eaa4f98..cf8ec4ec6b0e 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -10,6 +10,7 @@ from collections.abc import Mapping from os import PathLike from pathlib import Path +from tempfile import TemporaryDirectory from typing import IO, Any, AnyStr, Dict, List, Optional, Union from ._models import ( @@ -138,6 +139,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self._name: Optional[str] = None self._id: Optional[str] = None self._system_data: Optional[SystemData] = None + self._component_code_dirs: List[TemporaryDirectory] = [] @classmethod def _convert_jobs(cls, jobs: Dict[str, Any], default_compute: Optional[str]) -> Dict[str, Any]: diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index 2b6cfb06be97..0e78aa181137 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -256,11 +256,9 @@ def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: continue component["code"] = self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") finally: - code_dirs = getattr(job, "_component_code_dirs", None) - if code_dirs is not None: - for directory in code_dirs: - directory.cleanup() - code_dirs.clear() + for directory in job._component_code_dirs: + directory.cleanup() + job._component_code_dirs.clear() def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -352,7 +350,7 @@ def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: # ty return _from_rest_job(rest_result) @overload - def create_or_update( + def create_or_update( # type: ignore[override] self, name: PipelineJob, job: None = None, From c88a1ec1b7dffc71c50c639bd7370f9ae584f739 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:41:17 -0700 Subject: [PATCH 12/52] Type-check native pipeline submission and sample annotations Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/aio/operations/_patch_jobs_async.py | 4 ++-- .../azure/ai/projects/operations/_patch_jobs.py | 4 ++-- sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 8e8fbfbb2e5f..7c97327ff1ab 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -341,8 +341,8 @@ async def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: rest_result = await super().get(name=name, **kwargs) return _from_rest_job(rest_result) - @overload - async def create_or_update( # type: ignore[override] + @overload # type: ignore[override] + async def create_or_update( self, name: PipelineJob, job: None = None, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index 0e78aa181137..e69fea52ad6b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -349,8 +349,8 @@ def get(self, name: str, **kwargs: Any) -> Union[CommandJob, PipelineJob]: # ty rest_result = super().get(name=name, **kwargs) return _from_rest_job(rest_result) - @overload - def create_or_update( # type: ignore[override] + @overload # type: ignore[override] + def create_or_update( self, name: PipelineJob, job: None = None, diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py index d488ca4173b3..2ffe3f500358 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py @@ -19,12 +19,12 @@ @dsl.component -def produce(text: str, message: Output(type="uri_file")) -> None: +def produce(text: str, message: Output(type="uri_file")) -> None: # type: ignore[valid-type] Path(message).write_text(text, encoding="utf-8") @dsl.component -def consume(message: Input(type="uri_file"), receipt: Output(type="uri_file")) -> None: +def consume(message: Input(type="uri_file"), receipt: Output(type="uri_file")) -> None: # type: ignore[valid-type] Path(receipt).write_text(Path(message).read_text(encoding="utf-8").upper(), encoding="utf-8") From 82f2d8138b24391bda137111128c17bf2c0799a0 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:43:35 -0700 Subject: [PATCH 13/52] Cover typed pipeline ports and component alias offline Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/jobs/test_pipeline_jobs.py | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 4add1fc6c383..f77b1d59fdbd 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -858,6 +858,75 @@ def workflow(text: str): directory.cleanup() +def test_dsl_typed_primitives_and_remote_file_input(tmp_path: Path) -> None: + assert dsl.command_component is dsl.component + + @dsl.component + def transform( + count: int, + scale: float, + enabled: bool, + source: dsl.Input(type="uri_file"), + result: dsl.Output(type="uri_file"), + ) -> None: + from pathlib import Path + + if enabled: + Path(result).write_text(Path(source).read_text(encoding="utf-8") * count + str(scale), encoding="utf-8") + + @dsl.pipeline( + compute_id=_COMPUTE, + environment_image_reference="example.azurecr.io/train:latest", + user_assigned_identity_id="/subscriptions/test/identities/hello", + instance_type="Singularity.D4_v3", + ) + def workflow(count: int, scale: float, enabled: bool, source: dsl.Input(type="uri_file")): + node = transform(count=count, scale=scale, enabled=enabled, source=source) + return {"result": node.outputs.result} + + job = workflow( + count=3, + scale=1.5, + enabled=True, + source=dsl.Input(type="uri_file", path="azureml://datastores/test/paths/input.txt"), + ) + try: + assert job.inputs["count"].value == "3" + assert job.inputs["scale"].value == "1.5" + assert job.inputs["enabled"].value == "True" + assert job.inputs["source"].path == "azureml://datastores/test/paths/input.txt" + node = job.jobs["transform"] + assert node["component"]["inputs"] == { + "count": {"type": "integer"}, + "scale": {"type": "number"}, + "enabled": {"type": "boolean"}, + "source": {"type": "uri_file"}, + } + assert node["inputs"]["source"]["value"] == "${{parent.inputs.source}}" + + source = tmp_path / "source.txt" + output = tmp_path / "output.txt" + source.write_text("go", encoding="utf-8") + subprocess.run( + [ + sys.executable, + str(_dsl_code_paths(job)["transform"] / "component.py"), + "3", + "1.5", + "True", + str(source), + str(output), + ], + check=True, + capture_output=True, + text=True, + ) + assert output.read_text(encoding="utf-8") == "gogogo1.5" + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + def test_dsl_rejects_unsupported_module_globals_and_outside_calls() -> None: @dsl.component def write(result: dsl.Output(type="uri_file")) -> None: From 96386026061ac9f72e39b8f7bb21fe3969b1e870 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:45:05 -0700 Subject: [PATCH 14/52] Assert normalized PipelineJob input payloads Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/jobs/test_pipeline_jobs.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index f77b1d59fdbd..34cb71461407 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -891,10 +891,13 @@ def workflow(count: int, scale: float, enabled: bool, source: dsl.Input(type="ur source=dsl.Input(type="uri_file", path="azureml://datastores/test/paths/input.txt"), ) try: - assert job.inputs["count"].value == "3" - assert job.inputs["scale"].value == "1.5" - assert job.inputs["enabled"].value == "True" - assert job.inputs["source"].path == "azureml://datastores/test/paths/input.txt" + assert job.inputs["count"] == {"jobInputType": "literal", "value": "3"} + assert job.inputs["scale"] == {"jobInputType": "literal", "value": "1.5"} + assert job.inputs["enabled"] == {"jobInputType": "literal", "value": "True"} + assert job.inputs["source"] == { + "jobInputType": "uri_file", + "uri": "azureml://datastores/test/paths/input.txt", + } node = job.jobs["transform"] assert node["component"]["inputs"] == { "count": {"type": "integer"}, From 36a0c3f37697a15ae516dc7d7c98bdbf99bb5edf Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:47:57 -0700 Subject: [PATCH 15/52] Make unsupported-global component fixture unambiguous Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 34cb71461407..c7eb84f4c64e 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -932,7 +932,7 @@ def workflow(count: int, scale: float, enabled: bool, source: dsl.Input(type="ur def test_dsl_rejects_unsupported_module_globals_and_outside_calls() -> None: @dsl.component - def write(result: dsl.Output(type="uri_file")) -> None: + def write_with_global(result: dsl.Output(type="uri_file")) -> None: Path(result).write_text(_COMPUTE, encoding="utf-8") @dsl.pipeline( @@ -942,10 +942,10 @@ def write(result: dsl.Output(type="uri_file")) -> None: instance_type="Singularity.D4_v3", ) def workflow() -> None: - write() + write_with_global() with pytest.raises(RuntimeError, match="inside a @pipeline"): - write() + write_with_global() with pytest.raises(ValueError, match="unsupported module globals"): workflow() From fe3c1d7b2c453d6debf66d91be1b6b0be3006af5 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 18:54:32 -0700 Subject: [PATCH 16/52] Show direct Foundry pipeline decorators in examples Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/README.md | 11 ++++++----- .../samples/jobs/sample_pipeline_dsl.py | 10 +++++----- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index 9a5709b3f053..c04120eb5996 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -175,11 +175,12 @@ Full descriptions and working code for all of the above are available in: ### Author Python function pipeline jobs (preview) -Use `from azure.ai.projects import dsl` to define a Python function body with `@dsl.component` and -call that component inside an `@dsl.pipeline` function. `dsl.Input(type="uri_file")` and -`dsl.Output(type="uri_file")` declare file ports; output names are inferred from parameter names -and file outputs use read-write mounts by default. The pipeline decorator supplies the compute -resource ID, container image, user-assigned identity ID, and instance type inherited by its nodes. +Use `from azure.ai.projects.dsl import Input, Output, component, pipeline` to define a Python +function body with `@component` and call that component inside a `@pipeline` function. +`Input(type="uri_file")` and `Output(type="uri_file")` declare file ports; output names are inferred +from parameter names and file outputs use read-write mounts by default. The pipeline decorator +supplies the compute resource ID, container image, user-assigned identity ID, and instance type +inherited by its nodes. Calling the decorated pipeline function constructs a native Foundry `PipelineJob` without an outer builder. Submit it with `client.beta.jobs.create_or_update(job)` for an autogenerated job name, optionally passing `experiment_name="pipeline_samples"`, or use the existing diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py index 2ffe3f500358..690e9d12afb7 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py @@ -13,22 +13,22 @@ import os from pathlib import Path -from azure.ai.projects import AIProjectClient, dsl -from azure.ai.projects.dsl import Input, Output +from azure.ai.projects import AIProjectClient +from azure.ai.projects.dsl import Input, Output, component, pipeline from azure.identity import AzureCliCredential -@dsl.component +@component def produce(text: str, message: Output(type="uri_file")) -> None: # type: ignore[valid-type] Path(message).write_text(text, encoding="utf-8") -@dsl.component +@component def consume(message: Input(type="uri_file"), receipt: Output(type="uri_file")) -> None: # type: ignore[valid-type] Path(receipt).write_text(Path(message).read_text(encoding="utf-8").upper(), encoding="utf-8") -@dsl.pipeline( +@pipeline( compute_id=os.environ["JOB_COMPUTE_ID"], environment_image_reference=os.environ["JOB_ENVIRONMENT_IMAGE"], user_assigned_identity_id=os.environ["JOB_NODE_UAI_RESOURCE_ID"], From 74143d7335460b7897fde3bd8d7ad0b3fd73ed2c Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:01:57 -0700 Subject: [PATCH 17/52] [azure-ai-projects] Run Python pipeline components from source snapshots Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 1 + sdk/ai/azure-ai-projects/README.md | 14 ++ .../azure/ai/projects/_component_runner.py | 39 ++++ .../azure/ai/projects/_component_source.py | 109 +++++++++++ .../aio/operations/_patch_jobs_async.py | 6 +- .../azure/ai/projects/dsl.py | 152 ++++++++++----- .../ai/projects/operations/_patch_jobs.py | 6 +- sdk/ai/azure-ai-projects/pyproject.toml | 2 +- .../samples/jobs/pipeline_source/README.md | 22 +++ .../pipeline_source/sample_pipeline_source.py | 49 +++++ .../jobs/pipeline_source/steps/__init__.py | 5 + .../jobs/pipeline_source/steps/components.py | 25 +++ .../jobs/pipeline_source/steps/greeting.txt | 1 + .../jobs/pipeline_source/steps/helpers.py | 12 ++ .../tests/jobs/test_pipeline_jobs.py | 181 ++++++++++++++++++ 15 files changed, 569 insertions(+), 55 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/azure/ai/projects/_component_runner.py create mode 100644 sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/__init__.py create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/components.py create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/greeting.txt create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/helpers.py diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 8fbb23f9389d..6dfc850a4715 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -27,6 +27,7 @@ * Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Local code folders on inline command nodes are registered as Code datasets before submission; local input handling and validation remain specific to standalone Command jobs. * When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. * Added `azure.ai.projects.dsl` function-body `@component` and `@pipeline` authoring for native two-step PipelineJobs. Calling the pipeline function builds its graph, packages each Python component body as its own executable Code folder, binds typed inputs and file outputs, and supports repeated component calls. `.beta.jobs.create_or_update(pipeline_job)` now generates a unique name (sync and async), while the existing explicit-name form remains available. +* Added opt-in `@component(code=...)` source-backed components for local helper functions, sibling modules, and resources. Code roots are snapshot with ignore rules before upload and shared by nodes in the same pipeline. Executing these components requires the image to contain a compatible `azure-ai-projects` package and other imported dependencies; bare `@component` keeps its existing standalone execution behavior. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index c04120eb5996..063e5964a5e6 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -195,6 +195,20 @@ third-party modules must already exist in the container image. This native Found does not accept an unmodified `azure.ai.ml.dsl` PipelineJob or provide full Azure ML component registration and environment features; local pipeline file inputs are not supported. +For helpers and local modules, use `@component(code="..")` to opt into a source-backed Code +snapshot. The path is relative to the file defining the component; it must include that file +and the top-level Python package to import. The runtime imports the original module and invokes +its undecorated function, so module globals, sibling Python files, and resources inside that +root are available. Define components in import-safe modules separate from submission-time +configuration. The selected image must contain a compatible `azure-ai-projects` version and +any other imported Python packages; the snapshot does not install dependencies or capture +closure values. Shared code roots are uploaded once per pipeline submission. +The snapshot honors `.amlignore` (or `.gitignore` when no `.amlignore` exists) in each directory, +always omits `.env` files and common Python/Git artifacts, and rejects included symlinks. +Review the code root before submitting: only files not excluded by these rules are uploaded. +See the [multi-file source-backed sample](samples/jobs/pipeline_source/README.md) for this +layout; the original single-file sample retains its standalone, SDK-free execution mode. + ### Hosted agents (preview) Hosted agents let you run your own containerized agent runtime while using Microsoft Foundry for managed hosting and scaling. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_runner.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_runner.py new file mode 100644 index 000000000000..8baa8c3d21f6 --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_runner.py @@ -0,0 +1,39 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Execute a source-backed component from a mounted Code snapshot.""" + +import importlib +import sys +from typing import Callable, Dict + + +def _boolean(value: str) -> bool: + return value == "True" + + +_CONVERSIONS: Dict[str, Callable[[str], object]] = { + "str": str, + "int": int, + "float": float, + "bool": _boolean, +} + + +def main() -> None: + module_name, function_name, port_spec = sys.argv[1:4] + ports = [] if port_spec == "-" else [port.split(":", 1) for port in port_spec.split(",")] + values = sys.argv[4:] + if len(ports) != len(values): + raise ValueError(f"Component '{function_name}' expected {len(ports)} arguments, got {len(values)}.") + + wrapped = getattr(importlib.import_module(module_name), function_name) + function = getattr(wrapped, "__wrapped__", None) + if function is None: + raise TypeError(f"Component '{module_name}.{function_name}' is not decorated with @component.") + function(**{name: _CONVERSIONS[conversion](value) for (name, conversion), value in zip(ports, values)}) + + +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py new file mode 100644 index 000000000000..9349e4a71c58 --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py @@ -0,0 +1,109 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Snapshot source files for Python-backed pipeline components.""" + +import inspect +import keyword +import shutil +from dataclasses import dataclass +from os import PathLike +from pathlib import Path +from typing import Callable, List, Tuple, Union + +from pathspec import GitIgnoreSpec + +_RUNNER_NAME = "__foundry_component_runner__.py" +_IGNORE_FILES = (".amlignore", ".gitignore") +_EXCLUDED_DIRECTORIES = frozenset((".git", ".venv", "__pycache__")) + + +@dataclass(frozen=True) +class _ComponentSource: + root: Path + relative_file: Path + module: str + + +def _source_for_component(func: Callable[..., object], code: Union[str, PathLike[str]]) -> _ComponentSource: + source_name = inspect.getsourcefile(func) + if source_name is None: + raise ValueError(f"Component '{func.__name__}' must be defined in a readable Python source file.") + source_file = Path(source_name).resolve() + if not source_file.is_file() or source_file.suffix != ".py": + raise ValueError(f"Component '{func.__name__}' must be defined in a readable Python source file.") + + root = Path(code) + if not root.is_absolute(): + root = source_file.parent / root + root = root.resolve() + if not root.is_dir(): + raise ValueError(f"Component '{func.__name__}' code root '{root}' must be an existing directory.") + try: + relative_file = source_file.relative_to(root) + except ValueError as error: + raise ValueError(f"Component '{func.__name__}' source file must be inside its code root '{root}'.") from error + + if func.__qualname__ != func.__name__: + raise ValueError(f"Source-backed component '{func.__name__}' must be a module-level function.") + free_vars = inspect.getclosurevars(func) + if free_vars.nonlocals: + raise ValueError(f"Component '{func.__name__}' cannot capture enclosing variables: {sorted(free_vars.nonlocals)}.") + + module_path = relative_file.parent if relative_file.name == "__init__.py" else relative_file.with_suffix("") + if not module_path.parts or any(not part.isidentifier() or keyword.iskeyword(part) for part in module_path.parts): + raise ValueError(f"Component '{func.__name__}' needs an importable Python module under its code root.") + return _ComponentSource(root=root, relative_file=relative_file, module=".".join(module_path.parts)) + + +def _is_ignored(relative_path: Path, is_directory: bool, rules: List[Tuple[Path, GitIgnoreSpec]]) -> bool: + ignored = False + for directory, spec in rules: + path_from_ignore = relative_path.relative_to(directory).as_posix() + result = spec.check_file(path_from_ignore + ("/" if is_directory else "")) + if result.include is not None: + ignored = result.include + return ignored + + +def _copy_source_tree( + source: Path, destination: Path, code_root: Path, rules: List[Tuple[Path, GitIgnoreSpec]] +) -> None: + ignore_path = next((source / name for name in _IGNORE_FILES if (source / name).exists()), None) + if ignore_path is not None: + if ignore_path.is_symlink() or not ignore_path.is_file(): + raise ValueError(f"Code ignore file '{ignore_path}' must be a regular file.") + relative_directory = source.relative_to(code_root) + rules = [*rules, (relative_directory, GitIgnoreSpec.from_lines(ignore_path.read_text(encoding="utf-8").splitlines()))] + + for path in sorted(source.iterdir()): + if path.name in _IGNORE_FILES: + continue + relative_path = path.relative_to(code_root) + is_directory = path.is_dir() + if ( + path.name in _EXCLUDED_DIRECTORIES + or path.name == ".env" + or path.name.startswith(".env.") + or path.suffix == ".pyc" + or _is_ignored(relative_path, is_directory, rules) + ): + continue + if path.is_symlink(): + raise ValueError(f"Code root '{code_root}' contains an included symbolic link: '{relative_path}'.") + target = destination / path.name + if is_directory: + target.mkdir() + _copy_source_tree(path, target, code_root, rules) + elif path.is_file(): + shutil.copy2(path, target) + else: + raise ValueError(f"Code root '{code_root}' contains a non-file entry: '{relative_path}'.") + + +def _stage_component_source(root: Path, destination: Path) -> None: + if (root / _RUNNER_NAME).exists() or (root / _RUNNER_NAME).is_symlink(): + raise ValueError(f"Code root '{root}' contains the reserved runner name '{_RUNNER_NAME}'.") + _copy_source_tree(root, destination, root, []) + shutil.copyfile(Path(__file__).with_name("_component_runner.py"), destination / _RUNNER_NAME) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 7c97327ff1ab..3361d5b0ba29 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -245,13 +245,17 @@ async def _resolve_local_paths(self, name: str, job: CommandJob) -> None: async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: """Resolve local code folders on inline command nodes to dataset asset URIs.""" try: + resolved_code: Dict[str, str] = {} for node_name, node in (job.jobs or {}).items(): if not isinstance(node, dict) or node.get("type") != "command": continue component = node.get("component") if not isinstance(component, dict) or not isinstance(component.get("code"), str): continue - component["code"] = await self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + code = component["code"] + if code not in resolved_code: + resolved_code[code] = await self._resolve_asset_uri(code, f"{name}-{node_name}-code") + component["code"] = resolved_code[code] finally: for directory in job._component_code_dirs: directory.cleanup() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 5a7dec873b69..a7d2a192ab51 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -10,11 +10,13 @@ from contextvars import ContextVar from dataclasses import dataclass from functools import wraps +from os import PathLike from pathlib import Path from tempfile import TemporaryDirectory from types import SimpleNamespace -from typing import Any, Callable, Dict, List, Optional, Tuple, Union, get_type_hints +from typing import Any, Callable, Dict, List, Optional, Tuple, Union, get_type_hints, overload +from ._component_source import _ComponentSource, _RUNNER_NAME, _source_for_component, _stage_component_source from .models import AssetTypes, CommandJob, Input, InputOutputModes, JobResourceConfiguration, PipelineJob from .models import Output as _JobOutput @@ -168,9 +170,15 @@ def __init__(self, compute_id: str, image: str, identity: str, instance_type: st self.instance_type = instance_type self.jobs: Dict[str, Dict[str, Any]] = {} self.code_dirs: List[TemporaryDirectory] = [] + self.code_dirs_by_root: Dict[Path, TemporaryDirectory] = {} def add( - self, func: Callable[..., Any], inputs: List[_Port], outputs: List[_Port], arguments: Dict[str, Any] + self, + func: Callable[..., Any], + inputs: List[_Port], + outputs: List[_Port], + arguments: Dict[str, Any], + source: Optional[_ComponentSource], ) -> SimpleNamespace: name = func.__name__ suffix = 2 @@ -203,15 +211,31 @@ def add( input_type = AssetTypes.URI_FILE if port.type == AssetTypes.URI_FILE else AssetTypes.LITERAL bound_inputs[port.name] = Input(type=input_type, value=serialized) - code_dir = TemporaryDirectory(prefix="foundry-component-") - self.code_dirs.append(code_dir) - (Path(code_dir.name) / "component.py").write_text(_function_script(func, inputs, outputs), encoding="utf-8") + arguments_in_command = " ".join( + [f'"${{{{inputs.{port.name}}}}}"' for port in inputs] + + [f'"${{{{outputs.{port.name}}}}}"' for port in outputs] + ) + if source is None: + code_dir = TemporaryDirectory(prefix="foundry-component-") + self.code_dirs.append(code_dir) + (Path(code_dir.name) / "component.py").write_text(_function_script(func, inputs, outputs), encoding="utf-8") + command = "python component.py " + arguments_in_command + else: + code_dir = self.code_dirs_by_root.get(source.root) + if code_dir is None: + code_dir = TemporaryDirectory(prefix="foundry-component-source-") + self.code_dirs.append(code_dir) + self.code_dirs_by_root[source.root] = code_dir + _stage_component_source(source.root, Path(code_dir.name)) + if not (Path(code_dir.name) / source.relative_file).is_file(): + raise ValueError(f"Component '{func.__name__}' source file is excluded by its code ignore rules.") + port_spec = ",".join(f"{port.name}:{port.conversion}" for port in inputs + outputs) or "-" + command = f"python {_RUNNER_NAME} {source.module} {func.__name__} {port_spec}" + if arguments_in_command: + command += " " + arguments_in_command + job = CommandJob( - command="python component.py " - + " ".join( - [f'"${{{{inputs.{port.name}}}}}"' for port in inputs] - + [f'"${{{{outputs.{port.name}}}}}"' for port in outputs] - ), + command=command, code=code_dir.name, environment_image_reference=self.image, compute=self.compute_id, @@ -243,27 +267,48 @@ def add( ) -def component(func: Callable[..., Any]) -> Callable[..., SimpleNamespace]: +@overload +def component( + func: Callable[..., Any], *, code: Optional[Union[str, PathLike[str]]] = None +) -> Callable[..., SimpleNamespace]: ... + + +@overload +def component( + func: None = None, *, code: Optional[Union[str, PathLike[str]]] = None +) -> Callable[[Callable[..., Any]], Callable[..., SimpleNamespace]]: ... + + +def component( + func: Optional[Callable[..., Any]] = None, *, code: Optional[Union[str, PathLike[str]]] = None +) -> Union[Callable[..., SimpleNamespace], Callable[[Callable[..., Any]], Callable[..., SimpleNamespace]]]: """Decorate a Python function to create a command node when invoked inside a pipeline. - The function body is packaged as code and runs remotely, not during graph creation. + With ``code``, snapshot that directory and import the original module at runtime. + Otherwise, package the function body as a standalone script. Code-backed components + require the authoring SDK and their other imports in the container image. """ - inputs, outputs = _component_ports(func) - input_names = {port.name for port in inputs} - input_signature = inspect.Signature( - [parameter for parameter in inspect.signature(func).parameters.values() if parameter.name in input_names] - ) - @wraps(func) - def invoke(**kwargs: Any) -> SimpleNamespace: - context = _ACTIVE_PIPELINE.get() - if context is None: - raise RuntimeError(f"Component '{func.__name__}' must be called inside a @pipeline function.") - bound = input_signature.bind(**kwargs) - bound.apply_defaults() - return context.add(func, inputs, outputs, dict(bound.arguments)) + def decorate(source_func: Callable[..., Any]) -> Callable[..., SimpleNamespace]: + inputs, outputs = _component_ports(source_func) + source = _source_for_component(source_func, code) if code is not None else None + input_names = {port.name for port in inputs} + input_signature = inspect.Signature( + [parameter for parameter in inspect.signature(source_func).parameters.values() if parameter.name in input_names] + ) + + @wraps(source_func) + def invoke(**kwargs: Any) -> SimpleNamespace: + context = _ACTIVE_PIPELINE.get() + if context is None: + raise RuntimeError(f"Component '{source_func.__name__}' must be called inside a @pipeline function.") + bound = input_signature.bind(**kwargs) + bound.apply_defaults() + return context.add(source_func, inputs, outputs, dict(bound.arguments), source) - return invoke + return invoke + + return decorate(func) if func is not None else decorate command_component = component @@ -317,36 +362,39 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: references[name] = _InputRef(context, name, port_type) token = _ACTIVE_PIPELINE.set(context) + job: Optional[PipelineJob] = None try: result = func(**references) + job_outputs: Dict[str, Dict[str, Any]] = {} + if result is not None: + if not isinstance(result, dict): + raise TypeError("Pipeline outputs must be returned as a dictionary of node outputs.") + for name, value in result.items(): + if not isinstance(value, _OutputRef) or value.owner is not context: + raise TypeError(f"Pipeline output '{name}' must reference an output from this pipeline.") + node_output = context.jobs[value.node]["outputs"][value.name] + if "path" in node_output: + raise ValueError( + f"Node output '{value.node}.{value.name}' cannot bind to multiple pipeline outputs." + ) + node_output["path"] = f"${{{{parent.outputs.{name}}}}}" + job_outputs[name] = {"type": value.type, "mode": value.mode} + + job = PipelineJob( + display_name=func.__name__, + compute_id=compute_id, + settings={"default_compute": compute_id, "force_rerun": True}, + inputs=job_inputs, + outputs=job_outputs, + jobs=context.jobs, + ) + job._component_code_dirs = context.code_dirs + return job finally: _ACTIVE_PIPELINE.reset(token) - - job_outputs: Dict[str, Dict[str, Any]] = {} - if result is not None: - if not isinstance(result, dict): - raise TypeError("Pipeline outputs must be returned as a dictionary of node outputs.") - for name, value in result.items(): - if not isinstance(value, _OutputRef) or value.owner is not context: - raise TypeError(f"Pipeline output '{name}' must reference an output from this pipeline.") - node_output = context.jobs[value.node]["outputs"][value.name] - if "path" in node_output: - raise ValueError( - f"Node output '{value.node}.{value.name}' cannot bind to multiple pipeline outputs." - ) - node_output["path"] = f"${{{{parent.outputs.{name}}}}}" - job_outputs[name] = {"type": value.type, "mode": value.mode} - - job = PipelineJob( - display_name=func.__name__, - compute_id=compute_id, - settings={"default_compute": compute_id, "force_rerun": True}, - inputs=job_inputs, - outputs=job_outputs, - jobs=context.jobs, - ) - job._component_code_dirs = context.code_dirs - return job + if job is None: + for directory in context.code_dirs: + directory.cleanup() return build diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index e69fea52ad6b..6e3e0017ac99 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -248,13 +248,17 @@ def _resolve_local_paths(self, name: str, job: CommandJob) -> None: def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: """Resolve local code folders on inline command nodes to dataset asset URIs.""" try: + resolved_code: Dict[str, str] = {} for node_name, node in (job.jobs or {}).items(): if not isinstance(node, dict) or node.get("type") != "command": continue component = node.get("component") if not isinstance(component, dict) or not isinstance(component.get("code"), str): continue - component["code"] = self._resolve_asset_uri(component["code"], f"{name}-{node_name}-code") + code = component["code"] + if code not in resolved_code: + resolved_code[code] = self._resolve_asset_uri(code, f"{name}-{node_name}-code") + component["code"] = resolved_code[code] finally: for directory in job._component_code_dirs: directory.cleanup() diff --git a/sdk/ai/azure-ai-projects/pyproject.toml b/sdk/ai/azure-ai-projects/pyproject.toml index e57e3c9f9be4..fe551d571419 100644 --- a/sdk/ai/azure-ai-projects/pyproject.toml +++ b/sdk/ai/azure-ai-projects/pyproject.toml @@ -39,6 +39,7 @@ dependencies = [ "openai>=2.8.0,<3", "httpx>=0.27.2,<1", "azure-storage-blob>=12.15.0", + "pathspec>=0.12.1", ] dynamic = [ "version", "readme" @@ -73,4 +74,3 @@ verifytypes = false [tool.azure-sdk-conda] in_bundle = false - diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md new file mode 100644 index 000000000000..2d7f6f7974fc --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md @@ -0,0 +1,22 @@ +# Source-backed Python pipeline components + +`sample_pipeline_source.py` builds a native two-node Foundry PipelineJob from +`steps/components.py`. Both components use `@component(code="..")`, so the Code +snapshot includes the sibling `helpers.py` module and `greeting.txt` resource. +The pipeline is built locally; component bodies run on the selected compute. +Both nodes share the same uploaded Code asset. + +Set `FOUNDRY_PROJECT_ENDPOINT`, `JOB_COMPUTE_ID`, `JOB_ENVIRONMENT_IMAGE`, +`JOB_NODE_UAI_RESOURCE_ID`, and `JOB_INSTANCE_TYPE` before running +`python sample_pipeline_source.py` from this directory. **Running the sample +uploads Code and submits a live job.** The container image must have a matching +`azure-ai-projects` version and all imports used by your components installed; +the source snapshot does not install Python dependencies. Keep component modules +import-safe: do not submit jobs or rely on submitter-only environment variables at +module import time. + +The code root is resolved relative to the file defining each component, not the +working directory. `.amlignore` takes precedence over `.gitignore` within each +directory; neither ignore file is uploaded. Common local artifacts and `.env` +files are excluded. Include only files intended for remote execution in the +code root; included symlinks cause an error rather than copying files outside it. diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py new file mode 100644 index 000000000000..5d1553d7ceb3 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py @@ -0,0 +1,49 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Submit a two-component PipelineJob that snapshots local helper modules. + +The image must include the same azure-ai-projects version used for authoring. +Running this file uploads one Code folder and submits a live pipeline job. +""" + +import os + +from azure.ai.projects import AIProjectClient +from azure.ai.projects.dsl import pipeline +from azure.identity import AzureCliCredential +from steps.components import consume, produce + + +@pipeline( + compute_id=os.environ["JOB_COMPUTE_ID"], + environment_image_reference=os.environ["JOB_ENVIRONMENT_IMAGE"], + user_assigned_identity_id=os.environ["JOB_NODE_UAI_RESOURCE_ID"], + instance_type=os.environ["JOB_INSTANCE_TYPE"], +) +def workflow(text: str): + first = produce(text=text) + second = consume(message=first.outputs.message) + return {"receipt": second.outputs.receipt} + + +def main() -> None: + job = workflow(text="world") + with ( + AzureCliCredential() as credential, + AIProjectClient( + endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"], + credential=credential, + allow_preview=True, + retry_total=0, + ) as client, + ): + created = client.beta.jobs.create_or_update( + job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} + ) + print(f"Submitted {created.name}: {created.id} (status: {created.status})") + + +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/__init__.py b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/__init__.py new file mode 100644 index 000000000000..9158ac6767c3 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/__init__.py @@ -0,0 +1,5 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Python components for the source-backed pipeline sample.""" diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/components.py b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/components.py new file mode 100644 index 000000000000..408b34ce13cc --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/components.py @@ -0,0 +1,25 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Import-safe component definitions; the pipeline submission lives elsewhere.""" + +from pathlib import Path + +from azure.ai.projects.dsl import Input, Output, component + +from .helpers import greeting + + +def normalize(text: str) -> str: + return text.strip() + + +@component(code="..") +def produce(text: str, message: Output(type="uri_file")) -> None: # type: ignore[valid-type] + Path(message).write_text(greeting(normalize(text)), encoding="utf-8") + + +@component(code="..") +def consume(message: Input(type="uri_file"), receipt: Output(type="uri_file")) -> None: # type: ignore[valid-type] + Path(receipt).write_text(Path(message).read_text(encoding="utf-8").upper(), encoding="utf-8") diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/greeting.txt b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/greeting.txt new file mode 100644 index 000000000000..ce013625030b --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/greeting.txt @@ -0,0 +1 @@ +hello diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/helpers.py b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/helpers.py new file mode 100644 index 000000000000..4aa68fcd90a7 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/helpers.py @@ -0,0 +1,12 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Shared functions and resources used by the pipeline components.""" + +from pathlib import Path + + +def greeting(text: str) -> str: + prefix = Path(__file__).with_name("greeting.txt").read_text(encoding="utf-8").strip() + return f"{prefix} {text}" diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index c7eb84f4c64e..0f56fd56ee19 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -5,6 +5,7 @@ """Offline wire and response tests for Command and Pipeline jobs.""" import json +import os import re import runpy import subprocess @@ -35,6 +36,8 @@ JobType, PipelineJob, ) +from azure.ai.projects.operations._job_helper import _content_hash +from azure.ai.projects._component_source import _RUNNER_NAME, _stage_component_source _ENDPOINT = "https://fake-account.services.ai.azure.com/api/projects/fake-project" _COMPUTE = "/subscriptions/test/resourceGroups/test/providers/Microsoft.CognitiveServices/accounts/test/computes/cpu" @@ -599,6 +602,17 @@ def _dsl_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: return sample["workflow"](text="hello") +def _source_dsl_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: + monkeypatch.setenv("JOB_COMPUTE_ID", _COMPUTE) + monkeypatch.setenv("JOB_ENVIRONMENT_IMAGE", "example.azurecr.io/train:latest") + monkeypatch.setenv("JOB_NODE_UAI_RESOURCE_ID", "/subscriptions/test/identities/hello") + monkeypatch.setenv("JOB_INSTANCE_TYPE", "Singularity.D4_v3") + sample = Path(__file__).resolve().parents[2] / "samples" / "jobs" / "pipeline_source" + monkeypatch.syspath_prepend(str(sample)) + workflow = runpy.run_path(str(sample / "sample_pipeline_source.py"))["workflow"] + return workflow(text=" world ") + + def _dsl_code_paths(job: PipelineJob) -> dict[str, Path]: assert job.jobs is not None return {name: Path(node["component"]["code"]) for name, node in job.jobs.items()} @@ -950,6 +964,173 @@ def workflow() -> None: workflow() +def test_dsl_source_components_run_with_helpers_imports_and_resources( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + job = _source_dsl_job(monkeypatch) + paths = _dsl_code_paths(job) + snapshot = paths["produce"] + try: + assert snapshot == paths["consume"] + assert len(job._component_code_dirs) == 1 + assert (snapshot / _RUNNER_NAME).is_file() + assert (snapshot / "steps" / "components.py").is_file() + assert (snapshot / "steps" / "helpers.py").is_file() + assert (snapshot / "steps" / "greeting.txt").read_text(encoding="utf-8").strip() == "hello" + assert job.jobs["produce"]["component"]["command"] == ( + f'python {_RUNNER_NAME} steps.components produce text:str,message:str ' + '"${{inputs.text}}" "${{outputs.message}}"' + ) + assert job.jobs["consume"]["inputs"]["message"]["value"] == "${{parent.jobs.produce.outputs.message}}" + + source_root = Path(__file__).resolve().parents[2] + environment = os.environ.copy() + environment["PYTHONPATH"] = os.pathsep.join([str(source_root), environment.get("PYTHONPATH", "")]) + message = tmp_path / "message.txt" + receipt = tmp_path / "receipt.txt" + subprocess.run( + [sys.executable, str(snapshot / _RUNNER_NAME), "steps.components", "produce", "text:str,message:str", + " world ", str(message)], + cwd=tmp_path, + env=environment, + check=True, + capture_output=True, + text=True, + ) + subprocess.run( + [sys.executable, str(snapshot / _RUNNER_NAME), "steps.components", "consume", + "message:str,receipt:str", str(message), str(receipt)], + cwd=tmp_path, + env=environment, + check=True, + capture_output=True, + text=True, + ) + assert message.read_text(encoding="utf-8") == "hello world" + assert receipt.read_text(encoding="utf-8") == "HELLO WORLD" + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + +def test_dsl_source_sync_uploads_shared_snapshot_once(monkeypatch: pytest.MonkeyPatch) -> None: + job = _source_dsl_job(monkeypatch) + snapshot = _dsl_code_paths(job)["produce"] + transport = _Transport([_response("Pipeline")]) + uploads: list[tuple[str, str]] = [] + + def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + assert (Path(folder) / "steps" / "helpers.py").is_file() + uploads.append((name, folder)) + return _uploaded_code(name, version) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + client.beta.jobs.create_or_update( + job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} + ) + + assert len(uploads) == 1 + assert uploads[0][1] == str(snapshot) + assert not snapshot.exists() + assert len(transport.requests) == 1 + properties = json.loads(transport.requests[0].body)["properties"] + assert properties["jobs"]["produce"]["component"]["code"] == properties["jobs"]["consume"]["component"]["code"] + assert properties["jobs"]["produce"]["component"]["code"] == job.jobs["produce"]["component"]["code"] + assert properties["experimentName"] == "pipeline_samples" + + +@pytest.mark.asyncio +async def test_dsl_source_async_uploads_shared_snapshot_once(monkeypatch: pytest.MonkeyPatch) -> None: + job = _source_dsl_job(monkeypatch) + snapshot = _dsl_code_paths(job)["produce"] + transport = _AsyncTransport([_response("Pipeline")]) + uploads: list[str] = [] + + async def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + uploads.append(folder) + return _uploaded_code(name, version) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + await client.beta.jobs.create_or_update( + job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} + ) + + assert uploads == [str(snapshot)] + assert not snapshot.exists() + assert len(transport.requests) == 1 + properties = json.loads(transport.requests[0].body)["properties"] + assert properties["jobs"]["produce"]["component"]["code"] == properties["jobs"]["consume"]["component"]["code"] + + +def test_dsl_source_snapshot_filters_files_before_hash_and_upload(tmp_path: Path) -> None: + root = tmp_path / "code" + nested = root / "pkg" + nested.mkdir(parents=True) + (root / ".gitignore").write_text("*.tmp\n!keep.tmp\n", encoding="utf-8") + (root / ".env").write_text("not-for-upload", encoding="utf-8") + (root / "discard.tmp").write_text("ignored", encoding="utf-8") + (root / "keep.tmp").write_text("included", encoding="utf-8") + (nested / ".gitignore").write_text("private.txt\n", encoding="utf-8") + (nested / "private.txt").write_text("ignored", encoding="utf-8") + (nested / "public.txt").write_text("included", encoding="utf-8") + + snapshots = [tmp_path / "first", tmp_path / "second"] + snapshots[0].mkdir() + _stage_component_source(root, snapshots[0]) + (root / "discard.tmp").write_text("changed", encoding="utf-8") + (nested / "private.txt").write_text("changed", encoding="utf-8") + snapshots[1].mkdir() + _stage_component_source(root, snapshots[1]) + + assert _content_hash(snapshots[0]) == _content_hash(snapshots[1]) + assert sorted(path.relative_to(snapshots[0]).as_posix() for path in snapshots[0].rglob("*") if path.is_file()) == [ + _RUNNER_NAME, + "keep.tmp", + "pkg/public.txt", + ] + + +def test_dsl_source_snapshot_rejects_included_symlinks(tmp_path: Path) -> None: + root = tmp_path / "code" + root.mkdir() + outside = tmp_path / "outside.txt" + outside.write_text("outside", encoding="utf-8") + try: + (root / "link.txt").symlink_to(outside) + except OSError: + pytest.skip("Symbolic links are unavailable on this host") + stage = tmp_path / "stage" + stage.mkdir() + with pytest.raises(ValueError, match="included symbolic link"): + _stage_component_source(root, stage) + + +def test_dsl_source_requires_importable_function_inside_root(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="inside its code root"): + + @dsl.component(code=tmp_path) + def outside(result: dsl.Output(type="uri_file")) -> None: + Path(result).write_text("outside", encoding="utf-8") + + with pytest.raises(ValueError, match="module-level"): + + @dsl.component(code=Path(__file__).resolve().parent) + def nested(result: dsl.Output(type="uri_file")) -> None: + Path(result).write_text("nested", encoding="utf-8") + + def test_jobs_sync_job_only_names_are_unique() -> None: job = PipelineJob(compute_id=_COMPUTE, jobs={}) transport = _Transport([_response("Pipeline"), _response("Pipeline")]) From ad00cb40f347d9a8949f53c65a87ba91cb55219b Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:05:33 -0700 Subject: [PATCH 18/52] [azure-ai-projects] Format component snapshots and fix shared-directory typing Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/_component_source.py | 9 +++++-- .../azure/ai/projects/dsl.py | 12 +++++++--- .../tests/jobs/test_pipeline_jobs.py | 24 +++++++++++++++---- 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py index 9349e4a71c58..9b1c721503d9 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py @@ -49,7 +49,9 @@ def _source_for_component(func: Callable[..., object], code: Union[str, PathLike raise ValueError(f"Source-backed component '{func.__name__}' must be a module-level function.") free_vars = inspect.getclosurevars(func) if free_vars.nonlocals: - raise ValueError(f"Component '{func.__name__}' cannot capture enclosing variables: {sorted(free_vars.nonlocals)}.") + raise ValueError( + f"Component '{func.__name__}' cannot capture enclosing variables: {sorted(free_vars.nonlocals)}." + ) module_path = relative_file.parent if relative_file.name == "__init__.py" else relative_file.with_suffix("") if not module_path.parts or any(not part.isidentifier() or keyword.iskeyword(part) for part in module_path.parts): @@ -75,7 +77,10 @@ def _copy_source_tree( if ignore_path.is_symlink() or not ignore_path.is_file(): raise ValueError(f"Code ignore file '{ignore_path}' must be a regular file.") relative_directory = source.relative_to(code_root) - rules = [*rules, (relative_directory, GitIgnoreSpec.from_lines(ignore_path.read_text(encoding="utf-8").splitlines()))] + rules = [ + *rules, + (relative_directory, GitIgnoreSpec.from_lines(ignore_path.read_text(encoding="utf-8").splitlines())), + ] for path in sorted(source.iterdir()): if path.name in _IGNORE_FILES: diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index a7d2a192ab51..53c239adf2c0 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -221,12 +221,14 @@ def add( (Path(code_dir.name) / "component.py").write_text(_function_script(func, inputs, outputs), encoding="utf-8") command = "python component.py " + arguments_in_command else: - code_dir = self.code_dirs_by_root.get(source.root) - if code_dir is None: + shared_code_dir = self.code_dirs_by_root.get(source.root) + if shared_code_dir is None: code_dir = TemporaryDirectory(prefix="foundry-component-source-") self.code_dirs.append(code_dir) self.code_dirs_by_root[source.root] = code_dir _stage_component_source(source.root, Path(code_dir.name)) + else: + code_dir = shared_code_dir if not (Path(code_dir.name) / source.relative_file).is_file(): raise ValueError(f"Component '{func.__name__}' source file is excluded by its code ignore rules.") port_spec = ",".join(f"{port.name}:{port.conversion}" for port in inputs + outputs) or "-" @@ -294,7 +296,11 @@ def decorate(source_func: Callable[..., Any]) -> Callable[..., SimpleNamespace]: source = _source_for_component(source_func, code) if code is not None else None input_names = {port.name for port in inputs} input_signature = inspect.Signature( - [parameter for parameter in inspect.signature(source_func).parameters.values() if parameter.name in input_names] + [ + parameter + for parameter in inspect.signature(source_func).parameters.values() + if parameter.name in input_names + ] ) @wraps(source_func) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 0f56fd56ee19..4adb1dd46492 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -978,7 +978,7 @@ def test_dsl_source_components_run_with_helpers_imports_and_resources( assert (snapshot / "steps" / "helpers.py").is_file() assert (snapshot / "steps" / "greeting.txt").read_text(encoding="utf-8").strip() == "hello" assert job.jobs["produce"]["component"]["command"] == ( - f'python {_RUNNER_NAME} steps.components produce text:str,message:str ' + f"python {_RUNNER_NAME} steps.components produce text:str,message:str " '"${{inputs.text}}" "${{outputs.message}}"' ) assert job.jobs["consume"]["inputs"]["message"]["value"] == "${{parent.jobs.produce.outputs.message}}" @@ -989,8 +989,15 @@ def test_dsl_source_components_run_with_helpers_imports_and_resources( message = tmp_path / "message.txt" receipt = tmp_path / "receipt.txt" subprocess.run( - [sys.executable, str(snapshot / _RUNNER_NAME), "steps.components", "produce", "text:str,message:str", - " world ", str(message)], + [ + sys.executable, + str(snapshot / _RUNNER_NAME), + "steps.components", + "produce", + "text:str,message:str", + " world ", + str(message), + ], cwd=tmp_path, env=environment, check=True, @@ -998,8 +1005,15 @@ def test_dsl_source_components_run_with_helpers_imports_and_resources( text=True, ) subprocess.run( - [sys.executable, str(snapshot / _RUNNER_NAME), "steps.components", "consume", - "message:str,receipt:str", str(message), str(receipt)], + [ + sys.executable, + str(snapshot / _RUNNER_NAME), + "steps.components", + "consume", + "message:str,receipt:str", + str(message), + str(receipt), + ], cwd=tmp_path, env=environment, check=True, From 491409d79d920ed5558f974c1636daa75bc45aa9 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:08:10 -0700 Subject: [PATCH 19/52] [azure-ai-projects] Keep live source-backed sample out of automatic execution Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/tools/azure-sdk-tools/azpysdk/samples.py | 6 +++++- .../samples/jobs/pipeline_source/README.md | 2 +- .../jobs/pipeline_source/sample_pipeline_source.py | 2 +- .../{components.py => source_pipeline_components.py} | 2 +- sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py | 8 ++++---- 5 files changed, 12 insertions(+), 8 deletions(-) rename sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/{components.py => source_pipeline_components.py} (89%) diff --git a/eng/tools/azure-sdk-tools/azpysdk/samples.py b/eng/tools/azure-sdk-tools/azpysdk/samples.py index 5e288157f2f2..fd45174cea76 100644 --- a/eng/tools/azure-sdk-tools/azpysdk/samples.py +++ b/eng/tools/azure-sdk-tools/azpysdk/samples.py @@ -75,7 +75,11 @@ # Add your library + sample file if you do not want a particular sample to be run IGNORED_SAMPLES = { - "azure-ai-projects": ["sample_pipeline_hello_world.py"], + "azure-ai-projects": [ + "sample_pipeline_hello_world.py", + "sample_pipeline_source.py", # Submits a live PipelineJob. + "source_pipeline_components.py", # Imports helpers relative to its package. + ], "azure-appconfiguration-provider": [ "key_vault_reference_customized_clients_sample.py", "aad_sample.py", diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md index 2d7f6f7974fc..b568325cf8a4 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md @@ -1,7 +1,7 @@ # Source-backed Python pipeline components `sample_pipeline_source.py` builds a native two-node Foundry PipelineJob from -`steps/components.py`. Both components use `@component(code="..")`, so the Code +`steps/source_pipeline_components.py`. Both components use `@component(code="..")`, so the Code snapshot includes the sibling `helpers.py` module and `greeting.txt` resource. The pipeline is built locally; component bodies run on the selected compute. Both nodes share the same uploaded Code asset. diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py index 5d1553d7ceb3..71ffe421ce23 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py @@ -13,7 +13,7 @@ from azure.ai.projects import AIProjectClient from azure.ai.projects.dsl import pipeline from azure.identity import AzureCliCredential -from steps.components import consume, produce +from steps.source_pipeline_components import consume, produce @pipeline( diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/components.py b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/source_pipeline_components.py similarity index 89% rename from sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/components.py rename to sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/source_pipeline_components.py index 408b34ce13cc..3023912bd050 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/components.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/steps/source_pipeline_components.py @@ -2,7 +2,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -"""Import-safe component definitions; the pipeline submission lives elsewhere.""" +"""Import-safe source-backed components; the pipeline submission lives elsewhere.""" from pathlib import Path diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 4adb1dd46492..1db260172cb4 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -974,11 +974,11 @@ def test_dsl_source_components_run_with_helpers_imports_and_resources( assert snapshot == paths["consume"] assert len(job._component_code_dirs) == 1 assert (snapshot / _RUNNER_NAME).is_file() - assert (snapshot / "steps" / "components.py").is_file() + assert (snapshot / "steps" / "source_pipeline_components.py").is_file() assert (snapshot / "steps" / "helpers.py").is_file() assert (snapshot / "steps" / "greeting.txt").read_text(encoding="utf-8").strip() == "hello" assert job.jobs["produce"]["component"]["command"] == ( - f"python {_RUNNER_NAME} steps.components produce text:str,message:str " + f"python {_RUNNER_NAME} steps.source_pipeline_components produce text:str,message:str " '"${{inputs.text}}" "${{outputs.message}}"' ) assert job.jobs["consume"]["inputs"]["message"]["value"] == "${{parent.jobs.produce.outputs.message}}" @@ -992,7 +992,7 @@ def test_dsl_source_components_run_with_helpers_imports_and_resources( [ sys.executable, str(snapshot / _RUNNER_NAME), - "steps.components", + "steps.source_pipeline_components", "produce", "text:str,message:str", " world ", @@ -1008,7 +1008,7 @@ def test_dsl_source_components_run_with_helpers_imports_and_resources( [ sys.executable, str(snapshot / _RUNNER_NAME), - "steps.components", + "steps.source_pipeline_components", "consume", "message:str,receipt:str", str(message), From 62386758e65f16646ebb303032cc5617398f594c Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:10:31 -0700 Subject: [PATCH 20/52] [azure-ai-projects] Cover source-backed ignore rules and primitive ports Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/dsl.py | 6 +- .../tests/jobs/test_pipeline_jobs.py | 80 +++++++++++++++++++ 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 53c239adf2c0..2c9520a9fcc9 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -370,7 +370,10 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: token = _ACTIVE_PIPELINE.set(context) job: Optional[PipelineJob] = None try: - result = func(**references) + try: + result = func(**references) + finally: + _ACTIVE_PIPELINE.reset(token) job_outputs: Dict[str, Dict[str, Any]] = {} if result is not None: if not isinstance(result, dict): @@ -397,7 +400,6 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: job._component_code_dirs = context.code_dirs return job finally: - _ACTIVE_PIPELINE.reset(token) if job is None: for directory in context.code_dirs: directory.cleanup() diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 1db260172cb4..ecfaa41c89cf 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -4,6 +4,7 @@ # ------------------------------------ """Offline wire and response tests for Command and Pipeline jobs.""" +import importlib import json import os import re @@ -1116,6 +1117,26 @@ def test_dsl_source_snapshot_filters_files_before_hash_and_upload(tmp_path: Path ] +def test_dsl_source_snapshot_amlignore_overrides_gitignore_and_excludes_directories(tmp_path: Path) -> None: + root = tmp_path / "code" + root.mkdir() + (root / ".gitignore").write_text("keep.txt\n", encoding="utf-8") + (root / ".amlignore").write_text("private/\n", encoding="utf-8") + (root / "keep.txt").write_text("included", encoding="utf-8") + private = root / "private" + private.mkdir() + (private / "secret.txt").write_text("excluded", encoding="utf-8") + stage = tmp_path / "stage" + stage.mkdir() + + _stage_component_source(root, stage) + + assert (stage / "keep.txt").read_text(encoding="utf-8") == "included" + assert not (stage / "private").exists() + assert not (stage / ".gitignore").exists() + assert not (stage / ".amlignore").exists() + + def test_dsl_source_snapshot_rejects_included_symlinks(tmp_path: Path) -> None: root = tmp_path / "code" root.mkdir() @@ -1145,6 +1166,65 @@ def nested(result: dsl.Output(type="uri_file")) -> None: Path(result).write_text("nested", encoding="utf-8") +def test_dsl_source_runner_converts_primitive_ports(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + code_root = tmp_path / "code" + code_root.mkdir() + module_name = "source_numeric_component" + (code_root / f"{module_name}.py").write_text( + "from pathlib import Path\n" + "from azure.ai.projects.dsl import Output, component\n" + "@component(code='.')\n" + "def write(count: int, ratio: float, enabled: bool, result: Output(type='uri_file')) -> None:\n" + " Path(result).write_text(f'{count}|{ratio}|{enabled}', encoding='utf-8')\n", + encoding="utf-8", + ) + monkeypatch.syspath_prepend(str(code_root)) + writer = importlib.import_module(module_name).write + + @dsl.pipeline( + compute_id=_COMPUTE, + environment_image_reference="example.azurecr.io/train:latest", + user_assigned_identity_id="/subscriptions/test/identities/hello", + instance_type="Singularity.D4_v3", + ) + def workflow(): + return {"result": writer(count=3, ratio=1.5, enabled=True).outputs.result} + + job = workflow() + try: + stage = _dsl_code_paths(job)["write"] + assert job.jobs["write"]["component"]["command"].startswith( + f"python {_RUNNER_NAME} {module_name} write count:int,ratio:float,enabled:bool,result:str " + ) + environment = os.environ.copy() + environment["PYTHONPATH"] = os.pathsep.join( + [str(Path(__file__).resolve().parents[2]), environment.get("PYTHONPATH", "")] + ) + result = tmp_path / "result.txt" + subprocess.run( + [ + sys.executable, + str(stage / _RUNNER_NAME), + module_name, + "write", + "count:int,ratio:float,enabled:bool,result:str", + "3", + "1.5", + "True", + str(result), + ], + cwd=tmp_path, + env=environment, + check=True, + capture_output=True, + text=True, + ) + assert result.read_text(encoding="utf-8") == "3|1.5|True" + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + def test_jobs_sync_job_only_names_are_unique() -> None: job = PipelineJob(compute_id=_COMPUTE, jobs={}) transport = _Transport([_response("Pipeline"), _response("Pipeline")]) From bb5e27751f8d84fdee5b9024725a21e64f878cea Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:13:24 -0700 Subject: [PATCH 21/52] [azure-ai-projects] Reject Windows junctions in component source snapshots Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/_component_source.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py index 9b1c721503d9..1feaf6c5ae16 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py @@ -6,7 +6,9 @@ import inspect import keyword +import os import shutil +import stat from dataclasses import dataclass from os import PathLike from pathlib import Path @@ -19,6 +21,13 @@ _EXCLUDED_DIRECTORIES = frozenset((".git", ".venv", "__pycache__")) +def _is_link(path: Path) -> bool: + """Detect symlinks and Windows junctions before copying any source files.""" + return path.is_symlink() or ( + os.name == "nt" and bool(path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) + ) + + @dataclass(frozen=True) class _ComponentSource: root: Path @@ -74,7 +83,7 @@ def _copy_source_tree( ) -> None: ignore_path = next((source / name for name in _IGNORE_FILES if (source / name).exists()), None) if ignore_path is not None: - if ignore_path.is_symlink() or not ignore_path.is_file(): + if _is_link(ignore_path) or not ignore_path.is_file(): raise ValueError(f"Code ignore file '{ignore_path}' must be a regular file.") relative_directory = source.relative_to(code_root) rules = [ @@ -95,8 +104,8 @@ def _copy_source_tree( or _is_ignored(relative_path, is_directory, rules) ): continue - if path.is_symlink(): - raise ValueError(f"Code root '{code_root}' contains an included symbolic link: '{relative_path}'.") + if _is_link(path): + raise ValueError(f"Code root '{code_root}' contains an included link or junction: '{relative_path}'.") target = destination / path.name if is_directory: target.mkdir() From 372aa72c7745396be7455a3a8d0d6bc95f96eb72 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:17:14 -0700 Subject: [PATCH 22/52] [azure-ai-projects] Exercise Windows junction rejection in source snapshots Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/_component_source.py | 3 ++- .../tests/jobs/test_pipeline_jobs.py | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py index 1feaf6c5ae16..677016223318 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py @@ -105,7 +105,8 @@ def _copy_source_tree( ): continue if _is_link(path): - raise ValueError(f"Code root '{code_root}' contains an included link or junction: '{relative_path}'.") + kind = "symbolic link" if path.is_symlink() else "junction" + raise ValueError(f"Code root '{code_root}' contains an included {kind}: '{relative_path}'.") target = destination / path.name if is_directory: target.mkdir() diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index ecfaa41c89cf..ad15d723a32d 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -1152,6 +1152,32 @@ def test_dsl_source_snapshot_rejects_included_symlinks(tmp_path: Path) -> None: _stage_component_source(root, stage) +@pytest.mark.skipif(os.name != "nt", reason="Windows junctions only") +def test_dsl_source_snapshot_rejects_included_junctions(tmp_path: Path) -> None: + root = tmp_path / "code" + outside = tmp_path / "outside" + root.mkdir() + outside.mkdir() + link = str(root / "link").replace("'", "''") + target = str(outside).replace("'", "''") + subprocess.run( + [ + "powershell.exe", + "-NoProfile", + "-NonInteractive", + "-Command", + f"New-Item -ItemType Junction -Path '{link}' -Target '{target}' | Out-Null", + ], + check=True, + capture_output=True, + text=True, + ) + stage = tmp_path / "stage" + stage.mkdir() + with pytest.raises(ValueError, match="included junction"): + _stage_component_source(root, stage) + + def test_dsl_source_requires_importable_function_inside_root(tmp_path: Path) -> None: with pytest.raises(ValueError, match="inside its code root"): From 44c6351b90c74eb097f35fa40ccddcd9fc85afaa Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:21:00 -0700 Subject: [PATCH 23/52] [azure-ai-projects] Document junction exclusion for source components Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure-ai-projects/samples/jobs/pipeline_source/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md index b568325cf8a4..731252c9ca87 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md @@ -19,4 +19,5 @@ The code root is resolved relative to the file defining each component, not the working directory. `.amlignore` takes precedence over `.gitignore` within each directory; neither ignore file is uploaded. Common local artifacts and `.env` files are excluded. Include only files intended for remote execution in the -code root; included symlinks cause an error rather than copying files outside it. +code root; included symlinks and Windows junctions cause an error rather than copying +files outside it. From d1deb149d76649356712d3005efadd4e44103ab6 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 6 Oct 2026 20:23:16 -0700 Subject: [PATCH 24/52] [azure-ai-projects] Serialize pipeline output discriminator for service requests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py | 2 +- sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 2c9520a9fcc9..8b9825003175 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -387,7 +387,7 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: f"Node output '{value.node}.{value.name}' cannot bind to multiple pipeline outputs." ) node_output["path"] = f"${{{{parent.outputs.{name}}}}}" - job_outputs[name] = {"type": value.type, "mode": value.mode} + job_outputs[name] = {"jobOutputType": value.type, "mode": value.mode} job = PipelineJob( display_name=func.__name__, diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index ad15d723a32d..04cb0e8688b7 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -639,7 +639,7 @@ def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: "computeId": _COMPUTE, "settings": {"default_compute": _COMPUTE, "force_rerun": True}, "inputs": {"text": {"jobInputType": "literal", "value": "hello"}}, - "outputs": {"receipt": {"type": "uri_file", "mode": "ReadWriteMount"}}, + "outputs": {"receipt": {"jobOutputType": "uri_file", "mode": "ReadWriteMount"}}, "jobs": { "produce": { "type": "command", From 78b002ee74cafcd764b14d00105d9730a1650064 Mon Sep 17 00:00:00 2001 From: Dhivakar Mani Date: Wed, 7 Oct 2026 15:40:30 +0530 Subject: [PATCH 25/52] Support uri_folder PipelineJob node bindings Allow typed CommandJob nodes to bind value-backed uri_folder inputs and add wire-shape coverage for producer-consumer folder handoffs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 2 +- .../azure/ai/projects/models/_patch_jobs.py | 15 ++-- .../tests/jobs/test_pipeline_jobs.py | 84 +++++++++++++++++++ 3 files changed, 95 insertions(+), 6 deletions(-) diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 8c7aac612401..ed1756092cd3 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -25,7 +25,7 @@ * New optional `blueprint_reference` parameters on `agents.create_version` method. * New `.beta.jobs` sub-client with CommandJob operations: `create_or_update`, `get`, `list`, `begin_delete`, `begin_cancel`, `validate`, `show_services`, `stream`, `download`. * Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Local code folders on inline command nodes are registered as Code datasets before submission; local input handling and validation remain specific to standalone Command jobs. -* When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. +* When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound literal, `uri_file`, and `uri_folder` inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index bbed3eaa4f98..e7c78aad428d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -109,9 +109,9 @@ class PipelineJob(_RestPipelineJob): """A pipeline job with graph nodes, inputs, and outputs. When constructing a pipeline, ``jobs`` accepts raw graph node dictionaries - or :class:`CommandJob` instances with value-bound inputs, code, and outputs. - Command jobs are converted to inline command nodes; use raw dictionaries - for other features. + or :class:`CommandJob` instances with value-bound literal, URI file, and + URI folder inputs, code, and outputs. Command jobs are converted to inline + command nodes; use raw dictionaries for other features. :ivar name: The name of the job. Read-only; populated after the job is created. :vartype name: str or None @@ -177,13 +177,18 @@ def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> for input_name, job_input in (job.inputs or {}).items(): if ( not isinstance(job_input, Input) - or job_input.type not in ("literal", "uri_file") + or job_input.type not in ( + "literal", + "uri_file", + "uri_folder", + ) or job_input.value is None or set(job_input.as_dict()) - {"jobInputType", "value"} ): raise ValueError( f"Pipeline node '{name}' cannot convert input '{input_name}'; " - "only value-bound literal and uri_file CommandJob inputs are supported. " + "only value-bound literal, uri_file, and uri_folder " + "CommandJob inputs are supported. " "Use a raw graph node for other inputs." ) inputs[input_name] = {"job_input_type": "literal", "value": job_input.value} diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index d69a478b75ef..d48350de05a8 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -28,8 +28,10 @@ CommandJob, DatasetVersion, Input, + InputOutputModes, JobResourceConfiguration, JobType, + Output, PipelineJob, ) @@ -427,6 +429,76 @@ def test_pipeline_composes_commands_and_preserves_raw_graph_nodes() -> None: assert first.jobs["hello"] == _INLINE_PIPELINE_PROPERTIES["jobs"]["hello"] +def test_pipeline_converts_value_bound_uri_folder_input() -> None: + producer = CommandJob( + command="python produce.py ${{outputs.bundle}}", + environment_image_reference="example.azurecr.io/train:latest", + compute=_COMPUTE, + outputs={ + "bundle": Output( + type=AssetTypes.URI_FOLDER, + asset_name="bundle", + mode=InputOutputModes.READ_WRITE_MOUNT, + ) + }, + ) + consumer = CommandJob( + command="python consume.py ${{inputs.bundle}}", + environment_image_reference="example.azurecr.io/train:latest", + compute=_COMPUTE, + inputs={ + "bundle": Input( + type=AssetTypes.URI_FOLDER, + value="${{parent.jobs.producer.outputs.bundle}}", + ) + }, + ) + + pipeline = PipelineJob( + compute_id=_COMPUTE, + settings={"default_compute": _COMPUTE}, + jobs={"producer": producer, "consumer": consumer}, + ) + graph = pipeline.as_dict(exclude_readonly=True)["jobs"] + + assert graph["producer"]["component"]["outputs"]["bundle"] == { + "type": "uri_folder" + } + assert graph["producer"]["outputs"]["bundle"] == { + "job_output_type": "uri_folder", + "mode": "ReadWriteMount", + } + assert graph["consumer"]["component"]["inputs"]["bundle"] == { + "type": "uri_folder" + } + assert graph["consumer"]["inputs"]["bundle"] == { + "job_input_type": "literal", + "value": "${{parent.jobs.producer.outputs.bundle}}", + } + + transport = _Transport([_response("Pipeline")]) + with AIProjectClient( + endpoint=_ENDPOINT, + credential=_Credential(), + transport=transport, # type: ignore[arg-type] + ) as client: + _assert_job( + client.beta.jobs.create_or_update("folder-handoff", pipeline), + "Pipeline", + ) + + submitted_jobs = json.loads(transport.requests[0].body)[ + "properties" + ]["jobs"] + assert submitted_jobs["consumer"]["component"]["inputs"][ + "bundle" + ] == {"type": "uri_folder"} + assert submitted_jobs["consumer"]["inputs"]["bundle"] == { + "job_input_type": "literal", + "value": "${{parent.jobs.producer.outputs.bundle}}", + } + + def test_pipeline_uploads_both_local_code_folders(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: pipeline, code_dirs = _two_code_job(tmp_path) transport = _Transport([_response("Pipeline")]) @@ -535,6 +607,18 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat {"outputs": {"message": {"job_output_type": "uri_file", "mode": "ReadWriteMount"}}}, "output 'message'", ), + ( + { + "inputs": { + "folder": Input( + type=AssetTypes.URI_FOLDER, + value="${{parent.inputs.folder}}", + mode=InputOutputModes.READ_ONLY_MOUNT, + ) + } + }, + "input 'folder'", + ), ({"compute": "/subscriptions/test/computes/other"}, "default compute"), ({"resources": JobResourceConfiguration({"shmSize": "1g"})}, "shmSize"), ], From f68b7caa4dba4b2afbe053f79ec8d1aa80efde69 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 9 Oct 2026 22:35:06 -0700 Subject: [PATCH 26/52] Fix pipeline SDK documentation build warnings Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/README.md | 4 ++-- sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index 063e5964a5e6..07da76283b78 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -186,7 +186,7 @@ builder. Submit it with `client.beta.jobs.create_or_update(job)` for an autogene optionally passing `experiment_name="pipeline_samples"`, or use the existing `create_or_update(name=..., job=...)` form. -See the [two-component Python sample](samples/jobs/sample_pipeline_dsl.py) for a producer and +See the [two-component Python sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py) for a producer and consumer connected through a mounted file. Each function body is packaged into a separate Code folder and runs on the selected compute, not when the graph is built. Component functions must be defined in a readable `.py` file; referenced module-level imports are copied into the generated @@ -206,7 +206,7 @@ closure values. Shared code roots are uploaded once per pipeline submission. The snapshot honors `.amlignore` (or `.gitignore` when no `.amlignore` exists) in each directory, always omits `.env` files and common Python/Git artifacts, and rejects included symlinks. Review the code root before submitting: only files not excluded by these rules are uploaded. -See the [multi-file source-backed sample](samples/jobs/pipeline_source/README.md) for this +See the [multi-file source-backed sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/README.md) for this layout; the original single-file sample retains its standalone, SDK-free execution mode. ### Hosted agents (preview) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 8b9825003175..7ac688aecce1 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -20,7 +20,8 @@ from .models import AssetTypes, CommandJob, Input, InputOutputModes, JobResourceConfiguration, PipelineJob from .models import Output as _JobOutput -__all__ = ["Input", "Output", "component", "pipeline"] +# Keep Input available for explicit imports without documenting the same model twice in Sphinx. +__all__ = ["Output", "component", "pipeline"] @dataclass(frozen=True) From b8d8fb9ea9b82cd04e34ac29644631caface502b Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 9 Oct 2026 23:03:05 -0700 Subject: [PATCH 27/52] Preinstall SDK runtime dependencies for APIView generation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/dev_requirements.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sdk/ai/azure-ai-projects/dev_requirements.txt b/sdk/ai/azure-ai-projects/dev_requirements.txt index 6641c1e8f14a..5615e45c76d2 100644 --- a/sdk/ai/azure-ai-projects/dev_requirements.txt +++ b/sdk/ai/azure-ai-projects/dev_requirements.txt @@ -11,7 +11,11 @@ azure-mgmt-resource azure-mgmt-subscription azure-monitor-opentelemetry azure-monitor-query +# Pre-install runtime dependencies before APIView's time-limited wheel install. +azure-storage-blob>=12.15.0 +httpx>=0.27.2,<1 jsonref +openai>=2.8.0,<3 opentelemetry-sdk python-dotenv black From b30c3eb635e361f54e8057309f2163b20dae760a Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 9 Oct 2026 23:50:39 -0700 Subject: [PATCH 28/52] Fix PipelineJob SDK analysis and dependency checks Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/_component_source.py | 10 ++++-- .../ai/projects/aio/operations/_operations.py | 11 +++---- .../aio/operations/_patch_jobs_async.py | 8 ++++- .../azure/ai/projects/dsl.py | 32 +++++++++++++------ .../azure/ai/projects/models/_patch_jobs.py | 2 +- .../ai/projects/operations/_operations.py | 11 +++---- .../ai/projects/operations/_patch_jobs.py | 8 ++++- shared_requirements.txt | 1 + 8 files changed, 57 insertions(+), 26 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py index 677016223318..307de17e018f 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_component_source.py @@ -22,9 +22,15 @@ def _is_link(path: Path) -> bool: - """Detect symlinks and Windows junctions before copying any source files.""" + """Detect symlinks and Windows junctions before copying any source files. + + :param path: Path to inspect. + :type path: ~pathlib.Path + :return: Whether the path is a symlink or junction. + :rtype: bool + """ return path.is_symlink() or ( - os.name == "nt" and bool(path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) + os.name == "nt" and bool(getattr(path.lstat(), "st_file_attributes") & stat.FILE_ATTRIBUTE_REPARSE_POINT) ) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py index ec7cc20374f0..ad0028f27c40 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py @@ -9305,6 +9305,11 @@ def list_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) content_type = content_type or "application/json" + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} _content = None if isinstance(body, (IOBase, bytes)): _content = body @@ -9312,12 +9317,6 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} - body = {k: v for k, v in body.items() if v is not None} - _request = build_beta_memory_stores_list_memories_request( name=name, kind=kind, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 3361d5b0ba29..a074e8c7e8bf 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -243,7 +243,13 @@ async def _resolve_local_paths(self, name: str, job: CommandJob) -> None: await self._resolve_input_paths(name, job) async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: - """Resolve local code folders on inline command nodes to dataset asset URIs.""" + """Resolve local code folders on inline command nodes to dataset asset URIs. + + :param name: Name of the pipeline job. + :type name: str + :param job: Pipeline job containing inline command nodes. + :type job: ~azure.ai.projects.models.PipelineJob + """ try: resolved_code: Dict[str, str] = {} for node_name, node in (job.jobs or {}).items(): diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 7ac688aecce1..666ca552ac79 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -200,12 +200,7 @@ def add( serialized = f"${{{{parent.jobs.{value.node}.outputs.{value.name}}}}}" elif port.type == AssetTypes.URI_FILE: raise TypeError(f"Component input '{port.name}' needs a pipeline input or node file output.") - elif ( - (port.conversion == "int" and type(value) is int) - or (port.conversion == "float" and type(value) is float) - or (port.conversion == "bool" and type(value) is bool) - or (port.conversion == "str" and type(value) is str) - ): + elif type(value) in _PRIMITIVES and _PRIMITIVES[type(value)][1] == port.conversion: serialized = str(value) else: raise TypeError(f"Component input '{port.name}' has an incompatible primitive value.") @@ -224,6 +219,7 @@ def add( else: shared_code_dir = self.code_dirs_by_root.get(source.root) if shared_code_dir is None: + # pylint: disable-next=consider-using-with code_dir = TemporaryDirectory(prefix="foundry-component-source-") self.code_dirs.append(code_dir) self.code_dirs_by_root[source.root] = code_dir @@ -253,7 +249,7 @@ def add( inputs=bound_inputs, outputs={port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs}, ) - node = PipelineJob._command_node(name, job, self.compute_id) + node = PipelineJob._command_node(name, job, self.compute_id) # pylint: disable=protected-access for port in inputs: if port.type != AssetTypes.URI_FILE: node["component"]["inputs"][port.name]["type"] = port.type @@ -290,6 +286,13 @@ def component( With ``code``, snapshot that directory and import the original module at runtime. Otherwise, package the function body as a standalone script. Code-backed components require the authoring SDK and their other imports in the container image. + + :param func: The Python function to decorate, or None to create a decorator. + :type func: callable or None + :keyword code: Source directory to include with the component. + :paramtype code: str or os.PathLike or None + :return: A callable that adds the function as a pipeline node. + :rtype: callable """ def decorate(source_func: Callable[..., Any]) -> Callable[..., SimpleNamespace]: @@ -331,6 +334,17 @@ def pipeline( """Decorate a pipeline builder; calling it returns a native Foundry PipelineJob. Compute, image, identity, and instance type are inherited by each command node. + + :keyword compute_id: Compute resource ID inherited by the pipeline nodes. + :paramtype compute_id: str + :keyword environment_image_reference: Container image inherited by the pipeline nodes. + :paramtype environment_image_reference: str + :keyword user_assigned_identity_id: Identity resource ID inherited by the pipeline nodes. + :paramtype user_assigned_identity_id: str + :keyword instance_type: Instance type inherited by the pipeline nodes. + :paramtype instance_type: str + :return: A decorator for a pipeline builder function. + :rtype: callable """ def decorate(func: Callable[..., Any]) -> Callable[..., PipelineJob]: @@ -361,7 +375,7 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: ) job_inputs[name] = value port_type: str = AssetTypes.URI_FILE - elif annotation in _PRIMITIVES and type(value) is annotation: + elif annotation in _PRIMITIVES and type(value) is annotation: # pylint: disable=unidiomatic-typecheck job_inputs[name] = Input(type=AssetTypes.LITERAL, value=str(value)) port_type = _PRIMITIVES[annotation][0] else: @@ -398,7 +412,7 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: outputs=job_outputs, jobs=context.jobs, ) - job._component_code_dirs = context.code_dirs + job._component_code_dirs = context.code_dirs # pylint: disable=protected-access return job finally: if job is None: diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index 3e47ed63ac6e..95870fd8faad 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -239,7 +239,7 @@ def _command_node(name: str, job: CommandJob, default_compute: Optional[str]) -> f"Pipeline node '{name}' cannot convert resource fields {sorted(unsupported_resources)}; " "use a raw graph node for these fields." ) - resources = {} + resources: Dict[str, Any] = {} if job.resources.instance_count is not None: resources["instance_count"] = job.resources.instance_count if job.resources.instance_type is not None: diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py index 2297f661553d..16617251741d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py @@ -13170,6 +13170,11 @@ def list_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) content_type = content_type or "application/json" + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} _content = None if isinstance(body, (IOBase, bytes)): _content = body @@ -13177,12 +13182,6 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} - body = {k: v for k, v in body.items() if v is not None} - _request = build_beta_memory_stores_list_memories_request( name=name, kind=kind, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index 6e3e0017ac99..f9f1a341464b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -246,7 +246,13 @@ def _resolve_local_paths(self, name: str, job: CommandJob) -> None: self._resolve_input_paths(name, job) def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: - """Resolve local code folders on inline command nodes to dataset asset URIs.""" + """Resolve local code folders on inline command nodes to dataset asset URIs. + + :param name: Name of the pipeline job. + :type name: str + :param job: Pipeline job containing inline command nodes. + :type job: ~azure.ai.projects.models.PipelineJob + """ try: resolved_code: Dict[str, str] = {} for node_name, node in (job.jobs or {}).items(): diff --git a/shared_requirements.txt b/shared_requirements.txt index 7be249c3bd61..a3fc932f38c0 100644 --- a/shared_requirements.txt +++ b/shared_requirements.txt @@ -44,6 +44,7 @@ azure-storage-blob azure-storage-file-share azure-storage-file-datalake pydash +pathspec azure-mgmt-resourcegraph azure-mgmt-resource fixedint From c352950915ce0160ae97450fef9d72cff2337123 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Sat, 10 Oct 2026 10:13:09 -0700 Subject: [PATCH 29/52] Exclude live PipelineJob samples from standalone checks Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/tools/azure-sdk-tools/azpysdk/samples.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eng/tools/azure-sdk-tools/azpysdk/samples.py b/eng/tools/azure-sdk-tools/azpysdk/samples.py index fd45174cea76..d0b61a1a93c1 100644 --- a/eng/tools/azure-sdk-tools/azpysdk/samples.py +++ b/eng/tools/azure-sdk-tools/azpysdk/samples.py @@ -76,8 +76,10 @@ # Add your library + sample file if you do not want a particular sample to be run IGNORED_SAMPLES = { "azure-ai-projects": [ + "sample_pipeline_dsl.py", "sample_pipeline_hello_world.py", "sample_pipeline_source.py", # Submits a live PipelineJob. + "sample_pipeline_two_code.py", "source_pipeline_components.py", # Imports helpers relative to its package. ], "azure-appconfiguration-provider": [ From 47581825e3499d3b2253e0a848e3127154581d0e Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Mon, 12 Oct 2026 18:00:03 -0700 Subject: [PATCH 30/52] feat(ai-projects): allow uri_folder in pipeline decorators Carry uri_folder outputs and node inputs through the existing @component and @pipeline authoring path. Verify the real file-to-folder-to-file worker handoff and serialized ports. Authored-by: GitHub Copilot CLI v1.0.94-3 Model: GPT-6 Sol (gpt-6-sol) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3158b2da-2e97-48e9-88e8-9f9555b9dd9e --- .../azure/ai/projects/dsl.py | 26 ++++---- .../tests/jobs/test_pipeline_jobs.py | 65 +++++++++++++++++++ 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 666ca552ac79..e7b751cdadb6 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -26,7 +26,7 @@ @dataclass(frozen=True) class Output: - """A writable file output in a Python component signature. + """A writable file or folder output in a Python component signature. The parameter name becomes the output asset name. Outputs are read-write mounted unless ``mode`` is specified. @@ -61,6 +61,7 @@ class _OutputRef: _ACTIVE_PIPELINE: ContextVar[Optional["_PipelineContext"]] = ContextVar("foundry_pipeline", default=None) +_DATA_PORT_TYPES = (AssetTypes.URI_FILE, AssetTypes.URI_FOLDER) _PRIMITIVES: Dict[Any, Tuple[str, str]] = { str: ("string", "str"), int: ("integer", "int"), @@ -78,22 +79,25 @@ def _component_ports(func: Callable[..., Any]) -> Tuple[List[_Port], List[_Port] raise TypeError(f"Component '{func.__name__}' supports only named parameters.") annotation = annotations.get(parameter.name, parameter.annotation) if isinstance(annotation, Output): - if annotation.type != AssetTypes.URI_FILE: - raise ValueError(f"Component output '{parameter.name}' must be a uri_file.") + if annotation.type not in _DATA_PORT_TYPES: + raise ValueError(f"Component output '{parameter.name}' must be a uri_file or uri_folder.") if parameter.default is not inspect.Parameter.empty: raise TypeError(f"Component output '{parameter.name}' cannot have a default.") outputs.append( _Port( parameter.name, - AssetTypes.URI_FILE, + annotation.type, "str", annotation.mode if annotation.mode is not None else InputOutputModes.READ_WRITE_MOUNT, ) ) elif isinstance(annotation, Input): - if annotation.type != AssetTypes.URI_FILE or annotation.path or annotation.value or annotation.mode: - raise ValueError(f"Component input '{parameter.name}' supports only Input(type='uri_file').") - inputs.append(_Port(parameter.name, AssetTypes.URI_FILE, "str")) + if annotation.type not in _DATA_PORT_TYPES or annotation.path or annotation.value or annotation.mode: + raise ValueError( + f"Component input '{parameter.name}' supports only Input(type='uri_file') " + "or Input(type='uri_folder')." + ) + inputs.append(_Port(parameter.name, annotation.type, "str")) elif annotation in _PRIMITIVES: component_type, conversion = _PRIMITIVES[annotation] inputs.append(_Port(parameter.name, component_type, conversion)) @@ -198,13 +202,13 @@ def add( if value.owner is not self or value.type != port.type: raise ValueError(f"Component input '{port.name}' has an incompatible node output.") serialized = f"${{{{parent.jobs.{value.node}.outputs.{value.name}}}}}" - elif port.type == AssetTypes.URI_FILE: - raise TypeError(f"Component input '{port.name}' needs a pipeline input or node file output.") + elif port.type in _DATA_PORT_TYPES: + raise TypeError(f"Component input '{port.name}' needs a pipeline input or node data output.") elif type(value) in _PRIMITIVES and _PRIMITIVES[type(value)][1] == port.conversion: serialized = str(value) else: raise TypeError(f"Component input '{port.name}' has an incompatible primitive value.") - input_type = AssetTypes.URI_FILE if port.type == AssetTypes.URI_FILE else AssetTypes.LITERAL + input_type = port.type if port.type in _DATA_PORT_TYPES else AssetTypes.LITERAL bound_inputs[port.name] = Input(type=input_type, value=serialized) arguments_in_command = " ".join( @@ -251,7 +255,7 @@ def add( ) node = PipelineJob._command_node(name, job, self.compute_id) # pylint: disable=protected-access for port in inputs: - if port.type != AssetTypes.URI_FILE: + if port.type not in _DATA_PORT_TYPES: node["component"]["inputs"][port.name]["type"] = port.type self.jobs[name] = node return SimpleNamespace( diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index eadb4a846471..b24ac63a2c5c 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -1029,6 +1029,71 @@ def workflow(count: int, scale: float, enabled: bool, source: dsl.Input(type="ur directory.cleanup() +def test_dsl_folder_handoff_with_pipeline_file_input_and_output(tmp_path: Path) -> None: + @dsl.component + def produce(source: dsl.Input(type="uri_file"), parts: dsl.Output(type="uri_folder")) -> None: + from pathlib import Path + + folder = Path(parts) + folder.mkdir(parents=True, exist_ok=True) + for index, word in enumerate(Path(source).read_text(encoding="utf-8").split()): + (folder / f"part-{index:04d}.txt").write_text(word, encoding="utf-8") + + @dsl.component + def consume(parts: dsl.Input(type="uri_folder"), receipt: dsl.Output(type="uri_file")) -> None: + from pathlib import Path + + words = [path.read_text(encoding="utf-8") for path in sorted(Path(parts).glob("part-*.txt"))] + Path(receipt).write_text(" ".join(words).upper() + "\n", encoding="utf-8") + + @dsl.pipeline( + compute_id=_COMPUTE, + environment_image_reference="example.azurecr.io/train:latest", + user_assigned_identity_id="/subscriptions/test/identities/hello", + instance_type="Singularity.D4_v3", + ) + def workflow(source: dsl.Input(type="uri_file")): + first = produce(source=source) + second = consume(parts=first.outputs.parts) + return {"receipt": second.outputs.receipt} + + uri = "azureai://accounts/test/projects/demo/data/message/versions/1" + job = workflow(source=dsl.Input(type="uri_file", path=uri, mode="ReadOnlyMount")) + try: + assert job.inputs["source"] == {"jobInputType": "uri_file", "uri": uri, "mode": "ReadOnlyMount"} + assert job.outputs["receipt"]["type"] == "uri_file" + assert job.jobs["produce"]["component"]["outputs"]["parts"]["type"] == "uri_folder" + assert job.jobs["produce"]["outputs"]["parts"] == { + "job_output_type": "uri_folder", + "mode": "ReadWriteMount", + } + assert job.jobs["consume"]["component"]["inputs"]["parts"]["type"] == "uri_folder" + assert job.jobs["consume"]["inputs"]["parts"]["value"] == "${{parent.jobs.produce.outputs.parts}}" + assert job.jobs["consume"]["outputs"]["receipt"]["path"] == "${{parent.outputs.receipt}}" + + source = tmp_path / "message.txt" + source.write_text("hello foundry", encoding="utf-8") + folder = tmp_path / "parts" + receipt = tmp_path / "receipt.txt" + code = _dsl_code_paths(job) + subprocess.run( + [sys.executable, str(code["produce"] / "component.py"), str(source), str(folder)], + check=True, + capture_output=True, + text=True, + ) + subprocess.run( + [sys.executable, str(code["consume"] / "component.py"), str(folder), str(receipt)], + check=True, + capture_output=True, + text=True, + ) + assert receipt.read_text(encoding="utf-8") == "HELLO FOUNDRY\n" + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + def test_dsl_rejects_unsupported_module_globals_and_outside_calls() -> None: @dsl.component def write_with_global(result: dsl.Output(type="uri_file")) -> None: From f036f6ddc4f28f94f7b08241d066361dd2edacae Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Mon, 12 Oct 2026 18:02:36 -0700 Subject: [PATCH 31/52] test(ai-projects): assert serialized pipeline output type Authored-by: GitHub Copilot CLI v1.0.94-3 Model: GPT-6 Sol (gpt-6-sol) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3158b2da-2e97-48e9-88e8-9f9555b9dd9e --- sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index b24ac63a2c5c..b566b0e59cb9 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -1061,7 +1061,7 @@ def workflow(source: dsl.Input(type="uri_file")): job = workflow(source=dsl.Input(type="uri_file", path=uri, mode="ReadOnlyMount")) try: assert job.inputs["source"] == {"jobInputType": "uri_file", "uri": uri, "mode": "ReadOnlyMount"} - assert job.outputs["receipt"]["type"] == "uri_file" + assert job.outputs["receipt"]["jobOutputType"] == "uri_file" assert job.jobs["produce"]["component"]["outputs"]["parts"]["type"] == "uri_folder" assert job.jobs["produce"]["outputs"]["parts"] == { "job_output_type": "uri_folder", From 4f22c44763058efeb8259b34f07597ca833b1e6d Mon Sep 17 00:00:00 2001 From: Dhivakar Mani Date: Thu, 22 Oct 2026 11:58:38 +0530 Subject: [PATCH 32/52] feat(ai-projects): expose dedicated pipeline jobs client Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 4 +- sdk/ai/azure-ai-projects/README.md | 5 +- .../azure-ai-projects/apiview-properties.json | 11 +- .../azure/ai/projects/_client.py | 4 + .../azure/ai/projects/aio/_client.py | 4 + .../ai/projects/aio/operations/__init__.py | 2 + .../ai/projects/aio/operations/_operations.py | 334 +++++++++++++- .../ai/projects/aio/operations/_patch.py | 2 + .../aio/operations/_patch_jobs_async.py | 22 +- .../operations/_patch_pipeline_jobs_async.py | 197 +++++++++ .../azure/ai/projects/models/__init__.py | 2 + .../azure/ai/projects/models/_models.py | 46 ++ .../azure/ai/projects/models/_patch_jobs.py | 10 +- .../azure/ai/projects/operations/__init__.py | 2 + .../ai/projects/operations/_operations.py | 415 +++++++++++++++++- .../azure/ai/projects/operations/_patch.py | 2 + .../ai/projects/operations/_patch_jobs.py | 22 +- .../operations/_patch_pipeline_jobs.py | 196 +++++++++ .../pipeline_source/sample_pipeline_source.py | 4 +- .../samples/jobs/sample_pipeline_dsl.py | 4 +- .../jobs/sample_pipeline_hello_world.py | 3 +- .../samples/jobs/sample_pipeline_two_code.py | 3 +- .../tests/jobs/test_pipeline_jobs.py | 143 +++--- sdk/ai/azure-ai-projects/tsp-location.yaml | 2 +- 24 files changed, 1346 insertions(+), 93 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py create mode 100644 sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index b71fdd4e21f3..25f354a62ad8 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -24,9 +24,9 @@ * New optional `force` parameter on `agents.delete` and `agents.delete_version` methods. * New optional `blueprint_reference` parameters on `agents.create_version` method. * New `.beta.jobs` sub-client with CommandJob operations: `create_or_update`, `get`, `list`, `begin_delete`, `begin_cancel`, `validate`, `show_services`, `stream`, `download`. -* Added `PipelineJob` support to `.beta.jobs.create_or_update`, `.get`, and `.list` (sync and async). Local code folders on inline command nodes are registered as Code datasets before submission; local input handling and validation remain specific to standalone Command jobs. +* Added dedicated `.pipeline_jobs.create_or_update`, `.get`, and `.list` operations (sync and async) on the `/pipeline_jobs` ingress. Local code folders on inline command nodes are registered as Code datasets before submission. The earlier `.beta.jobs` Pipeline support remains for preview compatibility. * When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound literal, `uri_file`, and `uri_folder` inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. -* Added `azure.ai.projects.dsl` function-body `@component` and `@pipeline` authoring for native two-step PipelineJobs. Calling the pipeline function builds its graph, packages each Python component body as its own executable Code folder, binds typed inputs and file outputs, and supports repeated component calls. `.beta.jobs.create_or_update(pipeline_job)` now generates a unique name (sync and async), while the existing explicit-name form remains available. +* Added `azure.ai.projects.dsl` function-body `@component` and `@pipeline` authoring for native two-step PipelineJobs. Calling the pipeline function builds its graph, packages each Python component body as its own executable Code folder, binds typed inputs and file outputs, and supports repeated component calls. `.pipeline_jobs.create_or_update(pipeline_job)` generates a unique name (sync and async), while the explicit-name form remains available. * Added opt-in `@component(code=...)` source-backed components for local helper functions, sibling modules, and resources. Code roots are snapshot with ignore rules before upload and shared by nodes in the same pipeline. Executing these components requires the image to contain a compatible `azure-ai-projects` package and other imported dependencies; bare `@component` keeps its existing standalone execution behavior. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index 07da76283b78..688b3a69637c 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -37,7 +37,8 @@ resources in your Microsoft Foundry Project. Use it to: * **Upload documents and create Datasets** to reference them using `.datasets` operations. * **Register and manage local model weights** as Foundry `ModelVersion` resources using `.beta.models` operations, including the `create` end-to-end helper. * **Create and enumerate Search Indexes** using `.indexes` operations. -* **Submit and manage Command and Pipeline Jobs (preview)** on compute using `.beta.jobs` operations. +* **Submit and manage Command Jobs (preview)** on compute using `.beta.jobs` operations. +* **Submit and inspect Pipeline Jobs (preview)** using the dedicated `.pipeline_jobs` operations. The client library uses version `v1` of the Microsoft Foundry [data plane REST APIs](https://aka.ms/azsdk/azure-ai-projects-v2/api-reference-v1). @@ -182,7 +183,7 @@ from parameter names and file outputs use read-write mounts by default. The pipe supplies the compute resource ID, container image, user-assigned identity ID, and instance type inherited by its nodes. Calling the decorated pipeline function constructs a native Foundry `PipelineJob` without an outer -builder. Submit it with `client.beta.jobs.create_or_update(job)` for an autogenerated job name, +builder. Submit it with `client.pipeline_jobs.create_or_update(job)` for an autogenerated job name, optionally passing `experiment_name="pipeline_samples"`, or use the existing `create_or_update(name=..., job=...)` form. diff --git a/sdk/ai/azure-ai-projects/apiview-properties.json b/sdk/ai/azure-ai-projects/apiview-properties.json index 3fbcdf169639..347378df3c71 100644 --- a/sdk/ai/azure-ai-projects/apiview-properties.json +++ b/sdk/ai/azure-ai-projects/apiview-properties.json @@ -268,6 +268,7 @@ "azure.ai.projects.models.PendingUploadRequest": "Azure.AI.Projects.PendingUploadRequest", "azure.ai.projects.models.PendingUploadResponse": "Azure.AI.Projects.PendingUploadResponse", "azure.ai.projects.models.PipelineJob": "Azure.AI.Projects.PipelineJob", + "azure.ai.projects.models.PipelineJobResource": "Azure.AI.Projects.PipelineJobResource", "azure.ai.projects.models.ProceduralMemoryItem": "Azure.AI.Projects.ProceduralMemoryItem", "azure.ai.projects.models.PromoteCandidateRequest": "Azure.AI.Projects.PromoteCandidateRequest", "azure.ai.projects.models.PromoteCandidateResponse": "Azure.AI.Projects.PromoteCandidateResponse", @@ -502,7 +503,13 @@ "azure.ai.projects.operations.IndexesOperations.delete": "Azure.AI.Projects.Indexes.deleteVersion", "azure.ai.projects.aio.operations.IndexesOperations.delete": "Azure.AI.Projects.Indexes.deleteVersion", "azure.ai.projects.operations.IndexesOperations.create_or_update": "Azure.AI.Projects.Indexes.createOrUpdateVersion", - "azure.ai.projects.aio.operations.IndexesOperations.create_or_update": "Azure.AI.Projects.Indexes.createOrUpdateVersion" + "azure.ai.projects.aio.operations.IndexesOperations.create_or_update": "Azure.AI.Projects.Indexes.createOrUpdateVersion", + "azure.ai.projects.operations.PipelineJobsOperations.list": "Azure.AI.Projects.PipelineJobs.list", + "azure.ai.projects.aio.operations.PipelineJobsOperations.list": "Azure.AI.Projects.PipelineJobs.list", + "azure.ai.projects.operations.PipelineJobsOperations.get": "Azure.AI.Projects.PipelineJobs.get", + "azure.ai.projects.aio.operations.PipelineJobsOperations.get": "Azure.AI.Projects.PipelineJobs.get", + "azure.ai.projects.operations.PipelineJobsOperations.create_or_update": "Azure.AI.Projects.PipelineJobs.createOrUpdate", + "azure.ai.projects.aio.operations.PipelineJobsOperations.create_or_update": "Azure.AI.Projects.PipelineJobs.createOrUpdate" }, - "CrossLanguageVersion": "33bdc2e1e817" + "CrossLanguageVersion": "fa3ed1607aa3" } \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py index 5a5f3b9e1d1d..166d41bcb0ac 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py @@ -24,6 +24,7 @@ DeploymentsOperations, EvaluationRulesOperations, IndexesOperations, + PipelineJobsOperations, ) if sys.version_info >= (3, 11): @@ -52,6 +53,8 @@ class AIProjectClient: # pylint: disable=too-many-instance-attributes :vartype deployments: azure.ai.projects.operations.DeploymentsOperations :ivar indexes: IndexesOperations operations :vartype indexes: azure.ai.projects.operations.IndexesOperations + :ivar pipeline_jobs: PipelineJobsOperations operations + :vartype pipeline_jobs: azure.ai.projects.operations.PipelineJobsOperations :param endpoint: Foundry Project endpoint in the form "https://{ai-services-account-name}.services.ai.azure.com/api/projects/{project-name}". If you only have one Project in your Foundry Hub, or to target the default Project in your Hub, use @@ -108,6 +111,7 @@ def __init__( self.datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) self.deployments = DeploymentsOperations(self._client, self._config, self._serialize, self._deserialize) self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) + self.pipeline_jobs = PipelineJobsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py index 217df480ea3a..ae4bd1086f98 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py @@ -24,6 +24,7 @@ DeploymentsOperations, EvaluationRulesOperations, IndexesOperations, + PipelineJobsOperations, ) if sys.version_info >= (3, 11): @@ -52,6 +53,8 @@ class AIProjectClient: # pylint: disable=too-many-instance-attributes :vartype deployments: azure.ai.projects.aio.operations.DeploymentsOperations :ivar indexes: IndexesOperations operations :vartype indexes: azure.ai.projects.aio.operations.IndexesOperations + :ivar pipeline_jobs: PipelineJobsOperations operations + :vartype pipeline_jobs: azure.ai.projects.aio.operations.PipelineJobsOperations :param endpoint: Foundry Project endpoint in the form "https://{ai-services-account-name}.services.ai.azure.com/api/projects/{project-name}". If you only have one Project in your Foundry Hub, or to target the default Project in your Hub, use @@ -108,6 +111,7 @@ def __init__( self.datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) self.deployments = DeploymentsOperations(self._client, self._config, self._serialize, self._deserialize) self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) + self.pipeline_jobs = PipelineJobsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py index 1a1c0ffec86c..f6c6e105a371 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py @@ -19,6 +19,7 @@ from ._operations import DatasetsOperations # type: ignore from ._operations import DeploymentsOperations # type: ignore from ._operations import IndexesOperations # type: ignore +from ._operations import PipelineJobsOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -32,6 +33,7 @@ "DatasetsOperations", "DeploymentsOperations", "IndexesOperations", + "PipelineJobsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py index ad0028f27c40..33eab96768ae 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py @@ -183,6 +183,9 @@ build_indexes_get_request, build_indexes_list_request, build_indexes_list_versions_request, + build_pipeline_jobs_create_or_update_request, + build_pipeline_jobs_get_request, + build_pipeline_jobs_list_request, ) from .._configuration import AIProjectClientConfiguration @@ -3098,6 +3101,326 @@ async def create_or_update( return deserialized # type: ignore +class PipelineJobsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`pipeline_jobs` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + *, + tag: Optional[str] = None, + list_view_type: Optional[Union[str, _models.ListViewType]] = None, + properties: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.PipelineJobResource"]: + """List Pipeline Jobs. Command Jobs are not returned by this dedicated collection. + + :keyword tag: Filter Pipeline Jobs by tag in the format 'key=value' (e.g., + 'framework=pytorch'). Default value is None. + :paramtype tag: str + :keyword list_view_type: Specifies which view type to apply when listing Pipeline Jobs. Known + values are: "ActiveOnly", "ArchivedOnly", and "All". Default value is None. + :paramtype list_view_type: str or ~azure.ai.projects.models.ListViewType + :keyword properties: Comma-separated user property names and optionally values. Example: + prop1,prop2=value2. Default value is None. + :paramtype properties: str + :return: An iterator like instance of PipelineJobResource + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.PipelineJobResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PipelineJobResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_pipeline_jobs_list_request( + tag=tag, + list_view_type=list_view_type, + properties=properties, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.PipelineJobResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, name: str, **kwargs: Any) -> _models.PipelineJobResource: + """Get a Pipeline Job by name. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PipelineJobResource] = kwargs.pop("cls", None) + + _request = build_pipeline_jobs_get_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PipelineJobResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, name: str, job: _models.PipelineJobResource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Required. + :type job: ~azure.ai.projects.models.PipelineJobResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, name: str, job: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Required. + :type job: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, name: str, job: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Required. + :type job: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, name: str, job: Union[_models.PipelineJobResource, JSON, IO[bytes]], **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Is one of the following types: + PipelineJobResource, JSON, IO[bytes] Required. + :type job: ~azure.ai.projects.models.PipelineJobResource or JSON or IO[bytes] + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PipelineJobResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(job, (IOBase, bytes)): + _content = job + else: + _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_pipeline_jobs_create_or_update_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PipelineJobResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + class BetaAgentsOperations: # pylint: disable=too-many-public-methods """ .. warning:: @@ -9305,11 +9628,6 @@ def list_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) content_type = content_type or "application/json" - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} - body = {k: v for k, v in body.items() if v is not None} _content = None if isinstance(body, (IOBase, bytes)): _content = body @@ -9317,6 +9635,12 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} + _request = build_beta_memory_stores_list_memories_request( name=name, kind=kind, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py index fbaa3db81dd0..3f29f75ad279 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py @@ -15,6 +15,7 @@ from ._patch_telemetry_async import TelemetryOperations from ._patch_connections_async import ConnectionsOperations from ._patch_jobs_async import JobsOperations as BetaJobsOperations +from ._patch_pipeline_jobs_async import PipelineJobsOperations from ._patch_memories_async import BetaMemoryStoresOperations from ._patch_models_async import BetaModelsOperations from ._patch_sessions_async import BetaAgentsOperations @@ -110,6 +111,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: "ConnectionsOperations", "DatasetsOperations", "EvaluationRulesOperations", + "PipelineJobsOperations", "TelemetryOperations", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index a074e8c7e8bf..849056c3c3f7 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -147,7 +147,7 @@ async def _resolve_asset_uri( existing = await self._datasets.get(name=dataset_name, version=version) if existing and existing.id: _logger.debug( - "[JobsOperations] Reusing existing dataset '%s' v%s.", + "[JobAssetResolver] Reusing existing dataset '%s' v%s.", dataset_name, version, ) @@ -158,7 +158,7 @@ async def _resolve_asset_uri( result: DatasetVersion if local_path.is_dir(): _logger.debug( - "[JobsOperations] Uploading folder '%s' as dataset '%s' v%s.", + "[JobAssetResolver] Uploading folder '%s' as dataset '%s' v%s.", local_path, dataset_name, version, @@ -172,7 +172,7 @@ async def _resolve_asset_uri( ) else: _logger.debug( - "[JobsOperations] Uploading file '%s' as dataset '%s' v%s.", + "[JobAssetResolver] Uploading file '%s' as dataset '%s' v%s.", local_path, dataset_name, version, @@ -182,18 +182,18 @@ async def _resolve_asset_uri( ) if not result.id: raise ValueError(f"Dataset upload succeeded but the service did not return a URI for '{local_path}'.") - _logger.debug("[JobsOperations] Resolved '%s' → '%s'.", uri, result.data_uri) + _logger.debug("[JobAssetResolver] Resolved '%s' to dataset '%s'.", uri, result.id) return result.id parsed = urlparse(uri) if parsed.scheme and not parsed.netloc: raw = uri[len("azureai:") :] if uri.startswith("azureai:") else uri ds_name, ds_version = raw.split(":", 1) - _logger.debug("[JobsOperations] Resolving name:version '%s' to dataset URI.", uri) + _logger.debug("[JobAssetResolver] Resolving name:version '%s' to a dataset URI.", uri) result = await self._datasets.get(name=ds_name, version=ds_version) if not result.id: raise ValueError(f"Dataset '{uri}' was fetched but the service did not return a URI.") - _logger.debug("[JobsOperations] Resolved '%s' → '%s'.", uri, result.data_uri) + _logger.debug("[JobAssetResolver] Resolved '%s' to dataset '%s'.", uri, result.id) return result.id # Already a datastore / remote URI — pass through unchanged. @@ -260,9 +260,19 @@ async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: continue code = component["code"] if code not in resolved_code: + _logger.debug( + "[PipelineJobCode] Resolving code for PipelineJob '%s', node '%s'.", + name, + node_name, + ) resolved_code[code] = await self._resolve_asset_uri(code, f"{name}-{node_name}-code") component["code"] = resolved_code[code] finally: + _logger.debug( + "[PipelineJobCode] Cleaning %d staged code directory item(s) for PipelineJob '%s'.", + len(job._component_code_dirs), + name, + ) for directory in job._component_code_dirs: directory.cleanup() job._component_code_dirs.clear() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py new file mode 100644 index 000000000000..454484ef8dba --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py @@ -0,0 +1,197 @@ +# pylint: disable=line-too-long,protected-access +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Async customized Pipeline Jobs operations.""" + +from copy import copy +import logging +from os import PathLike +from typing import Any, List, Optional, Union, overload +from uuid import uuid4 + +from azure.core.async_paging import AsyncItemPaged +from azure.core.tracing.decorator_async import distributed_trace_async + +from .._configuration import AIProjectClientConfiguration +from ._operations import PipelineJobsOperations as _GeneratedPipelineJobsOperations +from ._patch_datasets_async import DatasetsOperations +from ._patch_jobs_async import JobsOperations as _BetaJobsOperations +from ...models._enums import ListViewType, _FoundryFeaturesOptInKeys +from ...models._models import PipelineJobResource as _RestPipelineJobResource +from ...models._patch_jobs import PipelineJob, _from_rest_pipeline_job + +_logger = logging.getLogger(__name__) + + +class PipelineJobsOperations(_GeneratedPipelineJobsOperations): + """Async Pipeline-only operations exposed through ``client.pipeline_jobs``. + + The dedicated public ``/pipeline_jobs`` ingress forwards to the existing MFE + Pipeline implementation. Asset registration is intentionally shared with + ``client.beta.jobs`` so both surfaces produce identical Code identities. + + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, access it via ``client.pipeline_jobs``. + """ + + _config: AIProjectClientConfiguration + _JOBS_PREVIEW_HEADER: str = _FoundryFeaturesOptInKeys.JOBS_V1_PREVIEW.value + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + # Jobs use a preview API version, while the shared Dataset client used + # for local Code registration must retain the root client's v1 config. + original_config = self._config + self._config = copy(original_config) + self._config.api_version = "2026-01-15-preview" + self._datasets = DatasetsOperations( + self._client, original_config, self._serialize, self._deserialize + ) + + # Keep route-specific request handling in the generated Pipeline Jobs class, + # while reusing the proven local-asset contract from beta.jobs. + async def _resolve_asset_uri( + self, + uri: str, + dataset_name: str, + base_path: Optional[Union[str, PathLike[str]]] = None, + ) -> str: + return await _BetaJobsOperations._resolve_asset_uri( # type: ignore[arg-type] + self, uri, dataset_name, base_path + ) + + async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: + await _BetaJobsOperations._resolve_pipeline_code(self, name, job) # type: ignore[arg-type] + + def _inject_preview_header(self, kwargs: dict) -> None: + _BetaJobsOperations._inject_preview_header(self, kwargs) # type: ignore[arg-type] + + def list( + self, + *, + tag: Optional[str] = None, + list_view_type: Optional[Union[str, ListViewType]] = None, + properties: Optional[str] = None, + **kwargs: Any, + ) -> AsyncItemPaged[PipelineJob]: + """List Pipeline Jobs with the resource envelope flattened. + + :keyword tag: Filter by tag in ``key=value`` format. + :paramtype tag: str or None + :keyword list_view_type: Select active, archived, or all jobs. + :paramtype list_view_type: str or ~azure.ai.projects.models.ListViewType or None + :keyword properties: Comma-separated user property filters. + :paramtype properties: str or None + :return: An async iterator over PipelineJob objects. + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.PipelineJob] + :raises ~azure.core.exceptions.HttpResponseError: + """ + self._inject_preview_header(kwargs) + + def _convert_page(page: List[_RestPipelineJobResource]) -> List[PipelineJob]: + return [_from_rest_pipeline_job(item) for item in page] + + return super().list( + tag=tag, + list_view_type=list_view_type, + properties=properties, + cls=_convert_page, + **kwargs, + ) # type: ignore[return-value] + + @distributed_trace_async + async def get(self, name: str, **kwargs: Any) -> PipelineJob: # type: ignore[override] + """Get a Pipeline Job by name with the resource envelope flattened. + + :param name: The case-sensitive Pipeline Job name. + :type name: str + :return: The requested PipelineJob. + :rtype: ~azure.ai.projects.models.PipelineJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + self._inject_preview_header(kwargs) + return _from_rest_pipeline_job(await super().get(name=name, **kwargs)) + + @overload # type: ignore[override] + async def create_or_update( + self, + name: PipelineJob, + job: None = None, + *, + experiment_name: Optional[str] = None, + **kwargs: Any, + ) -> PipelineJob: ... + + @overload + async def create_or_update( + self, + name: str, + job: PipelineJob, + *, + experiment_name: None = None, + **kwargs: Any, + ) -> PipelineJob: ... + + @distributed_trace_async + async def create_or_update( # type: ignore[override] + self, + name: Union[str, PipelineJob], + job: Optional[PipelineJob] = None, + *, + experiment_name: Optional[str] = None, + **kwargs: Any, + ) -> PipelineJob: + """Create or update a Pipeline Job through the dedicated ingress. + + :param name: The Pipeline Job name, or a PipelineJob for an autogenerated name. + :type name: str or ~azure.ai.projects.models.PipelineJob + :param job: The PipelineJob when ``name`` is a string. + :type job: ~azure.ai.projects.models.PipelineJob or None + :keyword experiment_name: Experiment name for a job-only submission. + :paramtype experiment_name: str or None + :return: The created or updated PipelineJob. + :rtype: ~azure.ai.projects.models.PipelineJob + :raises TypeError: If arguments do not identify exactly one PipelineJob. + :raises ~azure.core.exceptions.HttpResponseError: + """ + if isinstance(name, PipelineJob): + if job is not None: + raise TypeError( + "A job cannot be supplied when the first argument is a PipelineJob." + ) + job = name + name = f"pipeline-{uuid4().hex}" + if experiment_name is not None: + job.experiment_name = experiment_name + elif not isinstance(name, str) or job is None: + raise TypeError( + "create_or_update requires a job name and PipelineJob, or one PipelineJob." + ) + elif experiment_name is not None: + raise TypeError( + "Set job.experiment_name when submitting a PipelineJob with an explicit name." + ) + + if not isinstance(job, PipelineJob): + raise TypeError("job must be a PipelineJob") + + await self._resolve_pipeline_code(name, job) + self._inject_preview_header(kwargs) + _logger.debug( + "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /pipeline_jobs.", + name, + len(job.jobs or {}), + ) + # The generated wire contract retains the polymorphic resource envelope + # so /jobs keeps both Command and Pipeline discriminator mappings. + rest_body = _RestPipelineJobResource(properties=job) + return _from_rest_pipeline_job( + await super().create_or_update(name=name, job=rest_body, **kwargs) + ) + + +__all__ = ["PipelineJobsOperations"] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py index c658b7dea95b..09c6b449d299 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py @@ -270,6 +270,7 @@ PendingUploadRequest, PendingUploadResponse, PipelineJob, + PipelineJobResource, ProceduralMemoryItem, PromoteCandidateRequest, PromoteCandidateResponse, @@ -727,6 +728,7 @@ "PendingUploadRequest", "PendingUploadResponse", "PipelineJob", + "PipelineJobResource", "ProceduralMemoryItem", "PromoteCandidateRequest", "PromoteCandidateResponse", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py index 831bfb0bcf48..7abbae751111 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py @@ -12627,6 +12627,52 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.job_type = "Pipeline" # type: ignore +class PipelineJobResource(_Model): + """Pipeline Job resource exposed through the dedicated Pipeline Jobs ingress. + + :ivar name: The name of the Pipeline Job. This is case-sensitive. Required. + :vartype name: str + :ivar id: The resource ID. + :vartype id: str + :ivar type: The resource type. + :vartype type: str + :ivar properties: Properties of the Pipeline Job. The dedicated Pipeline Jobs operations + require jobType to be Pipeline. Required. + :vartype properties: ~azure.ai.projects.models.JobProperties + :ivar system_data: Metadata pertaining to creation and last modification of the resource. + :vartype system_data: ~azure.ai.projects.models.SystemData + """ + + name: str = rest_field(visibility=["read"]) + """The name of the Pipeline Job. This is case-sensitive. Required.""" + id: Optional[str] = rest_field(visibility=["read"]) + """The resource ID.""" + type: Optional[str] = rest_field(visibility=["read"]) + """The resource type.""" + properties: "_models.JobProperties" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Properties of the Pipeline Job. The dedicated Pipeline Jobs operations require jobType to be + Pipeline. Required.""" + system_data: Optional["_models.SystemData"] = rest_field(name="systemData", visibility=["read"]) + """Metadata pertaining to creation and last modification of the resource.""" + + @overload + def __init__( + self, + *, + properties: "_models.JobProperties", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class ProceduralMemoryItem(MemoryItem, discriminator="procedural"): """A memory item containing a procedure extracted from conversations. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index 95870fd8faad..5133c1f8a3c6 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -22,6 +22,7 @@ MpiDistribution, Output, PipelineJob as _RestPipelineJob, + PipelineJobResource as _RestPipelineJobResource, PyTorchDistribution, QueueSettings, ServiceInstance as _RestServiceInstance, @@ -265,7 +266,7 @@ def system_data(self) -> Optional[SystemData]: return self._system_data @classmethod - def _from_rest_object(cls, rest_obj: _RestJob) -> "PipelineJob": + def _from_rest_object(cls, rest_obj: Union[_RestJob, _RestPipelineJobResource]) -> "PipelineJob": props = rest_obj.properties if not isinstance(props, _RestPipelineJob): raise TypeError( @@ -279,9 +280,14 @@ def _from_rest_object(cls, rest_obj: _RestJob) -> "PipelineJob": return obj +def _from_rest_pipeline_job(rest_obj: Union[_RestJob, _RestPipelineJobResource]) -> PipelineJob: + """Flatten a Pipeline Job resource envelope into the public PipelineJob model.""" + return PipelineJob._from_rest_object(rest_obj) + + def _from_rest_job(rest_obj: _RestJob) -> Union[CommandJob, PipelineJob]: if isinstance(rest_obj.properties, _RestPipelineJob): - return PipelineJob._from_rest_object(rest_obj) + return _from_rest_pipeline_job(rest_obj) return CommandJob._from_rest_object(rest_obj) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py index 1a1c0ffec86c..f6c6e105a371 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py @@ -19,6 +19,7 @@ from ._operations import DatasetsOperations # type: ignore from ._operations import DeploymentsOperations # type: ignore from ._operations import IndexesOperations # type: ignore +from ._operations import PipelineJobsOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -32,6 +33,7 @@ "DatasetsOperations", "DeploymentsOperations", "IndexesOperations", + "PipelineJobsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py index 16617251741d..8328b459313d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py @@ -804,6 +804,90 @@ def build_indexes_create_or_update_request(name: str, version: str, **kwargs: An return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) +def build_pipeline_jobs_list_request( + *, + tag: Optional[str] = None, + list_view_type: Optional[Union[str, _models.ListViewType]] = None, + properties: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/pipeline_jobs" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if tag is not None: + _params["tag"] = _SERIALIZER.query("tag", tag, "str") + if list_view_type is not None: + _params["listViewType"] = _SERIALIZER.query("list_view_type", list_view_type, "str") + if properties is not None: + _params["properties"] = _SERIALIZER.query("properties", properties, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_pipeline_jobs_get_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/pipeline_jobs/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_pipeline_jobs_create_or_update_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/pipeline_jobs/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + def build_beta_agents_patch_agent_details_request( # pylint: disable=name-too-long agent_name: str, **kwargs: Any ) -> HttpRequest: @@ -6970,6 +7054,326 @@ def create_or_update( return deserialized # type: ignore +class PipelineJobsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`pipeline_jobs` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + *, + tag: Optional[str] = None, + list_view_type: Optional[Union[str, _models.ListViewType]] = None, + properties: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.PipelineJobResource"]: + """List Pipeline Jobs. Command Jobs are not returned by this dedicated collection. + + :keyword tag: Filter Pipeline Jobs by tag in the format 'key=value' (e.g., + 'framework=pytorch'). Default value is None. + :paramtype tag: str + :keyword list_view_type: Specifies which view type to apply when listing Pipeline Jobs. Known + values are: "ActiveOnly", "ArchivedOnly", and "All". Default value is None. + :paramtype list_view_type: str or ~azure.ai.projects.models.ListViewType + :keyword properties: Comma-separated user property names and optionally values. Example: + prop1,prop2=value2. Default value is None. + :paramtype properties: str + :return: An iterator like instance of PipelineJobResource + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.PipelineJobResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PipelineJobResource]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_pipeline_jobs_list_request( + tag=tag, + list_view_type=list_view_type, + properties=properties, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.PipelineJobResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, name: str, **kwargs: Any) -> _models.PipelineJobResource: + """Get a Pipeline Job by name. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PipelineJobResource] = kwargs.pop("cls", None) + + _request = build_pipeline_jobs_get_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PipelineJobResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, name: str, job: _models.PipelineJobResource, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Required. + :type job: ~azure.ai.projects.models.PipelineJobResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, name: str, job: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Required. + :type job: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, name: str, job: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Required. + :type job: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, name: str, job: Union[_models.PipelineJobResource, JSON, IO[bytes]], **kwargs: Any + ) -> _models.PipelineJobResource: + """Create and execute a Pipeline Job. For update, the tags in the submitted definition replace the + existing tags. + + :param name: The name of the Pipeline Job. This is case-sensitive. Required. + :type name: str + :param job: The Pipeline Job to create or update. Is one of the following types: + PipelineJobResource, JSON, IO[bytes] Required. + :type job: ~azure.ai.projects.models.PipelineJobResource or JSON or IO[bytes] + :return: PipelineJobResource. The PipelineJobResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PipelineJobResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PipelineJobResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(job, (IOBase, bytes)): + _content = job + else: + _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_pipeline_jobs_create_or_update_request( + name=name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PipelineJobResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + class BetaAgentsOperations: # pylint: disable=too-many-public-methods """ .. warning:: @@ -13170,11 +13574,6 @@ def list_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) content_type = content_type or "application/json" - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} - body = {k: v for k, v in body.items() if v is not None} _content = None if isinstance(body, (IOBase, bytes)): _content = body @@ -13182,6 +13581,12 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} + _request = build_beta_memory_stores_list_memories_request( name=name, kind=kind, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py index 9b788c68ba8d..5e365c7a8008 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py @@ -18,6 +18,7 @@ from ._patch_telemetry import TelemetryOperations from ._patch_connections import ConnectionsOperations from ._patch_jobs import JobsOperations as BetaJobsOperations +from ._patch_pipeline_jobs import PipelineJobsOperations from ._patch_memories import BetaMemoryStoresOperations from ._patch_models import BetaModelsOperations from ._patch_sessions import BetaAgentsOperations @@ -165,6 +166,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: "ConnectionsOperations", "DatasetsOperations", "EvaluationRulesOperations", + "PipelineJobsOperations", "TelemetryOperations", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index f9f1a341464b..961fc468e8fb 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -150,7 +150,7 @@ def _resolve_asset_uri( existing = self._datasets.get(name=dataset_name, version=version) if existing and existing.id: _logger.debug( - "[JobsOperations] Reusing existing dataset '%s' v%s.", + "[JobAssetResolver] Reusing existing dataset '%s' v%s.", dataset_name, version, ) @@ -161,7 +161,7 @@ def _resolve_asset_uri( result: DatasetVersion if local_path.is_dir(): _logger.debug( - "[JobsOperations] Uploading folder '%s' as dataset '%s' v%s.", + "[JobAssetResolver] Uploading folder '%s' as dataset '%s' v%s.", local_path, dataset_name, version, @@ -175,7 +175,7 @@ def _resolve_asset_uri( ) else: _logger.debug( - "[JobsOperations] Uploading file '%s' as dataset '%s' v%s.", + "[JobAssetResolver] Uploading file '%s' as dataset '%s' v%s.", local_path, dataset_name, version, @@ -185,18 +185,18 @@ def _resolve_asset_uri( ) if not result.id: raise ValueError(f"Dataset upload succeeded but the service did not return a URI for '{local_path}'.") - _logger.debug("[JobsOperations] Resolved '%s' → '%s'.", uri, result.data_uri) + _logger.debug("[JobAssetResolver] Resolved '%s' to dataset '%s'.", uri, result.id) return result.id parsed = urlparse(uri) if parsed.scheme and not parsed.netloc: raw = uri[len("azureai:") :] if uri.startswith("azureai:") else uri ds_name, ds_version = raw.split(":", 1) - _logger.debug("[JobsOperations] Resolving name:version '%s' to dataset URI.", uri) + _logger.debug("[JobAssetResolver] Resolving name:version '%s' to a dataset URI.", uri) result = self._datasets.get(name=ds_name, version=ds_version) if not result.id: raise ValueError(f"Dataset '{uri}' was fetched but the service did not return a URI.") - _logger.debug("[JobsOperations] Resolved '%s' → '%s'.", uri, result.data_uri) + _logger.debug("[JobAssetResolver] Resolved '%s' to dataset '%s'.", uri, result.id) return result.id # Already a datastore / remote URI — pass through unchanged. @@ -263,9 +263,19 @@ def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: continue code = component["code"] if code not in resolved_code: + _logger.debug( + "[PipelineJobCode] Resolving code for PipelineJob '%s', node '%s'.", + name, + node_name, + ) resolved_code[code] = self._resolve_asset_uri(code, f"{name}-{node_name}-code") component["code"] = resolved_code[code] finally: + _logger.debug( + "[PipelineJobCode] Cleaning %d staged code directory item(s) for PipelineJob '%s'.", + len(job._component_code_dirs), + name, + ) for directory in job._component_code_dirs: directory.cleanup() job._component_code_dirs.clear() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py new file mode 100644 index 000000000000..365a2cdeda69 --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py @@ -0,0 +1,196 @@ +# pylint: disable=line-too-long,protected-access +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customized Pipeline Jobs operations.""" + +from copy import copy +import logging +from os import PathLike +from typing import Any, List, Optional, Union, overload +from uuid import uuid4 + +from azure.core.paging import ItemPaged +from azure.core.tracing.decorator import distributed_trace + +from .._configuration import AIProjectClientConfiguration +from ._operations import PipelineJobsOperations as _GeneratedPipelineJobsOperations +from ._patch_datasets import DatasetsOperations +from ._patch_jobs import JobsOperations as _BetaJobsOperations +from ..models._enums import ListViewType, _FoundryFeaturesOptInKeys +from ..models._models import PipelineJobResource as _RestPipelineJobResource +from ..models._patch_jobs import PipelineJob, _from_rest_pipeline_job + +_logger = logging.getLogger(__name__) + + +class PipelineJobsOperations(_GeneratedPipelineJobsOperations): + """Pipeline-only operations exposed through ``client.pipeline_jobs``. + + The dedicated public ``/pipeline_jobs`` ingress forwards to the existing MFE + Pipeline implementation. Asset registration is intentionally shared with + ``client.beta.jobs`` so both surfaces produce identical Code identities. + + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, access it via ``client.pipeline_jobs``. + """ + + _config: AIProjectClientConfiguration + _JOBS_PREVIEW_HEADER: str = _FoundryFeaturesOptInKeys.JOBS_V1_PREVIEW.value + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + # Jobs use a preview API version, while the shared Dataset client used + # for local Code registration must retain the root client's v1 config. + original_config = self._config + self._config = copy(original_config) + self._config.api_version = "2026-01-15-preview" + self._datasets = DatasetsOperations( + self._client, original_config, self._serialize, self._deserialize + ) + + # Keep route-specific request handling in the generated Pipeline Jobs class, + # while reusing the proven local-asset contract from beta.jobs. + def _resolve_asset_uri( + self, + uri: str, + dataset_name: str, + base_path: Optional[Union[str, PathLike[str]]] = None, + ) -> str: + return _BetaJobsOperations._resolve_asset_uri(self, uri, dataset_name, base_path) # type: ignore[arg-type] + + def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: + _BetaJobsOperations._resolve_pipeline_code(self, name, job) # type: ignore[arg-type] + + def _inject_preview_header(self, kwargs: dict) -> None: + _BetaJobsOperations._inject_preview_header(self, kwargs) # type: ignore[arg-type] + + @distributed_trace + def list( + self, + *, + tag: Optional[str] = None, + list_view_type: Optional[Union[str, ListViewType]] = None, + properties: Optional[str] = None, + **kwargs: Any, + ) -> ItemPaged[PipelineJob]: + """List Pipeline Jobs with the resource envelope flattened. + + :keyword tag: Filter by tag in ``key=value`` format. + :paramtype tag: str or None + :keyword list_view_type: Select active, archived, or all jobs. + :paramtype list_view_type: str or ~azure.ai.projects.models.ListViewType or None + :keyword properties: Comma-separated user property filters. + :paramtype properties: str or None + :return: An iterator over PipelineJob objects. + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.PipelineJob] + :raises ~azure.core.exceptions.HttpResponseError: + """ + self._inject_preview_header(kwargs) + + def _convert_page(page: List[_RestPipelineJobResource]) -> List[PipelineJob]: + return [_from_rest_pipeline_job(item) for item in page] + + return super().list( + tag=tag, + list_view_type=list_view_type, + properties=properties, + cls=_convert_page, + **kwargs, + ) # type: ignore[return-value] + + @distributed_trace + def get(self, name: str, **kwargs: Any) -> PipelineJob: # type: ignore[override] + """Get a Pipeline Job by name with the resource envelope flattened. + + :param name: The case-sensitive Pipeline Job name. + :type name: str + :return: The requested PipelineJob. + :rtype: ~azure.ai.projects.models.PipelineJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + self._inject_preview_header(kwargs) + return _from_rest_pipeline_job(super().get(name=name, **kwargs)) + + @overload # type: ignore[override] + def create_or_update( + self, + name: PipelineJob, + job: None = None, + *, + experiment_name: Optional[str] = None, + **kwargs: Any, + ) -> PipelineJob: ... + + @overload + def create_or_update( + self, + name: str, + job: PipelineJob, + *, + experiment_name: None = None, + **kwargs: Any, + ) -> PipelineJob: ... + + @distributed_trace + def create_or_update( # type: ignore[override] + self, + name: Union[str, PipelineJob], + job: Optional[PipelineJob] = None, + *, + experiment_name: Optional[str] = None, + **kwargs: Any, + ) -> PipelineJob: + """Create or update a Pipeline Job through the dedicated ingress. + + :param name: The Pipeline Job name, or a PipelineJob for an autogenerated name. + :type name: str or ~azure.ai.projects.models.PipelineJob + :param job: The PipelineJob when ``name`` is a string. + :type job: ~azure.ai.projects.models.PipelineJob or None + :keyword experiment_name: Experiment name for a job-only submission. + :paramtype experiment_name: str or None + :return: The created or updated PipelineJob. + :rtype: ~azure.ai.projects.models.PipelineJob + :raises TypeError: If arguments do not identify exactly one PipelineJob. + :raises ~azure.core.exceptions.HttpResponseError: + """ + if isinstance(name, PipelineJob): + if job is not None: + raise TypeError( + "A job cannot be supplied when the first argument is a PipelineJob." + ) + job = name + name = f"pipeline-{uuid4().hex}" + if experiment_name is not None: + job.experiment_name = experiment_name + elif not isinstance(name, str) or job is None: + raise TypeError( + "create_or_update requires a job name and PipelineJob, or one PipelineJob." + ) + elif experiment_name is not None: + raise TypeError( + "Set job.experiment_name when submitting a PipelineJob with an explicit name." + ) + + if not isinstance(job, PipelineJob): + raise TypeError("job must be a PipelineJob") + + self._resolve_pipeline_code(name, job) + self._inject_preview_header(kwargs) + _logger.debug( + "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /pipeline_jobs.", + name, + len(job.jobs or {}), + ) + # The generated wire contract retains the polymorphic resource envelope + # so /jobs keeps both Command and Pipeline discriminator mappings. + rest_body = _RestPipelineJobResource(properties=job) + return _from_rest_pipeline_job( + super().create_or_update(name=name, job=rest_body, **kwargs) + ) + + +__all__ = ["PipelineJobsOperations"] diff --git a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py index 71ffe421ce23..45242c5666c5 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/pipeline_source/sample_pipeline_source.py @@ -39,9 +39,7 @@ def main() -> None: retry_total=0, ) as client, ): - created = client.beta.jobs.create_or_update( - job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} - ) + created = client.pipeline_jobs.create_or_update(job, experiment_name="pipeline_samples") print(f"Submitted {created.name}: {created.id} (status: {created.status})") diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py index 690e9d12afb7..55d0cc70bce8 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py @@ -51,9 +51,7 @@ def main() -> None: retry_total=0, ) as client, ): - created = client.beta.jobs.create_or_update( - job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} - ) + created = client.pipeline_jobs.create_or_update(job, experiment_name="pipeline_samples") print(f"Submitted {created.name}: {created.id} (status: {created.status})") diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py index 80671bf38562..6789c36b07c3 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_hello_world.py @@ -55,10 +55,9 @@ def main() -> None: DefaultAzureCredential() as credential, AIProjectClient(endpoint=endpoint, credential=credential) as client, ): - created = client.beta.jobs.create_or_update( + created = client.pipeline_jobs.create_or_update( name=job_name, job=job, - headers={"x-ms-foundry-job-route": "execution"}, ) print(f"Submitted {created.name}: {created.id} (status: {created.status})") diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py index 37d6fb695030..a8151c12a5d3 100644 --- a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_two_code.py @@ -103,10 +103,9 @@ def main() -> None: retry_total=0, ) as client, ): - created = client.beta.jobs.create_or_update( + created = client.pipeline_jobs.create_or_update( name=job_name, job=job, - headers={"x-ms-foundry-job-route": "execution"}, ) print(f"Submitted {created.name}: {created.id} (status: {created.status})") diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index b566b0e59cb9..77ab6a18eb21 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -235,6 +235,19 @@ def _assert_requests(requests: list[HttpRequest], kind: str, expected: dict[str, assert JobType.PIPELINE == "Pipeline" +def _assert_pipeline_jobs_requests(requests: list[HttpRequest], expected: dict[str, Any]) -> None: + assert len(requests) == 3 + assert [request.method for request in requests] == ["PUT", "GET", "GET"] + for request in requests: + assert request.headers["Foundry-Features"] == "Jobs=V1Preview" + assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] + assert urlparse(requests[0].url).path.endswith("/pipeline_jobs/pipeline") + assert urlparse(requests[1].url).path.endswith("/pipeline_jobs/pipeline") + assert urlparse(requests[2].url).path.endswith("/pipeline_jobs") + assert "jobType" not in parse_qs(urlparse(requests[2].url).query) + assert json.loads(requests[0].body) == {"properties": expected} + + def _inline_pipeline() -> tuple[PipelineJob, CommandJob]: command = CommandJob( command="echo hello ${{inputs.name}}", @@ -301,8 +314,8 @@ def _uploaded_code(name: str, version: str) -> DatasetVersion: def _assert_two_code_request(request: HttpRequest, code_uris: dict[str, str]) -> None: assert request.method == "PUT" assert request.headers["Foundry-Features"] == "Jobs=V1Preview" - assert request.headers["x-ms-foundry-job-route"] == "execution" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] + assert urlparse(request.url).path.endswith("/pipeline_jobs/two-code") resources = { "instance_count": 1, "instance_type": "Singularity.D4_v3", @@ -368,7 +381,7 @@ def test_jobs_sync_create_from_command_node() -> None: transport = _Transport([_response("Pipeline")]) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - _assert_job(client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") + _assert_job(client.pipeline_jobs.create_or_update("pipeline", pipeline), "Pipeline") assert len(transport.requests) == 1 _assert_inline_request(transport.requests[0]) @@ -386,7 +399,7 @@ async def test_jobs_async_create_from_command_node() -> None: async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] ) as client: - _assert_job(await client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") + _assert_job(await client.pipeline_jobs.create_or_update("pipeline", pipeline), "Pipeline") assert len(transport.requests) == 1 _assert_inline_request(transport.requests[0]) @@ -406,7 +419,7 @@ def test_jobs_sync_create_from_mapping_with_command_node() -> None: transport = _Transport([_response("Pipeline")]) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - _assert_job(client.beta.jobs.create_or_update("pipeline", pipeline), "Pipeline") + _assert_job(client.pipeline_jobs.create_or_update("pipeline", pipeline), "Pipeline") assert len(transport.requests) == 1 _assert_inline_request(transport.requests[0]) @@ -490,7 +503,7 @@ def test_pipeline_converts_value_bound_uri_folder_input() -> None: transport=transport, # type: ignore[arg-type] ) as client: _assert_job( - client.beta.jobs.create_or_update("folder-handoff", pipeline), + client.pipeline_jobs.create_or_update("folder-handoff", pipeline), "Pipeline", ) @@ -519,13 +532,12 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat return _uploaded_code(name, version) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) _assert_job( - client.beta.jobs.create_or_update( + client.pipeline_jobs.create_or_update( "two-code", pipeline, - headers={"x-ms-foundry-job-route": "execution"}, ), "Pipeline", ) @@ -561,13 +573,12 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] ) as client: - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) _assert_job( - await client.beta.jobs.create_or_update( + await client.pipeline_jobs.create_or_update( "two-code", pipeline, - headers={"x-ms-foundry-job-route": "execution"}, ), "Pipeline", ) @@ -597,10 +608,10 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat raise RuntimeError("upload failed") with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) with pytest.raises(RuntimeError, match="upload failed"): - client.beta.jobs.create_or_update("two-code", pipeline) + client.pipeline_jobs.create_or_update("two-code", pipeline) assert transport.requests == [] @@ -678,6 +689,43 @@ async def test_jobs_async_create_get_and_list(kind: str) -> None: _assert_requests(transport.requests, kind, expected) +def test_pipeline_jobs_sync_create_get_and_list() -> None: + job, expected = _job("Pipeline") + transport = _Transport([_response("Pipeline"), _response("Pipeline"), {"value": [_response("Pipeline")]}]) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + _assert_job(client.pipeline_jobs.create_or_update("pipeline", job), "Pipeline") # type: ignore[arg-type] + _assert_job(client.pipeline_jobs.get("pipeline"), "Pipeline") + listed = list(client.pipeline_jobs.list()) + assert len(listed) == 1 + _assert_job(listed[0], "Pipeline") + + with pytest.raises(TypeError, match="PipelineJob"): + client.pipeline_jobs.create_or_update("command", _job("Command")[0]) # type: ignore[arg-type] + + _assert_pipeline_jobs_requests(transport.requests, expected) + + +@pytest.mark.asyncio +async def test_pipeline_jobs_async_create_get_and_list() -> None: + job, expected = _job("Pipeline") + transport = _AsyncTransport([_response("Pipeline"), _response("Pipeline"), {"value": [_response("Pipeline")]}]) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + _assert_job(await client.pipeline_jobs.create_or_update("pipeline", job), "Pipeline") # type: ignore[arg-type] + _assert_job(await client.pipeline_jobs.get("pipeline"), "Pipeline") + listed = [item async for item in client.pipeline_jobs.list()] + assert len(listed) == 1 + _assert_job(listed[0], "Pipeline") + + with pytest.raises(TypeError, match="PipelineJob"): + await client.pipeline_jobs.create_or_update("command", _job("Command")[0]) # type: ignore[arg-type] + + _assert_pipeline_jobs_requests(transport.requests, expected) + + def _dsl_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: monkeypatch.setenv("JOB_COMPUTE_ID", _COMPUTE) monkeypatch.setenv("JOB_ENVIRONMENT_IMAGE", "example.azurecr.io/train:latest") @@ -706,9 +754,8 @@ def _dsl_code_paths(job: PipelineJob) -> dict[str, Path]: def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: assert request.method == "PUT" assert request.headers["Foundry-Features"] == "Jobs=V1Preview" - assert request.headers["x-ms-foundry-job-route"] == "execution" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] - assert re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", urlparse(request.url).path) + assert re.fullmatch(r"/api/projects/fake-project/pipeline_jobs/pipeline-[0-9a-f]{32}", urlparse(request.url).path) resources = { "instance_count": 1, "instance_type": "Singularity.D4_v3", @@ -823,11 +870,9 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat return _uploaded_code(name, version) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) - created = client.beta.jobs.create_or_update( - job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} - ) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) + created = client.pipeline_jobs.create_or_update(job, experiment_name="pipeline_samples") assert isinstance(created, PipelineJob) assert job.experiment_name == "pipeline_samples" @@ -858,11 +903,9 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] ) as client: - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) - created = await client.beta.jobs.create_or_update( - job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} - ) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) + created = await client.pipeline_jobs.create_or_update(job, experiment_name="pipeline_samples") assert isinstance(created, PipelineJob) assert len(uploads) == 2 @@ -888,10 +931,10 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat return _uploaded_code(name, version) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) with pytest.raises(RuntimeError, match="upload failed"): - client.beta.jobs.create_or_update(job) + client.pipeline_jobs.create_or_update(job) assert len(uploads) == 2 assert transport.requests == [] @@ -917,10 +960,10 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] ) as client: - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) with pytest.raises(RuntimeError, match="upload failed"): - await client.beta.jobs.create_or_update(job) + await client.pipeline_jobs.create_or_update(job) assert len(uploads) == 2 assert transport.requests == [] @@ -1192,11 +1235,9 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat return _uploaded_code(name, version) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) - client.beta.jobs.create_or_update( - job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} - ) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) + client.pipeline_jobs.create_or_update(job, experiment_name="pipeline_samples") assert len(uploads) == 1 assert uploads[0][1] == str(snapshot) @@ -1225,11 +1266,9 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] ) as client: - monkeypatch.setattr(client.beta.jobs._datasets, "get", missing_asset) - monkeypatch.setattr(client.beta.jobs._datasets, "upload_folder", upload_folder) - await client.beta.jobs.create_or_update( - job, experiment_name="pipeline_samples", headers={"x-ms-foundry-job-route": "execution"} - ) + monkeypatch.setattr(client.pipeline_jobs._datasets, "get", missing_asset) + monkeypatch.setattr(client.pipeline_jobs._datasets, "upload_folder", upload_folder) + await client.pipeline_jobs.create_or_update(job, experiment_name="pipeline_samples") assert uploads == [str(snapshot)] assert not snapshot.exists() @@ -1404,16 +1443,16 @@ def test_jobs_sync_job_only_names_are_unique() -> None: job = PipelineJob(compute_id=_COMPUTE, jobs={}) transport = _Transport([_response("Pipeline"), _response("Pipeline")]) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - client.beta.jobs.create_or_update(job) - client.beta.jobs.create_or_update(job) + client.pipeline_jobs.create_or_update(job) + client.pipeline_jobs.create_or_update(job) with pytest.raises(TypeError, match="one PipelineJob"): - client.beta.jobs.create_or_update("missing-job") + client.pipeline_jobs.create_or_update("missing-job") with pytest.raises(TypeError, match="A job cannot be supplied"): - client.beta.jobs.create_or_update(job, job) + client.pipeline_jobs.create_or_update(job, job) paths = [urlparse(request.url).path for request in transport.requests] assert len(paths) == len(set(paths)) == 2 - assert all(re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", path) for path in paths) + assert all(re.fullmatch(r"/api/projects/fake-project/pipeline_jobs/pipeline-[0-9a-f]{32}", path) for path in paths) @pytest.mark.asyncio @@ -1423,9 +1462,9 @@ async def test_jobs_async_job_only_names_are_unique() -> None: async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] ) as client: - await client.beta.jobs.create_or_update(job) - await client.beta.jobs.create_or_update(job) + await client.pipeline_jobs.create_or_update(job) + await client.pipeline_jobs.create_or_update(job) paths = [urlparse(request.url).path for request in transport.requests] assert len(paths) == len(set(paths)) == 2 - assert all(re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", path) for path in paths) + assert all(re.fullmatch(r"/api/projects/fake-project/pipeline_jobs/pipeline-[0-9a-f]{32}", path) for path in paths) diff --git a/sdk/ai/azure-ai-projects/tsp-location.yaml b/sdk/ai/azure-ai-projects/tsp-location.yaml index de893a73e51b..4fe20f91ffe6 100644 --- a/sdk/ai/azure-ai-projects/tsp-location.yaml +++ b/sdk/ai/azure-ai-projects/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/ai-foundry/data-plane/Foundry -commit: ba4d0e3c01618a703851b2e2dd1b6c829ec7d6e4 +commit: 211fd2c63d89d008eac57f39bc773abad9bdeed0 repo: Azure/azure-rest-api-specs additionalDirectories: From 1b705fcfd35635e56aa217dc50a0058837b5a2d7 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Mon, 2 Nov 2026 20:01:16 -0800 Subject: [PATCH 33/52] Support nested pipeline authoring and recursive component source upload Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 2 + sdk/ai/azure-ai-projects/README.md | 10 +- .../aio/operations/_patch_jobs_async.py | 8 +- .../azure/ai/projects/dsl.py | 183 ++++++---- .../ai/projects/operations/_job_helper.py | 26 ++ .../ai/projects/operations/_patch_jobs.py | 8 +- .../samples/jobs/sample_pipeline_nested.py | 74 ++++ .../tests/jobs/test_pipeline_jobs.py | 325 +++++++++++++++++- 8 files changed, 553 insertions(+), 83 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_nested.py diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 25f354a62ad8..f00066aebbc5 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -28,6 +28,7 @@ * When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound literal, `uri_file`, and `uri_folder` inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. * Added `azure.ai.projects.dsl` function-body `@component` and `@pipeline` authoring for native two-step PipelineJobs. Calling the pipeline function builds its graph, packages each Python component body as its own executable Code folder, binds typed inputs and file outputs, and supports repeated component calls. `.pipeline_jobs.create_or_update(pipeline_job)` generates a unique name (sync and async), while the explicit-name form remains available. * Added opt-in `@component(code=...)` source-backed components for local helper functions, sibling modules, and resources. Code roots are snapshot with ignore rules before upload and shared by nodes in the same pipeline. Executing these components requires the image to contain a compatible `azure-ai-projects` package and other imported dependencies; bare `@component` keeps its existing standalone execution behavior. +* Added nested `@pipeline` composition with parent-owned input/output bindings and preserved Pipeline component hierarchy. Nested command source folders are resolved on both job submission surfaces, shared code roots are uploaded once across the graph, and the root job owns staged-folder cleanup. Submission requires service support for inline Pipeline component registration. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. @@ -92,6 +93,7 @@ Breaking changes in beta classes: * Updated job samples `sample_jobs.py` and `sample_jobs_async.py` to show requesting GPUs with `gpu_count` on a GPU cluster versus whole nodes with `instance_count` on a CPU cluster, and to set the new `priority` property. * Added `sample_pipeline_two_code.py` to demonstrate a producer and consumer using separate local code folders and a mounted file output. * Added `sample_pipeline_dsl.py` to show Python function components and direct pipeline-function job construction. +* Added `sample_pipeline_nested.py` to show a two-command subgraph called from a parent pipeline and connected to an outer command through its exported output. ## 2.1.0 (2026-04-20) diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index 688b3a69637c..cd9a1d9f6212 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -187,6 +187,12 @@ builder. Submit it with `client.pipeline_jobs.create_or_update(job)` for an auto optionally passing `experiment_name="pipeline_samples"`, or use the existing `create_or_update(name=..., job=...)` form. +Call one decorated `@pipeline` function from another to add a nested Pipeline node, +then connect its exported outputs through `stage.outputs.` just like command +outputs. The nested graph is preserved, not flattened; its commands bind to their own +pipeline inputs and exported outputs. See the [nested pipeline sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_nested.py). +Submission requires a service version supporting inline Pipeline component registration. + See the [two-component Python sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py) for a producer and consumer connected through a mounted file. Each function body is packaged into a separate Code folder and runs on the selected compute, not when the graph is built. Component functions must be @@ -203,7 +209,9 @@ its undecorated function, so module globals, sibling Python files, and resources root are available. Define components in import-safe modules separate from submission-time configuration. The selected image must contain a compatible `azure-ai-projects` version and any other imported Python packages; the snapshot does not install dependencies or capture -closure values. Shared code roots are uploaded once per pipeline submission. +closure values. Shared code roots are uploaded once per pipeline submission, including +across nested pipelines. The root job owns all staged Code folders and cleans them up +after code resolution, including when a nested upload fails. The snapshot honors `.amlignore` (or `.gitignore` when no `.amlignore` exists) in each directory, always omits `.env` files and common Python/Git artifacts, and rejects included symlinks. Review the code root before submitting: only files not excluded by these rules are uploaded. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 849056c3c3f7..fa6d43bdac2b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -48,6 +48,7 @@ _validate_command_job, _emit_validation_warnings, _content_hash, + _iter_pipeline_command_components, _get_sorted_streamable_logs, _incremental_print, _wait_before_polling, @@ -252,11 +253,8 @@ async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: """ try: resolved_code: Dict[str, str] = {} - for node_name, node in (job.jobs or {}).items(): - if not isinstance(node, dict) or node.get("type") != "command": - continue - component = node.get("component") - if not isinstance(component, dict) or not isinstance(component.get("code"), str): + for node_name, component in _iter_pipeline_command_components(job.jobs or {}): + if not isinstance(component.get("code"), str): continue code = component["code"] if code not in resolved_code: diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index e7b751cdadb6..1d9169d9cb1d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -184,6 +184,7 @@ def add( outputs: List[_Port], arguments: Dict[str, Any], source: Optional[_ComponentSource], + jobs: Optional[Dict[str, Any]] = None, ) -> SimpleNamespace: name = func.__name__ suffix = 2 @@ -211,49 +212,70 @@ def add( input_type = port.type if port.type in _DATA_PORT_TYPES else AssetTypes.LITERAL bound_inputs[port.name] = Input(type=input_type, value=serialized) - arguments_in_command = " ".join( - [f'"${{{{inputs.{port.name}}}}}"' for port in inputs] - + [f'"${{{{outputs.{port.name}}}}}"' for port in outputs] - ) - if source is None: - code_dir = TemporaryDirectory(prefix="foundry-component-") - self.code_dirs.append(code_dir) - (Path(code_dir.name) / "component.py").write_text(_function_script(func, inputs, outputs), encoding="utf-8") - command = "python component.py " + arguments_in_command + if jobs is not None: + node: Dict[str, Any] = { + "type": "pipeline", + "component": { + "name": name, + "version": "1", + "type": "pipeline", + "inputs": {port.name: {"type": port.type} for port in inputs}, + "outputs": {port.name: {"type": port.type} for port in outputs}, + "jobs": jobs, + }, + "inputs": { + port_name: {"job_input_type": "literal", "value": value.value} + for port_name, value in bound_inputs.items() + }, + "outputs": { + port.name: {"job_output_type": port.type, "mode": port.mode} + for port in outputs + }, + } else: - shared_code_dir = self.code_dirs_by_root.get(source.root) - if shared_code_dir is None: - # pylint: disable-next=consider-using-with - code_dir = TemporaryDirectory(prefix="foundry-component-source-") + arguments_in_command = " ".join( + [f'"${{{{inputs.{port.name}}}}}"' for port in inputs] + + [f'"${{{{outputs.{port.name}}}}}"' for port in outputs] + ) + if source is None: + code_dir = TemporaryDirectory(prefix="foundry-component-") self.code_dirs.append(code_dir) - self.code_dirs_by_root[source.root] = code_dir - _stage_component_source(source.root, Path(code_dir.name)) + (Path(code_dir.name) / "component.py").write_text(_function_script(func, inputs, outputs), encoding="utf-8") + command = "python component.py " + arguments_in_command else: - code_dir = shared_code_dir - if not (Path(code_dir.name) / source.relative_file).is_file(): - raise ValueError(f"Component '{func.__name__}' source file is excluded by its code ignore rules.") - port_spec = ",".join(f"{port.name}:{port.conversion}" for port in inputs + outputs) or "-" - command = f"python {_RUNNER_NAME} {source.module} {func.__name__} {port_spec}" - if arguments_in_command: - command += " " + arguments_in_command - - job = CommandJob( - command=command, - code=code_dir.name, - environment_image_reference=self.image, - compute=self.compute_id, - user_assigned_identity_id=self.identity, - resources=JobResourceConfiguration( - { - "instanceCount": 1, - "instanceType": self.instance_type, - "properties": {"AISuperComputer": {"SLATier": "Premium"}}, - } - ), - inputs=bound_inputs, - outputs={port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs}, - ) - node = PipelineJob._command_node(name, job, self.compute_id) # pylint: disable=protected-access + shared_code_dir = self.code_dirs_by_root.get(source.root) + if shared_code_dir is None: + # pylint: disable-next=consider-using-with + code_dir = TemporaryDirectory(prefix="foundry-component-source-") + self.code_dirs.append(code_dir) + self.code_dirs_by_root[source.root] = code_dir + _stage_component_source(source.root, Path(code_dir.name)) + else: + code_dir = shared_code_dir + if not (Path(code_dir.name) / source.relative_file).is_file(): + raise ValueError(f"Component '{func.__name__}' source file is excluded by its code ignore rules.") + port_spec = ",".join(f"{port.name}:{port.conversion}" for port in inputs + outputs) or "-" + command = f"python {_RUNNER_NAME} {source.module} {func.__name__} {port_spec}" + if arguments_in_command: + command += " " + arguments_in_command + + job = CommandJob( + command=command, + code=code_dir.name, + environment_image_reference=self.image, + compute=self.compute_id, + user_assigned_identity_id=self.identity, + resources=JobResourceConfiguration( + { + "instanceCount": 1, + "instanceType": self.instance_type, + "properties": {"AISuperComputer": {"SLATier": "Premium"}}, + } + ), + inputs=bound_inputs, + outputs={port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs}, + ) + node = PipelineJob._command_node(name, job, self.compute_id) # pylint: disable=protected-access for port in inputs: if port.type not in _DATA_PORT_TYPES: node["component"]["inputs"][port.name]["type"] = port.type @@ -334,10 +356,12 @@ def pipeline( environment_image_reference: str, user_assigned_identity_id: str, instance_type: str, -) -> Callable[[Callable[..., Any]], Callable[..., PipelineJob]]: +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: """Decorate a pipeline builder; calling it returns a native Foundry PipelineJob. Compute, image, identity, and instance type are inherited by each command node. + Calling it inside another pipeline adds a nested Pipeline component and returns + parent-owned output references instead of a standalone job. :keyword compute_id: Compute resource ID inherited by the pipeline nodes. :paramtype compute_id: str @@ -351,49 +375,62 @@ def pipeline( :rtype: callable """ - def decorate(func: Callable[..., Any]) -> Callable[..., PipelineJob]: + def decorate(func: Callable[..., Any]) -> Callable[..., Any]: signature = inspect.signature(func) annotations = get_type_hints(func) @wraps(func) - def build(*args: Any, **kwargs: Any) -> PipelineJob: + def build(*args: Any, **kwargs: Any) -> Union[PipelineJob, SimpleNamespace]: bound = signature.bind(*args, **kwargs) bound.apply_defaults() + parent = _ACTIVE_PIPELINE.get() context = _PipelineContext( compute_id, environment_image_reference, user_assigned_identity_id, instance_type ) + if parent is not None: + context.code_dirs_by_root.update(parent.code_dirs_by_root) job_inputs: Dict[str, Input] = {} + input_ports: List[_Port] = [] references: Dict[str, _InputRef] = {} for name, value in bound.arguments.items(): annotation = annotations.get(name, signature.parameters[name].annotation) if isinstance(annotation, Input): if ( annotation.type != AssetTypes.URI_FILE - or not isinstance(value, Input) - or value.type != AssetTypes.URI_FILE + or ( + parent is None + and (not isinstance(value, Input) or value.type != AssetTypes.URI_FILE) + ) ): raise TypeError(f"Pipeline input '{name}' requires Input(type='uri_file', path=...).") - if not value.path or "://" not in value.path: - raise ValueError( - f"Pipeline input '{name}' requires a remote URI; local files are not supported." - ) - job_inputs[name] = value + if parent is None: + if not value.path or "://" not in value.path: + raise ValueError( + f"Pipeline input '{name}' requires a remote URI; local files are not supported." + ) + job_inputs[name] = value port_type: str = AssetTypes.URI_FILE - elif annotation in _PRIMITIVES and type(value) is annotation: # pylint: disable=unidiomatic-typecheck - job_inputs[name] = Input(type=AssetTypes.LITERAL, value=str(value)) - port_type = _PRIMITIVES[annotation][0] + conversion = "str" + elif annotation in _PRIMITIVES and ( + parent is not None or type(value) is annotation + ): # pylint: disable=unidiomatic-typecheck + if parent is None: + job_inputs[name] = Input(type=AssetTypes.LITERAL, value=str(value)) + port_type, conversion = _PRIMITIVES[annotation] else: raise TypeError(f"Pipeline input '{name}' needs a matching primitive or uri_file Input value.") + input_ports.append(_Port(name, port_type, conversion)) references[name] = _InputRef(context, name, port_type) token = _ACTIVE_PIPELINE.set(context) - job: Optional[PipelineJob] = None + job: Optional[Union[PipelineJob, SimpleNamespace]] = None try: try: result = func(**references) finally: _ACTIVE_PIPELINE.reset(token) job_outputs: Dict[str, Dict[str, Any]] = {} + output_ports: List[_Port] = [] if result is not None: if not isinstance(result, dict): raise TypeError("Pipeline outputs must be returned as a dictionary of node outputs.") @@ -401,22 +438,36 @@ def build(*args: Any, **kwargs: Any) -> PipelineJob: if not isinstance(value, _OutputRef) or value.owner is not context: raise TypeError(f"Pipeline output '{name}' must reference an output from this pipeline.") node_output = context.jobs[value.node]["outputs"][value.name] - if "path" in node_output: + if "path" in node_output or "value" in node_output: raise ValueError( f"Node output '{value.node}.{value.name}' cannot bind to multiple pipeline outputs." ) - node_output["path"] = f"${{{{parent.outputs.{name}}}}}" + binding = f"${{{{parent.outputs.{name}}}}}" + if parent is None: + node_output["path"] = binding + else: + context.jobs[value.node]["outputs"][value.name] = { + "job_output_type": AssetTypes.LITERAL, + "value": binding, + } job_outputs[name] = {"jobOutputType": value.type, "mode": value.mode} - - job = PipelineJob( - display_name=func.__name__, - compute_id=compute_id, - settings={"default_compute": compute_id, "force_rerun": True}, - inputs=job_inputs, - outputs=job_outputs, - jobs=context.jobs, - ) - job._component_code_dirs = context.code_dirs # pylint: disable=protected-access + output_ports.append(_Port(name, value.type, "str", value.mode)) + + if parent is None: + job = PipelineJob( + display_name=func.__name__, + compute_id=compute_id, + settings={"default_compute": compute_id, "force_rerun": True}, + inputs=job_inputs, + outputs=job_outputs, + jobs=context.jobs, + ) + job._component_code_dirs = context.code_dirs # pylint: disable=protected-access + else: + node = parent.add(func, input_ports, output_ports, dict(bound.arguments), None, jobs=context.jobs) + parent.code_dirs.extend(context.code_dirs) + parent.code_dirs_by_root.update(context.code_dirs_by_root) + job = node return job finally: if job is None: diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py index 2dc55cc1cedf..7c28b2945f08 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py @@ -17,6 +17,7 @@ Callable, Dict, Iterable, + Iterator, List, Optional, Set, @@ -179,6 +180,31 @@ def _collect_files(directory: Path, ignore_patterns: List[str]) -> List[Tuple[Pa return sorted(files, key=lambda x: x[1].lower()) +def _iter_pipeline_command_components( + jobs: Dict[str, Any], prefix: str = "" +) -> Iterator[Tuple[str, Dict[str, Any]]]: + """Yield inline command components, including those inside Pipeline components. + + :param jobs: Graph nodes to traverse. + :type jobs: dict[str, Any] + :param prefix: Ancestor node names used to qualify nested nodes. + :type prefix: str + :returns: Qualified node names and their inline component dictionaries. + :rtype: Iterator[tuple[str, dict[str, Any]]] + """ + for name, node in jobs.items(): + if not isinstance(node, dict): + continue + component = node.get("component") + if not isinstance(component, dict): + continue + node_name = f"{prefix}-{name}" if prefix else name + if node.get("type") == "command": + yield node_name, component + elif node.get("type") == "pipeline" and isinstance(component.get("jobs"), dict): + yield from _iter_pipeline_command_components(component["jobs"], node_name) + + def _content_hash(path: Path) -> str: """Compute a truncated SHA-256 content hash for a file or directory. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index 961fc468e8fb..6d22bde39a11 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -49,6 +49,7 @@ _validate_command_job, _emit_validation_warnings, _content_hash, + _iter_pipeline_command_components, _get_sorted_streamable_logs, _incremental_print, _wait_before_polling, @@ -255,11 +256,8 @@ def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: """ try: resolved_code: Dict[str, str] = {} - for node_name, node in (job.jobs or {}).items(): - if not isinstance(node, dict) or node.get("type") != "command": - continue - component = node.get("component") - if not isinstance(component, dict) or not isinstance(component.get("code"), str): + for node_name, component in _iter_pipeline_command_components(job.jobs or {}): + if not isinstance(component.get("code"), str): continue code = component["code"] if code not in resolved_code: diff --git a/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_nested.py b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_nested.py new file mode 100644 index 000000000000..91f74f651ea0 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_nested.py @@ -0,0 +1,74 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Compose a two-step Pipeline component inside a parent pipeline. + +Set FOUNDRY_PROJECT_ENDPOINT, JOB_COMPUTE_ID, JOB_ENVIRONMENT_IMAGE, +JOB_NODE_UAI_RESOURCE_ID, and JOB_INSTANCE_TYPE before running. The service must +support inline Pipeline component registration. Running this sample uploads +three Code folders and submits a job; the nested graph is not flattened. +""" + +import os +from pathlib import Path + +from azure.ai.projects import AIProjectClient +from azure.ai.projects.dsl import Input, Output, component, pipeline +from azure.identity import AzureCliCredential + + +@component +def produce(text: str, message: Output(type="uri_file")) -> None: # type: ignore[valid-type] + Path(message).write_text(text, encoding="utf-8") + + +@component +def normalize(message: Input(type="uri_file"), normalized: Output(type="uri_file")) -> None: # type: ignore[valid-type] + Path(normalized).write_text(Path(message).read_text(encoding="utf-8").strip().upper(), encoding="utf-8") + + +@component +def consume(message: Input(type="uri_file"), receipt: Output(type="uri_file")) -> None: # type: ignore[valid-type] + Path(receipt).write_text(Path(message).read_text(encoding="utf-8"), encoding="utf-8") + + +_RUNTIME = { + "compute_id": os.environ["JOB_COMPUTE_ID"], + "environment_image_reference": os.environ["JOB_ENVIRONMENT_IMAGE"], + "user_assigned_identity_id": os.environ["JOB_NODE_UAI_RESOURCE_ID"], + "instance_type": os.environ["JOB_INSTANCE_TYPE"], +} + + +@pipeline(**_RUNTIME) +def text_subgraph(text: str): + first = produce(text=text) + second = normalize(message=first.outputs.message) + return {"message": second.outputs.normalized} + + +@pipeline(**_RUNTIME) +def workflow(text: str): + stage = text_subgraph(text=text) + final = consume(message=stage.outputs.message) + return {"receipt": final.outputs.receipt} + + +def main() -> None: + job = workflow(text="hello") + with ( + AzureCliCredential() as credential, + AIProjectClient( + endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"], + credential=credential, + allow_preview=True, + retry_total=0, + ) as client, + ): + created = client.pipeline_jobs.create_or_update(job, experiment_name="pipeline_samples") + print(f"Submitted {created.name}: {created.id} (status: {created.status})") + + +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 77ab6a18eb21..707fa0666a4b 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -44,6 +44,12 @@ _ENDPOINT = "https://fake-account.services.ai.azure.com/api/projects/fake-project" _COMPUTE = "/subscriptions/test/resourceGroups/test/providers/Microsoft.CognitiveServices/accounts/test/computes/cpu" +_DSL_RUNTIME = { + "compute_id": _COMPUTE, + "environment_image_reference": "example.azurecr.io/train:latest", + "user_assigned_identity_id": "/subscriptions/test/identities/hello", + "instance_type": "Singularity.D4_v3", +} _TWO_CODE_BUILDER = runpy.run_path( str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / "sample_pipeline_two_code.py") )["build_job"] @@ -726,29 +732,336 @@ async def test_pipeline_jobs_async_create_get_and_list() -> None: _assert_pipeline_jobs_requests(transport.requests, expected) -def _dsl_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: +def _dsl_job(monkeypatch: pytest.MonkeyPatch, sample_name: str = "sample_pipeline_dsl.py") -> PipelineJob: monkeypatch.setenv("JOB_COMPUTE_ID", _COMPUTE) monkeypatch.setenv("JOB_ENVIRONMENT_IMAGE", "example.azurecr.io/train:latest") monkeypatch.setenv("JOB_NODE_UAI_RESOURCE_ID", "/subscriptions/test/identities/hello") monkeypatch.setenv("JOB_INSTANCE_TYPE", "Singularity.D4_v3") - sample = runpy.run_path(str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / "sample_pipeline_dsl.py")) + sample = runpy.run_path(str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / sample_name)) return sample["workflow"](text="hello") -def _source_dsl_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: +def _source_dsl_job(monkeypatch: pytest.MonkeyPatch, *, nested: bool = False) -> PipelineJob: monkeypatch.setenv("JOB_COMPUTE_ID", _COMPUTE) monkeypatch.setenv("JOB_ENVIRONMENT_IMAGE", "example.azurecr.io/train:latest") monkeypatch.setenv("JOB_NODE_UAI_RESOURCE_ID", "/subscriptions/test/identities/hello") monkeypatch.setenv("JOB_INSTANCE_TYPE", "Singularity.D4_v3") sample = Path(__file__).resolve().parents[2] / "samples" / "jobs" / "pipeline_source" monkeypatch.syspath_prepend(str(sample)) - workflow = runpy.run_path(str(sample / "sample_pipeline_source.py"))["workflow"] - return workflow(text=" world ") + source = runpy.run_path(str(sample / "sample_pipeline_source.py")) + if not nested: + return source["workflow"](text=" world ") + + @dsl.pipeline(**_DSL_RUNTIME) + def text_subgraph(text: str): + stage = source["workflow"](text=text) + return {"message": stage.outputs.receipt} + + @dsl.pipeline(**_DSL_RUNTIME) + def parent_workflow(text: str): + stage = text_subgraph(text=text) + final = source["consume"](message=stage.outputs.message) + return {"receipt": final.outputs.receipt} + + return parent_workflow(text=" world ") + + +def _dsl_components(jobs: dict[str, Any], prefix: str = "") -> dict[str, dict[str, Any]]: + components: dict[str, dict[str, Any]] = {} + for name, node in jobs.items(): + component = node["component"] + if not isinstance(component, dict): + continue + qualified_name = f"{prefix}{name}" + if node["type"] == "pipeline": + components.update(_dsl_components(component["jobs"], qualified_name + "-")) + elif node["type"] == "command": + components[qualified_name] = component + return components def _dsl_code_paths(job: PipelineJob) -> dict[str, Path]: assert job.jobs is not None - return {name: Path(node["component"]["code"]) for name, node in job.jobs.items()} + return {name: Path(component["code"]) for name, component in _dsl_components(job.jobs).items()} + + +def test_dsl_nested_pipeline_preserves_graph_and_boundary_bindings( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + job = _dsl_job(monkeypatch, "sample_pipeline_nested.py") + paths = _dsl_code_paths(job) + try: + assert isinstance(job, PipelineJob) + assert list(job.jobs) == ["text_subgraph", "consume"] + stage = job.jobs["text_subgraph"] + assert stage["type"] == "pipeline" + assert stage["component"]["name"] == "text_subgraph" + assert stage["component"]["version"] == "1" + assert stage["component"]["type"] == "pipeline" + assert stage["component"]["inputs"] == {"text": {"type": "string"}} + assert stage["component"]["outputs"] == {"message": {"type": "uri_file"}} + assert stage["inputs"] == {"text": {"job_input_type": "literal", "value": "${{parent.inputs.text}}"}} + assert stage["outputs"] == {"message": {"job_output_type": "uri_file", "mode": "ReadWriteMount"}} + children = stage["component"]["jobs"] + assert list(children) == ["produce", "normalize"] + assert children["produce"]["inputs"]["text"]["value"] == "${{parent.inputs.text}}" + assert children["normalize"]["inputs"]["message"]["value"] == "${{parent.jobs.produce.outputs.message}}" + assert children["normalize"]["outputs"]["normalized"] == { + "job_output_type": "literal", + "value": "${{parent.outputs.message}}", + } + assert job.jobs["consume"]["inputs"]["message"]["value"] == ( + "${{parent.jobs.text_subgraph.outputs.message}}" + ) + assert job.jobs["consume"]["outputs"]["receipt"] == { + "job_output_type": "uri_file", + "mode": "ReadWriteMount", + "path": "${{parent.outputs.receipt}}", + } + assert job.outputs == {"receipt": {"jobOutputType": "uri_file", "mode": "ReadWriteMount"}} + assert set(paths) == {"text_subgraph-produce", "text_subgraph-normalize", "consume"} + assert len(job._component_code_dirs) == 3 + + message, normalized, receipt = (tmp_path / name for name in ("message.txt", "normalized.txt", "receipt.txt")) + for node, arguments in ( + ("text_subgraph-produce", [" hello ", str(message)]), + ("text_subgraph-normalize", [str(message), str(normalized)]), + ("consume", [str(normalized), str(receipt)]), + ): + subprocess.run( + [sys.executable, str(paths[node] / "component.py"), *arguments], + check=True, + capture_output=True, + text=True, + ) + assert receipt.read_text(encoding="utf-8") == "HELLO" + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + sample = runpy.run_path( + str(Path(__file__).resolve().parents[2] / "samples" / "jobs" / "sample_pipeline_nested.py") + ) + standalone = sample["text_subgraph"](text="hello") + try: + assert isinstance(standalone, PipelineJob) + assert list(standalone.jobs) == ["produce", "normalize"] + assert standalone.jobs["normalize"]["outputs"]["normalized"] == { + "job_output_type": "uri_file", + "mode": "ReadWriteMount", + "path": "${{parent.outputs.message}}", + } + finally: + for directory in standalone._component_code_dirs: + directory.cleanup() + + +def test_dsl_nested_pipeline_accepts_parent_node_outputs_and_repeated_calls() -> None: + @dsl.component + def produce(text: str, message: dsl.Output(type="uri_file")) -> None: + Path(message).write_text(text, encoding="utf-8") + + @dsl.component + def relay(message: dsl.Input(type="uri_file"), result: dsl.Output(type="uri_file")) -> None: + Path(result).write_text(Path(message).read_text(encoding="utf-8"), encoding="utf-8") + + @dsl.pipeline(**_DSL_RUNTIME) + def subgraph(source: dsl.Input(type="uri_file")): + return {"file": relay(message=source).outputs.result} + + @dsl.pipeline(**_DSL_RUNTIME) + def workflow(text: str): + first = produce(text=text) + stage = subgraph(source=first.outputs.message) + repeated = subgraph(source=stage.outputs.file) + return {"receipt": repeated.outputs.file} + + job = workflow(text="hello") + try: + assert list(job.jobs) == ["produce", "subgraph", "subgraph_2"] + first, second = job.jobs["subgraph"], job.jobs["subgraph_2"] + assert first["inputs"]["source"]["value"] == "${{parent.jobs.produce.outputs.message}}" + assert second["inputs"]["source"]["value"] == "${{parent.jobs.subgraph.outputs.file}}" + assert first["component"]["inputs"] == {"source": {"type": "uri_file"}} + assert first["component"]["jobs"]["relay"]["inputs"]["message"]["value"] == "${{parent.inputs.source}}" + assert first["component"]["jobs"]["relay"]["outputs"]["result"] == { + "job_output_type": "literal", + "value": "${{parent.outputs.file}}", + } + assert second["outputs"]["file"]["path"] == "${{parent.outputs.receipt}}" + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + +def test_dsl_nested_authoring_failures_preserve_parent_sources_and_cleanup_new_directories( + monkeypatch: pytest.MonkeyPatch, +) -> None: + sample = Path(__file__).resolve().parents[2] / "samples" / "jobs" / "pipeline_source" + monkeypatch.syspath_prepend(str(sample)) + source = importlib.import_module("steps.source_pipeline_components") + original_directory = dsl.TemporaryDirectory + paths: list[Path] = [] + + def temporary_directory(*args: Any, **kwargs: Any) -> Any: + directory = original_directory(*args, **kwargs) + paths.append(Path(directory.name)) + return directory + + monkeypatch.setattr(dsl, "TemporaryDirectory", temporary_directory) + + @dsl.component + def fresh(text: str, result: dsl.Output(type="uri_file")) -> None: + Path(result).write_text(text, encoding="utf-8") + + @dsl.pipeline(**_DSL_RUNTIME) + def broken(text: str): + source.produce(text=text) + fresh(text=text) + raise RuntimeError("child authoring failed") + + @dsl.pipeline(**_DSL_RUNTIME) + def workflow(text: str): + first = source.produce(text=text) + with pytest.raises(RuntimeError, match="child authoring failed"): + broken(text=text) + final = source.consume(message=first.outputs.message) + return {"receipt": final.outputs.receipt} + + job = workflow(text="hello") + try: + assert list(job.jobs) == ["produce", "consume"] + assert len(paths) == 2 + assert paths[0].is_dir() + assert not paths[1].exists() + assert len(job._component_code_dirs) == 1 + assert set(_dsl_code_paths(job).values()) == {paths[0]} + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + @dsl.pipeline(**_DSL_RUNTIME) + def failing_parent(text: str): + workflow(text=text) + raise RuntimeError("parent authoring failed") + + with pytest.raises(RuntimeError, match="parent authoring failed"): + failing_parent(text="hello") + assert len(paths) == 4 + assert all(not path.exists() for path in paths) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("surface", ["jobs", "pipeline_jobs"]) +@pytest.mark.parametrize("source_backed", [False, True], ids=["function-body", "source-backed"]) +@pytest.mark.parametrize("outcome", ["uploaded", "cached", "upload_failed", "submit_failed"]) +async def test_dsl_nested_pipeline_resolves_code_and_cleans_all_submission_paths( + monkeypatch: pytest.MonkeyPatch, asynchronous: bool, surface: str, source_backed: bool, outcome: str +) -> None: + job = ( + _source_dsl_job(monkeypatch, nested=True) + if source_backed + else _dsl_job(monkeypatch, "sample_pipeline_nested.py") + ) + paths = _dsl_code_paths(job) + snapshots = set(paths.values()) + versions = {_content_hash(path) for path in snapshots} + lookups: list[tuple[str, str]] = [] + uploads: list[str] = [] + registered = {"type": "pipeline", "component": "azureml:registered-pipeline:1"} + registered_command = {"type": "command", "component": "azureml:registered-command:1"} + job.jobs["registered"] = registered + job.jobs["registered_command"] = registered_command + + def get(*, name: str, version: str) -> DatasetVersion: + assert all(path.is_dir() for path in snapshots) + lookups.append((name, version)) + if outcome == "cached": + return _uploaded_code(name, version) + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + assert all(path.is_dir() for path in snapshots) + if source_backed: + assert (Path(folder) / "steps" / "helpers.py").is_file() + uploads.append(folder) + if outcome == "upload_failed" and len(uploads) == len(snapshots): + raise RuntimeError("upload_failed") + return _uploaded_code(name, version) + + async def get_async(**kwargs: Any) -> DatasetVersion: + return get(**kwargs) + + async def upload_folder_async(**kwargs: Any) -> DatasetVersion: + return upload_folder(**kwargs) + + if asynchronous: + async_transport = _AsyncTransport([_response("Pipeline")]) + requests = async_transport.requests + + async def send_async(request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + requests.append(request) + raise RuntimeError("submit_failed") + + if outcome == "submit_failed": + monkeypatch.setattr(async_transport, "send", send_async) + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=async_transport # type: ignore[arg-type] + ) as client: + operations = client.beta.jobs if surface == "jobs" else client.pipeline_jobs + monkeypatch.setattr(operations._datasets, "get", get_async) + monkeypatch.setattr(operations._datasets, "upload_folder", upload_folder_async) + if outcome.endswith("_failed"): + with pytest.raises(RuntimeError, match=outcome): + await operations.create_or_update(name="nested", job=job) + else: + assert isinstance(await operations.create_or_update(name="nested", job=job), PipelineJob) + else: + sync_transport = _Transport([_response("Pipeline")]) + requests = sync_transport.requests + + def send(request: HttpRequest, **kwargs: Any) -> HttpResponse: + requests.append(request) + raise RuntimeError("submit_failed") + + if outcome == "submit_failed": + monkeypatch.setattr(sync_transport, "send", send) + with AIProjectClient( + endpoint=_ENDPOINT, credential=_Credential(), transport=sync_transport # type: ignore[arg-type] + ) as sync_client: + sync_operations = sync_client.beta.jobs if surface == "jobs" else sync_client.pipeline_jobs + monkeypatch.setattr(sync_operations._datasets, "get", get) + monkeypatch.setattr(sync_operations._datasets, "upload_folder", upload_folder) + if outcome.endswith("_failed"): + with pytest.raises(RuntimeError, match=outcome): + sync_operations.create_or_update(name="nested", job=job) + else: + assert isinstance(sync_operations.create_or_update(name="nested", job=job), PipelineJob) + + assert all(not path.exists() for path in snapshots) + assert job._component_code_dirs == [] + assert len(snapshots) == (1 if source_backed else 3) + assert len(lookups) == len(snapshots) + assert {version for _, version in lookups} == versions + assert len(uploads) == (0 if outcome == "cached" else len(snapshots)) + if outcome == "upload_failed": + assert requests == [] + else: + assert len(requests) == 1 + request = requests[0] + assert request.method == "PUT" + assert urlparse(request.url).path.endswith(f"/{surface}/nested") + assert request.headers["Foundry-Features"] == "Jobs=V1Preview" + assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] + properties = json.loads(request.body)["properties"] + components = _dsl_components(properties["jobs"]) + assert len(components) == 3 + assert {component["code"] for component in components.values()} == { + _code_uri(name, version) for name, version in lookups + } + assert properties["jobs"]["registered"] == registered + assert properties["jobs"]["registered_command"] == registered_command def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: From 2db625432e2fbc41c5780a3c7636d2bf267491af Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Mon, 2 Nov 2026 22:03:04 -0800 Subject: [PATCH 34/52] Preserve explicit compute selection in nested pipelines Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 2 +- sdk/ai/azure-ai-projects/README.md | 1 + .../azure/ai/projects/dsl.py | 15 ++++-- .../tests/jobs/test_pipeline_jobs.py | 50 +++++++++++++++++++ 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index f00066aebbc5..50210d8be9b6 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -28,7 +28,7 @@ * When constructing `PipelineJob`, `jobs` accepts `CommandJob` instances with value-bound literal, `uri_file`, and `uri_folder` inputs, code, and outputs and converts them to inline command nodes. Raw graph dictionaries remain supported for other node features. * Added `azure.ai.projects.dsl` function-body `@component` and `@pipeline` authoring for native two-step PipelineJobs. Calling the pipeline function builds its graph, packages each Python component body as its own executable Code folder, binds typed inputs and file outputs, and supports repeated component calls. `.pipeline_jobs.create_or_update(pipeline_job)` generates a unique name (sync and async), while the explicit-name form remains available. * Added opt-in `@component(code=...)` source-backed components for local helper functions, sibling modules, and resources. Code roots are snapshot with ignore rules before upload and shared by nodes in the same pipeline. Executing these components requires the image to contain a compatible `azure-ai-projects` package and other imported dependencies; bare `@component` keeps its existing standalone execution behavior. -* Added nested `@pipeline` composition with parent-owned input/output bindings and preserved Pipeline component hierarchy. Nested command source folders are resolved on both job submission surfaces, shared code roots are uploaded once across the graph, and the root job owns staged-folder cleanup. Submission requires service support for inline Pipeline component registration. +* Added nested `@pipeline` composition with parent-owned input/output bindings, preserved Pipeline component hierarchy, and explicit nested compute selection. Nested command source folders are resolved on both job submission surfaces, shared code roots are uploaded once across the graph, and the root job owns staged-folder cleanup. Submission requires service support for inline Pipeline component registration. * New optional `priority` property on class `CommandJob`, typed as the new `JobPriority` enum (`LOW`, `MID`, `HIGH`). If omitted, the service defaults to `LOW`. * New optional `experiment_name` property on class `CommandJob`, used to group related runs. If omitted, the service uses `Default`. * `.beta.jobs.create_or_update` now emits a `UserWarning` when a newly created job sets `resources.instance_type`, `resources.shm_size`, `resources.docker_args` or `resources.properties`. The service infers these from the target compute and ignores them, so they were previously dropped silently. The call still succeeds, and jobs retrieved with `.beta.jobs.get` are not affected. diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index cd9a1d9f6212..9b01c5c9c4c7 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -191,6 +191,7 @@ Call one decorated `@pipeline` function from another to add a nested Pipeline no then connect its exported outputs through `stage.outputs.` just like command outputs. The nested graph is preserved, not flattened; its commands bind to their own pipeline inputs and exported outputs. See the [nested pipeline sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_nested.py). +If the nested decorator selects a different compute resource ID, its Pipeline invocation retains that selection instead of inheriting the parent default. Submission requires a service version supporting inline Pipeline component registration. See the [two-component Python sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py) for a producer and diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 1d9169d9cb1d..e4287741f224 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -184,7 +184,7 @@ def add( outputs: List[_Port], arguments: Dict[str, Any], source: Optional[_ComponentSource], - jobs: Optional[Dict[str, Any]] = None, + pipeline_context: Optional["_PipelineContext"] = None, ) -> SimpleNamespace: name = func.__name__ suffix = 2 @@ -212,7 +212,7 @@ def add( input_type = port.type if port.type in _DATA_PORT_TYPES else AssetTypes.LITERAL bound_inputs[port.name] = Input(type=input_type, value=serialized) - if jobs is not None: + if pipeline_context is not None: node: Dict[str, Any] = { "type": "pipeline", "component": { @@ -221,7 +221,7 @@ def add( "type": "pipeline", "inputs": {port.name: {"type": port.type} for port in inputs}, "outputs": {port.name: {"type": port.type} for port in outputs}, - "jobs": jobs, + "jobs": pipeline_context.jobs, }, "inputs": { port_name: {"job_input_type": "literal", "value": value.value} @@ -232,6 +232,8 @@ def add( for port in outputs }, } + if pipeline_context.compute_id != self.compute_id: + node["compute"] = pipeline_context.compute_id else: arguments_in_command = " ".join( [f'"${{{{inputs.{port.name}}}}}"' for port in inputs] @@ -361,7 +363,8 @@ def pipeline( Compute, image, identity, and instance type are inherited by each command node. Calling it inside another pipeline adds a nested Pipeline component and returns - parent-owned output references instead of a standalone job. + parent-owned output references instead of a standalone job. A different nested + compute resource ID is retained on that Pipeline node. :keyword compute_id: Compute resource ID inherited by the pipeline nodes. :paramtype compute_id: str @@ -464,7 +467,9 @@ def build(*args: Any, **kwargs: Any) -> Union[PipelineJob, SimpleNamespace]: ) job._component_code_dirs = context.code_dirs # pylint: disable=protected-access else: - node = parent.add(func, input_ports, output_ports, dict(bound.arguments), None, jobs=context.jobs) + node = parent.add( + func, input_ports, output_ports, dict(bound.arguments), None, pipeline_context=context + ) parent.code_dirs.extend(context.code_dirs) parent.code_dirs_by_root.update(context.code_dirs_by_root) job = node diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 707fa0666a4b..6c0419698d16 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -894,6 +894,56 @@ def workflow(text: str): directory.cleanup() +@pytest.mark.parametrize("surface", ["jobs", "pipeline_jobs"]) +@pytest.mark.parametrize("different_compute", [False, True], ids=["inherited", "explicit"]) +def test_dsl_nested_pipeline_preserves_compute( + monkeypatch: pytest.MonkeyPatch, surface: str, different_compute: bool +) -> None: + inner_compute = _COMPUTE + "-nested" if different_compute else _COMPUTE + + @dsl.component + def write(text: str, message: dsl.Output(type="uri_file")) -> None: + Path(message).write_text(text, encoding="utf-8") + + @dsl.pipeline(**{**_DSL_RUNTIME, "compute_id": inner_compute}) + def text_subgraph(text: str): + return {"message": write(text=text).outputs.message} + + @dsl.pipeline(**_DSL_RUNTIME) + def workflow(text: str): + return {"receipt": text_subgraph(text=text).outputs.message} + + job = workflow(text="hello") + paths = _dsl_code_paths(job) + transport = _Transport([_response("Pipeline")]) + + def get(*, name: str, version: str) -> DatasetVersion: + return _uploaded_code(name, version) + + try: + assert job.compute_id == _COMPUTE + assert job.settings["default_compute"] == _COMPUTE + stage = job.jobs["text_subgraph"] + expected_compute = {"compute": inner_compute} if different_compute else {} + assert {key: value for key, value in stage.items() if key == "compute"} == expected_compute + assert "compute" not in stage["component"]["jobs"]["write"] + with AIProjectClient( + endpoint=_ENDPOINT, credential=_Credential(), transport=transport # type: ignore[arg-type] + ) as client: + operations = client.beta.jobs if surface == "jobs" else client.pipeline_jobs + monkeypatch.setattr(operations._datasets, "get", get) + operations.create_or_update(name="nested-compute", job=job) + properties = json.loads(transport.requests[0].body)["properties"] + wire_stage = properties["jobs"]["text_subgraph"] + assert {key: value for key, value in wire_stage.items() if key == "compute"} == expected_compute + assert properties["computeId"] == _COMPUTE + assert properties["settings"]["default_compute"] == _COMPUTE + assert all(not path.exists() for path in paths.values()) + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + def test_dsl_nested_authoring_failures_preserve_parent_sources_and_cleanup_new_directories( monkeypatch: pytest.MonkeyPatch, ) -> None: From 5619eee362ed7d07e986ce1afe40b6485a2dd90b Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Mon, 2 Nov 2026 23:31:41 -0800 Subject: [PATCH 35/52] Route Pipeline Jobs facade through existing Jobs ingress Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../operations/_patch_pipeline_jobs_async.py | 28 ++++++++++--------- .../operations/_patch_pipeline_jobs.py | 28 ++++++++++--------- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py index 454484ef8dba..4a9b3761acb3 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py @@ -15,11 +15,12 @@ from azure.core.tracing.decorator_async import distributed_trace_async from .._configuration import AIProjectClientConfiguration +from ._operations import BetaJobsOperations as _GeneratedJobsOperations from ._operations import PipelineJobsOperations as _GeneratedPipelineJobsOperations from ._patch_datasets_async import DatasetsOperations from ._patch_jobs_async import JobsOperations as _BetaJobsOperations -from ...models._enums import ListViewType, _FoundryFeaturesOptInKeys -from ...models._models import PipelineJobResource as _RestPipelineJobResource +from ...models._enums import JobType, ListViewType, _FoundryFeaturesOptInKeys +from ...models._models import Job as _RestJob from ...models._patch_jobs import PipelineJob, _from_rest_pipeline_job _logger = logging.getLogger(__name__) @@ -28,8 +29,8 @@ class PipelineJobsOperations(_GeneratedPipelineJobsOperations): """Async Pipeline-only operations exposed through ``client.pipeline_jobs``. - The dedicated public ``/pipeline_jobs`` ingress forwards to the existing MFE - Pipeline implementation. Asset registration is intentionally shared with + This pipeline-only facade uses the existing ``/jobs`` REST operations. + Asset registration is intentionally shared with ``client.beta.jobs`` so both surfaces produce identical Code identities. .. warning:: @@ -48,12 +49,12 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: original_config = self._config self._config = copy(original_config) self._config.api_version = "2026-01-15-preview" + self._jobs = _GeneratedJobsOperations(self._client, self._config, self._serialize, self._deserialize) self._datasets = DatasetsOperations( self._client, original_config, self._serialize, self._deserialize ) - # Keep route-specific request handling in the generated Pipeline Jobs class, - # while reusing the proven local-asset contract from beta.jobs. + # Reuse /jobs transport without exposing its Command-only methods on this facade. async def _resolve_asset_uri( self, uri: str, @@ -92,10 +93,11 @@ def list( """ self._inject_preview_header(kwargs) - def _convert_page(page: List[_RestPipelineJobResource]) -> List[PipelineJob]: + def _convert_page(page: List[_RestJob]) -> List[PipelineJob]: return [_from_rest_pipeline_job(item) for item in page] - return super().list( + return self._jobs.list( + job_type=JobType.PIPELINE, tag=tag, list_view_type=list_view_type, properties=properties, @@ -114,7 +116,7 @@ async def get(self, name: str, **kwargs: Any) -> PipelineJob: # type: ignore[ov :raises ~azure.core.exceptions.HttpResponseError: """ self._inject_preview_header(kwargs) - return _from_rest_pipeline_job(await super().get(name=name, **kwargs)) + return _from_rest_pipeline_job(await self._jobs.get(name=name, **kwargs)) @overload # type: ignore[override] async def create_or_update( @@ -145,7 +147,7 @@ async def create_or_update( # type: ignore[override] experiment_name: Optional[str] = None, **kwargs: Any, ) -> PipelineJob: - """Create or update a Pipeline Job through the dedicated ingress. + """Create or update a Pipeline Job through the existing Jobs ingress. :param name: The Pipeline Job name, or a PipelineJob for an autogenerated name. :type name: str or ~azure.ai.projects.models.PipelineJob @@ -182,15 +184,15 @@ async def create_or_update( # type: ignore[override] await self._resolve_pipeline_code(name, job) self._inject_preview_header(kwargs) _logger.debug( - "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /pipeline_jobs.", + "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /jobs.", name, len(job.jobs or {}), ) # The generated wire contract retains the polymorphic resource envelope # so /jobs keeps both Command and Pipeline discriminator mappings. - rest_body = _RestPipelineJobResource(properties=job) + rest_body = _RestJob(properties=job) return _from_rest_pipeline_job( - await super().create_or_update(name=name, job=rest_body, **kwargs) + await self._jobs.create_or_update(name=name, job=rest_body, **kwargs) ) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py index 365a2cdeda69..da5ce0f5f77a 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py @@ -15,11 +15,12 @@ from azure.core.tracing.decorator import distributed_trace from .._configuration import AIProjectClientConfiguration +from ._operations import BetaJobsOperations as _GeneratedJobsOperations from ._operations import PipelineJobsOperations as _GeneratedPipelineJobsOperations from ._patch_datasets import DatasetsOperations from ._patch_jobs import JobsOperations as _BetaJobsOperations -from ..models._enums import ListViewType, _FoundryFeaturesOptInKeys -from ..models._models import PipelineJobResource as _RestPipelineJobResource +from ..models._enums import JobType, ListViewType, _FoundryFeaturesOptInKeys +from ..models._models import Job as _RestJob from ..models._patch_jobs import PipelineJob, _from_rest_pipeline_job _logger = logging.getLogger(__name__) @@ -28,8 +29,8 @@ class PipelineJobsOperations(_GeneratedPipelineJobsOperations): """Pipeline-only operations exposed through ``client.pipeline_jobs``. - The dedicated public ``/pipeline_jobs`` ingress forwards to the existing MFE - Pipeline implementation. Asset registration is intentionally shared with + This pipeline-only facade uses the existing ``/jobs`` REST operations. + Asset registration is intentionally shared with ``client.beta.jobs`` so both surfaces produce identical Code identities. .. warning:: @@ -48,12 +49,12 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: original_config = self._config self._config = copy(original_config) self._config.api_version = "2026-01-15-preview" + self._jobs = _GeneratedJobsOperations(self._client, self._config, self._serialize, self._deserialize) self._datasets = DatasetsOperations( self._client, original_config, self._serialize, self._deserialize ) - # Keep route-specific request handling in the generated Pipeline Jobs class, - # while reusing the proven local-asset contract from beta.jobs. + # Reuse /jobs transport without exposing its Command-only methods on this facade. def _resolve_asset_uri( self, uri: str, @@ -91,10 +92,11 @@ def list( """ self._inject_preview_header(kwargs) - def _convert_page(page: List[_RestPipelineJobResource]) -> List[PipelineJob]: + def _convert_page(page: List[_RestJob]) -> List[PipelineJob]: return [_from_rest_pipeline_job(item) for item in page] - return super().list( + return self._jobs.list( + job_type=JobType.PIPELINE, tag=tag, list_view_type=list_view_type, properties=properties, @@ -113,7 +115,7 @@ def get(self, name: str, **kwargs: Any) -> PipelineJob: # type: ignore[override :raises ~azure.core.exceptions.HttpResponseError: """ self._inject_preview_header(kwargs) - return _from_rest_pipeline_job(super().get(name=name, **kwargs)) + return _from_rest_pipeline_job(self._jobs.get(name=name, **kwargs)) @overload # type: ignore[override] def create_or_update( @@ -144,7 +146,7 @@ def create_or_update( # type: ignore[override] experiment_name: Optional[str] = None, **kwargs: Any, ) -> PipelineJob: - """Create or update a Pipeline Job through the dedicated ingress. + """Create or update a Pipeline Job through the existing Jobs ingress. :param name: The Pipeline Job name, or a PipelineJob for an autogenerated name. :type name: str or ~azure.ai.projects.models.PipelineJob @@ -181,15 +183,15 @@ def create_or_update( # type: ignore[override] self._resolve_pipeline_code(name, job) self._inject_preview_header(kwargs) _logger.debug( - "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /pipeline_jobs.", + "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /jobs.", name, len(job.jobs or {}), ) # The generated wire contract retains the polymorphic resource envelope # so /jobs keeps both Command and Pipeline discriminator mappings. - rest_body = _RestPipelineJobResource(properties=job) + rest_body = _RestJob(properties=job) return _from_rest_pipeline_job( - super().create_or_update(name=name, job=rest_body, **kwargs) + self._jobs.create_or_update(name=name, job=rest_body, **kwargs) ) From c693a82fb5ad81c50522f167c85b753abd8ec5b7 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Wed, 4 Nov 2026 20:15:53 -0800 Subject: [PATCH 36/52] Register authored Pipeline Command components before job submission Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 1 + sdk/ai/azure-ai-projects/README.md | 7 + .../aio/operations/_patch_jobs_async.py | 37 +- .../operations/_patch_pipeline_jobs_async.py | 12 +- ...eline_component_registration_operations.py | 164 ++ .../ai/projects/operations/_patch_jobs.py | 37 +- .../operations/_patch_pipeline_jobs.py | 12 +- ...eline_component_registration_operations.py | 196 ++ .../test_pipeline_component_registration.py | 336 +++ .../component-registration/.gitignore | 4 + .../emitter-package-lock.json | 2388 +++++++++++++++++ .../emitter-package.json | 7 + .../component-registration/generate.ps1 | 28 + .../ai-foundry/data-plane/Foundry/client.tsp | 7 + .../ai-foundry/data-plane/Foundry/main.tsp | 31 + .../data-plane/Foundry/tspconfig.yaml | 15 + .../component-registration/tsp-location.yaml | 7 + 17 files changed, 3273 insertions(+), 16 deletions(-) create mode 100644 sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py create mode 100644 sdk/ai/azure-ai-projects/azure/ai/projects/operations/_pipeline_component_registration_operations.py create mode 100644 sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/.gitignore create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package-lock.json create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package.json create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/generate.ps1 create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/client.tsp create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/main.tsp create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/tspconfig.yaml create mode 100644 sdk/ai/azure-ai-projects/typespec/component-registration/tsp-location.yaml diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 25f354a62ad8..d2c92b6ca9d4 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -69,6 +69,7 @@ Breaking changes in beta classes: ### Bugs Fixed +* Pipeline submissions register top-level inline Command components after uploading their Code and submit the returned opaque component IDs. Registration failures prevent job submission, and the original authored components remain reusable. * Fixed telemetry instrumentor to correctly call is_recording() as a method on spans, ensuring non-recording spans are properly skipped (e.g., when sampling is configured) ([GitHub issue 46544](https://github.com/Azure/azure-sdk-for-python/issues/46544)). * Fixed `load_job` dropping the `outputs` block of a job YAML file. Unlike `inputs`, outputs were not converted into `Output` instances, so a YAML file using the documented snake_case field names (for example `asset_name`) was serialized with those names verbatim instead of their wire names, and the values never reached the service. Outputs are now converted in the same way as inputs. * Fixed `ModuleNotFoundError: No module named 'httpx'` when installing the package into a clean environment. `httpx` is imported directly by the client but was only ever satisfied transitively through `openai`; `openai` 3.0.0 replaced that dependency with `httpx2`, so `httpx` stopped being installed. `httpx` is now declared explicitly, and `openai` is capped below 3.0.0 because the client still passes an `httpx.Client` to `OpenAI(http_client=...)`. diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md index 688b3a69637c..af1a51abe4ce 100644 --- a/sdk/ai/azure-ai-projects/README.md +++ b/sdk/ai/azure-ai-projects/README.md @@ -187,6 +187,13 @@ builder. Submit it with `client.pipeline_jobs.create_or_update(job)` for an auto optionally passing `experiment_name="pipeline_samples"`, or use the existing `create_or_update(name=..., job=...)` form. +Submission uploads local Code first, then registers each top-level inline Command component +using its existing name and version. The submitted graph contains the service's opaque +`componentId`; the authored component remains reusable. Registration errors prevent job +submission, with no inline fallback or default GET. Existing registered references are +preserved. This requires the project's Component PUT route for `2026-01-15-preview` +to be deployed and authorized; nested Pipeline component registration is not supported. + See the [two-component Python sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/samples/jobs/sample_pipeline_dsl.py) for a producer and consumer connected through a mounted file. Each function body is packaged into a separate Code folder and runs on the selected compute, not when the graph is built. Component functions must be diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 849056c3c3f7..4bd1e444846a 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -6,7 +6,7 @@ """Async customized jobs operations — flat CommandJob and PipelineJob UX, no envelope required.""" import asyncio # pylint: disable=do-not-import-asyncio -from copy import copy +from copy import copy, deepcopy import json import logging import sys @@ -29,6 +29,9 @@ from ._operations import BetaJobsOperations as _GeneratedJobsOps from ._operations import BetaModelsOperations as _GeneratedModelsOps +from ._pipeline_component_registration_operations import ( + PipelineComponentRegistrationOperations as _GeneratedComponentRegistrationOperations, +) from ._patch_datasets_async import DatasetsOperations from ...operations._job_helper import ( _TERMINAL_JOB_STATUSES, @@ -95,6 +98,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self._config.api_version = "2026-01-15-preview" self._datasets = DatasetsOperations(self._client, original_config, self._serialize, self._deserialize) self._models = _GeneratedModelsOps(self._client, original_config, self._serialize, self._deserialize) + self._component_registration = _GeneratedComponentRegistrationOperations( + self._client, original_config, self._serialize, self._deserialize + ) @distributed_trace_async async def validate( @@ -242,18 +248,20 @@ async def _resolve_local_paths(self, name: str, job: CommandJob) -> None: await self._resolve_code(name, job) await self._resolve_input_paths(name, job) - async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: - """Resolve local code folders on inline command nodes to dataset asset URIs. + async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> PipelineJob: + """Resolve code and register inline Commands on a submission copy. :param name: Name of the pipeline job. :type name: str :param job: Pipeline job containing inline command nodes. :type job: ~azure.ai.projects.models.PipelineJob + :return: A submission copy referencing registered Command component IDs. + :rtype: ~azure.ai.projects.models.PipelineJob """ try: resolved_code: Dict[str, str] = {} for node_name, node in (job.jobs or {}).items(): - if not isinstance(node, dict) or node.get("type") != "command": + if not isinstance(node, dict) or node.get("type") != "command" or "componentId" in node: continue component = node.get("component") if not isinstance(component, dict) or not isinstance(component.get("code"), str): @@ -277,6 +285,25 @@ async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: directory.cleanup() job._component_code_dirs.clear() + submission = PipelineJob(deepcopy(job.as_dict(exclude_readonly=True))) + for node in (submission.jobs or {}).values(): + if not isinstance(node, dict) or node.get("type") != "command" or "componentId" in node: + continue + component = node.get("component") + if not isinstance(component, dict): + continue + registered = await self._component_registration._register_command_component( + name=component["name"], + version=str(component["version"]), + component={"properties": {"componentSpec": component}}, + ) + component_id = registered.get("id") + if not isinstance(component_id, str) or not component_id: + raise ValueError(f"Component '{component['name']}' registration did not return an executable ID.") + node["componentId"] = component_id + del node["component"] + return submission + def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -425,7 +452,7 @@ async def create_or_update( # type: ignore[override] _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) await self._resolve_local_paths(name, job) elif isinstance(job, PipelineJob): - await self._resolve_pipeline_code(name, job) + job = await self._resolve_pipeline_code(name, job) else: raise TypeError("job must be a CommandJob or PipelineJob") self._inject_preview_header(kwargs) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py index 454484ef8dba..af3cf7b1305d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py @@ -16,6 +16,9 @@ from .._configuration import AIProjectClientConfiguration from ._operations import PipelineJobsOperations as _GeneratedPipelineJobsOperations +from ._pipeline_component_registration_operations import ( + PipelineComponentRegistrationOperations as _GeneratedComponentRegistrationOperations, +) from ._patch_datasets_async import DatasetsOperations from ._patch_jobs_async import JobsOperations as _BetaJobsOperations from ...models._enums import ListViewType, _FoundryFeaturesOptInKeys @@ -51,6 +54,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self._datasets = DatasetsOperations( self._client, original_config, self._serialize, self._deserialize ) + self._component_registration = _GeneratedComponentRegistrationOperations( + self._client, original_config, self._serialize, self._deserialize + ) # Keep route-specific request handling in the generated Pipeline Jobs class, # while reusing the proven local-asset contract from beta.jobs. @@ -64,8 +70,8 @@ async def _resolve_asset_uri( self, uri, dataset_name, base_path ) - async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: - await _BetaJobsOperations._resolve_pipeline_code(self, name, job) # type: ignore[arg-type] + async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> PipelineJob: + return await _BetaJobsOperations._resolve_pipeline_code(self, name, job) # type: ignore[arg-type] def _inject_preview_header(self, kwargs: dict) -> None: _BetaJobsOperations._inject_preview_header(self, kwargs) # type: ignore[arg-type] @@ -179,7 +185,7 @@ async def create_or_update( # type: ignore[override] if not isinstance(job, PipelineJob): raise TypeError("job must be a PipelineJob") - await self._resolve_pipeline_code(name, job) + job = await self._resolve_pipeline_code(name, job) self._inject_preview_header(kwargs) _logger.debug( "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /pipeline_jobs.", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py new file mode 100644 index 000000000000..e3b262279e4f --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py @@ -0,0 +1,164 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, cast, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ..._utils.serialization import Deserializer, Serializer +from ...operations._pipeline_component_registration_operations import build_register_command_component_request +from .._configuration import AIProjectClientConfiguration + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class PipelineComponentRegistrationOperations: # pylint: disable=docstring-missing-param + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`pipeline_component_registration` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def _register_command_component( + self, name: str, version: str, component: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: ... + @overload + async def _register_command_component( + self, name: str, version: str, component: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: ... + + @distributed_trace_async + async def _register_command_component( + self, name: str, version: str, component: Union[JSON, IO[bytes]], **kwargs: Any + ) -> JSON: + """register_command_component. + + :param name: Required. + :type name: str + :param version: Required. + :type version: str + :param component: Is either a JSON type or a IO[bytes] type. Required. + :type component: JSON or IO[bytes] + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + component = { + "properties": { + "componentSpec": { + "str": {} + } + } + } + + # response body for status code(s): 200, 201 + response == { + "id": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + api_version: Literal["2026-01-15-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2026-01-15-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(component, (IOBase, bytes)): + _content = component + else: + _json = component + + _request = build_register_command_component_request( + name=name, + version=version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index 961fc468e8fb..ef80e19ba751 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -5,7 +5,7 @@ # ------------------------------------ """Customized jobs operations — flat CommandJob and PipelineJob UX, no envelope required.""" -from copy import copy +from copy import copy, deepcopy import json import logging import sys @@ -30,6 +30,9 @@ from ._operations import BetaJobsOperations as _GeneratedJobsOps from ._operations import BetaModelsOperations as _GeneratedModelsOps +from ._pipeline_component_registration_operations import ( + PipelineComponentRegistrationOperations as _GeneratedComponentRegistrationOperations, +) from ._patch_datasets import DatasetsOperations from ._job_helper import ( _TERMINAL_JOB_STATUSES, @@ -98,6 +101,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self._config.api_version = "2026-01-15-preview" self._datasets = DatasetsOperations(self._client, original_config, self._serialize, self._deserialize) self._models = _GeneratedModelsOps(self._client, original_config, self._serialize, self._deserialize) + self._component_registration = _GeneratedComponentRegistrationOperations( + self._client, original_config, self._serialize, self._deserialize + ) @distributed_trace def validate( @@ -245,18 +251,20 @@ def _resolve_local_paths(self, name: str, job: CommandJob) -> None: self._resolve_code(name, job) self._resolve_input_paths(name, job) - def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: - """Resolve local code folders on inline command nodes to dataset asset URIs. + def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> PipelineJob: + """Resolve code and register inline Commands on a submission copy. :param name: Name of the pipeline job. :type name: str :param job: Pipeline job containing inline command nodes. :type job: ~azure.ai.projects.models.PipelineJob + :return: A submission copy referencing registered Command component IDs. + :rtype: ~azure.ai.projects.models.PipelineJob """ try: resolved_code: Dict[str, str] = {} for node_name, node in (job.jobs or {}).items(): - if not isinstance(node, dict) or node.get("type") != "command": + if not isinstance(node, dict) or node.get("type") != "command" or "componentId" in node: continue component = node.get("component") if not isinstance(component, dict) or not isinstance(component.get("code"), str): @@ -280,6 +288,25 @@ def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: directory.cleanup() job._component_code_dirs.clear() + submission = PipelineJob(deepcopy(job.as_dict(exclude_readonly=True))) + for node in (submission.jobs or {}).values(): + if not isinstance(node, dict) or node.get("type") != "command" or "componentId" in node: + continue + component = node.get("component") + if not isinstance(component, dict): + continue + registered = self._component_registration._register_command_component( + name=component["name"], + version=str(component["version"]), + component={"properties": {"componentSpec": component}}, + ) + component_id = registered.get("id") + if not isinstance(component_id, str) or not component_id: + raise ValueError(f"Component '{component['name']}' registration did not return an executable ID.") + node["componentId"] = component_id + del node["component"] + return submission + def _inject_preview_header(self, kwargs: dict) -> None: """Add the Jobs preview feature header if not already present. @@ -433,7 +460,7 @@ def create_or_update( # type: ignore[override] _emit_validation_warnings(_validate_command_job(job).try_raise(raise_on_failure=True)) self._resolve_local_paths(name, job) elif isinstance(job, PipelineJob): - self._resolve_pipeline_code(name, job) + job = self._resolve_pipeline_code(name, job) else: raise TypeError("job must be a CommandJob or PipelineJob") self._inject_preview_header(kwargs) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py index 365a2cdeda69..3b75543342f2 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py @@ -16,6 +16,9 @@ from .._configuration import AIProjectClientConfiguration from ._operations import PipelineJobsOperations as _GeneratedPipelineJobsOperations +from ._pipeline_component_registration_operations import ( + PipelineComponentRegistrationOperations as _GeneratedComponentRegistrationOperations, +) from ._patch_datasets import DatasetsOperations from ._patch_jobs import JobsOperations as _BetaJobsOperations from ..models._enums import ListViewType, _FoundryFeaturesOptInKeys @@ -51,6 +54,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self._datasets = DatasetsOperations( self._client, original_config, self._serialize, self._deserialize ) + self._component_registration = _GeneratedComponentRegistrationOperations( + self._client, original_config, self._serialize, self._deserialize + ) # Keep route-specific request handling in the generated Pipeline Jobs class, # while reusing the proven local-asset contract from beta.jobs. @@ -62,8 +68,8 @@ def _resolve_asset_uri( ) -> str: return _BetaJobsOperations._resolve_asset_uri(self, uri, dataset_name, base_path) # type: ignore[arg-type] - def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: - _BetaJobsOperations._resolve_pipeline_code(self, name, job) # type: ignore[arg-type] + def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> PipelineJob: + return _BetaJobsOperations._resolve_pipeline_code(self, name, job) # type: ignore[arg-type] def _inject_preview_header(self, kwargs: dict) -> None: _BetaJobsOperations._inject_preview_header(self, kwargs) # type: ignore[arg-type] @@ -178,7 +184,7 @@ def create_or_update( # type: ignore[override] if not isinstance(job, PipelineJob): raise TypeError("job must be a PipelineJob") - self._resolve_pipeline_code(name, job) + job = self._resolve_pipeline_code(name, job) self._inject_preview_header(kwargs) _logger.debug( "[PipelineJobsOperations] Submitting PipelineJob '%s' with %d graph node(s) through /pipeline_jobs.", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_pipeline_component_registration_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_pipeline_component_registration_operations.py new file mode 100644 index 000000000000..8b51972aa516 --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_pipeline_component_registration_operations.py @@ -0,0 +1,196 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, cast, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .._configuration import AIProjectClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +JSON = MutableMapping[str, Any] +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_register_command_component_request(name: str, version: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2026-01-15-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2026-01-15-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/components/{name}/versions/{version}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class PipelineComponentRegistrationOperations: # pylint: disable=docstring-missing-param + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`pipeline_component_registration` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def _register_command_component( + self, name: str, version: str, component: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: ... + @overload + def _register_command_component( + self, name: str, version: str, component: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: ... + + @distributed_trace + def _register_command_component( + self, name: str, version: str, component: Union[JSON, IO[bytes]], **kwargs: Any + ) -> JSON: + """register_command_component. + + :param name: Required. + :type name: str + :param version: Required. + :type version: str + :param component: Is either a JSON type or a IO[bytes] type. Required. + :type component: JSON or IO[bytes] + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + component = { + "properties": { + "componentSpec": { + "str": {} + } + } + } + + # response body for status code(s): 200, 201 + response == { + "id": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + api_version: Literal["2026-01-15-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2026-01-15-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(component, (IOBase, bytes)): + _content = component + else: + _json = component + + _request = build_register_command_component_request( + name=name, + version=version, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py new file mode 100644 index 000000000000..7459342938bc --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py @@ -0,0 +1,336 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Offline contract regressions for registering authored Command components.""" + +import json +from copy import deepcopy +from pathlib import Path +from typing import Any, Iterator +from urllib.parse import parse_qs, quote, urlparse + +import pytest +from azure.core.exceptions import HttpResponseError, ResourceNotFoundError +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest, HttpResponse + +from azure.ai.projects import AIProjectClient +from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient +from azure.ai.projects.dsl import Output as ComponentOutput, component, pipeline +from azure.ai.projects.models import DatasetVersion, PipelineJob + +from test_pipeline_jobs import ( + _AsyncCredential, + _AsyncJsonResponse, + _AsyncTransport, + _COMPUTE, + _Credential, + _ENDPOINT, + _JsonResponse, + _Transport, + _response, + _uploaded_code, +) + +_SURFACES = ("pipeline_jobs", "beta.jobs") +_JOB_NAME = "hello-world" +_IMAGE = "example.azurecr.io/train:latest" +# Fixture only: the returned physical-workspace ID must remain opaque. +_COMPONENT_ID = ( + "/subscriptions/test/resourceGroups/test/providers/Microsoft.MachineLearningServices/" + "workspaces/fake-account@fake-project@AML/components/hello_world/versions/1" +) + + +def _author_job() -> PipelineJob: + @component + def hello_world(text: str, message: ComponentOutput(type="uri_file")) -> None: + from pathlib import Path + + Path(message).write_text(text, encoding="utf-8") + + @pipeline( + compute_id=_COMPUTE, + environment_image_reference=_IMAGE, + user_assigned_identity_id="/subscriptions/test/identities/hello", + instance_type="Singularity.D4_v3", + ) + def workflow(text: str): + hello = hello_world(text=text) + return {"message": hello.outputs.message} + + return workflow(text="hello") + + +@pytest.fixture +def authored_job() -> Iterator[PipelineJob]: + job = _author_job() + try: + yield job + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + +def _job_path(surface: str) -> str: + collection = "pipeline_jobs" if surface == "pipeline_jobs" else "jobs" + return f"{urlparse(_ENDPOINT).path}/{collection}/{_JOB_NAME}" + + +class _RegistrationScenario: + def __init__(self, job: PipelineJob, surface: str, *, fail_registration: bool = False) -> None: + self.authored = deepcopy(job.as_dict(exclude_readonly=True)) + self.spec = self.authored["jobs"]["hello_world"]["component"] + self.component_path = ( + f"{urlparse(_ENDPOINT).path}/components/{quote(self.spec['name'], safe='')}" + f"/versions/{quote(str(self.spec['version']), safe='')}" + ) + self.job_path = _job_path(surface) + self.fail_registration = fail_registration + self.events: list[str] = [] + self.submissions: list[dict[str, Any]] = [] + self.code_uri: str = "" + + def uploaded_authoring(self) -> dict[str, Any]: + authored = deepcopy(self.authored) + authored["jobs"]["hello_world"]["component"]["code"] = self.code_uri + return authored + + def registered_payload(self) -> dict[str, Any]: + payload = self.uploaded_authoring() + node = payload["jobs"]["hello_world"] + del node["component"] + node["componentId"] = _COMPONENT_ID + return payload + + def respond(self, request: HttpRequest) -> tuple[dict[str, Any], int]: + assert request.method == "PUT", "Submission must not GET each component by default." + url = urlparse(request.url) + body = json.loads(request.body) + if url.path == self.component_path: + self.events.append("register") + assert self.code_uri, "Source upload must finish before component registration." + assert parse_qs(url.query)["api-version"] == ["2026-01-15-preview"] + spec = deepcopy(self.spec) + spec["code"] = self.code_uri + assert body == {"properties": {"componentSpec": spec}} + if self.fail_registration: + return {"error": {"code": "InvalidComponent", "message": "Component registration rejected"}}, 400 + return {"id": _COMPONENT_ID, "properties": {"componentSpec": spec}}, 201 + assert url.path == self.job_path, f"Unexpected request: {request.method} {request.url}" + self.events.append("job") + assert request.headers["Foundry-Features"] == "Jobs=V1Preview" + assert parse_qs(url.query)["api-version"] == ["2026-01-15-preview"] + self.submissions.append(body["properties"]) + return {"name": _JOB_NAME, "id": f"/jobs/{_JOB_NAME}", "properties": body["properties"]}, 200 + + +class _RegistrationTransport(_Transport): + def __init__(self, scenario: _RegistrationScenario) -> None: + super().__init__([]) + self.scenario = scenario + + def send(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + self.requests.append(request) + payload, status = self.scenario.respond(request) + response = _JsonResponse(request, payload) + response.status_code = status + return response + + +class _AsyncRegistrationTransport(_AsyncTransport): + def __init__(self, scenario: _RegistrationScenario) -> None: + super().__init__([]) + self.scenario = scenario + + async def send(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + self.requests.append(request) + payload, status = self.scenario.respond(request) + response = _AsyncJsonResponse(request, payload) + response.status_code = status + return response + + +def _mock_source_upload( + operations: Any, scenario: _RegistrationScenario, monkeypatch: pytest.MonkeyPatch, *, is_async: bool = False +) -> None: + def missing_asset(*, name: str, version: str) -> DatasetVersion: + raise ResourceNotFoundError(f"Dataset {name}:{version} not found") + + def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + assert (Path(folder) / "component.py").is_file() + scenario.events.append("upload") + uploaded = _uploaded_code(name, version) + assert uploaded.id is not None + scenario.code_uri = uploaded.id + return uploaded + + async def missing_asset_async(*, name: str, version: str) -> DatasetVersion: + return missing_asset(name=name, version=version) + + async def upload_folder_async(*, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: + return upload_folder(name=name, version=version, folder=folder, **kwargs) + + monkeypatch.setattr(operations._datasets, "get", missing_asset_async if is_async else missing_asset) + monkeypatch.setattr(operations._datasets, "upload_folder", upload_folder_async if is_async else upload_folder) + + +def _assert_registered_submission(scenario: _RegistrationScenario, job: PipelineJob) -> None: + assert scenario.events[:3] == ["upload", "register", "job"] + assert scenario.submissions[-1] == scenario.registered_payload() + # Existing code-URI resolution may update code; registration must retain the authored component. + assert job.as_dict(exclude_readonly=True) == scenario.uploaded_authoring() + + +@pytest.mark.parametrize("surface", _SURFACES) +def test_pipeline_registers_command_after_upload_and_preserves_reusable_authoring( + authored_job: PipelineJob, surface: str, monkeypatch: pytest.MonkeyPatch +) -> None: + scenario = _RegistrationScenario(authored_job, surface) + transport = _RegistrationTransport(scenario) + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + operations = client.pipeline_jobs if surface == "pipeline_jobs" else client.beta.jobs + _mock_source_upload(operations, scenario, monkeypatch) + for _ in range(2): + assert isinstance(operations.create_or_update(_JOB_NAME, authored_job), PipelineJob) + _assert_registered_submission(scenario, authored_job) + assert len(scenario.submissions) == 2 + assert all(request.method == "PUT" for request in transport.requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("surface", _SURFACES) +async def test_pipeline_registers_command_after_upload_and_preserves_reusable_authoring_async( + authored_job: PipelineJob, surface: str, monkeypatch: pytest.MonkeyPatch +) -> None: + scenario = _RegistrationScenario(authored_job, surface) + transport = _AsyncRegistrationTransport(scenario) + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + operations = client.pipeline_jobs if surface == "pipeline_jobs" else client.beta.jobs + _mock_source_upload(operations, scenario, monkeypatch, is_async=True) + for _ in range(2): + assert isinstance(await operations.create_or_update(_JOB_NAME, authored_job), PipelineJob) + _assert_registered_submission(scenario, authored_job) + assert len(scenario.submissions) == 2 + assert all(request.method == "PUT" for request in transport.requests) + + +@pytest.mark.parametrize("surface", _SURFACES) +def test_component_registration_failure_prevents_job_without_inline_fallback( + authored_job: PipelineJob, surface: str, monkeypatch: pytest.MonkeyPatch +) -> None: + scenario = _RegistrationScenario(authored_job, surface, fail_registration=True) + transport = _RegistrationTransport(scenario) + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + operations = client.pipeline_jobs if surface == "pipeline_jobs" else client.beta.jobs + _mock_source_upload(operations, scenario, monkeypatch) + with pytest.raises(HttpResponseError, match="Component registration rejected"): + operations.create_or_update(_JOB_NAME, authored_job) + assert scenario.events == ["upload", "register"] + assert scenario.submissions == [] + assert authored_job.as_dict(exclude_readonly=True) == scenario.uploaded_authoring() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("surface", _SURFACES) +async def test_component_registration_failure_prevents_job_without_inline_fallback_async( + authored_job: PipelineJob, surface: str, monkeypatch: pytest.MonkeyPatch +) -> None: + scenario = _RegistrationScenario(authored_job, surface, fail_registration=True) + transport = _AsyncRegistrationTransport(scenario) + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + operations = client.pipeline_jobs if surface == "pipeline_jobs" else client.beta.jobs + _mock_source_upload(operations, scenario, monkeypatch, is_async=True) + with pytest.raises(HttpResponseError, match="Component registration rejected"): + await operations.create_or_update(_JOB_NAME, authored_job) + assert scenario.events == ["upload", "register"] + assert scenario.submissions == [] + assert authored_job.as_dict(exclude_readonly=True) == scenario.uploaded_authoring() + + +@pytest.mark.parametrize("surface", _SURFACES) +@pytest.mark.parametrize("reference_field", ("componentId", "component")) +def test_existing_component_references_are_not_registered_or_rewritten( + authored_job: PipelineJob, surface: str, reference_field: str +) -> None: + assert authored_job.jobs is not None + node = authored_job.jobs["hello_world"] + del node["component"] + node[reference_field] = _COMPONENT_ID + expected = deepcopy(authored_job.as_dict(exclude_readonly=True)) + transport = _Transport([_response("Pipeline")]) + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + operations = client.pipeline_jobs if surface == "pipeline_jobs" else client.beta.jobs + assert isinstance(operations.create_or_update(_JOB_NAME, authored_job), PipelineJob) + assert len(transport.requests) == 1 + assert transport.requests[0].method == "PUT" + assert urlparse(transport.requests[0].url).path == _job_path(surface) + assert json.loads(transport.requests[0].body) == {"properties": expected} + assert authored_job.as_dict(exclude_readonly=True) == expected + + +@pytest.mark.asyncio +@pytest.mark.parametrize("surface", _SURFACES) +@pytest.mark.parametrize("reference_field", ("componentId", "component")) +async def test_existing_component_references_are_not_registered_or_rewritten_async( + authored_job: PipelineJob, surface: str, reference_field: str +) -> None: + assert authored_job.jobs is not None + node = authored_job.jobs["hello_world"] + del node["component"] + node[reference_field] = _COMPONENT_ID + expected = deepcopy(authored_job.as_dict(exclude_readonly=True)) + transport = _AsyncTransport([_response("Pipeline")]) + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + operations = client.pipeline_jobs if surface == "pipeline_jobs" else client.beta.jobs + assert isinstance(await operations.create_or_update(_JOB_NAME, authored_job), PipelineJob) + assert len(transport.requests) == 1 + assert transport.requests[0].method == "PUT" + assert urlparse(transport.requests[0].url).path == _job_path(surface) + assert json.loads(transport.requests[0].body) == {"properties": expected} + assert authored_job.as_dict(exclude_readonly=True) == expected + + +def test_component_decorators_and_pipeline_serialization_stay_offline() -> None: + transport = _Transport([]) + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport): # type: ignore[arg-type] + job = _author_job() + try: + payload = job.as_dict(exclude_readonly=True) + spec = payload["jobs"]["hello_world"]["component"] + assert spec["name"] == "hello_world" + assert spec["version"] == "1" + assert spec["inputs"] == {"text": {"type": "string"}} + assert spec["outputs"] == {"message": {"type": "uri_file"}} + assert spec["environment"] == {"image": _IMAGE} + assert transport.requests == [] + finally: + for directory in job._component_code_dirs: + directory.cleanup() + + +@pytest.mark.asyncio +async def test_component_decorators_and_pipeline_serialization_stay_offline_async() -> None: + transport = _AsyncTransport([]) + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ): + job = _author_job() + try: + payload = job.as_dict(exclude_readonly=True) + spec = payload["jobs"]["hello_world"]["component"] + assert spec["name"] == "hello_world" + assert spec["version"] == "1" + assert spec["inputs"] == {"text": {"type": "string"}} + assert spec["outputs"] == {"message": {"type": "uri_file"}} + assert spec["environment"] == {"image": _IMAGE} + assert transport.requests == [] + finally: + for directory in job._component_code_dirs: + directory.cleanup() diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/.gitignore b/sdk/ai/azure-ai-projects/typespec/component-registration/.gitignore new file mode 100644 index 000000000000..9fae80bffb63 --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +TempTypeSpecFiles/ +output/ +tsp-client-metadata.yaml diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package-lock.json b/sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package-lock.json new file mode 100644 index 000000000000..1d67273b95e7 --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package-lock.json @@ -0,0 +1,2388 @@ +{ + "name": "typespec-tools", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@azure-tools/typespec-client-generator-cli": "0.33.1", + "@azure-tools/typespec-python": "0.63.10" + } + }, + "node_modules/@azure-tools/typespec-autorest": { + "version": "0.73.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-autorest/-/typespec-autorest-0.73.2.tgz", + "integrity": "sha512-Qm9m+4Ok2XxLvOm5l9dr6EmTN15ArGaktefSKZ5uNU2lt26RDntj2GP2tkudXjDijwqYGKnGsIU8l5wK9yMOvQ==", + "license": "MIT", + "dependencies": { + "@azure-tools/typespec-azure-examples": "^0.2.2", + "yaml": "^2.9.0" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@azure-tools/typespec-azure-core": "^0.73.0", + "@azure-tools/typespec-azure-resource-manager": "^0.73.0", + "@azure-tools/typespec-client-generator-core": "^0.73.0", + "@typespec/compiler": "^1.17.0", + "@typespec/http": "^1.17.0", + "@typespec/openapi": "^1.17.0", + "@typespec/rest": "^0.87.0", + "@typespec/versioning": "^0.87.0", + "@typespec/xml": "^0.87.0" + }, + "peerDependenciesMeta": { + "@typespec/xml": { + "optional": true + } + } + }, + "node_modules/@azure-tools/typespec-azure-core": { + "version": "0.73.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-azure-core/-/typespec-azure-core-0.73.0.tgz", + "integrity": "sha512-RSiXLLPvBowaDeliOsa2z9ChT4Z6DE5zJVz6wVhpA3Jh5kZgT3irN8Rqtg6BJO9T5TBVLPUPcUgXMQ5X8JFhLQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0", + "@typespec/http": "^1.17.0", + "@typespec/rest": "^0.87.0" + } + }, + "node_modules/@azure-tools/typespec-azure-examples": { + "version": "0.2.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-azure-examples/-/typespec-azure-examples-0.2.2.tgz", + "integrity": "sha512-7T6JLezY3uMbhCcyLU4rDQACt5eTjJLMMuKgq1ma1tYhoZmLX2yu5TcOUqfFkzkxypWI7JOdG7kgQHKhvPTduQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", + "picocolors": "^1.1.1", + "yaml": "^2.9.0", + "yargs": "^18.1.0" + }, + "bin": { + "tsp-examples": "dist/src/cli.js", + "tsp-examples-legacy-expand": "dist/src/legacy-expand-cli.js", + "tsp-examples-migrate": "dist/src/migrate-cli.js" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0" + }, + "peerDependenciesMeta": { + "@typespec/compiler": { + "optional": true + } + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha1-wETV3MUhoHZBNHJZehrLHxA8QEE=", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha1-b3iQ84b28feZU63B943sRvzC0pE=", + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha1-tbuOIWXOJ11NQ0dt0nAK2Qkdttw=", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha1-vz1uj3+P0ipl2XA0dbwBRzV6aw0=", + "license": "MIT" + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha1-0iomlSKDamJ6+NBLXD/Sx/o+MuM=", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha1-lWgy3qlJQwbm0gnrhxZDu4c9fJg=", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha1-tbuOIWXOJ11NQ0dt0nAK2Qkdttw=", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/yargs": { + "version": "18.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yargs/-/yargs-18.2.0.tgz", + "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==", + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/@azure-tools/typespec-azure-examples/node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha1-h7gglAUbBWdxc0bs0A/RSASzV8g=", + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/@azure-tools/typespec-azure-resource-manager": { + "version": "0.73.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-azure-resource-manager/-/typespec-azure-resource-manager-0.73.0.tgz", + "integrity": "sha512-Eh9993XDpPgQVmSE9+XXFlBP2eq6mitA7YWr3GwasR3wpdtkbWTXCleMeVl+nlPEbjyEIJmJByeIbApP/043Pg==", + "license": "MIT", + "peer": true, + "dependencies": { + "change-case": "^5.4.4", + "pluralize": "^8.0.0" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@azure-tools/typespec-azure-core": "^0.73.0", + "@typespec/compiler": "^1.17.0", + "@typespec/http": "^1.17.0", + "@typespec/openapi": "^1.17.0", + "@typespec/rest": "^0.87.0", + "@typespec/versioning": "^0.87.0" + } + }, + "node_modules/@azure-tools/typespec-azure-rulesets": { + "version": "0.73.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-azure-rulesets/-/typespec-azure-rulesets-0.73.0.tgz", + "integrity": "sha512-+Wyc8lKEO0ZH+3Zq+4sDz6Yif7UBDzZQKQuegVpX7oWqTHcjr/oknII8PVRBzLKyM8tkiY/ffslT9lEmUoc7tQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@azure-tools/typespec-azure-core": "^0.73.0", + "@azure-tools/typespec-azure-resource-manager": "^0.73.0", + "@azure-tools/typespec-client-generator-core": "^0.73.0", + "@typespec/compiler": "^1.17.0" + } + }, + "node_modules/@azure-tools/typespec-client-generator-cli": { + "version": "0.33.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-client-generator-cli/-/typespec-client-generator-cli-0.33.1.tgz", + "integrity": "sha1-d86PxyFIlQth/VrwkOre8+TGv/Y=", + "license": "MIT", + "dependencies": { + "@azure-tools/typespec-autorest": ">=0.53.0 <1.0.0", + "@azure/core-rest-pipeline": "^1.12.0", + "@types/shell-quote": "^1.7.5", + "@types/yargs": "^17.0.32", + "chalk": "^5.3.0", + "dotenv": "^16.4.5", + "prompt-sync": "^4.2.0", + "shell-quote": "^1.8.3", + "simple-git": "^3.20.0", + "yaml": "^2.3.1", + "yargs": "^17.2.1" + }, + "bin": { + "tsp-client": "cmd/tsp-client.js" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@typespec/compiler": "1.0.0-rc.1 || >=1.0.0 <2.0.0" + } + }, + "node_modules/@azure-tools/typespec-client-generator-core": { + "version": "0.73.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.73.1.tgz", + "integrity": "sha512-3HybxFUoKcF5Y2C1zCSO7i2I6gbFe9SZmDbqSSA6oV2pdCDm6jikEQdRbBnyM70U6ZXY0TFPX5kcV266QDvnfQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "change-case": "^5.4.4", + "pluralize": "^8.0.0", + "yaml": "^2.9.0" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@azure-tools/typespec-azure-core": "^0.73.0", + "@typespec/compiler": "^1.17.0", + "@typespec/events": "^0.87.0", + "@typespec/http": "^1.17.0", + "@typespec/openapi": "^1.17.0", + "@typespec/rest": "^0.87.0", + "@typespec/sse": "^0.87.0", + "@typespec/streams": "^0.87.0", + "@typespec/versioning": "^0.87.0", + "@typespec/xml": "^0.87.0" + } + }, + "node_modules/@azure-tools/typespec-python": { + "version": "0.63.10", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure-tools/typespec-python/-/typespec-python-0.63.10.tgz", + "integrity": "sha512-BVnxBopqEctOcx4pkWGOS8sTpVSfxMLkJiWY5Kc1W8fjPc9OKRd1NG+B+R7iOZxOtPwGmX3zAWDu/CoUEkjQyQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@typespec/http-client-python": ">=0.39.0 <1.0.0", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@azure-tools/typespec-autorest": "^0.73.0", + "@azure-tools/typespec-azure-core": "^0.73.0", + "@azure-tools/typespec-azure-resource-manager": "^0.73.0", + "@azure-tools/typespec-azure-rulesets": "^0.73.0", + "@azure-tools/typespec-client-generator-core": "^0.73.0", + "@typespec/compiler": "^1.17.0", + "@typespec/events": "^0.87.0", + "@typespec/http": "^1.17.0", + "@typespec/openapi": "^1.17.0", + "@typespec/rest": "^0.87.0", + "@typespec/sse": "^0.87.0", + "@typespec/streams": "^0.87.0", + "@typespec/versioning": "^0.87.0", + "@typespec/xml": "^0.87.0" + } + }, + "node_modules/@azure/abort-controller": { + "version": "2.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure/abort-controller/-/abort-controller-2.2.0.tgz", + "integrity": "sha1-k+DoKwGGLn6jtbaZWHGdPz/SyKw=", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-auth": { + "version": "1.11.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure/core-auth/-/core-auth-1.11.0.tgz", + "integrity": "sha1-Ha7/32LRqHHSK4ZfnzFkpj6h9XU=", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.1.2", + "@azure/core-util": "^1.13.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-rest-pipeline": { + "version": "1.25.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure/core-rest-pipeline/-/core-rest-pipeline-1.25.0.tgz", + "integrity": "sha1-kupJEu27H3OV9IKaMAYxF0qoLwg=", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.1.2", + "@azure/core-auth": "^1.10.0", + "@azure/core-tracing": "^1.3.0", + "@azure/core-util": "^1.13.0", + "@azure/logger": "^1.3.0", + "@typespec/ts-http-runtime": "^0.3.4", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-tracing": { + "version": "1.4.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure/core-tracing/-/core-tracing-1.4.0.tgz", + "integrity": "sha1-1lenAOJNJW0ZXmKKeV22qMxHXqs=", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-util": { + "version": "1.14.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure/core-util/-/core-util-1.14.0.tgz", + "integrity": "sha1-fOn+V5WPEy3UIlc4VuWkXHIyuwQ=", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.1.2", + "@typespec/ts-http-runtime": "^0.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/logger": { + "version": "1.4.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@azure/logger/-/logger-1.4.0.tgz", + "integrity": "sha1-PVpif+WaJ27OdIenndkq1cUIwzk=", + "license": "MIT", + "dependencies": { + "@typespec/ts-http-runtime": "^0.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "8.0.6", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@babel/code-frame/-/code-frame-8.0.6.tgz", + "integrity": "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/helper-validator-identifier": "^8.0.6", + "js-tokens": "^10.0.0" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "8.0.6", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz", + "integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha1-v24QMDvPLnxoaXX6Uvk37Cco2Lw=", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha1-LYTs5qTiaE2SvibuE9QnV9gxw4E=", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha1-DGJGvI0sTRcqrC2z+xGQ1yvWVQQ=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha1-/DjU1jWNjcHPU/CfdYn+Q262SAE=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha1-+Dr+6sHX2sAcei/QErPkUaBZH8w=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha1-UQFHwFWnlViNu+FP1rG4rQovMN4=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha1-CTuSAOzwsRW6Tl4kinSFycX4vV4=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha1-C+Irbfkl0hPoQeqHEjr134Cw+vc=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha1-vrEq1yuE9y0oSIzBuO6ffrFB11M=", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha1-G9vGUc2pupmVxT7ZxxzqplCUdi0=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha1-uB+dVVKbRcIGpGoTghSxqmh5aWs=", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha1-WYZnJBoEyZt27W75QKxQA4xBn5g=", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha1-HFHrnOqQP1PZe1rzsYQdtw9Vlso=", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha1-Y91h8XzrMagSJ/QT/qyKcbwsUfI=", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha1-N2Owj95c8lqx+suOd1Lt/kX7/Cc=", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha1-GhN/8pOoKQbrMXY4W9fo4OXPt8s=", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha1-Jos2IRwUbKVPj+EsV4qNbviXlIU=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha1-Ilca2VHWK7aszILY0frVyMGsC6E=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha1-QvzFcpfrCgyj9fxHUpH0waP3wN4=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha1-nrMq8QSsPaz07coB9ZZmSqsMc+8=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha1-/r7SQC1giCJekfIPtM4lIq0KTv0=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha1-hWQcPUZkKL+8zqXyHCaDZmP+9c4=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha1-pzb52JYkgQRfxMPlT1R58iyHD7Q=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha1-7lq0D60YYgG2UqM/il6xSenkJTI=", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha1-xA0optmaEn2mcR8q/XSxHLY7Bqc=", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha1-shr/uATMFnwTPZX0WzodwTI7moc=", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@inquirer/ansi": { + "version": "2.0.10", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/ansi/-/ansi-2.0.10.tgz", + "integrity": "sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/checkbox": { + "version": "5.2.8", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/checkbox/-/checkbox-5.2.8.tgz", + "integrity": "sha512-NY/S1EalQhlonqhwwsarrcnkH7s9ByQuvjWYdk1jB2Gb9EPQJjKkhCTWjM3yQ0UpHaLm1XbIL89b+32G8rhO5w==", + "license": "MIT", + "peer": true, + "dependencies": { + "@inquirer/ansi": "^2.0.10", + "@inquirer/core": "^12.0.6", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/confirm": { + "version": "6.3.5", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/confirm/-/confirm-6.3.5.tgz", + "integrity": "sha512-BJ59BOyURiZiAxdr9AuRu38/k+rV+DcTIM2fUF/c/BXrab6H8zMZTTOl3LgkSJH96Xob2vOJxDiBkHiz32Xx2w==", + "license": "MIT", + "peer": true, + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "12.0.6", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/core/-/core-12.0.6.tgz", + "integrity": "sha512-5yxn2LsJ8Tu4ei2a+yNkmFRhM/cb+JMEsEs/AW6CCOnBnpMy4IjYiPMFyHtYq8weOmlTyqqCx40y0DsD7OsEPw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@inquirer/ansi": "^2.0.10", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1", + "cli-width": "^4.1.0", + "fast-wrap-ansi": "^0.2.0", + "mute-stream": "^3.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/figures": { + "version": "2.0.10", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/figures/-/figures-2.0.10.tgz", + "integrity": "sha512-51elrUJV3jZpvD0ygz8+U10Kc6+Lzqln+/tYmnbhy6jo5oXpE6hMCcv+OTBC0enwJXsb3JIuT3VtEinRNCSK2A==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/input": { + "version": "5.1.9", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/input/-/input-5.1.9.tgz", + "integrity": "sha512-2Vd5T7lTxfgJMpAd3aOu6bQpbUnCU7tBgvTQIZkP/7juJzmRmTM2t5XfOCuirFduWLTSJI/WZp32Cq1E01TVeg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select": { + "version": "5.2.8", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/select/-/select-5.2.8.tgz", + "integrity": "sha512-BklkkAAOpjdCfuQw5fVGcDuhKxA7T1iBpn6b2JUvDDdkIsO3Ftlg+WnWUCVpkUBFagL2o036OFW+xL4lC9wIPw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@inquirer/ansi": "^2.0.10", + "@inquirer/core": "^12.0.6", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha1-LVmuOrSzj7QnC/oj0w+OLobH/jI=", + "license": "ISC", + "peer": true, + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@kwsites/file-exists": { + "version": "1.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@kwsites/file-exists/-/file-exists-1.1.1.tgz", + "integrity": "sha1-rR78rBPhmH2NuvI17zvlsNlvqpk=", + "license": "MIT", + "dependencies": { + "debug": "^4.1.1" + } + }, + "node_modules/@kwsites/promise-deferred": { + "version": "1.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz", + "integrity": "sha1-is5SWSVEJszvV/MXW8ZO1wle2Rk=", + "license": "MIT" + }, + "node_modules/@simple-git/args-pathspec": { + "version": "1.0.4", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@simple-git/args-pathspec/-/args-pathspec-1.0.4.tgz", + "integrity": "sha512-EtMX6XjRWSastG2SdkmSQByPtJ9dx/NIjnHbpQPCYt62j4RmSx5rgLTGpw0YCjF5h191gZOmBfheOT23cRSFdw==", + "license": "MIT" + }, + "node_modules/@simple-git/argv-parser": { + "version": "1.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@simple-git/argv-parser/-/argv-parser-1.1.1.tgz", + "integrity": "sha1-J1uDnG7rUDCHLHOx6oOaQWiF2p0=", + "license": "MIT", + "dependencies": { + "@simple-git/args-pathspec": "^1.0.3" + } + }, + "node_modules/@types/shell-quote": { + "version": "1.7.5", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@types/shell-quote/-/shell-quote-1.7.5.tgz", + "integrity": "sha1-bbRwR0LTB81tYE4STjrWzV7ZQ/M=", + "license": "MIT" + }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha1-BwE+RqpNfX1QpJ4VYEwcU0DU6yQ=", + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha1-gV4wt4bS6PDc2F/VvPXhoE0AjxU=", + "license": "MIT" + }, + "node_modules/@typespec/compiler": { + "version": "1.17.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/compiler/-/compiler-1.17.0.tgz", + "integrity": "sha512-Prj9o2bjoWNS9wJ6sUk532jGm8h2AtpQ/lCFH6dhcywiP7UTj9cJtNlDAHptAS9Irh3YJM2g5D4/7S/u/vcG8Q==", + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/code-frame": "^8.0.0", + "@inquirer/checkbox": "^5.2.2", + "@inquirer/confirm": "^6.2.0", + "@inquirer/input": "^5.1.3", + "@inquirer/select": "^5.2.2", + "ajv": "^8.20.0", + "change-case": "^5.4.4", + "env-paths": "^4.0.0", + "is-unicode-supported": "^2.1.0", + "mustache": "^4.2.0", + "picocolors": "^1.1.1", + "prettier": "^3.9.6", + "semver": "^7.8.5", + "tar": "^7.5.22", + "temporal-polyfill": "^1.0.4", + "vscode-languageserver": "^10.1.0", + "vscode-languageserver-textdocument": "^1.0.13", + "yaml": "^2.9.0", + "yargs": "^18.1.0" + }, + "bin": { + "tsp": "cmd/tsp.js", + "tsp-server": "cmd/tsp-server.js" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@typespec/compiler/node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@typespec/compiler/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha1-wETV3MUhoHZBNHJZehrLHxA8QEE=", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@typespec/compiler/node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha1-b3iQ84b28feZU63B943sRvzC0pE=", + "license": "ISC", + "peer": true, + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@typespec/compiler/node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha1-tbuOIWXOJ11NQ0dt0nAK2Qkdttw=", + "license": "MIT", + "peer": true, + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@typespec/compiler/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha1-vz1uj3+P0ipl2XA0dbwBRzV6aw0=", + "license": "MIT", + "peer": true + }, + "node_modules/@typespec/compiler/node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@typespec/compiler/node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha1-0iomlSKDamJ6+NBLXD/Sx/o+MuM=", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@typespec/compiler/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha1-lWgy3qlJQwbm0gnrhxZDu4c9fJg=", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@typespec/compiler/node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha1-tbuOIWXOJ11NQ0dt0nAK2Qkdttw=", + "license": "MIT", + "peer": true, + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@typespec/compiler/node_modules/yargs": { + "version": "18.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yargs/-/yargs-18.2.0.tgz", + "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==", + "license": "MIT", + "peer": true, + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/@typespec/compiler/node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha1-h7gglAUbBWdxc0bs0A/RSASzV8g=", + "license": "ISC", + "peer": true, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/@typespec/events": { + "version": "0.87.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/events/-/events-0.87.0.tgz", + "integrity": "sha512-LZHZHnrqOZrQT9bokd9InaXpG35XoChHK4lZqAfJtTTx8zq0kzm5WIZ8fnXttUj332mjjgSNVtZyyrrZFzpKQw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0" + } + }, + "node_modules/@typespec/http": { + "version": "1.17.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/http/-/http-1.17.0.tgz", + "integrity": "sha512-XLwL+NvkQ4hWhnIwZms2CNoxCULFt/jMa+QGaKg4hDwPFLvrXsUm7JWPHi1QOcwzGFG8Z1NglqRPzKl2der2ww==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0", + "@typespec/streams": "^0.87.0" + }, + "peerDependenciesMeta": { + "@typespec/streams": { + "optional": true + } + } + }, + "node_modules/@typespec/http-client-python": { + "version": "0.39.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/http-client-python/-/http-client-python-0.39.0.tgz", + "integrity": "sha512-JgvwmnH3Dm/LrQidAq8BIKTetedwHEayTLsolC4NpvOnYo0SloP3oxiJ5evIxiyUKbHg8Ir3/9L5tGu85q72+g==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "js-yaml": "^4.3.1", + "marked": "^15.0.6", + "pyodide": "0.26.2", + "semver": "~7.6.2", + "tsx": "^4.23.13" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@azure-tools/typespec-autorest": ">=0.73.0 <1.0.0", + "@azure-tools/typespec-azure-core": ">=0.73.0 <1.0.0", + "@azure-tools/typespec-azure-resource-manager": ">=0.73.0 <1.0.0", + "@azure-tools/typespec-azure-rulesets": ">=0.73.0 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.73.0 <1.0.0", + "@typespec/compiler": "^1.17.0", + "@typespec/events": ">=0.87.0 <1.0.0", + "@typespec/http": "^1.17.0", + "@typespec/openapi": "^1.17.0", + "@typespec/rest": ">=0.87.0 <1.0.0", + "@typespec/sse": ">=0.87.0 <1.0.0", + "@typespec/streams": ">=0.87.0 <1.0.0", + "@typespec/versioning": ">=0.87.0 <1.0.0", + "@typespec/xml": ">=0.87.0 <1.0.0" + } + }, + "node_modules/@typespec/http-client-python/node_modules/semver": { + "version": "7.6.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/semver/-/semver-7.6.3.tgz", + "integrity": "sha1-mA97VVC8F1+03AlAMIVif56zMUM=", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typespec/openapi": { + "version": "1.17.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/openapi/-/openapi-1.17.0.tgz", + "integrity": "sha512-0ScXsaovyFZWJv0nnokGI25vK5nRvJ8KfxiKokyXyQrwzK51eb61P/yZr/cZDGjk/w/qKHz2Vz1OvVC4ztdQdA==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0", + "@typespec/http": "^1.17.0" + } + }, + "node_modules/@typespec/rest": { + "version": "0.87.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/rest/-/rest-0.87.0.tgz", + "integrity": "sha512-Oi47F6IJWyP/efMXf+OUwJTKRrfPpsXPzFZIxG5x2HpAgTwQ0xAUPkrQ6XoQ4rdmwN3XPm0nV54lw5GKljB9LQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0", + "@typespec/http": "^1.17.0" + } + }, + "node_modules/@typespec/sse": { + "version": "0.87.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/sse/-/sse-0.87.0.tgz", + "integrity": "sha512-6bAe4zlL+ZYzPCbAXSurTnZ9Jkze1/FAlK2d0i8L81syDtyDs2xWm8quElLzyVks2LkttsO14vFdN2ek5vUJ+g==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0", + "@typespec/events": "^0.87.0", + "@typespec/http": "^1.17.0", + "@typespec/streams": "^0.87.0" + } + }, + "node_modules/@typespec/streams": { + "version": "0.87.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/streams/-/streams-0.87.0.tgz", + "integrity": "sha512-m7QLb6VuJiVNM4xuQZMTxoL5xyseLsgmOhUMpmg5HGtAp8toDWaT2N9fxen9BJ3swqdB4P5huQJSVO2BcFB96A==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0" + } + }, + "node_modules/@typespec/ts-http-runtime": { + "version": "0.3.9", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/ts-http-runtime/-/ts-http-runtime-0.3.9.tgz", + "integrity": "sha1-MyhVu9cpqzbgd5st/CTtySDRJGE=", + "license": "MIT", + "dependencies": { + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@typespec/versioning": { + "version": "0.87.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/versioning/-/versioning-0.87.0.tgz", + "integrity": "sha512-GPL92BH29XAh10o0stg1LfW6RZyyQnlt8LAQ1i1Bfgnf6W0S32nCwbtVgHy8WX1u/g4sXWq74O3xi6Ng5+i68w==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0" + } + }, + "node_modules/@typespec/xml": { + "version": "0.87.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@typespec/xml/-/xml-0.87.0.tgz", + "integrity": "sha512-wjcXyYGUEegtMnpqjZzEThhSjILNWuOhEdAriwok4gfxicXcZVNj0l+F+tQcnVjhua0u5dsZimhnohPF/kNqQQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "^1.17.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha1-48121MVI7oldPD/Y3B9sW5Ay56g=", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha1-MEs2Nq3Yi6fZNnYN1Q7OAG3qlfk=", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha1-PV3HYryhdnnDwup+kK1rdTIwlXg=", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-regex": { + "version": "4.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha1-Fk2qyHqy1vbbOimHXi0XZlgtq+0=", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha1-7dgDYornHATIWuegkG7a00tkiTc=", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha1-JG9Q88p4oyQPbJl+ipvR6sSeSzg=", + "license": "Python-2.0" + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha1-sSOLbiPqM3r3HH+KKV21rwwViuo=", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/change-case": { + "version": "5.4.4", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/change-case/-/change-case-5.4.4.tgz", + "integrity": "sha1-DVK1B9j7jyBDQ0MjgdGm17/5egI=", + "license": "MIT", + "peer": true + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha1-mFXmTs0kCpzEJnzopKpdJKHaFeQ=", + "license": "BlueOak-1.0.0", + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha1-QtqsQdPCVO84rYrAN2chMBc2kcU=", + "license": "ISC", + "peer": true, + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha1-DASwddsCy/5g3I5s8vVIaxo2CKo=", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha1-CCyyyJyf6GWaMRpTvWpNxTAdswQ=", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha1-nibGPTD1NEPpSJSVshBdN7Z6hdk=", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha1-ctOmjVmMm9s68q0ehPIdiWq9TeM=", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha1-wqCah6y95pVD3m9j+jmVyCbFNqI=", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/debug/-/debug-4.4.3.tgz", + "integrity": "sha1-xq5DLZvZZiWC/OCHCbA4xY6ePWo=", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha1-dz8OaVJ6gxXHKF1e5zxEWdIKgCA=", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha1-6Bj9ac5cz8tARZT4QpY79TFkzDc=", + "license": "MIT" + }, + "node_modules/env-paths": { + "version": "4.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/env-paths/-/env-paths-4.0.0.tgz", + "integrity": "sha1-0LsfhKgdJUJYG/e36AhdBoOzkJc=", + "license": "MIT", + "peer": true, + "dependencies": { + "is-safe-filename": "^0.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha1-D0O9G62VW3LSTiJh46vllXzPCBY=", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha1-ARo/aYVroYnf+n3I/M6Z0qh5A+U=", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha1-On1WtVnWy8PrUSMlJE5hmmXGxSU=", + "license": "MIT" + }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha1-I6/g2mfXUsoHJ1OPHmlndZcozkk=", + "license": "MIT", + "peer": true + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha1-FturtJHOVYW17LZ1tlwWXXFojus=", + "license": "MIT", + "peer": true, + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", + "integrity": "sha1-lelSoBRbzj9ZrVbhefhMSNQHKTU=", + "license": "MIT", + "peer": true, + "dependencies": { + "fast-string-width": "^3.0.2" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha1-ysZAd4XQNnWipeGlMFxpezR9kNY=", + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha1-T5RBKoLbMvNuOwuXQfipf+sDH34=", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha1-mosfJGhmwChQlIZYX2K48sGMJw4=", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha1-2o3+rH2hMLBcK6S1nJts1mYRprk=", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha1-8Rb4Bk/pCz94RKOJl8C3UFEmnx0=", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-safe-filename": { + "version": "0.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/is-safe-filename/-/is-safe-filename-0.1.1.tgz", + "integrity": "sha1-+yLurQl8YUxHqmdN5deaFkilPmY=", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha1-CfCrDebTdE1I0mXruY9l0R8qmzo=", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha1-3/51mbSou3/jCv+NAjUjTf+3mDE=", + "license": "MIT", + "peer": true + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha1-jkT7FKJkPFlya7FXh7XxUSyz0/s=", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha1-rnvLNlard6c7pcSb9lTzjmtoYOI=", + "license": "MIT" + }, + "node_modules/marked": { + "version": "15.0.12", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/marked/-/marked-15.0.12.tgz", + "integrity": "sha1-MHIsc0bhLQotAgermwxPAQLYbE4=", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha1-eTibTrG7LQA6m7qH1JLyvTe9xls=", + "license": "BlueOak-1.0.0", + "peer": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha1-atdsOo8QInybUdHJrI4wsn9aJRw=", + "license": "MIT", + "peer": true, + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ms/-/ms-2.1.3.tgz", + "integrity": "sha1-V0yBOM4dK1hh8LRFedut1gxmFbI=", + "license": "MIT" + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha1-5YkjJNYKEuycKnM1ntylKXK/b2Q=", + "license": "MIT", + "peer": true, + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/mute-stream": { + "version": "3.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/mute-stream/-/mute-stream-3.0.0.tgz", + "integrity": "sha1-zYAU3SrLcuHpG7Z8dPABnmILotE=", + "license": "ISC", + "peer": true, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha1-PTIa8+q5ObCDyPkpodEs2oHCa2s=", + "license": "ISC" + }, + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha1-Gm+hajjRKhkB4DIPoBcFHFOc47E=", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/prettier": { + "version": "3.9.10", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/prettier/-/prettier-3.9.10.tgz", + "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", + "license": "MIT", + "peer": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prompt-sync": { + "version": "4.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/prompt-sync/-/prompt-sync-4.2.0.tgz", + "integrity": "sha1-AZj3PFtw47A+S5AzpQVAp8mh1/Q=", + "license": "MIT", + "dependencies": { + "strip-ansi": "^5.0.0" + } + }, + "node_modules/pyodide": { + "version": "0.26.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/pyodide/-/pyodide-0.26.2.tgz", + "integrity": "sha1-WuioUOm3m/O+O5CVPX98YkRpxxc=", + "license": "Apache-2.0", + "dependencies": { + "ws": "^8.5.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha1-iaf92TgmEmcxjq/hT5wy5ZjDaQk=", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/semver/-/semver-7.8.5.tgz", + "integrity": "sha1-ObZGA33VDBT7RR5+TKxY7YuGP2k=", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shell-quote": { + "version": "1.12.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha1-lSGIwcvVRgcOLdIND0HArgUwywQ=", + "license": "ISC", + "peer": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-git": { + "version": "3.36.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/simple-git/-/simple-git-3.36.0.tgz", + "integrity": "sha1-AZsowKNYR+40KZxvtjdwqxst/7c=", + "license": "MIT", + "dependencies": { + "@kwsites/file-exists": "^1.1.1", + "@kwsites/promise-deferred": "^1.1.1", + "@simple-git/args-pathspec": "^1.0.3", + "@simple-git/argv-parser": "^1.1.0", + "debug": "^4.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/steveukx/git-js?sponsor=1" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha1-JpxxF9J7Ba0uU2gwqOyJXvnG0BA=", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha1-CCyyyJyf6GWaMRpTvWpNxTAdswQ=", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha1-nibGPTD1NEPpSJSVshBdN7Z6hdk=", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha1-jJpTb+tq/JYr36WxBKUJHBrZwK4=", + "license": "MIT", + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar": { + "version": "7.5.22", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/tar/-/tar-7.5.22.tgz", + "integrity": "sha1-ppb5mBNucUh9w/hpqFu6LGeXG6k=", + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/temporal-polyfill": { + "version": "1.0.6", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/temporal-polyfill/-/temporal-polyfill-1.0.6.tgz", + "integrity": "sha512-tYyEry1HLGUDbm2356W3iYD0OZdo7rlP7h98Zr/EnjqLZQwTAfcBDUvJnJbfA15v/vQad57hJZScG5O0W2oKEA==", + "license": "MIT", + "peer": true, + "dependencies": { + "temporal-spec": "1.0.1", + "temporal-utils": "1.0.3" + } + }, + "node_modules/temporal-spec": { + "version": "1.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/temporal-spec/-/temporal-spec-1.0.1.tgz", + "integrity": "sha1-VnnOLdAImGWv6A4Ki9IqkDPBZxc=", + "license": "Apache-2.0", + "peer": true + }, + "node_modules/temporal-utils": { + "version": "1.0.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/temporal-utils/-/temporal-utils-1.0.3.tgz", + "integrity": "sha512-9jbTSX3HvkOWvDpNpFzwX/d1mkCrgQgwLmVTOEiuocZGKHsrQJtttGZFmybJ2zYP5zCSZuU5ZyeS8+eOEPABiQ==", + "license": "MIT", + "peer": true + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/vscode-jsonrpc": { + "version": "9.0.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/vscode-jsonrpc/-/vscode-jsonrpc-9.0.3.tgz", + "integrity": "sha512-qETYf9PCl1lVfwR+oBmMfc4vP2nqLNA35ABxorw3j06+xlKRgDVxbLgKm4Y/xPL0YWdeDjLoI4ImICIT3nB0zQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/vscode-languageserver": { + "version": "10.1.2", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/vscode-languageserver/-/vscode-languageserver-10.1.2.tgz", + "integrity": "sha512-pXPWde3RytdeBVEs6PulOOT5OpeXC5GkWRpcT11f5rNn41jviQsAYPyAqJ/0oVGETQLKPJtYbHNiMPlfLb0NTQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "vscode-languageserver-protocol": "3.18.4" + }, + "bin": { + "installServerIntoExtension": "bin/installServerIntoExtension" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.18.4", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.4.tgz", + "integrity": "sha512-CCXbyr99dafRJzJH/0Ryk7ly5T8XPmSR0//OuF2w4m+9JiOin7zcAT5iET8GRE7Z9taFBejb3GbM0a0mbjdbrg==", + "license": "MIT", + "peer": true, + "dependencies": { + "vscode-jsonrpc": "9.0.3", + "vscode-languageserver-types": "3.18.4" + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.16", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.16.tgz", + "integrity": "sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==", + "license": "MIT", + "peer": true + }, + "node_modules/vscode-languageserver-types": { + "version": "3.18.4", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/vscode-languageserver-types/-/vscode-languageserver-types-3.18.4.tgz", + "integrity": "sha512-nQsacoiijvl0fRf2q28uFDrAVwRhdCa3QveiF7/CX0r18mLR5FU/1WskSsCKOjmEbtteKUnY8x8Yzxop+k0zwg==", + "license": "MIT", + "peer": true + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha1-Z+FFz/UQpqaYS98RUpEdadLrnkM=", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha1-CCyyyJyf6GWaMRpTvWpNxTAdswQ=", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha1-nibGPTD1NEPpSJSVshBdN7Z6hdk=", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha1-f0k00PfKjFb5UxSTndzS3ZHOHVU=", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha1-AOLeRDY57Q14/YfeDSdGn7z/tTM=", + "license": "BlueOak-1.0.0", + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha1-d53/5ryv7FlqcXLpgyiaWIZH+qo=", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha1-kJa87r+ZDSG7MfqVFuDt4pSnfTU=", + "license": "ISC", + "engines": { + "node": ">=12" + } + } + } +} diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package.json b/sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package.json new file mode 100644 index 000000000000..c3d5c280d67d --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "@azure-tools/typespec-python": "0.63.10", + "@azure-tools/typespec-client-generator-cli": "0.33.1" + } +} diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/generate.ps1 b/sdk/ai/azure-ai-projects/typespec/component-registration/generate.ps1 new file mode 100644 index 000000000000..da3124abe586 --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/generate.ps1 @@ -0,0 +1,28 @@ +param([switch]$SkipInstall) + +$ErrorActionPreference = 'Stop' +$packageRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$source = Join-Path $PSScriptRoot 'specification\ai-foundry\data-plane\Foundry' +$arguments = @( + 'update', + '--output-dir', $PSScriptRoot, + '--local-spec-repo', $source, + '--no-prompt' +) +if ($SkipInstall) { + $arguments += '--skip-install' +} + +& tsp-client @arguments +if ($LASTEXITCODE -ne 0) { + throw 'Internal Component registration generation failed.' +} + +# Keep only the generated operations; reuse the SDK's existing client and helpers. +foreach ($relativePath in @( + 'operations\_pipeline_component_registration_operations.py', + 'aio\operations\_pipeline_component_registration_operations.py' +)) { + Copy-Item -LiteralPath (Join-Path $PSScriptRoot "output\azure\ai\projects\$relativePath") ` + -Destination (Join-Path $packageRoot "azure\ai\projects\$relativePath") +} diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/client.tsp b/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/client.tsp new file mode 100644 index 000000000000..e61eaa364444 --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/client.tsp @@ -0,0 +1,7 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; + +@@clientName(Azure.AI.Projects, "AIProjectClient"); +@@access(Azure.AI.Projects.PipelineComponentRegistration.registerCommandComponent, Access.internal, "python"); diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/main.tsp b/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/main.tsp new file mode 100644 index 000000000000..93d92afda18b --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/main.tsp @@ -0,0 +1,31 @@ +import "@typespec/http"; + +using TypeSpec.Http; + +@service(#{ title: "Microsoft Foundry Pipeline component registration" }) +@server("{endpoint}", "Microsoft Foundry project endpoint", { endpoint: url }) +namespace Azure.AI.Projects; + +model ComponentVersionRequest { + properties: { + componentSpec: Record; + }; +} + +model RegisteredComponentVersion { + id: string; +} + +interface PipelineComponentRegistration { + @route("/components/{name}/versions/{version}") + @put + registerCommandComponent( + @path name: string, + @path version: string, + @query("api-version") apiVersion: "2026-01-15-preview", + @body component: ComponentVersionRequest, + ): { + @statusCode statusCode: 200 | 201; + @body body: RegisteredComponentVersion; + }; +} diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/tspconfig.yaml b/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/tspconfig.yaml new file mode 100644 index 000000000000..da2bcdd2fed1 --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry/tspconfig.yaml @@ -0,0 +1,15 @@ +emit: + - "@azure-tools/typespec-python" +options: + "@azure-tools/typespec-python": + emitter-output-dir: "{output-dir}/sdk/ai/azure-ai-projects/typespec/component-registration/output" + namespace: azure.ai.projects + package-name: azure-ai-projects + flavor: azure + models-mode: none + generate-typeddict: false + generate-packaging-files: false + generate-sample: false + generate-test: false + emit-cross-language-definition-file: false + combine-operation-files: false diff --git a/sdk/ai/azure-ai-projects/typespec/component-registration/tsp-location.yaml b/sdk/ai/azure-ai-projects/typespec/component-registration/tsp-location.yaml new file mode 100644 index 000000000000..56ca15fbe8a1 --- /dev/null +++ b/sdk/ai/azure-ai-projects/typespec/component-registration/tsp-location.yaml @@ -0,0 +1,7 @@ +# Local-only generation input, not a declaration in the external Foundry spec. +directory: sdk/ai/azure-ai-projects/typespec/component-registration/specification/ai-foundry/data-plane/Foundry +repo: Azure/azure-sdk-for-python +commit: local +additionalDirectories: [] +entrypointFile: client.tsp +emitterPackageJsonPath: sdk/ai/azure-ai-projects/typespec/component-registration/emitter-package.json From 08db0ec892061c7e672cdd4ddf545b8e2f33d611 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Wed, 4 Nov 2026 20:18:21 -0800 Subject: [PATCH 37/52] Update offline Pipeline fixtures for registered component submissions Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../test_pipeline_component_registration.py | 24 +++- .../tests/jobs/test_pipeline_jobs.py | 103 ++++++++++++------ 2 files changed, 93 insertions(+), 34 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py index 7459342938bc..d3d9c7996ce9 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py @@ -183,9 +183,19 @@ def _assert_registered_submission(scenario: _RegistrationScenario, job: Pipeline @pytest.mark.parametrize("surface", _SURFACES) +@pytest.mark.parametrize( + "component_name, component_version", + [("hello_world", "1"), ("hello/world name", "release/1+candidate")], +) def test_pipeline_registers_command_after_upload_and_preserves_reusable_authoring( - authored_job: PipelineJob, surface: str, monkeypatch: pytest.MonkeyPatch + authored_job: PipelineJob, + surface: str, + component_name: str, + component_version: str, + monkeypatch: pytest.MonkeyPatch, ) -> None: + authored_job.jobs["hello_world"]["component"]["name"] = component_name + authored_job.jobs["hello_world"]["component"]["version"] = component_version scenario = _RegistrationScenario(authored_job, surface) transport = _RegistrationTransport(scenario) with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] @@ -200,9 +210,19 @@ def test_pipeline_registers_command_after_upload_and_preserves_reusable_authorin @pytest.mark.asyncio @pytest.mark.parametrize("surface", _SURFACES) +@pytest.mark.parametrize( + "component_name, component_version", + [("hello_world", "1"), ("hello/world name", "release/1+candidate")], +) async def test_pipeline_registers_command_after_upload_and_preserves_reusable_authoring_async( - authored_job: PipelineJob, surface: str, monkeypatch: pytest.MonkeyPatch + authored_job: PipelineJob, + surface: str, + component_name: str, + component_version: str, + monkeypatch: pytest.MonkeyPatch, ) -> None: + authored_job.jobs["hello_world"]["component"]["name"] = component_name + authored_job.jobs["hello_world"]["component"]["version"] = component_version scenario = _RegistrationScenario(authored_job, surface) transport = _AsyncRegistrationTransport(scenario) async with AsyncAIProjectClient( diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 77ab6a18eb21..8f12e86d6239 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -5,6 +5,7 @@ """Offline wire and response tests for Command and Pipeline jobs.""" import importlib +from copy import deepcopy import json import os import re @@ -13,7 +14,7 @@ import sys from pathlib import Path from typing import Any, Union -from urllib.parse import parse_qs, urlparse +from urllib.parse import parse_qs, quote, urlparse import pytest from azure.core.credentials import AccessToken @@ -120,6 +121,10 @@ def __init__(self, request: HttpRequest, payload: dict[str, Any]) -> None: def body(self) -> bytes: return self._content + @property + def content(self) -> bytes: + return self._content + def json(self) -> Any: return json.loads(self._content) @@ -134,6 +139,10 @@ def __init__(self, request: HttpRequest, payload: dict[str, Any]) -> None: def body(self) -> bytes: return self._content + @property + def content(self) -> bytes: + return self._content + async def read(self) -> bytes: return self._content @@ -148,6 +157,9 @@ def __init__(self, responses: list[dict[str, Any]]) -> None: def send(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: self.requests.append(request) + if "/components/" in urlparse(request.url).path: + spec = json.loads(request.body)["properties"]["componentSpec"] + return _JsonResponse(request, {"id": _registered_component_id(spec["name"], spec["version"])}) return _JsonResponse(request, next(self._responses)) def open(self) -> None: @@ -167,6 +179,9 @@ def __init__(self, responses: list[dict[str, Any]]) -> None: async def send(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: self.requests.append(request) + if "/components/" in urlparse(request.url).path: + spec = json.loads(request.body)["properties"]["componentSpec"] + return _AsyncJsonResponse(request, {"id": _registered_component_id(spec["name"], spec["version"])}) return _AsyncJsonResponse(request, next(self._responses)) async def open(self) -> None: @@ -273,10 +288,38 @@ def _inline_pipeline() -> tuple[PipelineJob, CommandJob]: return pipeline, command -def _assert_inline_request(request: HttpRequest) -> None: +def _registered_component_id(name: str, version: str) -> str: + return ( + "/subscriptions/test/resourceGroups/test/providers/Microsoft.MachineLearningServices/" + f"workspaces/fake-account@fake-project@AML/components/{name}/versions/{version}" + ) + + +def _assert_registered_pipeline_requests(requests: list[HttpRequest], properties: dict[str, Any]) -> None: + expected = deepcopy(properties) + nodes = [ + node for node in expected["jobs"].values() + if node.get("type") == "command" and isinstance(node.get("component"), dict) + ] + assert len(requests) == len(nodes) + 1 + for request, node in zip(requests[:-1], nodes): + spec = node.pop("component") + assert request.method == "PUT" + assert urlparse(request.url).path == ( + f"{urlparse(_ENDPOINT).path}/components/{quote(spec['name'], safe='')}" + f"/versions/{quote(str(spec['version']), safe='')}" + ) + assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] + assert json.loads(request.body) == {"properties": {"componentSpec": spec}} + node["componentId"] = _registered_component_id(spec["name"], spec["version"]) + assert json.loads(requests[-1].body) == {"properties": expected} + + +def _assert_inline_request(requests: list[HttpRequest]) -> None: + request = requests[-1] assert request.method == "PUT" assert request.headers["Foundry-Features"] == "Jobs=V1Preview" - assert json.loads(request.body) == {"properties": _INLINE_PIPELINE_PROPERTIES} + _assert_registered_pipeline_requests(requests, _INLINE_PIPELINE_PROPERTIES) def _two_code_job(tmp_path: Path) -> tuple[PipelineJob, dict[str, Path]]: @@ -311,7 +354,8 @@ def _uploaded_code(name: str, version: str) -> DatasetVersion: ) -def _assert_two_code_request(request: HttpRequest, code_uris: dict[str, str]) -> None: +def _assert_two_code_request(requests: list[HttpRequest], code_uris: dict[str, str]) -> None: + request = requests[-1] assert request.method == "PUT" assert request.headers["Foundry-Features"] == "Jobs=V1Preview" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] @@ -373,7 +417,7 @@ def _assert_two_code_request(request: HttpRequest, code_uris: dict[str, str]) -> }, } } - assert json.loads(request.body) == expected + _assert_registered_pipeline_requests(requests, expected["properties"]) def test_jobs_sync_create_from_command_node() -> None: @@ -383,8 +427,7 @@ def test_jobs_sync_create_from_command_node() -> None: with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] _assert_job(client.pipeline_jobs.create_or_update("pipeline", pipeline), "Pipeline") - assert len(transport.requests) == 1 - _assert_inline_request(transport.requests[0]) + _assert_inline_request(transport.requests) assert command.inputs is not None assert command.inputs["name"].value == "${{parent.inputs.name}}" assert command.resources is not None @@ -401,8 +444,7 @@ async def test_jobs_async_create_from_command_node() -> None: ) as client: _assert_job(await client.pipeline_jobs.create_or_update("pipeline", pipeline), "Pipeline") - assert len(transport.requests) == 1 - _assert_inline_request(transport.requests[0]) + _assert_inline_request(transport.requests) def test_jobs_sync_create_from_mapping_with_command_node() -> None: @@ -421,8 +463,7 @@ def test_jobs_sync_create_from_mapping_with_command_node() -> None: with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] _assert_job(client.pipeline_jobs.create_or_update("pipeline", pipeline), "Pipeline") - assert len(transport.requests) == 1 - _assert_inline_request(transport.requests[0]) + _assert_inline_request(transport.requests) def test_pipeline_composes_commands_and_preserves_raw_graph_nodes() -> None: @@ -507,12 +548,11 @@ def test_pipeline_converts_value_bound_uri_folder_input() -> None: "Pipeline", ) - submitted_jobs = json.loads(transport.requests[0].body)[ + _assert_registered_pipeline_requests(transport.requests, pipeline.as_dict(exclude_readonly=True)) + submitted_jobs = json.loads(transport.requests[-1].body)[ "properties" ]["jobs"] - assert submitted_jobs["consumer"]["component"]["inputs"][ - "bundle" - ] == {"type": "uri_folder"} + assert submitted_jobs["consumer"]["componentId"] == _registered_component_id("consumer", "1") assert submitted_jobs["consumer"]["inputs"]["bundle"] == { "job_input_type": "literal", "value": "${{parent.jobs.producer.outputs.bundle}}", @@ -547,9 +587,8 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat ("two-code-consume-code", str(code_dirs["consume"])), ] assert uploads[0][1] != uploads[1][1] - assert len(transport.requests) == 1 _assert_two_code_request( - transport.requests[0], + transport.requests, { name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) for name, version, _ in uploads @@ -587,9 +626,8 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) ("two-code-produce-code", str(code_dirs["produce"])), ("two-code-consume-code", str(code_dirs["consume"])), ] - assert len(transport.requests) == 1 _assert_two_code_request( - transport.requests[0], + transport.requests, { name.removeprefix("two-code-").removesuffix("-code"): _code_uri(name, version) for name, version, _ in uploads @@ -751,7 +789,8 @@ def _dsl_code_paths(job: PipelineJob) -> dict[str, Path]: return {name: Path(node["component"]["code"]) for name, node in job.jobs.items()} -def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: +def _assert_dsl_request(requests: list[HttpRequest], uploaded: dict[str, str]) -> None: + request = requests[-1] assert request.method == "PUT" assert request.headers["Foundry-Features"] == "Jobs=V1Preview" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] @@ -762,7 +801,7 @@ def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: "properties": {"AISuperComputer": {"SLATier": "Premium"}}, } identity = {"type": "managed", "msi_resource_id": "/subscriptions/test/identities/hello"} - assert json.loads(request.body) == { + expected = { "properties": { "jobType": "Pipeline", "displayName": "workflow", @@ -820,6 +859,7 @@ def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: }, } } + _assert_registered_pipeline_requests(requests, expected["properties"]) def test_dsl_component_bodies_execute_with_module_level_imports( @@ -880,9 +920,8 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat assert [name.rsplit("-", 2)[-2] for name, _ in uploads] == ["produce", "consume"] assert [folder for _, folder in uploads] == [str(paths["produce"]), str(paths["consume"])] assert all(not path.exists() for path in paths.values()) - assert len(transport.requests) == 1 code_uris = {name.rsplit("-", 2)[-2]: job.jobs[name.rsplit("-", 2)[-2]]["component"]["code"] for name, _ in uploads} - _assert_dsl_request(transport.requests[0], code_uris) + _assert_dsl_request(transport.requests, code_uris) @pytest.mark.asyncio @@ -911,8 +950,8 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) assert len(uploads) == 2 assert [folder for _, folder in uploads] == [str(paths["produce"]), str(paths["consume"])] assert all(not path.exists() for path in paths.values()) - assert len(transport.requests) == 1 - assert json.loads(transport.requests[0].body)["properties"]["experimentName"] == "pipeline_samples" + _assert_registered_pipeline_requests(transport.requests, job.as_dict(exclude_readonly=True)) + assert json.loads(transport.requests[-1].body)["properties"]["experimentName"] == "pipeline_samples" def test_dsl_upload_failure_cleans_code_without_put(monkeypatch: pytest.MonkeyPatch) -> None: @@ -1242,10 +1281,10 @@ def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) -> Dat assert len(uploads) == 1 assert uploads[0][1] == str(snapshot) assert not snapshot.exists() - assert len(transport.requests) == 1 - properties = json.loads(transport.requests[0].body)["properties"] - assert properties["jobs"]["produce"]["component"]["code"] == properties["jobs"]["consume"]["component"]["code"] - assert properties["jobs"]["produce"]["component"]["code"] == job.jobs["produce"]["component"]["code"] + _assert_registered_pipeline_requests(transport.requests, job.as_dict(exclude_readonly=True)) + specs = [json.loads(request.body)["properties"]["componentSpec"] for request in transport.requests[:-1]] + assert specs[0]["code"] == specs[1]["code"] == job.jobs["produce"]["component"]["code"] + properties = json.loads(transport.requests[-1].body)["properties"] assert properties["experimentName"] == "pipeline_samples" @@ -1272,9 +1311,9 @@ async def upload_folder(*, name: str, version: str, folder: str, **kwargs: Any) assert uploads == [str(snapshot)] assert not snapshot.exists() - assert len(transport.requests) == 1 - properties = json.loads(transport.requests[0].body)["properties"] - assert properties["jobs"]["produce"]["component"]["code"] == properties["jobs"]["consume"]["component"]["code"] + _assert_registered_pipeline_requests(transport.requests, job.as_dict(exclude_readonly=True)) + specs = [json.loads(request.body)["properties"]["componentSpec"] for request in transport.requests[:-1]] + assert specs[0]["code"] == specs[1]["code"] def test_dsl_source_snapshot_filters_files_before_hash_and_upload(tmp_path: Path) -> None: From 7c0c029b4457f62ad6a78153c5ee03392770173f Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Wed, 4 Nov 2026 20:23:41 -0800 Subject: [PATCH 38/52] Verify registration with standard azure-core REST responses Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../test_pipeline_component_registration.py | 54 ++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py index d3d9c7996ce9..de44580c3bb8 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py @@ -11,8 +11,15 @@ from urllib.parse import parse_qs, quote, urlparse import pytest +import requests from azure.core.exceptions import HttpResponseError, ResourceNotFoundError -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest, HttpResponse +from azure.core.pipeline.transport import ( + AsyncHttpResponse, + AsyncioRequestsTransport, + HttpRequest, + HttpResponse, + RequestsTransport, +) from azure.ai.projects import AIProjectClient from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient @@ -182,6 +189,51 @@ def _assert_registered_submission(scenario: _RegistrationScenario, job: Pipeline assert job.as_dict(exclude_readonly=True) == scenario.uploaded_authoring() +def _mock_requests_session(scenario: _RegistrationScenario, monkeypatch: pytest.MonkeyPatch) -> requests.Session: + session = requests.Session() + + def respond(method: str, url: str, **kwargs: Any) -> requests.Response: + request = HttpRequest(method, url, headers=kwargs.get("headers"), data=kwargs.get("data")) + payload, status = scenario.respond(request) + response = requests.Response() + response.status_code = status + response.headers["Content-Type"] = "application/json" + response.url = url + response._content = json.dumps(payload).encode() + response._content_consumed = True + return response + + monkeypatch.setattr(session, "request", respond) + return session + + +def test_registration_with_standard_core_rest_responses( + authored_job: PipelineJob, monkeypatch: pytest.MonkeyPatch +) -> None: + scenario = _RegistrationScenario(authored_job, "pipeline_jobs") + with _mock_requests_session(scenario, monkeypatch) as session: + transport = RequestsTransport(session=session, session_owner=False) + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + _mock_source_upload(client.pipeline_jobs, scenario, monkeypatch) + client.pipeline_jobs.create_or_update(_JOB_NAME, authored_job) + _assert_registered_submission(scenario, authored_job) + + +@pytest.mark.asyncio +async def test_registration_with_standard_core_rest_responses_async( + authored_job: PipelineJob, monkeypatch: pytest.MonkeyPatch +) -> None: + scenario = _RegistrationScenario(authored_job, "pipeline_jobs") + with _mock_requests_session(scenario, monkeypatch) as session: + transport = AsyncioRequestsTransport(session=session, session_owner=False) + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + _mock_source_upload(client.pipeline_jobs, scenario, monkeypatch, is_async=True) + await client.pipeline_jobs.create_or_update(_JOB_NAME, authored_job) + _assert_registered_submission(scenario, authored_job) + + @pytest.mark.parametrize("surface", _SURFACES) @pytest.mark.parametrize( "component_name, component_version", From 3dfe427a95609fda997e041bb529cbe610736aa6 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Wed, 4 Nov 2026 20:24:47 -0800 Subject: [PATCH 39/52] Provide a complete in-memory Requests response fixture Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/jobs/test_pipeline_component_registration.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py index de44580c3bb8..28afcad8b3b2 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py @@ -12,6 +12,7 @@ import pytest import requests +from urllib3.response import HTTPResponse as Urllib3Response from azure.core.exceptions import HttpResponseError, ResourceNotFoundError from azure.core.pipeline.transport import ( AsyncHttpResponse, @@ -201,6 +202,7 @@ def respond(method: str, url: str, **kwargs: Any) -> requests.Response: response.url = url response._content = json.dumps(payload).encode() response._content_consumed = True + response.raw = Urllib3Response(body=response._content, status=status, headers=response.headers) return response monkeypatch.setattr(session, "request", respond) From 020bb6ac4106565069ba4b95820bfe438491fd43 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 10 Nov 2026 18:28:47 -0800 Subject: [PATCH 40/52] Fix Pipeline and single-file job output downloads Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/CHANGELOG.md | 1 + .../aio/operations/_patch_jobs_async.py | 30 ++- .../ai/projects/operations/_job_helper.py | 8 +- .../ai/projects/operations/_patch_jobs.py | 31 ++- .../tests/jobs/test_pipeline_jobs.py | 254 +++++++++++++++++- 5 files changed, 296 insertions(+), 28 deletions(-) diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 25f354a62ad8..af68e89563e3 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -69,6 +69,7 @@ Breaking changes in beta classes: ### Bugs Fixed +* Fixed synchronous and asynchronous `.beta.jobs.download` to handle Pipeline output mappings and download exact `uri_file` blobs without including similarly prefixed sibling blobs. * Fixed telemetry instrumentor to correctly call is_recording() as a method on spans, ensuring non-recording spans are properly skipped (e.g., when sampling is configured) ([GitHub issue 46544](https://github.com/Azure/azure-sdk-for-python/issues/46544)). * Fixed `load_job` dropping the `outputs` block of a job YAML file. Unlike `inputs`, outputs were not converted into `Output` instances, so a YAML file using the documented snake_case field names (for example `asset_name`) was serialized with those names verbatim instead of their wire names, and the values never reached the service. Outputs are now converted in the same way as inputs. * Fixed `ModuleNotFoundError: No module named 'httpx'` when installing the package into a clean environment. `httpx` is imported directly by the client but was only ever satisfied transitively through `openai`; `openai` 3.0.0 replaced that dependency with `httpx2`, so `httpx` stopped being installed. `httpx` is now declared explicitly, and `openai` is capped below 3.0.0 because the client still passes an `httpx.Client` to `OpenAI(http_client=...)`. diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 849056c3c3f7..4a7c4369e600 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -14,7 +14,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed from os import PathLike from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Union, cast, overload +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union, cast, overload from urllib.parse import urlparse from uuid import uuid4 @@ -635,17 +635,17 @@ async def stream(self, name: str, **kwargs: Any) -> None: # type: ignore[overri error_text = json.dumps(error_payload, indent=4) if isinstance(error_payload, dict) else error_payload raise RuntimeError("Exception : \n {} ".format(error_text)) - async def _resolve_output_to_blob_ref(self, output_name: str, output: _Output) -> BlobReference: + async def _resolve_output_to_blob_ref(self, output_name: str, output: Union[_Output, Mapping[str, Any]]) -> BlobReference: """Resolve a job ``Output`` to a :class:`~azure.ai.projects.models.BlobReference`. :param output_name: The output name. :type output_name: str :param output: The job output object from the Get Job response. - :type output: ~azure.ai.projects.models.Output + :type output: ~azure.ai.projects.models.Output or Mapping[str, Any] :return: A blob reference describing the storage location and SAS credential. :rtype: ~azure.ai.projects.models.BlobReference """ - _validate_output_for_download(output_name, output) + output = _validate_output_for_download(output_name, output) assert output.asset_name is not None and output.asset_version is not None if output.type == AssetTypes.SAFETENSORS_MODEL: model_version = await self._models.get(name=output.asset_name, version=output.asset_version) @@ -659,7 +659,7 @@ async def _resolve_output_to_blob_ref(self, output_name: str, output: _Output) - return credential.blob_reference async def _download_blob_reference(self, blob_ref: BlobReference, destination: Path) -> Tuple[int, int]: - """Download every blob under ``blob_ref`` into ``destination``. + """Download the exact file or the folder contents at ``blob_ref`` into ``destination``. :param blob_ref: The blob reference to download. :type blob_ref: ~azure.ai.projects.models.BlobReference @@ -682,22 +682,26 @@ async def _download_blob_reference(self, blob_ref: BlobReference, destination: P async with AsyncContainerClient.from_container_url(container_url=sas_uri) as container_client: list_prefix = (prefix + "/") if prefix else "" blobs = [] - async for blob in container_client.list_blobs(name_starts_with=list_prefix or None, include=["metadata"]): - blobs.append(blob) + async for blob in container_client.list_blobs(name_starts_with=prefix or None, include=["metadata"]): + if blob.name == prefix or blob.name.startswith(list_prefix): + blobs.append(blob) all_names = {b.name for b in blobs} file_count = 0 total_bytes = 0 for blob in blobs: blob_name = blob.name - if list_prefix and blob_name.startswith(list_prefix): - relative = blob_name[len(list_prefix) :] + is_folder = _is_folder_marker(blob, all_names) + if blob_name == prefix: + if is_folder: + continue + relative = blob_name.rsplit("/", 1)[-1] else: - relative = blob_name + relative = blob_name[len(list_prefix) :] if not relative: continue local_path = destination / relative - if _is_folder_marker(blob, all_names): + if is_folder: _ensure_dir(local_path) continue _ensure_dir(local_path.parent) @@ -790,7 +794,7 @@ async def _download_named_output( self, job_name: str, output_name: str, - output: _Output, + output: Union[_Output, Mapping[str, Any]], dest_root: Path, ) -> None: """Resolve and download a single named output into ``/named-outputs//``. @@ -800,7 +804,7 @@ async def _download_named_output( :param output_name: The output name to download. :type output_name: str :param output: The job output object from the Get Job response. - :type output: ~azure.ai.projects.models.Output + :type output: ~azure.ai.projects.models.Output or Mapping[str, Any] :param dest_root: The base local directory; the output is written into ``/named-outputs//``. :type dest_root: ~pathlib.Path diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py index 2dc55cc1cedf..4cb96d79f0c4 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py @@ -18,6 +18,7 @@ Dict, Iterable, List, + Mapping, Optional, Set, TextIO, @@ -228,7 +229,10 @@ def _ensure_dir(p: Path) -> None: p.mkdir(parents=True, exist_ok=True) -def _validate_output_for_download(output_name: str, output: _Output) -> None: +def _validate_output_for_download(output_name: str, output: Union[_Output, Mapping[str, Any]]) -> _Output: + if not isinstance(output, _Output): + output = _Output(output) + if not output.asset_name or not output.asset_version: raise ValueError( f"Output '{output_name}' has no registered asset (assetName / assetVersion is missing). " @@ -241,7 +245,7 @@ def _validate_output_for_download(output_name: str, output: _Output) -> None: AssetTypes.URI_FOLDER, AssetTypes.SAFETENSORS_MODEL, ): - return + return output raise ValueError( f"Output '{output_name}' has unsupported jobOutputType '{out_type}'. " diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py index 961fc468e8fb..2bb8d1b76bea 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_jobs.py @@ -13,7 +13,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed from os import PathLike from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Union, overload +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union, overload from urllib.parse import urlparse from uuid import uuid4 @@ -648,17 +648,17 @@ def stream(self, name: str, **kwargs: Any) -> None: # type: ignore[override] error_text = json.dumps(error_payload, indent=4) if isinstance(error_payload, dict) else error_payload raise RuntimeError("Exception : \n {} ".format(error_text)) - def _resolve_output_to_blob_ref(self, output_name: str, output: _Output) -> BlobReference: + def _resolve_output_to_blob_ref(self, output_name: str, output: Union[_Output, Mapping[str, Any]]) -> BlobReference: """Resolve a job ``Output`` to a :class:`~azure.ai.projects.models.BlobReference`. :param output_name: The output name. :type output_name: str :param output: The job output object from the Get Job response. - :type output: ~azure.ai.projects.models.Output + :type output: ~azure.ai.projects.models.Output or Mapping[str, Any] :return: A blob reference describing the storage location and SAS credential. :rtype: ~azure.ai.projects.models.BlobReference """ - _validate_output_for_download(output_name, output) + output = _validate_output_for_download(output_name, output) assert output.asset_name is not None and output.asset_version is not None if output.type == AssetTypes.SAFETENSORS_MODEL: model_version = self._models.get(name=output.asset_name, version=output.asset_version) @@ -672,7 +672,7 @@ def _resolve_output_to_blob_ref(self, output_name: str, output: _Output) -> Blob return credential.blob_reference def _download_blob_reference(self, blob_ref: BlobReference, destination: Path) -> Tuple[int, int]: - """Download every blob under ``blob_ref`` into ``destination``. + """Download the exact file or the folder contents at ``blob_ref`` into ``destination``. :param blob_ref: The blob reference to download. :type blob_ref: ~azure.ai.projects.models.BlobReference @@ -694,21 +694,28 @@ def _download_blob_reference(self, blob_ref: BlobReference, destination: Path) - with ContainerClient.from_container_url(container_url=sas_uri) as container_client: list_prefix = (prefix + "/") if prefix else "" - blobs = list(container_client.list_blobs(name_starts_with=list_prefix or None, include=["metadata"])) + blobs = [ + blob + for blob in container_client.list_blobs(name_starts_with=prefix or None, include=["metadata"]) + if blob.name == prefix or blob.name.startswith(list_prefix) + ] all_names = {b.name for b in blobs} file_count = 0 total_bytes = 0 for blob in blobs: blob_name = blob.name - if list_prefix and blob_name.startswith(list_prefix): - relative = blob_name[len(list_prefix) :] + is_folder = _is_folder_marker(blob, all_names) + if blob_name == prefix: + if is_folder: + continue + relative = blob_name.rsplit("/", 1)[-1] else: - relative = blob_name + relative = blob_name[len(list_prefix) :] if not relative: continue local_path = destination / relative - if _is_folder_marker(blob, all_names): + if is_folder: _ensure_dir(local_path) continue _ensure_dir(local_path.parent) @@ -803,7 +810,7 @@ def _download_named_output( self, job_name: str, output_name: str, - output: _Output, + output: Union[_Output, Mapping[str, Any]], dest_root: Path, ) -> None: """Resolve and download a single named output into ``/named-outputs//``. @@ -813,7 +820,7 @@ def _download_named_output( :param output_name: The output name to download. :type output_name: str :param output: The job output object from the Get Job response. - :type output: ~azure.ai.projects.models.Output + :type output: ~azure.ai.projects.models.Output or Mapping[str, Any] :param dest_root: The base local directory; the output is written into ``/named-outputs//``. :type dest_root: ~pathlib.Path diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 77ab6a18eb21..ee7bc7e9e2dd 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -12,7 +12,9 @@ import subprocess import sys from pathlib import Path -from typing import Any, Union +from types import SimpleNamespace +from typing import Any, Optional, Union +from unittest.mock import AsyncMock, MagicMock, Mock from urllib.parse import parse_qs, urlparse import pytest @@ -25,11 +27,13 @@ HttpResponse, HttpTransport, ) +from azure.storage.blob import BlobProperties from azure.ai.projects import AIProjectClient, dsl from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient from azure.ai.projects.models import ( AssetTypes, + BlobReference, CommandJob, DatasetVersion, Input, @@ -248,6 +252,254 @@ def _assert_pipeline_jobs_requests(requests: list[HttpRequest], expected: dict[s assert json.loads(requests[0].body) == {"properties": expected} +def _download_job_response(kind: str) -> dict[str, Any]: + return { + "name": "download-job", + "properties": { + "jobType": kind, + "status": "Completed", + "outputs": { + "message": {"jobOutputType": "uri_file", "assetName": "offline-output", "assetVersion": "1"}, + }, + }, + } + + +def _download_blob_response(prefix: str) -> dict[str, Any]: + return { + "blobUri": f"https://fake-storage.blob.core.windows.net/outputs/{prefix}", + "storageAccountArmId": "/storageAccounts/fake-storage", + "credential": {"sasUri": "https://fake-storage.blob.core.windows.net/outputs", "type": "SAS"}, + } + + +@pytest.mark.parametrize("kind", ["Pipeline", "Command"]) +@pytest.mark.parametrize("download_all", [False, True]) +def test_jobs_download_registered_outputs( + kind: str, download_all: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + response = _download_job_response(kind) + if download_all: + response["properties"]["outputs"]["unregistered"] = {"jobOutputType": "uri_file"} + blob_response = _download_blob_response("jobs/run/message") + transport = _Transport([response, {"blobReference": blob_response}]) + download = Mock(return_value=(1, 12)) + artifacts = Mock() + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + monkeypatch.setattr(client.beta.jobs, "_download_blob_reference", download) + monkeypatch.setattr(client.beta.jobs, "_download_default_artifacts", artifacts) + client.beta.jobs.download( + "download-job", download_path=tmp_path, output_name=None if download_all else "message", all=download_all + ) + + download.assert_called_once() + assert download.call_args.args[0].as_dict() == blob_response + assert download.call_args.args[1] == tmp_path / "named-outputs" / "message" + assert len(transport.requests) == 2 + assert urlparse(transport.requests[1].url).path.endswith("/datasets/offline-output/versions/1/credentials") + if download_all: + artifacts.assert_called_once() + assert "Skipping output 'unregistered'" in caplog.text + assert "has no registered asset" in caplog.text + else: + artifacts.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["Pipeline", "Command"]) +@pytest.mark.parametrize("download_all", [False, True]) +async def test_jobs_download_registered_outputs_async( + kind: str, download_all: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + response = _download_job_response(kind) + if download_all: + response["properties"]["outputs"]["unregistered"] = {"jobOutputType": "uri_file"} + blob_response = _download_blob_response("jobs/run/message") + transport = _AsyncTransport([response, {"blobReference": blob_response}]) + download = AsyncMock(return_value=(1, 12)) + artifacts = AsyncMock() + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + monkeypatch.setattr(client.beta.jobs, "_download_blob_reference", download) + monkeypatch.setattr(client.beta.jobs, "_download_default_artifacts", artifacts) + await client.beta.jobs.download( + "download-job", download_path=tmp_path, output_name=None if download_all else "message", all=download_all + ) + + download.assert_awaited_once() + assert download.call_args.args[0].as_dict() == blob_response + assert download.call_args.args[1] == tmp_path / "named-outputs" / "message" + assert len(transport.requests) == 2 + assert urlparse(transport.requests[1].url).path.endswith("/datasets/offline-output/versions/1/credentials") + if download_all: + artifacts.assert_awaited_once() + assert "Skipping output 'unregistered'" in caplog.text + assert "has no registered asset" in caplog.text + else: + artifacts.assert_not_awaited() + + +def test_jobs_download_unregistered_pipeline_output(tmp_path: Path) -> None: + response = _download_job_response("Pipeline") + response["properties"]["outputs"]["message"].update(assetName=None, assetVersion=None, uri=None) + transport = _Transport([response]) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] + with pytest.raises(ValueError, match="Output 'message' has no registered asset"): + client.beta.jobs.download("download-job", output_name="message", download_path=tmp_path) + + assert len(transport.requests) == 1 + + +@pytest.mark.asyncio +async def test_jobs_download_unregistered_pipeline_output_async(tmp_path: Path) -> None: + response = _download_job_response("Pipeline") + response["properties"]["outputs"]["message"].update(assetName=None, assetVersion=None, uri=None) + transport = _AsyncTransport([response]) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] + ) as client: + with pytest.raises(ValueError, match="Output 'message' has no registered asset"): + await client.beta.jobs.download("download-job", output_name="message", download_path=tmp_path) + + assert len(transport.requests) == 1 + + +_OUTPUT_DOWNLOAD_CASES = [ + pytest.param("jobs/run/message", {"message": b"hello world\n"}, set(), id="exact-file"), + pytest.param("jobs/run/empty", {"empty": b""}, set(), id="empty-file"), + pytest.param( + "jobs/run/output/", + {"nested/result.txt": b"nested\n", "zero": b""}, + {"nested", "empty-directory"}, + id="folder", + ), + pytest.param( + "", + { + "jobs/run/message": b"hello world\n", + "jobs/run/message-other": b"sibling", + "jobs/run/empty": b"", + "jobs/run/output/nested/result.txt": b"nested\n", + "jobs/run/output/zero": b"", + "jobs/run/output-other/ignored": b"sibling", + }, + { + "jobs", + "jobs/run", + "jobs/run/output", + "jobs/run/output/nested", + "jobs/run/output/empty-directory", + "jobs/run/output-other", + }, + id="container", + ), +] + + +@pytest.fixture +def output_blob_contents() -> dict[str, bytes]: + return { + "jobs/run/message": b"hello world\n", + "jobs/run/message-other": b"sibling", + "jobs/run/empty": b"", + "jobs/run/output": b"", + "jobs/run/output/nested": b"", + "jobs/run/output/nested/result.txt": b"nested\n", + "jobs/run/output/zero": b"", + "jobs/run/output/empty-directory": b"", + "jobs/run/output-other/ignored": b"sibling", + } + + +def _list_output_blobs( + contents: dict[str, bytes], name_starts_with: Optional[str] = None, **kwargs: Any +) -> list[BlobProperties]: + return [ + BlobProperties( + name=name, + size=len(content), + metadata={"hdi_isfolder": "true"} if name.endswith("/empty-directory") else {}, + ) + for name, content in contents.items() + if name.startswith(name_starts_with or "") + ] + + +def _assert_downloaded_output( + destination: Path, result: tuple[int, int], expected_files: dict[str, bytes], expected_dirs: set[str] +) -> None: + assert result == (len(expected_files), sum(len(content) for content in expected_files.values())) + assert { + path.relative_to(destination).as_posix(): path.read_bytes() for path in destination.rglob("*") if path.is_file() + } == expected_files + assert {path.relative_to(destination).as_posix() for path in destination.rglob("*") if path.is_dir()} == expected_dirs + + +@pytest.mark.parametrize("prefix, expected_files, expected_dirs", _OUTPUT_DOWNLOAD_CASES) +def test_jobs_download_blob_reference( + prefix: str, + expected_files: dict[str, bytes], + expected_dirs: set[str], + output_blob_contents: dict[str, bytes], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + container = MagicMock() + container.__enter__.return_value = container + container.list_blobs.side_effect = lambda **kwargs: _list_output_blobs(output_blob_contents, **kwargs) + container.download_blob.side_effect = lambda *, blob, **kwargs: SimpleNamespace( + readinto=lambda stream: stream.write(output_blob_contents[blob]) + ) + monkeypatch.setattr( + "azure.ai.projects.operations._patch_jobs.ContainerClient.from_container_url", Mock(return_value=container) + ) + + with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=_Transport([])) as client: # type: ignore[arg-type] + result = client.beta.jobs._download_blob_reference(BlobReference(_download_blob_response(prefix)), tmp_path) + + _assert_downloaded_output(tmp_path, result, expected_files, expected_dirs) + assert container.download_blob.call_count == len(expected_files) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("prefix, expected_files, expected_dirs", _OUTPUT_DOWNLOAD_CASES) +async def test_jobs_download_blob_reference_async( + prefix: str, + expected_files: dict[str, bytes], + expected_dirs: set[str], + output_blob_contents: dict[str, bytes], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def list_blobs(**kwargs: Any) -> Any: + for blob in _list_output_blobs(output_blob_contents, **kwargs): + yield blob + + container = AsyncMock() + container.__aenter__.return_value = container + container.list_blobs = Mock(side_effect=list_blobs) + container.download_blob.side_effect = lambda *, blob, **kwargs: SimpleNamespace( + readinto=AsyncMock(side_effect=lambda stream: stream.write(output_blob_contents[blob])) + ) + monkeypatch.setattr( + "azure.ai.projects.aio.operations._patch_jobs_async.AsyncContainerClient.from_container_url", + Mock(return_value=container), + ) + + async with AsyncAIProjectClient( + endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=_AsyncTransport([]) # type: ignore[arg-type] + ) as client: + result = await client.beta.jobs._download_blob_reference(BlobReference(_download_blob_response(prefix)), tmp_path) + + _assert_downloaded_output(tmp_path, result, expected_files, expected_dirs) + assert container.download_blob.await_count == len(expected_files) + + def _inline_pipeline() -> tuple[PipelineJob, CommandJob]: command = CommandJob( command="echo hello ${{inputs.name}}", From db873824a55cab793ef197d2ef46dfbcc0a483d7 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Tue, 10 Nov 2026 18:32:28 -0800 Subject: [PATCH 41/52] Refine offline output download fixtures Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../aio/operations/_patch_jobs_async.py | 4 ++- .../tests/jobs/test_pipeline_jobs.py | 29 +++++++++++++------ 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py index 4a7c4369e600..02e8a4792666 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_jobs_async.py @@ -635,7 +635,9 @@ async def stream(self, name: str, **kwargs: Any) -> None: # type: ignore[overri error_text = json.dumps(error_payload, indent=4) if isinstance(error_payload, dict) else error_payload raise RuntimeError("Exception : \n {} ".format(error_text)) - async def _resolve_output_to_blob_ref(self, output_name: str, output: Union[_Output, Mapping[str, Any]]) -> BlobReference: + async def _resolve_output_to_blob_ref( + self, output_name: str, output: Union[_Output, Mapping[str, Any]] + ) -> BlobReference: """Resolve a job ``Output`` to a :class:`~azure.ai.projects.models.BlobReference`. :param output_name: The output name. diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index ee7bc7e9e2dd..8a3f81734e0b 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -27,7 +27,6 @@ HttpResponse, HttpTransport, ) -from azure.storage.blob import BlobProperties from azure.ai.projects import AIProjectClient, dsl from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient @@ -287,8 +286,12 @@ def test_jobs_download_registered_outputs( artifacts = Mock() with AIProjectClient(endpoint=_ENDPOINT, credential=_Credential(), transport=transport) as client: # type: ignore[arg-type] - monkeypatch.setattr(client.beta.jobs, "_download_blob_reference", download) - monkeypatch.setattr(client.beta.jobs, "_download_default_artifacts", artifacts) + monkeypatch.setattr( + "azure.ai.projects.operations._patch_jobs.JobsOperations._download_blob_reference", download + ) + monkeypatch.setattr( + "azure.ai.projects.operations._patch_jobs.JobsOperations._download_default_artifacts", artifacts + ) client.beta.jobs.download( "download-job", download_path=tmp_path, output_name=None if download_all else "message", all=download_all ) @@ -323,8 +326,12 @@ async def test_jobs_download_registered_outputs_async( async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=transport # type: ignore[arg-type] ) as client: - monkeypatch.setattr(client.beta.jobs, "_download_blob_reference", download) - monkeypatch.setattr(client.beta.jobs, "_download_default_artifacts", artifacts) + monkeypatch.setattr( + "azure.ai.projects.aio.operations._patch_jobs_async.JobsOperations._download_blob_reference", download + ) + monkeypatch.setattr( + "azure.ai.projects.aio.operations._patch_jobs_async.JobsOperations._download_default_artifacts", artifacts + ) await client.beta.jobs.download( "download-job", download_path=tmp_path, output_name=None if download_all else "message", all=download_all ) @@ -418,9 +425,9 @@ def output_blob_contents() -> dict[str, bytes]: def _list_output_blobs( contents: dict[str, bytes], name_starts_with: Optional[str] = None, **kwargs: Any -) -> list[BlobProperties]: +) -> list[SimpleNamespace]: return [ - BlobProperties( + SimpleNamespace( name=name, size=len(content), metadata={"hdi_isfolder": "true"} if name.endswith("/empty-directory") else {}, @@ -437,7 +444,9 @@ def _assert_downloaded_output( assert { path.relative_to(destination).as_posix(): path.read_bytes() for path in destination.rglob("*") if path.is_file() } == expected_files - assert {path.relative_to(destination).as_posix() for path in destination.rglob("*") if path.is_dir()} == expected_dirs + assert { + path.relative_to(destination).as_posix() for path in destination.rglob("*") if path.is_dir() + } == expected_dirs @pytest.mark.parametrize("prefix, expected_files, expected_dirs", _OUTPUT_DOWNLOAD_CASES) @@ -494,7 +503,9 @@ async def list_blobs(**kwargs: Any) -> Any: async with AsyncAIProjectClient( endpoint=_ENDPOINT, credential=_AsyncCredential(), transport=_AsyncTransport([]) # type: ignore[arg-type] ) as client: - result = await client.beta.jobs._download_blob_reference(BlobReference(_download_blob_response(prefix)), tmp_path) + result = await client.beta.jobs._download_blob_reference( + BlobReference(_download_blob_response(prefix)), tmp_path + ) _assert_downloaded_output(tmp_path, result, expected_files, expected_dirs) assert container.download_blob.await_count == len(expected_files) From 835c35d3c3b2be26778d9be2a60e413737474408 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 13 Nov 2026 10:17:59 -0800 Subject: [PATCH 42/52] Fix PipelineJob typing and memory paging request Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/aio/operations/_operations.py | 12 ++++++------ .../aio/operations/_patch_pipeline_jobs_async.py | 6 +++--- .../azure/ai/projects/operations/_operations.py | 12 ++++++------ .../ai/projects/operations/_patch_pipeline_jobs.py | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py index 33eab96768ae..b51e620e4305 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py @@ -9628,6 +9628,12 @@ def list_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) content_type = content_type or "application/json" + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} + _content = None if isinstance(body, (IOBase, bytes)): _content = body @@ -9635,12 +9641,6 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} - body = {k: v for k, v in body.items() if v is not None} - _request = build_beta_memory_stores_list_memories_request( name=name, kind=kind, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py index 454484ef8dba..8c5e1907bc7b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch_pipeline_jobs_async.py @@ -60,8 +60,8 @@ async def _resolve_asset_uri( dataset_name: str, base_path: Optional[Union[str, PathLike[str]]] = None, ) -> str: - return await _BetaJobsOperations._resolve_asset_uri( # type: ignore[arg-type] - self, uri, dataset_name, base_path + return await _BetaJobsOperations._resolve_asset_uri( + self, uri, dataset_name, base_path # type: ignore[arg-type] ) async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: @@ -70,7 +70,7 @@ async def _resolve_pipeline_code(self, name: str, job: PipelineJob) -> None: def _inject_preview_header(self, kwargs: dict) -> None: _BetaJobsOperations._inject_preview_header(self, kwargs) # type: ignore[arg-type] - def list( + def list( # type: ignore[override] self, *, tag: Optional[str] = None, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py index 8328b459313d..bc55e9acfbc4 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py @@ -13574,6 +13574,12 @@ def list_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) content_type = content_type or "application/json" + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} + _content = None if isinstance(body, (IOBase, bytes)): _content = body @@ -13581,12 +13587,6 @@ def list_memories( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore def prepare_request(_continuation_token=None): - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} - body = {k: v for k, v in body.items() if v is not None} - _request = build_beta_memory_stores_list_memories_request( name=name, kind=kind, diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py index 365a2cdeda69..d7c5d662eb9b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_pipeline_jobs.py @@ -69,7 +69,7 @@ def _inject_preview_header(self, kwargs: dict) -> None: _BetaJobsOperations._inject_preview_header(self, kwargs) # type: ignore[arg-type] @distributed_trace - def list( + def list( # type: ignore[override] self, *, tag: Optional[str] = None, From 0e1db7c25d04ccc88d51dd5d443480375282f138 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 13 Nov 2026 10:20:10 -0800 Subject: [PATCH 43/52] Cover memory list scope serialization Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/memories/test_list_memories.py | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py diff --git a/sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py b/sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py new file mode 100644 index 000000000000..74969c76f8da --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py @@ -0,0 +1,84 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Offline request tests for listing memory-store items.""" + +import json +from typing import Any + +import pytest +from azure.core.credentials import AccessToken +from azure.core.pipeline.transport import AsyncHttpTransport, HttpRequest, HttpTransport + +from azure.ai.projects import AIProjectClient +from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient + + +class _Credential: + def get_token(self, *args: Any, **kwargs: Any) -> AccessToken: + return AccessToken("fake-token", 9_999_999_999) + + +class _AsyncCredential: + async def get_token(self, *args: Any, **kwargs: Any) -> AccessToken: + return AccessToken("fake-token", 9_999_999_999) + + +class _RequestCaptured(Exception): + def __init__(self, request: HttpRequest) -> None: + self.request = request + + +class _Transport(HttpTransport): + def send(self, request: HttpRequest, **kwargs: Any) -> Any: + raise _RequestCaptured(request) + + def open(self) -> None: + pass + + def close(self) -> None: + pass + + def __exit__(self, *args: Any) -> None: + pass + + +class _AsyncTransport(AsyncHttpTransport): + async def send(self, request: HttpRequest, **kwargs: Any) -> Any: + raise _RequestCaptured(request) + + async def open(self) -> None: + pass + + async def close(self) -> None: + pass + + async def __aexit__(self, *args: Any) -> None: + pass + + +@pytest.mark.parametrize("kwargs", [{"scope": "user-123"}, {"body": {"scope": "user-123"}}]) +def test_list_memories_sends_scope(kwargs: dict[str, Any]) -> None: + with AIProjectClient( + endpoint="https://example.services.ai.azure.com/api/projects/test", + credential=_Credential(), # type: ignore[arg-type] + transport=_Transport(), + ) as client: + with pytest.raises(_RequestCaptured) as captured: + next(iter(client.beta.memory_stores.list_memories("store", **kwargs))) + assert json.loads(captured.value.request.body) == {"scope": "user-123"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kwargs", [{"scope": "user-123"}, {"body": {"scope": "user-123"}}]) +async def test_list_memories_sends_scope_async(kwargs: dict[str, Any]) -> None: + async with AsyncAIProjectClient( + endpoint="https://example.services.ai.azure.com/api/projects/test", + credential=_AsyncCredential(), # type: ignore[arg-type] + transport=_AsyncTransport(), + ) as client: + with pytest.raises(_RequestCaptured) as captured: + async for _ in client.beta.memory_stores.list_memories("store", **kwargs): + pass + assert json.loads(captured.value.request.body) == {"scope": "user-123"} From 87fa4e06bd69b759c8bd6af1cdf9ed63b4ab1b34 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 13 Nov 2026 10:25:10 -0800 Subject: [PATCH 44/52] Document PipelineJob response conversion for pylint Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/models/_patch_jobs.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index 5133c1f8a3c6..9f706a6476c5 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -281,7 +281,12 @@ def _from_rest_object(cls, rest_obj: Union[_RestJob, _RestPipelineJobResource]) def _from_rest_pipeline_job(rest_obj: Union[_RestJob, _RestPipelineJobResource]) -> PipelineJob: - """Flatten a Pipeline Job resource envelope into the public PipelineJob model.""" + """Flatten a Pipeline Job resource envelope into the public PipelineJob model. + + :param rest_obj: The deserialized Pipeline Job resource response. + :returns: A PipelineJob with its resource metadata populated. + :rtype: ~azure.ai.projects.models.PipelineJob + """ return PipelineJob._from_rest_object(rest_obj) From 8bd27915c21d025dc2031a84d531356d5fed62da Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 13 Nov 2026 10:28:08 -0800 Subject: [PATCH 45/52] Complete PipelineJob converter parameter docs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py index 9f706a6476c5..c093645f25b0 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch_jobs.py @@ -284,6 +284,7 @@ def _from_rest_pipeline_job(rest_obj: Union[_RestJob, _RestPipelineJobResource]) """Flatten a Pipeline Job resource envelope into the public PipelineJob model. :param rest_obj: The deserialized Pipeline Job resource response. + :type rest_obj: ~azure.ai.projects.models.Job or ~azure.ai.projects.models.PipelineJobResource :returns: A PipelineJob with its resource metadata populated. :rtype: ~azure.ai.projects.models.PipelineJob """ From 5c1ee096469d4db44f6f3f53771948dab0642286 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 13 Nov 2026 10:29:03 -0800 Subject: [PATCH 46/52] Format memory scope regression tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/memories/test_list_memories.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py b/sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py index 74969c76f8da..ef5123da759e 100644 --- a/sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py +++ b/sdk/ai/azure-ai-projects/tests/memories/test_list_memories.py @@ -58,7 +58,9 @@ async def __aexit__(self, *args: Any) -> None: pass -@pytest.mark.parametrize("kwargs", [{"scope": "user-123"}, {"body": {"scope": "user-123"}}]) +@pytest.mark.parametrize( + "kwargs", [{"scope": "user-123"}, {"body": {"scope": "user-123"}}] +) def test_list_memories_sends_scope(kwargs: dict[str, Any]) -> None: with AIProjectClient( endpoint="https://example.services.ai.azure.com/api/projects/test", @@ -71,7 +73,9 @@ def test_list_memories_sends_scope(kwargs: dict[str, Any]) -> None: @pytest.mark.asyncio -@pytest.mark.parametrize("kwargs", [{"scope": "user-123"}, {"body": {"scope": "user-123"}}]) +@pytest.mark.parametrize( + "kwargs", [{"scope": "user-123"}, {"body": {"scope": "user-123"}}] +) async def test_list_memories_sends_scope_async(kwargs: dict[str, Any]) -> None: async with AsyncAIProjectClient( endpoint="https://example.services.ai.azure.com/api/projects/test", From 347ad71e2a213dd2e2c23782c110e034e2103dda Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 4 Dec 2026 00:58:33 -0800 Subject: [PATCH 47/52] Assert pipeline_jobs requests use the /jobs route Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/jobs/test_pipeline_jobs.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 77ab6a18eb21..0f74efada6f3 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -241,10 +241,10 @@ def _assert_pipeline_jobs_requests(requests: list[HttpRequest], expected: dict[s for request in requests: assert request.headers["Foundry-Features"] == "Jobs=V1Preview" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] - assert urlparse(requests[0].url).path.endswith("/pipeline_jobs/pipeline") - assert urlparse(requests[1].url).path.endswith("/pipeline_jobs/pipeline") - assert urlparse(requests[2].url).path.endswith("/pipeline_jobs") - assert "jobType" not in parse_qs(urlparse(requests[2].url).query) + assert urlparse(requests[0].url).path.endswith("/jobs/pipeline") + assert urlparse(requests[1].url).path.endswith("/jobs/pipeline") + assert urlparse(requests[2].url).path.endswith("/jobs") + assert parse_qs(urlparse(requests[2].url).query)["jobType"] == ["Pipeline"] assert json.loads(requests[0].body) == {"properties": expected} @@ -315,7 +315,7 @@ def _assert_two_code_request(request: HttpRequest, code_uris: dict[str, str]) -> assert request.method == "PUT" assert request.headers["Foundry-Features"] == "Jobs=V1Preview" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] - assert urlparse(request.url).path.endswith("/pipeline_jobs/two-code") + assert urlparse(request.url).path.endswith("/jobs/two-code") resources = { "instance_count": 1, "instance_type": "Singularity.D4_v3", @@ -755,7 +755,7 @@ def _assert_dsl_request(request: HttpRequest, uploaded: dict[str, str]) -> None: assert request.method == "PUT" assert request.headers["Foundry-Features"] == "Jobs=V1Preview" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] - assert re.fullmatch(r"/api/projects/fake-project/pipeline_jobs/pipeline-[0-9a-f]{32}", urlparse(request.url).path) + assert re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", urlparse(request.url).path) resources = { "instance_count": 1, "instance_type": "Singularity.D4_v3", @@ -1452,7 +1452,7 @@ def test_jobs_sync_job_only_names_are_unique() -> None: paths = [urlparse(request.url).path for request in transport.requests] assert len(paths) == len(set(paths)) == 2 - assert all(re.fullmatch(r"/api/projects/fake-project/pipeline_jobs/pipeline-[0-9a-f]{32}", path) for path in paths) + assert all(re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", path) for path in paths) @pytest.mark.asyncio @@ -1467,4 +1467,4 @@ async def test_jobs_async_job_only_names_are_unique() -> None: paths = [urlparse(request.url).path for request in transport.requests] assert len(paths) == len(set(paths)) == 2 - assert all(re.fullmatch(r"/api/projects/fake-project/pipeline_jobs/pipeline-[0-9a-f]{32}", path) for path in paths) + assert all(re.fullmatch(r"/api/projects/fake-project/jobs/pipeline-[0-9a-f]{32}", path) for path in paths) From d1fce88aee795b8da75f844172d5d79c439b8436 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 4 Dec 2026 01:02:48 -0800 Subject: [PATCH 48/52] Expect nested pipeline submissions on the /jobs route Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index f76bde8b312c..2d81ec0f9f8c 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -1101,7 +1101,7 @@ def send(request: HttpRequest, **kwargs: Any) -> HttpResponse: assert len(requests) == 1 request = requests[0] assert request.method == "PUT" - assert urlparse(request.url).path.endswith(f"/{surface}/nested") + assert urlparse(request.url).path.endswith("/jobs/nested") assert request.headers["Foundry-Features"] == "Jobs=V1Preview" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] properties = json.loads(request.body)["properties"] From 62afc16815231a09e61c9d020f70eb6d92a44e72 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 4 Dec 2026 01:08:31 -0800 Subject: [PATCH 49/52] Align registration tests with /jobs routing and nested pipelines Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../test_pipeline_component_registration.py | 6 ++--- .../tests/jobs/test_pipeline_jobs.py | 25 ++++++++++++++++--- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py index 28afcad8b3b2..f15084edf2e6 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_component_registration.py @@ -80,9 +80,9 @@ def authored_job() -> Iterator[PipelineJob]: directory.cleanup() -def _job_path(surface: str) -> str: - collection = "pipeline_jobs" if surface == "pipeline_jobs" else "jobs" - return f"{urlparse(_ENDPOINT).path}/{collection}/{_JOB_NAME}" +def _job_path(surface: str) -> str: # pylint: disable=unused-argument + # Both surfaces submit through the /jobs collection. + return f"{urlparse(_ENDPOINT).path}/jobs/{_JOB_NAME}" class _RegistrationScenario: diff --git a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py index 7def617b2d5d..d9a9855626a7 100644 --- a/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py +++ b/sdk/ai/azure-ai-projects/tests/jobs/test_pipeline_jobs.py @@ -807,7 +807,7 @@ def parent_workflow(text: str): def _dsl_components(jobs: dict[str, Any], prefix: str = "") -> dict[str, dict[str, Any]]: components: dict[str, dict[str, Any]] = {} for name, node in jobs.items(): - component = node["component"] + component = node.get("component") if not isinstance(component, dict): continue qualified_name = f"{prefix}{name}" @@ -1088,7 +1088,11 @@ async def upload_folder_async(**kwargs: Any) -> DatasetVersion: async_transport = _AsyncTransport([_response("Pipeline")]) requests = async_transport.requests + original_send_async = async_transport.send + async def send_async(request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + if "/components/" in urlparse(request.url).path: + return await original_send_async(request, **kwargs) requests.append(request) raise RuntimeError("submit_failed") @@ -1109,7 +1113,11 @@ async def send_async(request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: sync_transport = _Transport([_response("Pipeline")]) requests = sync_transport.requests + original_send = sync_transport.send + def send(request: HttpRequest, **kwargs: Any) -> HttpResponse: + if "/components/" in urlparse(request.url).path: + return original_send(request, **kwargs) requests.append(request) raise RuntimeError("submit_failed") @@ -1136,14 +1144,25 @@ def send(request: HttpRequest, **kwargs: Any) -> HttpResponse: if outcome == "upload_failed": assert requests == [] else: - assert len(requests) == 1 - request = requests[0] + component_requests = [r for r in requests if "/components/" in urlparse(r.url).path] + job_requests = [r for r in requests if r not in component_requests] + assert len(job_requests) == 1 + request = job_requests[0] assert request.method == "PUT" assert urlparse(request.url).path.endswith("/jobs/nested") assert request.headers["Foundry-Features"] == "Jobs=V1Preview" assert parse_qs(urlparse(request.url).query)["api-version"] == ["2026-01-15-preview"] properties = json.loads(request.body)["properties"] components = _dsl_components(properties["jobs"]) + # Only top-level inline Commands are registered; nested Pipeline Commands stay inline. + registered_nodes = [name for name, node in properties["jobs"].items() if "componentId" in node] + assert len(registered_nodes) == len(component_requests) == 1 + for node_name, component_request in zip(registered_nodes, component_requests): + spec = json.loads(component_request.body)["properties"]["componentSpec"] + assert properties["jobs"][node_name]["componentId"] == _registered_component_id( + spec["name"], spec["version"] + ) + components[node_name] = spec assert len(components) == 3 assert {component["code"] for component in components.values()} == { _code_uri(name, version) for name, version in lookups From 4c785781726fbe333f88d19897c9bc0bb2e73291 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 4 Dec 2026 01:10:39 -0800 Subject: [PATCH 50/52] Apply black formatting to nested pipeline changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../azure/ai/projects/dsl.py | 21 ++++++++----------- .../ai/projects/operations/_job_helper.py | 4 +--- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index e4287741f224..028d5640d8c2 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -227,10 +227,7 @@ def add( port_name: {"job_input_type": "literal", "value": value.value} for port_name, value in bound_inputs.items() }, - "outputs": { - port.name: {"job_output_type": port.type, "mode": port.mode} - for port in outputs - }, + "outputs": {port.name: {"job_output_type": port.type, "mode": port.mode} for port in outputs}, } if pipeline_context.compute_id != self.compute_id: node["compute"] = pipeline_context.compute_id @@ -242,7 +239,9 @@ def add( if source is None: code_dir = TemporaryDirectory(prefix="foundry-component-") self.code_dirs.append(code_dir) - (Path(code_dir.name) / "component.py").write_text(_function_script(func, inputs, outputs), encoding="utf-8") + (Path(code_dir.name) / "component.py").write_text( + _function_script(func, inputs, outputs), encoding="utf-8" + ) command = "python component.py " + arguments_in_command else: shared_code_dir = self.code_dirs_by_root.get(source.root) @@ -275,7 +274,9 @@ def add( } ), inputs=bound_inputs, - outputs={port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs}, + outputs={ + port.name: _JobOutput(type=port.type, asset_name=port.name, mode=port.mode) for port in outputs + }, ) node = PipelineJob._command_node(name, job, self.compute_id) # pylint: disable=protected-access for port in inputs: @@ -398,12 +399,8 @@ def build(*args: Any, **kwargs: Any) -> Union[PipelineJob, SimpleNamespace]: for name, value in bound.arguments.items(): annotation = annotations.get(name, signature.parameters[name].annotation) if isinstance(annotation, Input): - if ( - annotation.type != AssetTypes.URI_FILE - or ( - parent is None - and (not isinstance(value, Input) or value.type != AssetTypes.URI_FILE) - ) + if annotation.type != AssetTypes.URI_FILE or ( + parent is None and (not isinstance(value, Input) or value.type != AssetTypes.URI_FILE) ): raise TypeError(f"Pipeline input '{name}' requires Input(type='uri_file', path=...).") if parent is None: diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py index 7c28b2945f08..2446af57d718 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_job_helper.py @@ -180,9 +180,7 @@ def _collect_files(directory: Path, ignore_patterns: List[str]) -> List[Tuple[Pa return sorted(files, key=lambda x: x[1].lower()) -def _iter_pipeline_command_components( - jobs: Dict[str, Any], prefix: str = "" -) -> Iterator[Tuple[str, Dict[str, Any]]]: +def _iter_pipeline_command_components(jobs: Dict[str, Any], prefix: str = "") -> Iterator[Tuple[str, Dict[str, Any]]]: """Yield inline command components, including those inside Pipeline components. :param jobs: Graph nodes to traverse. From d4738ceebecf30cc4d4271ed06c31ee58a7417e2 Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 4 Dec 2026 01:15:01 -0800 Subject: [PATCH 51/52] Scope pylint suppressions for pipeline DSL builder Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py index 028d5640d8c2..bc1b913b42c6 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/dsl.py @@ -177,7 +177,7 @@ def __init__(self, compute_id: str, image: str, identity: str, instance_type: st self.code_dirs: List[TemporaryDirectory] = [] self.code_dirs_by_root: Dict[Path, TemporaryDirectory] = {} - def add( + def add( # pylint: disable=too-many-statements self, func: Callable[..., Any], inputs: List[_Port], @@ -353,7 +353,7 @@ def invoke(**kwargs: Any) -> SimpleNamespace: command_component = component -def pipeline( +def pipeline( # pylint: disable=too-many-statements *, compute_id: str, environment_image_reference: str, @@ -379,12 +379,14 @@ def pipeline( :rtype: callable """ - def decorate(func: Callable[..., Any]) -> Callable[..., Any]: + def decorate(func: Callable[..., Any]) -> Callable[..., Any]: # pylint: disable=too-many-statements signature = inspect.signature(func) annotations = get_type_hints(func) @wraps(func) - def build(*args: Any, **kwargs: Any) -> Union[PipelineJob, SimpleNamespace]: + def build( # pylint: disable=too-many-branches,too-many-statements + *args: Any, **kwargs: Any + ) -> Union[PipelineJob, SimpleNamespace]: bound = signature.bind(*args, **kwargs) bound.apply_defaults() parent = _ACTIVE_PIPELINE.get() @@ -412,8 +414,8 @@ def build(*args: Any, **kwargs: Any) -> Union[PipelineJob, SimpleNamespace]: port_type: str = AssetTypes.URI_FILE conversion = "str" elif annotation in _PRIMITIVES and ( - parent is not None or type(value) is annotation - ): # pylint: disable=unidiomatic-typecheck + parent is not None or type(value) is annotation # pylint: disable=unidiomatic-typecheck + ): if parent is None: job_inputs[name] = Input(type=AssetTypes.LITERAL, value=str(value)) port_type, conversion = _PRIMITIVES[annotation] From 67ce2b7186f4e927110b1530adb5e993d1302f6c Mon Sep 17 00:00:00 2001 From: Zhidong Zhu Date: Fri, 4 Dec 2026 01:18:23 -0800 Subject: [PATCH 52/52] Suppress sibling-module import false positive in async registration operations Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../operations/_pipeline_component_registration_operations.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py index e3b262279e4f..a1b5e7f156ad 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_pipeline_component_registration_operations.py @@ -26,7 +26,9 @@ from azure.core.utils import case_insensitive_dict from ..._utils.serialization import Deserializer, Serializer -from ...operations._pipeline_component_registration_operations import build_register_command_component_request +from ...operations._pipeline_component_registration_operations import ( # pylint: disable=no-cross-package-private-import + build_register_command_component_request, +) from .._configuration import AIProjectClientConfiguration JSON = MutableMapping[str, Any]