diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index 2d53e879c2..467f8b7b1b 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -40,7 +40,7 @@ TargetTypeResponse, UnregisteredTarget, ) -from pyrit.backend.services.component_lifecycle import construct_component_async, release_component_async +from pyrit.backend.services.component_lifecycle import release_component_async from pyrit.common import AUTH_MODES, REQUIRED_VALUE, AuthMode, default_values from pyrit.models import Parameter, PromptDataType, TargetCapabilities, TargetIdentifier from pyrit.models.catalog import ( @@ -141,7 +141,7 @@ def capabilities_scope( async def detect_capabilities_async(self, *, target_registry_name: str, expected_hash: str) -> TargetInstance: """ - Probe private targets and apply a completed result to the selected source. + Probe a live target and apply a completed result to it. Round-robin detection probes each child independently and combines their results. Only the selected parent is updated; live children are not changed. @@ -207,23 +207,19 @@ async def detect_capabilities_async(self, *, target_registry_name: str, expected async def _probe_capabilities_async(self, target: PromptTarget) -> TargetCapabilities: """ - Check one private target and release its resources. + Check one live target without changing it. + + Probes see their permissive settings only in their own task, so concurrent + requests to the target are unaffected and any target type can be checked. Returns: TargetCapabilities: Completed capability results. """ - probe = await construct_component_async(self._registry.recreate_instance, source=target, params={}) - try: - probe.apply_capabilities(capabilities=target.capabilities) - modalities: set[frozenset[PromptDataType]] = {frozenset({"text"})} - for modality in DEFAULT_TEST_ASSETS: - modalities.update({frozenset({modality}), frozenset({"text", modality})}) - modalities.update(TOOL_CALL_INPUT_MODALITIES) - return await discover_target_capabilities_async( - target=probe, test_modalities=modalities, raise_on_error=True - ) - finally: - await release_component_async(probe) + modalities: set[frozenset[PromptDataType]] = {frozenset({"text"})} + for modality in DEFAULT_TEST_ASSETS: + modalities.update({frozenset({modality}), frozenset({"text", modality})}) + modalities.update(TOOL_CALL_INPUT_MODALITIES) + return await discover_target_capabilities_async(target=target, test_modalities=modalities, raise_on_error=True) def _build_instance_from_entry( self, entry: RegistryEntry[PromptTarget], *, origin: RegistryEntryOrigin | None = None diff --git a/pyrit/prompt_target/common/discover_target_capabilities.py b/pyrit/prompt_target/common/discover_target_capabilities.py index 491543c063..1f10cac0b2 100644 --- a/pyrit/prompt_target/common/discover_target_capabilities.py +++ b/pyrit/prompt_target/common/discover_target_capabilities.py @@ -43,9 +43,10 @@ import logging import uuid from collections.abc import Awaitable, Callable, Generator, Iterable, Mapping -from contextlib import ExitStack, contextmanager +from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path +from typing import Any from pyrit.common.attack_result_scope import get_current_attack_result_id from pyrit.common.path import DATASETS_PATH @@ -148,15 +149,17 @@ def _permissive_configuration( extra_input_modalities: Iterable[frozenset[PromptDataType]] | None = None, ) -> Generator[None, None, None]: """ - Temporarily replace ``target``'s configuration with one that declares every - boolean capability as natively supported. + For this task only, give ``target`` a configuration that declares every + boolean capability as natively supported, and keep configured tools out of + probe requests. This bypasses ``PromptTarget._validate_request``, which would otherwise short-circuit probes for capabilities the target declares as unsupported - before any API call is made. The original configuration is restored on exit. + before any API call is made. The target itself is never modified, so + probes can run on a live target while other tasks use it. Args: - target (PromptTarget): The target whose configuration is temporarily replaced. + target (PromptTarget): The target to probe. extra_input_modalities (Iterable[frozenset[PromptDataType]] | None): Additional modality combinations to include in ``input_modalities`` during the override. Used by modality probes so that @@ -184,40 +187,34 @@ def _permissive_configuration( # probes bypass preflight validation without inheriting ADAPT policy or # custom normalizer overrides from the target's runtime configuration. probe_configuration = TargetConfiguration(capabilities=permissive_caps) - target._configuration = probe_configuration - try: - with _disable_probe_tools(target=target): - yield - finally: - target._configuration = original + # Both overrides apply to this task only, so other requests to a live target are unaffected. + with target._probe_scope(configuration=probe_configuration, attributes=_probe_tool_settings(target=target)): + yield -@contextmanager -def _disable_probe_tools(*, target: PromptTarget) -> Generator[None, None, None]: - """Disable configured tools during probes and restore all settings on exit.""" +def _probe_tool_settings(*, target: PromptTarget) -> dict[str, Any]: + """ + Return task-local settings that keep configured tools out of probe requests. + + Returns: + dict[str, Any]: Attribute values for ``PromptTarget._probe_scope``. + """ from pyrit.prompt_target.litellm_chat_target import LiteLLMChatTarget from pyrit.prompt_target.openai.openai_chat_target import OpenAIChatTarget from pyrit.prompt_target.openai.openai_response_target import OpenAIResponseTarget - with ExitStack() as stack: - if isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)): - original_body = target._extra_body_parameters - stack.callback(setattr, target, "_extra_body_parameters", original_body) - tool_settings = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"} - target._extra_body_parameters = { - key: value for key, value in (original_body or {}).items() if key not in tool_settings - } - extra_body = target._extra_body_parameters.get("extra_body") - if isinstance(extra_body, Mapping): - target._extra_body_parameters["extra_body"] = { - key: value for key, value in extra_body.items() if key not in tool_settings - } - if isinstance(target, (OpenAIResponseTarget, LiteLLMChatTarget)): - stack.callback(setattr, target, "_execute_tools", target._execute_tools) - stack.callback(setattr, target, "_suppress_tools", target._suppress_tools) - target._execute_tools = False - target._suppress_tools = True - yield + settings: dict[str, Any] = {} + if isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)): + tool_settings = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"} + body = {key: value for key, value in (target._extra_body_parameters or {}).items() if key not in tool_settings} + extra_body = body.get("extra_body") + if isinstance(extra_body, Mapping): + body["extra_body"] = {key: value for key, value in extra_body.items() if key not in tool_settings} + settings["_extra_body_parameters"] = body + if isinstance(target, (OpenAIResponseTarget, LiteLLMChatTarget)): + settings["_execute_tools"] = False + settings["_suppress_tools"] = True + return settings def _new_conversation_id() -> str: @@ -682,10 +679,13 @@ def _supports_chat_probes(target: PromptTarget) -> bool: bool: Whether chat features can be sent by this adapter. """ from pyrit.prompt_target.litellm_chat_target import LiteLLMChatTarget + from pyrit.prompt_target.litellm_decision_target import LiteLLMDecisionTarget from pyrit.prompt_target.openai.openai_chat_target import OpenAIChatTarget from pyrit.prompt_target.openai.openai_response_target import OpenAIResponseTarget - return isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)) + return isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)) and not isinstance( + target, LiteLLMDecisionTarget + ) async def _discover_capability_flags_async( @@ -849,7 +849,12 @@ async def _discover_input_modalities_async( queried.add(combination) continue try: - message = await asyncio.to_thread(_create_test_message, modalities=combination, test_assets=assets) + message = await asyncio.to_thread( + _create_test_message, + modalities=combination, + test_assets=assets, + text=target.capability_probe_text, + ) except FileNotFoundError as exc: # Skip combinations we cannot construct a valid probe payload for. logger.info("Skipping modality %s: %s", combination, exc) @@ -897,7 +902,12 @@ async def _check_control_request_async( with _permissive_configuration(target=target): for combination in combinations: try: - message = await asyncio.to_thread(_create_test_message, modalities=combination, test_assets=assets) + message = await asyncio.to_thread( + _create_test_message, + modalities=combination, + test_assets=assets, + text=target.capability_probe_text, + ) except (FileNotFoundError, ValueError) as exc: logger.info("Cannot prepare control input %s: %s", sorted(combination), exc) continue @@ -1077,6 +1087,7 @@ def _create_test_message( *, modalities: frozenset[PromptDataType], test_assets: dict[PromptDataType, str], + text: str = "test", ) -> Message: """ Build a minimal ``Message`` that exercises ``modalities``. @@ -1085,6 +1096,7 @@ def _create_test_message( modalities (frozenset[PromptDataType]): The modalities to include. test_assets (dict[PromptDataType, str]): Mapping from non-text modality to a file path used for the probe. + text (str): The text piece's value. Defaults to ``"test"``. Returns: Message: A message containing one piece per modality. @@ -1101,7 +1113,7 @@ def _create_test_message( pieces.append( MessagePiece( role="user", - original_value="test", + original_value=text, original_value_data_type="text", conversation_id=conversation_id, prompt_metadata=_probe_metadata(), diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index 14b38a75d7..c337a89bb1 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -78,6 +78,35 @@ def _is_credential_rejection(error: BaseException) -> bool: # compatibility); it is canonically defined in ``pyrit.common.auth_mode`` so # ``pyrit.auth`` resolvers can consume it without depending on the target layer. +_ATTRIBUTE_SCOPES: ContextVar[tuple[tuple["PromptTarget", Mapping[str, Any]], ...]] = ContextVar( + "target_attribute_scopes", default=() +) + + +class _TaskLocalAttribute: + """ + An instance attribute that ``PromptTarget._probe_scope`` can override for one task. + + Every other task, including a concurrent send on the same target, reads the stored value. + """ + + def __set_name__(self, owner: type, name: str) -> None: # pyrit-keyword-only-exempt descriptor protocol + self._name = name + + def __get__(self, instance: object, owner: type | None = None) -> Any: # pyrit-keyword-only-exempt descriptor + if instance is None: + return self + for target, overrides in reversed(_ATTRIBUTE_SCOPES.get()): + if target is instance and self._name in overrides: + return overrides[self._name] + try: + return instance.__dict__[self._name] + except KeyError: + raise AttributeError(self._name) from None + + def __set__(self, instance: object, value: Any) -> None: # pyrit-keyword-only-exempt descriptor protocol + instance.__dict__[self._name] = value + class PromptTarget(Identifiable): """ @@ -124,6 +153,10 @@ class PromptTarget(Identifiable): _CONFIGURATION_SCOPES: ClassVar[ContextVar[tuple[tuple["PromptTarget", TargetConfiguration], ...]]] = ContextVar( "target_configuration_scopes", default=() ) + # Tool settings that capability probes turn off for their own task only (see ``_probe_scope``). + _extra_body_parameters = _TaskLocalAttribute() + _execute_tools = _TaskLocalAttribute() + _suppress_tools = _TaskLocalAttribute() # Declarative auth facts consumed by the create-target service and catalog. # Kept off ``TargetCapabilities`` (auth is a construction/credential axis, not @@ -196,6 +229,10 @@ class PromptTarget(Identifiable): # with the endpoint it was configured for. COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset() + # Text capability discovery sends to check a text input. A target that accepts only structured text + # overrides it with a valid request. + capability_probe_text: ClassVar[str] = "test" + def __init_subclass__(cls, **kwargs: object) -> None: """ Validate that subclasses follow the keyword-only ``__init__`` contract. @@ -1076,6 +1113,36 @@ def capabilities_scope(self, capabilities: TargetCapabilities) -> Generator[None finally: self._CONFIGURATION_SCOPES.reset(token) + @contextmanager + def _probe_scope( + self, *, configuration: TargetConfiguration, attributes: Mapping[str, Any] + ) -> Generator[None, None, None]: + """ + Use a configuration and tool settings for this task only, so probes can run on a live target. + + Unlike ``capabilities_scope``, the configuration is used as given, without masking. + + Args: + configuration: The configuration this task sees. + attributes: Values for this target's task-local attributes, such as ``_execute_tools``. + + Yields: + None: The task-local scope, restored even on cancellation. + + Raises: + ValueError: If an attribute is not task-local, so setting it would change every task. + """ + for name in attributes: + if not isinstance(getattr(type(self), name, None), _TaskLocalAttribute): + raise ValueError(f"{type(self).__name__}.{name} cannot be overridden for one task.") + configuration_token = self._CONFIGURATION_SCOPES.set((*self._CONFIGURATION_SCOPES.get(), (self, configuration))) + attribute_token = _ATTRIBUTE_SCOPES.set((*_ATTRIBUTE_SCOPES.get(), (self, dict(attributes)))) + try: + yield + finally: + _ATTRIBUTE_SCOPES.reset(attribute_token) + self._CONFIGURATION_SCOPES.reset(configuration_token) + @property def capabilities(self) -> TargetCapabilities: """ diff --git a/pyrit/prompt_target/litellm_decision_target.py b/pyrit/prompt_target/litellm_decision_target.py index 3f3d926cc7..0a0a880641 100644 --- a/pyrit/prompt_target/litellm_decision_target.py +++ b/pyrit/prompt_target/litellm_decision_target.py @@ -4,7 +4,7 @@ import json import math from collections.abc import Awaitable, Callable -from typing import TYPE_CHECKING, Any, TypedDict, cast +from typing import TYPE_CHECKING, Any, ClassVar, TypedDict, cast from pyrit.exceptions import pyrit_target_retry from pyrit.models import ( @@ -44,6 +44,20 @@ class LiteLLMDecisionTarget(LiteLLMChatTarget): _SUPPORTS_TOOL_CALL_HISTORY = False _DEFAULT_CONFIGURATION = TargetConfiguration(capabilities=TargetCapabilities()) + # Capability detection's text probe must be a valid decision request, like DecisionScorer's. + capability_probe_text: ClassVar[str] = json.dumps( + { + "state": "test", + "questions": { + "probe": { + "type": "noul", + "instructions": "Is the state the word test?", + "criteria": {"true": "It is.", "false": "It is not."}, + } + }, + } + ) + def __init__( self, *, diff --git a/tests/unit/backend/test_target_detection.py b/tests/unit/backend/test_target_detection.py index 395c1b7407..93a9cff530 100644 --- a/tests/unit/backend/test_target_detection.py +++ b/tests/unit/backend/test_target_detection.py @@ -12,7 +12,7 @@ from pathlib import Path from types import SimpleNamespace from typing import Any -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest from fastapi import FastAPI @@ -45,7 +45,14 @@ ) from pyrit.models.catalog import RegistryEntryOrigin from pyrit.models.component_spec import SourceInstanceSpec, TargetBinding -from pyrit.prompt_target import OpenAIChatTarget, OpenAITTSTarget, RoundRobinTarget, TargetConfiguration +from pyrit.prompt_target import ( + LiteLLMDecisionTarget, + OpenAIChatTarget, + OpenAITTSTarget, + PromptShieldTarget, + RoundRobinTarget, + TargetConfiguration, +) from pyrit.prompt_target.common.discover_target_capabilities import DEFAULT_TEST_ASSETS, CapabilityDiscoveryError from pyrit.registry import TargetRegistry from pyrit.registry.instance_registry import SAVED_ENTRY_METADATA_KEY @@ -88,7 +95,7 @@ def composite_detection( return service, parent -async def test_composite_detection_probes_each_child_privately_and_updates_only_parent( +async def test_composite_detection_probes_each_live_child_and_updates_only_parent( composite_detection: tuple[TargetService, RoundRobinTarget], ) -> None: service, parent = composite_detection @@ -109,7 +116,6 @@ async def test_composite_detection_probes_each_child_privately_and_updates_only_ probes: list[_DetectableTarget] = [] async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCapabilities: - assert all(target is not child for child in children) probes.append(target) return results[len(probes) - 1] @@ -118,9 +124,7 @@ async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> Targ target_registry_name="round-robin", expected_hash=expected_hash ) - assert len(probes) == 2 - assert probes[0] is not probes[1] - assert all(probe.closed for probe in probes) + assert probes == children assert response.capabilities == parent.aggregate_capabilities(child_capabilities=results) assert parent.capabilities == response.capabilities assert parent.capabilities.supports_json_output @@ -155,8 +159,7 @@ async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> Targ target_registry_name="round-robin", expected_hash=parent.get_identifier().hash ) - assert len(probes) == 2 - assert all(probe.closed for probe in probes) + assert probes == children assert parent.configuration is original assert all(child.configuration is original for child, original in zip(children, originals, strict=True)) assert not service._detecting @@ -285,7 +288,7 @@ async def probe_async(target: _DetectableTarget) -> TargetCapabilities: assert not service._detecting_sources -async def test_composite_detection_reconstructs_each_openai_endpoint_with_its_own_client( +async def test_composite_detection_probes_each_openai_child_with_its_open_client( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, _ = detection_service @@ -310,14 +313,8 @@ async def discover_async(*, target: OpenAIChatTarget, **kwargs: object) -> Targe target_registry_name="openai-round-robin", expected_hash=parent.get_identifier().hash ) assert result.capabilities.supports_json_output - assert len(probes) == len(children) - for probe, child in zip(probes, children, strict=True): - assert probe.get_identifier().hash == child.get_identifier().hash - assert probe._async_client is not child._async_client - assert probe._async_client is not None - assert probe._async_client.is_closed() - assert child._async_client is not None - assert not child._async_client.is_closed() + assert probes == children + assert all(child._async_client is not None and not child._async_client.is_closed() for child in children) finally: for child in children: await child.cleanup_target_async() @@ -364,12 +361,12 @@ async def wait_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCa with pytest.raises(asyncio.CancelledError): await task assert parent.configuration is original - assert all(probe.closed for probe in probes) + assert not any(probe.closed for probe in probes) assert not service._detecting assert not service._detecting_sources -async def test_detection_applies_private_result_and_releases_probe( +async def test_detection_probes_and_updates_the_live_target( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, target = detection_service @@ -380,8 +377,8 @@ async def test_detection_applies_private_result_and_releases_probe( async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCapabilities: probes.append(target) - assert target is not detection_service[1] - assert detection_service[1].configuration is original + assert target is detection_service[1] + assert target.configuration is original assert kwargs["raise_on_error"] is True assert frozenset({"text", "image_path"}) in kwargs["test_modalities"] return detected @@ -395,11 +392,8 @@ async def discover_async(*, target: _DetectableTarget, **kwargs: object) -> Targ assert target.capabilities == detected assert target.configuration.policy == original.policy assert result.identifier.hash == expected_hash - assert probes[0].closed + assert probes == [target] assert not target.closed - rebuilt = service._registry.recreate_instance(source=target, params={}) - assert rebuilt.capabilities == detected - await rebuilt.cleanup_target_async() async def test_detection_returns_the_origin_of_the_registered_target( @@ -434,7 +428,7 @@ async def test_detection_preserves_declarations_without_verified_adapter_probes( assert result.capabilities.output_modalities == frozenset({frozenset({"text"})}) -async def test_detection_reconstructs_openai_without_closing_the_live_client( +async def test_detection_probes_openai_with_its_open_client( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, _ = detection_service @@ -455,17 +449,76 @@ async def discover_async(*, target: OpenAIChatTarget, **kwargs: object) -> Targe target_registry_name="openai", expected_hash=target.get_identifier().hash ) assert result.capabilities.supports_json_output - assert probes[0]._async_client is not target._async_client - assert probes[0]._async_client is not None + assert probes == [target] assert target._async_client is not None - assert probes[0]._async_client.is_closed() assert not target._async_client.is_closed() finally: await target.cleanup_target_async() +async def test_detection_sends_a_valid_control_request_to_the_decision_target_async( + detection_service: tuple[TargetService, _DetectableTarget], +) -> None: + litellm = pytest.importorskip("litellm") + from litellm.types.decisions import DecisionsResponse + + service, _ = detection_service + source = LiteLLMDecisionTarget(model_name="openrouter/decision", endpoint="https://example.test", api_key="key") + service._registry.instances.register(source, name="microsoft_decision") + original = source.capabilities + sdk = MagicMock(spec=litellm) + sdk.asystemone = None + sdk.adecisions = AsyncMock( + return_value=DecisionsResponse.model_validate( + {"model": "decision", "id": "probe", "answers": {"probe": {"type": "noul", "noul": 1.0}}, "usage": {}} + ) + ) + + with patch.object(LiteLLMDecisionTarget, "_import_litellm", return_value=sdk): + result = await service.detect_capabilities_async( + target_registry_name="microsoft_decision", expected_hash=source.get_identifier().hash + ) + + assert result.capabilities == original + assert source.capabilities == original + sdk.adecisions.assert_awaited_once() + body = sdk.adecisions.call_args.kwargs + assert body["api_key"] == "key" + assert body["api_base"] == "https://example.test" + assert set(body["questions"]) == {"probe"} + + +@pytest.mark.parametrize("api_key", ["key", MagicMock(return_value="token")], ids=["key", "token_provider"]) +async def test_detection_probes_prompt_shield_and_keeps_its_declarations_async( + detection_service: tuple[TargetService, _DetectableTarget], api_key: str | MagicMock +) -> None: + service, _ = detection_service + source = PromptShieldTarget(endpoint="https://example.test", api_key=api_key) + service._registry.instances.register(source, name="azure_content_safety") + original = source.capabilities + response = SimpleNamespace(content=b'{"userPromptAnalysis": {"attackDetected": false}, "documentsAnalysis": []}') + + with patch( + "pyrit.prompt_target.prompt_shield_target.net_utility.make_request_and_raise_if_error_async", + new=AsyncMock(return_value=response), + ) as shield: + result = await service.detect_capabilities_async( + target_registry_name="azure_content_safety", expected_hash=source.get_identifier().hash + ) + + assert result.capabilities == original + assert source.capabilities == original + shield.assert_awaited_once() + assert shield.call_args.kwargs["request_body"] == {"userPrompt": "test", "documents": []} + headers = shield.call_args.kwargs["headers"] + if isinstance(api_key, str): + assert headers["Ocp-Apim-Subscription-Key"] == "key" + else: + assert headers["Authorization"] == "Bearer token" + + @pytest.mark.parametrize("error", [CapabilityDiscoveryError("Connection failed"), TimeoutError()]) -async def test_detection_failure_keeps_source_and_releases_probe( +async def test_detection_failure_keeps_the_source_unchanged( detection_service: tuple[TargetService, _DetectableTarget], error: Exception ) -> None: service, target = detection_service @@ -482,7 +535,7 @@ async def fail_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCa target_registry_name="test-target", expected_hash=target.get_identifier().hash ) assert target.configuration is original - assert probes[0].closed + assert probes == [target] assert not service._detecting @@ -519,16 +572,12 @@ async def test_detection_rejects_missing_stale_and_duplicate_requests( ) -async def test_detection_rejects_unsafe_targets( +async def test_detection_rejects_unsupported_composites( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, _ = detection_service target = MockPromptTarget() service._registry.instances.register(target, name="unsafe") - with pytest.raises(ValueError, match="reconstruction"): - await service.detect_capabilities_async( - target_registry_name="unsafe", expected_hash=target.get_identifier().hash - ) target.inner_targets = [MockPromptTarget()] with pytest.raises(ValueError, match="composite"): await service.detect_capabilities_async( @@ -559,7 +608,7 @@ async def wait_async(**kwargs: object) -> TargetCapabilities: assert not service._detecting -async def test_detection_cancellation_releases_probe_and_admission( +async def test_detection_cancellation_releases_admission( detection_service: tuple[TargetService, _DetectableTarget], ) -> None: service, target = detection_service @@ -585,7 +634,8 @@ async def wait_async(*, target: _DetectableTarget, **kwargs: object) -> TargetCa task.cancel() with pytest.raises(asyncio.CancelledError): await task - assert probes[0].closed + assert probes == [target] + assert not target.closed assert target.configuration is original assert not service._detecting assert not service._detecting_sources diff --git a/tests/unit/prompt_target/target/test_prompt_target.py b/tests/unit/prompt_target/target/test_prompt_target.py index a2264ed070..9280792894 100644 --- a/tests/unit/prompt_target/target/test_prompt_target.py +++ b/tests/unit/prompt_target/target/test_prompt_target.py @@ -113,6 +113,42 @@ def scoped_operation() -> None: assert other.configuration is other_original +@pytest.mark.usefixtures("patch_central_database") +async def test_probe_scope_changes_settings_only_for_its_own_task() -> None: + target = MockPromptTarget() + target._execute_tools = True + original = target.configuration + probe_configuration = TargetConfiguration(capabilities=TargetCapabilities(supports_json_output=True)) + probing = asyncio.Event() + probed = asyncio.Event() + seen_by_other_task: list[object] = [] + + async def concurrent_send_async() -> None: + await probing.wait() + seen_by_other_task.extend([target.configuration, target._execute_tools]) + probed.set() + + other_task = asyncio.create_task(concurrent_send_async()) + with target._probe_scope(configuration=probe_configuration, attributes={"_execute_tools": False}): + assert target.configuration is probe_configuration + assert target._execute_tools is False + probing.set() + await asyncio.wait_for(probed.wait(), timeout=TEST_WATCHDOG_SECONDS) + await other_task + + assert seen_by_other_task == [original, True] + assert target.configuration is original + assert target._execute_tools is True + + +@pytest.mark.usefixtures("patch_central_database") +def test_probe_scope_rejects_attributes_that_would_change_every_task() -> None: + target = MockPromptTarget() + with pytest.raises(ValueError, match="MockPromptTarget._endpoint cannot be overridden for one task"): + with target._probe_scope(configuration=target.configuration, attributes={"_endpoint": "elsewhere"}): + pass + + @pytest.mark.usefixtures("patch_central_database") async def test_capabilities_scope_does_not_change_concurrent_target_reads_async() -> None: target = MockPromptTarget()