diff --git a/doc/getting_started/pyrit_conf.md b/doc/getting_started/pyrit_conf.md index c00c7baf78..64b8dc2b24 100644 --- a/doc/getting_started/pyrit_conf.md +++ b/doc/getting_started/pyrit_conf.md @@ -206,7 +206,7 @@ Each kind has its own folder under the source (`targets/`, `converters/`, `score A saved file doesn't record who saved it, so the backend rebuilds every entry in this source as an administrator, at startup and after a live apply. A file here can, for example, make the backend run a model's repository code, or use the server's identity on a storage container that the file names. Write access to this source is administrator authority on the backend: grant it only to principals you already trust as backend administrators, and use a dedicated directory or blob prefix that less-trusted users and services cannot write to. -The backend restores saved entries at startup and after a live apply, once the configured initializers have registered theirs. If any saved entry can't be restored, the backend doesn't become ready (state `failed`, outcome `restore-failed`) and lists each failure with its reason in `GET /api/config/runtime`, so a scan can't quietly run without an entry it expects. Until then, only the configuration and status routes answer; the rest return 503. Fix or delete the listed files, or, when a folder couldn't be listed, check that the backend can read this source. Then apply the configuration, if `enable_live_reinitialization` is on, or restart the backend. Files whose names aren't valid entry names (up to 64 lowercase letters, digits, and underscores, starting with a letter) are skipped without blocking startup; administrators can see them under `restore_ignored` in `GET /api/config/runtime`. +The backend restores saved entries at startup and after a live apply, once the configured initializers have registered theirs. If any saved entry can't be restored, the backend doesn't become ready (state `failed`, outcome `restore-failed`), so a scan can't quietly run without an entry it expects. Until then, only the configuration and status routes answer; the rest return 503. Administrators see each failure with its reason in `GET /api/config/runtime` and on the GUI's Configuration page; everyone else sees that an administrator has to fix saved entries. Fix or delete the listed files, or, when a folder couldn't be listed, check that the backend can read this source. Then apply the configuration, if `enable_live_reinitialization` is on and the backend runs as one worker and one replica, which live apply requires; otherwise, restart the backend. Files whose names aren't valid entry names (up to 64 lowercase letters, digits, and underscores, starting with a letter) aren't failures and don't block startup; administrators can see them under `restore_ignored` in `GET /api/config/runtime`. ### `initialization_scripts` diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx index 7519b77bd8..5c423233c3 100644 --- a/frontend/src/App.test.tsx +++ b/frontend/src/App.test.tsx @@ -4,6 +4,7 @@ */ import { Suspense, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { fluentProviderClassNames } from "@fluentui/react-components"; import { act, render, screen, fireEvent, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { MemoryRouter, parsePath, useLocation, useNavigate } from "react-router"; @@ -139,6 +140,7 @@ jest.mock("./components/Layout/MainLayout", () => { onLabelsChange, operatorReadOnly, featureNavigation, + banner, }: { children: React.ReactNode; currentView: string; @@ -147,10 +149,12 @@ jest.mock("./components/Layout/MainLayout", () => { onLabelsChange: (labels: Record) => void; operatorReadOnly: boolean; featureNavigation?: React.ReactNode; + banner?: React.ReactNode; }) => { const navigate = useNavigate(); return (
+ {banner} {JSON.stringify(labels)} {JSON.stringify(labels)} {String(operatorReadOnly)} @@ -870,6 +874,18 @@ describe("App", () => { expect(screen.getByTestId("home-view")).toBeInTheDocument(); }); + it("says inside the app's layout and theme that saved entries couldn't be restored", async () => { + const { runtimeApi } = jest.requireMock("./services/api"); + runtimeApi.getReadiness.mockResolvedValueOnce({ + ready: false, state: "failed", generation: "first", restore_failures: 1, + }); + renderApp(); + + const message = await screen.findByText(/Some saved entries couldn't be restored/); + expect(screen.getByTestId("main-layout")).toContainElement(message); + expect(message.closest(`.${fluentProviderClassNames.root}`)).not.toBeNull(); + }); + it("renders the view named by the initial URL", () => { renderApp("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/registry/targets"); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2ccb3e6bbe..bb0ff53a1e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -869,6 +869,7 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) { } currentView={currentView} onNavigate={handleNavigate} onOpenFeedback={() => setFeedbackOpen(true)} @@ -1106,7 +1107,6 @@ function App() { const operatorAlias = account?.username ? (account.username.split('@')[0]?.toLowerCase() ?? null) : null return ( - diff --git a/frontend/src/components/Configuration/Reinitialize.test.tsx b/frontend/src/components/Configuration/Reinitialize.test.tsx index 4d74590ca0..a40635f3fc 100644 --- a/frontend/src/components/Configuration/Reinitialize.test.tsx +++ b/frontend/src/components/Configuration/Reinitialize.test.tsx @@ -144,6 +144,66 @@ describe('Reinitialize', () => { await waitFor(() => expect(api.reinitialize).toHaveBeenCalledWith('saved-v1')) }) + it('should list the saved entries that could not be restored', async () => { + api.getRuntimeStatus.mockResolvedValue({ + ...ready, + state: 'failed', + outcome: 'restore-failed', + message: "3 saved registry entries couldn't be restored.", + restore_failures: [ + { + kind: 'targets', + name: 'pool', + reason: 'missing_dependency', + message: "Uses target 'gone', which doesn't exist.", + version: 'v1', + dependency: { kind: 'targets', name: 'gone' }, + }, + { + kind: 'scorers', + name: 'refusal', + reason: 'failed_dependency', + message: "It uses an entry that couldn't be restored.", + version: 'v2', + dependency: { kind: 'targets', name: 'pool' }, + }, + { + kind: 'converters', + name: null, + reason: 'unreadable_storage', + message: "The saved converters couldn't be listed: permission denied", + version: null, + dependency: null, + }, + ], + }) + render( + + + , + ) + + const region = await screen.findByRole('region', { name: "Saved entries that couldn't be restored" }) + expect(within(region).getByText("Target pool: Uses target 'gone', which doesn't exist.")).toBeInTheDocument() + expect(within(region).getByText("Scorer refusal: It uses an entry that couldn't be restored. (target pool)")) + .toBeInTheDocument() + expect(within(region).getByText("Saved converters: The saved converters couldn't be listed: permission denied")) + .toBeInTheDocument() + expect(region).toHaveAttribute('tabindex', '0') + }) + + it('should show no list when every saved entry was restored', async () => { + api.getRuntimeStatus.mockResolvedValue({ ...ready, restore_failures: [] }) + render( + + + , + ) + + await waitFor(() => expect(screen.getByRole('button', { name: 'Reinitialize PyRIT' })).toBeEnabled()) + expect(screen.queryByRole('region', { name: "Saved entries that couldn't be restored" })).not.toBeInTheDocument() + }) + describe('runtime status polling', () => { beforeEach(() => { jest.useFakeTimers() diff --git a/frontend/src/components/Configuration/Reinitialize.tsx b/frontend/src/components/Configuration/Reinitialize.tsx index 193a661459..2d17fc0d50 100644 --- a/frontend/src/components/Configuration/Reinitialize.tsx +++ b/frontend/src/components/Configuration/Reinitialize.tsx @@ -13,6 +13,7 @@ import { toApiError } from '@/services/errors' import type { RuntimeStatus } from '@/types' import { useReinitializeStyles } from './Reinitialize.styles' +import RestoreFailures from './RestoreFailures' interface ReinitializeProps { version: string @@ -81,13 +82,17 @@ export default function Reinitialize({ return (
{status && (showRuntimeStatus || statusIsError || !status.enabled) && ( - + // Multiline, since a status message such as a restore failure can be long and change after the bar lays out. + Runtime: {status.state}. {status.message} {!status.enabled && ' Reinitialization requires one backend worker and one replica.'} )} + {status?.restore_failures && status.restore_failures.length > 0 && ( + + )} {pollError && {pollError}} {applyError && {applyError}} {hasUnsavedChanges && Save or explicitly discard unsaved edits before reinitializing.} diff --git a/frontend/src/components/Configuration/RestoreFailures.styles.ts b/frontend/src/components/Configuration/RestoreFailures.styles.ts new file mode 100644 index 0000000000..cacf3e052f --- /dev/null +++ b/frontend/src/components/Configuration/RestoreFailures.styles.ts @@ -0,0 +1,15 @@ +import { makeStyles } from '@fluentui/react-components' + +export const useRestoreFailuresStyles = makeStyles({ + // The page doesn't scroll past the editor, so a long list scrolls on its own. It fills its column, and a long + // name or message wraps instead of widening the list past it. + list: { + alignSelf: 'stretch', + boxSizing: 'border-box', + maxWidth: '100%', + minWidth: 0, + maxHeight: '30vh', + overflowWrap: 'anywhere', + overflowY: 'auto', + }, +}) diff --git a/frontend/src/components/Configuration/RestoreFailures.tsx b/frontend/src/components/Configuration/RestoreFailures.tsx new file mode 100644 index 0000000000..7cf08c6b4b --- /dev/null +++ b/frontend/src/components/Configuration/RestoreFailures.tsx @@ -0,0 +1,42 @@ +import type { RegistryRecipeKind, RestoreFailure } from '@/types' + +import { useRestoreFailuresStyles } from './RestoreFailures.styles' + +const KIND_LABELS: Record = { + targets: 'Target', + converters: 'Converter', + scorers: 'Scorer', + techniques: 'Technique', +} + +function describeFailure(failure: RestoreFailure): string { + const subject = failure.name === null ? `Saved ${failure.kind}` : `${KIND_LABELS[failure.kind]} ${failure.name}` + // The message usually names the entry it depends on already. + const dependency = failure.dependency && !failure.message.includes(`'${failure.dependency.name}'`) + ? ` (${KIND_LABELS[failure.dependency.kind].toLowerCase()} ${failure.dependency.name})` + : '' + return `${subject}: ${failure.message}${dependency}` +} + +interface RestoreFailuresProps { + failures: RestoreFailure[] +} + +export default function RestoreFailures({ failures }: RestoreFailuresProps) { + const styles = useRestoreFailuresStyles() + return ( +
+
    + {failures.map((failure) => ( +
  • {describeFailure(failure)}
  • + ))} +
+
+ ) +} diff --git a/frontend/src/components/Layout/MainLayout.styles.ts b/frontend/src/components/Layout/MainLayout.styles.ts index ab38ec00d2..2e740fbfc2 100644 --- a/frontend/src/components/Layout/MainLayout.styles.ts +++ b/frontend/src/components/Layout/MainLayout.styles.ts @@ -33,6 +33,9 @@ export const useMainLayoutStyles = makeStyles({ transform: 'translateY(0)', }, }, + banner: { + flexShrink: 0, + }, topBar: { minHeight: '60px', flexShrink: 0, diff --git a/frontend/src/components/Layout/MainLayout.test.tsx b/frontend/src/components/Layout/MainLayout.test.tsx index 1fa3da9fc7..4f36c2f90a 100644 --- a/frontend/src/components/Layout/MainLayout.test.tsx +++ b/frontend/src/components/Layout/MainLayout.test.tsx @@ -77,6 +77,23 @@ describe("MainLayout", () => { expect(screen.getByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true"); }); + it("shows a banner between the skip link and the top bar, in the layout column", async () => { + mockedVersionApi.getVersion.mockResolvedValue({ version: "1.0.0" }); + + renderWithProvider( + Saved entries need attention
}> +
Child Content
+ + ); + + const skipLink = screen.getByRole("link", { name: "Skip to main content" }); + const banner = screen.getByRole("status"); + const subtitle = screen.getByText("Python Risk Identification Tool"); + expect(skipLink.compareDocumentPosition(banner) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(banner.compareDocumentPosition(subtitle) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(screen.getByRole("main")).not.toContainElement(banner); + }); + it("renders the header with title and subtitle", async () => { mockedVersionApi.getVersion.mockResolvedValue({ version: "1.0.0" }); diff --git a/frontend/src/components/Layout/MainLayout.tsx b/frontend/src/components/Layout/MainLayout.tsx index 7ae6bda593..0ef35898f0 100644 --- a/frontend/src/components/Layout/MainLayout.tsx +++ b/frontend/src/components/Layout/MainLayout.tsx @@ -35,6 +35,8 @@ interface MainLayoutProps extends OperationControlProps { onStartTour?: () => void labelsBusy?: boolean featureNavigation?: React.ReactNode + /** Shown above the top bar, so the content below gets smaller instead of losing its bottom. */ + banner?: React.ReactNode } export default function MainLayout({ @@ -53,6 +55,7 @@ export default function MainLayout({ onStartTour, labelsBusy = false, featureNavigation, + banner, }: MainLayoutProps) { usePreventFileNavigation() const styles = useMainLayoutStyles() @@ -89,6 +92,7 @@ export default function MainLayout({ Skip to main content + {banner &&
{banner}
}
({ runtimeApi: { getReadiness: jest.fn() } })) +jest.mock('@/services/api', () => ({ + runtimeApi: { getReadiness: jest.fn() }, +})) + +function TestWrapper({ children }: { children: ReactNode }) { + return {children} +} function Consumer() { const runtime = useRuntime() @@ -41,3 +49,59 @@ describe('RuntimeProvider', () => { expect(screen.getByRole('textbox', { name: 'Draft' })).toHaveValue('keep my draft') }) }) + +function renderBanner() { + render() +} + +describe('RuntimeBanner', () => { + beforeEach(() => { jest.clearAllMocks() }) + + it('should tell everyone that an administrator has to fix saved entries that could not be restored', async () => { + jest.mocked(runtimeApi.getReadiness).mockResolvedValue({ + ready: false, + state: 'failed', + generation: 'first', + restore_failures: 2, + }) + + renderBanner() + + expect(await screen.findByText(new RegExp( + "Some saved entries couldn't be restored, so new runs and sends are unavailable\\. An administrator has to " + + 'view the failures in Configuration, fix or delete the files in registry_recipes_source, then reinitialize ' + + 'PyRIT or restart the backend\\. Drafts are preserved\\.', + ))).toBeInTheDocument() + expect(screen.queryByRole('region')).not.toBeInTheDocument() + expect(screen.queryByRole('button')).not.toBeInTheDocument() + expect(screen.queryByText(/PyRIT runtime: failed/)).not.toBeInTheDocument() + }) + + it('should show the general runtime bar while the runtime is not ready for another reason', async () => { + jest.mocked(runtimeApi.getReadiness).mockResolvedValue({ + ready: false, + state: 'restart-required', + generation: '', + restore_failures: 1, + }) + + renderBanner() + + expect(await screen.findByText(/PyRIT runtime: restart-required/)).toBeInTheDocument() + expect(screen.queryByText(/couldn't be restored/)).not.toBeInTheDocument() + }) + + it('should show nothing while the runtime is ready', async () => { + jest.mocked(runtimeApi.getReadiness).mockResolvedValue({ + ready: true, + state: 'ready', + generation: 'first', + restore_failures: 0, + }) + + renderBanner() + + await waitFor(() => expect(screen.queryByText(/PyRIT runtime/)).not.toBeInTheDocument()) + expect(screen.queryByText(/couldn't be restored/)).not.toBeInTheDocument() + }) +}) diff --git a/frontend/src/hooks/useRuntime.tsx b/frontend/src/hooks/useRuntime.tsx index 2035358d63..485ca25e03 100644 --- a/frontend/src/hooks/useRuntime.tsx +++ b/frontend/src/hooks/useRuntime.tsx @@ -41,8 +41,21 @@ export function RuntimeProvider({ children }: { children: ReactNode }) { export function RuntimeBanner() { const runtime = useRuntime() if (runtime.ready) return null + // Multiline, since the text changes after the bar first lays out, and Fluent's automatic layout only rechecks + // on a resize. + if (runtime.state === 'failed' && (runtime.restore_failures ?? 0) > 0) { + return ( + + + Some saved entries couldn't be restored, so new runs and sends are unavailable. An administrator has to + view the failures in Configuration, fix or delete the files in registry_recipes_source, then reinitialize + PyRIT or restart the backend. Drafts are preserved. + + + ) + } return ( - + PyRIT runtime: {runtime.state}. New runs and sends are unavailable. Administrators can repair saved sources and retry from Configuration. Drafts are preserved. diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 3f3331a30f..46b0e5aed4 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -2496,6 +2496,25 @@ export interface RuntimeReadiness { ready: boolean state: string generation: string + /** How many saved entries couldn't be restored; administrators see why in the runtime status. */ + restore_failures?: number +} + +export type RegistryRecipeKind = 'targets' | 'converters' | 'scorers' | 'techniques' + +export interface SavedEntryRef { + kind: RegistryRecipeKind + name: string +} + +/** A saved entry, or a whole folder of them when `name` is null, that couldn't be restored. */ +export interface RestoreFailure { + kind: RegistryRecipeKind + name: string | null + reason: string + message: string + version: string | null + dependency: SavedEntryRef | null } export interface RuntimeStatus { @@ -2506,6 +2525,8 @@ export interface RuntimeStatus { applying: boolean outcome: string message: string + /** The saved entries that couldn't be restored; only administrators can read the runtime status. */ + restore_failures?: RestoreFailure[] } export type FindingSeverity = 'critical' | 'important' | 'moderate' | 'low' | 'informational' | 'other' diff --git a/pyrit/backend/middleware/error_handlers.py b/pyrit/backend/middleware/error_handlers.py index 6258e6fd05..10d7c2c481 100644 --- a/pyrit/backend/middleware/error_handlers.py +++ b/pyrit/backend/middleware/error_handlers.py @@ -6,6 +6,7 @@ """ import logging +import traceback from fastapi import FastAPI, Request, status from fastapi.exceptions import RequestValidationError @@ -13,6 +14,7 @@ from pyrit.backend.middleware.request_size import RequestTooLargeError, request_too_large_response from pyrit.backend.models import FieldError, ProblemDetail +from pyrit.common.azure_storage import redact_urls from pyrit.exceptions.analytics_exception import AnalyticsException from pyrit.exceptions.dataset_exception import DatasetAPIException from pyrit.registry.file_document_storage import DocumentStorageUnavailableError, DocumentUnreadableError @@ -201,13 +203,16 @@ async def storage_unavailable_handler( # pyrit-async-suffix-exempt """ Handle stored documents that can't be read or written as 503 Service Unavailable. - The log names the storage location, without credentials, and the reason. It leaves out the traceback, - since the error behind it can carry a SAS URL. The response never carries a path or URL. + The log names the storage location, without credentials, and the reason, with the traceback at debug + level. URL credentials are removed from the traceback, since the error behind it can carry a SAS URL. + The response never carries a path or URL. Returns: JSONResponse: RFC 7807 problem detail response with 503 status. """ logger.warning(f"{exc} ({request.method} {request.url.path})") + if logger.isEnabledFor(logging.DEBUG): + logger.debug(f"Storage error details:\n{redact_urls(''.join(traceback.format_exception(exc)).rstrip())}") if isinstance(exc, DocumentUnreadableError): detail = f"{exc.label} '{exc.name}' can't be read: {exc.reason}" else: diff --git a/pyrit/backend/routes/health.py b/pyrit/backend/routes/health.py index b6e06c91a4..e0cd361faa 100644 --- a/pyrit/backend/routes/health.py +++ b/pyrit/backend/routes/health.py @@ -13,30 +13,31 @@ router = APIRouter() -def _runtime_readiness(request: Request) -> dict[str, str | bool]: +def _runtime_readiness(request: Request) -> dict[str, str | bool | int]: runtime = getattr(request.app.state, "runtime_lifecycle", None) if runtime is None: - return {"ready": False, "state": "failed", "generation": ""} + return {"ready": False, "state": "failed", "generation": "", "restore_failures": 0} return { "ready": runtime.reported_state == "ready", "state": runtime.reported_state, "generation": runtime.generation, + "restore_failures": len(runtime.restore_failures), } @router.get("/runtime") -async def runtime_readiness_async(request: Request) -> dict[str, str | bool]: +async def runtime_readiness_async(request: Request) -> dict[str, str | bool | int]: """ - Expose readiness and generation without administrative details. + Expose readiness, generation, and how many saved entries couldn't be restored, without details. Returns: - dict[str, str | bool]: Lightweight runtime readiness. + dict[str, str | bool | int]: Lightweight runtime readiness. """ return _runtime_readiness(request) @router.get("/health") -async def health_check_async(*, request: Request, response: Response) -> dict[str, str | bool | None]: +async def health_check_async(*, request: Request, response: Response) -> dict[str, str | bool | int | None]: """ Check the health status of the backend service. @@ -48,7 +49,7 @@ async def health_check_async(*, request: Request, response: Response) -> dict[st deployment checks use the readiness fields instead. Returns: - dict[str, str | bool | None]: Health status, timestamp, runtime readiness, and serving ACA revision. + dict[str, str | bool | int | None]: Health status, timestamp, runtime readiness, and serving ACA revision. """ readiness = _runtime_readiness(request) response.headers["Cache-Control"] = "no-store" diff --git a/pyrit/backend/services/runtime_lifecycle.py b/pyrit/backend/services/runtime_lifecycle.py index ebeecf30c8..d19b615e44 100644 --- a/pyrit/backend/services/runtime_lifecycle.py +++ b/pyrit/backend/services/runtime_lifecycle.py @@ -146,7 +146,7 @@ async def _restore_saved_entries_async(self, config: ConfigurationLoader) -> boo restorer = RegistryRecipeRestorer(source=config.registry_recipes_source) # Reading can wait on storage, so it runs in a worker thread. Entries are built on this loop, through # the API's create for each kind, because a constructor such as HuggingFaceChatTarget's starts a task - # on it. A slow constructor holds the loop while it runs. + # on it; the target's create_async does its slow setup, such as importing torch, in a worker thread first. saved = await asyncio.to_thread(restorer.read) report = await restorer.restore_async( saved=saved, build_async=partial(build_saved_entry_async, upload_directory=config.target_upload_directory) @@ -274,6 +274,8 @@ async def _apply_async(self, *, version: str) -> None: return mutated = True + # The restore report describes the runtime being replaced. + self.restore_failures, self.restore_ignored = [], [] await close_services_async() await config.apply_prepared_reinitialization_async(prepared=prepared) await self._management_async(config) diff --git a/pyrit/backend/services/scenario_suite_service.py b/pyrit/backend/services/scenario_suite_service.py index ce1e436c2b..aeb9c514d4 100644 --- a/pyrit/backend/services/scenario_suite_service.py +++ b/pyrit/backend/services/scenario_suite_service.py @@ -5,6 +5,7 @@ import asyncio import logging +import traceback from dataclasses import dataclass from functools import lru_cache from typing import Literal @@ -14,6 +15,7 @@ ScenarioSuiteListResponse, ScenarioSuiteResponse, ) +from pyrit.common.azure_storage import redact_urls from pyrit.models import ( PresetIssue, ScenarioSuite, @@ -23,7 +25,7 @@ ScenarioSuiteRegistryEntry, ) from pyrit.registry import ScenarioPresetRegistry, ScenarioSuiteRegistry -from pyrit.registry.file_document_storage import DocumentStorageUnavailableError +from pyrit.registry.file_document_storage import DocumentStorageUnavailableError, DocumentUnreadableError logger = logging.getLogger(__name__) @@ -217,20 +219,23 @@ def _resolve_preset_projection( stored_version = registry.get_preset_version(name=preset_name) except DocumentStorageUnavailableError as error: - # The message leaves out credentials; the error behind it, which a traceback would show, may not. - logger.warning(f"Could not project scenario preset '{preset_name}': {error}") + # The error behind it can carry a SAS URL, so the traceback is logged with URL credentials removed. + details = redact_urls("".join(traceback.format_exception(error)).rstrip()) + logger.warning(f"Could not project scenario preset '{preset_name}': {error}\n{details}") + if isinstance(error, DocumentUnreadableError): + message = ( + f"Scenario preset '{preset_name}' can't be read: {error.reason}; " + "repair or replace the preset before running this suite." + ) + else: + message = ( + f"Scenario preset '{preset_name}' could not be checked because preset storage is " + "temporarily unavailable; retry when storage is available." + ) return _PresetProjection( origin=None, version=None, - issues=( - PresetIssue( - field="preset_name", - message=( - f"Scenario preset '{preset_name}' could not be checked because preset storage is " - "temporarily unavailable; retry when storage is available." - ), - ), - ), + issues=(PresetIssue(field="preset_name", message=message),), ) if stored_version is None: diff --git a/pyrit/backend/services/target_service.py b/pyrit/backend/services/target_service.py index a3d413e411..24ff4cd369 100644 --- a/pyrit/backend/services/target_service.py +++ b/pyrit/backend/services/target_service.py @@ -654,8 +654,11 @@ async def create_target_async( target_obj = ( await self.build_from_source_async(request.source) if request.source - else self._registry.create_instance_from_external_input( - request.type, params=params, allowed_path_params=self._allowed_path_params(target_cls=target_cls) + else await self._registry.create_instance_async( + name=request.type, + params=params, + external_input=True, + allowed_path_params=self._allowed_path_params(target_cls=target_cls), ) ) if not request.register: diff --git a/pyrit/models/catalog/registry_recipe.py b/pyrit/models/catalog/registry_recipe.py index c381f1c763..964fd685c0 100644 --- a/pyrit/models/catalog/registry_recipe.py +++ b/pyrit/models/catalog/registry_recipe.py @@ -152,7 +152,7 @@ class RestoreFailure(BaseModel): kind: RegistryRecipeKind name: str | None = Field(None, description="Entry name; None when the whole folder couldn't be read") reason: RestoreFailureReason - message: str = Field(..., description="Why, in words safe to show users") + message: str = Field(..., description="Why, for administrators; any credential in a URL is hidden") version: str | None = Field(None, description="Version of the stored document, when it could be read") dependency: SavedEntryRef | None = Field(None, description="The entry this one needed that is missing or failed") diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index d2b75a0ee7..789ef8fec2 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -6,7 +6,7 @@ from collections.abc import Generator, Mapping, Sequence from contextlib import contextmanager from contextvars import ContextVar -from typing import Any, ClassVar, final +from typing import Any, ClassVar, Self, final from pyrit.common import AuthMode, print_deprecation_message from pyrit.common.async_compatibility import legacy_sync_override @@ -154,6 +154,23 @@ def get_auth_mode_parameters(cls, *, auth_mode: AuthMode) -> dict[str, object]: """ return {} + @classmethod + async def create_async(cls, **kwargs: Any) -> Self: + """ + Build the target on the calling event loop. + + Targets whose construction needs slow setup, such as a first import, override this to do that setup in a + worker thread first. The constructor itself still runs on the calling loop, so the tasks and locks it creates + belong to that loop. + + Args: + **kwargs (Any): The constructor arguments. + + Returns: + Self: The new target. + """ + return cls(**kwargs) + @classmethod def _validate_auth_mode(cls, auth_mode: AuthMode | None) -> None: """ diff --git a/pyrit/prompt_target/hugging_face/hugging_face_chat_target.py b/pyrit/prompt_target/hugging_face/hugging_face_chat_target.py index 3488893403..4074505c4d 100644 --- a/pyrit/prompt_target/hugging_face/hugging_face_chat_target.py +++ b/pyrit/prompt_target/hugging_face/hugging_face_chat_target.py @@ -7,7 +7,7 @@ import warnings from concurrent.futures import ThreadPoolExecutor from pathlib import Path -from typing import TYPE_CHECKING, Any, ClassVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, Self, cast from pyrit.common import default_values from pyrit.exceptions import EmptyResponseException, pyrit_target_retry @@ -639,3 +639,36 @@ def disable_cache(cls) -> None: cls._cached_tokenizer = None cls._cached_model_id = None logger.info("Class-level cache disabled and cleared.") + + @classmethod + async def create_async(cls, **kwargs: Any) -> Self: + """ + Build the target after importing torch, and checking for CUDA when ``use_cuda`` is set, in a worker thread. + + Both can take seconds the first time and are quick after it, so the constructor, which runs on the calling + loop and starts model loading there, doesn't hold that loop. A missing torch is left for the constructor to + report. + + Args: + **kwargs (Any): The constructor arguments. + + Returns: + Self: The new target. + """ + await asyncio.to_thread(cls._import_torch, use_cuda=bool(kwargs.get("use_cuda", False))) + return await super().create_async(**kwargs) + + @staticmethod + def _import_torch(*, use_cuda: bool) -> None: + """ + Import torch, and check for CUDA when asked, as the constructor does. + + Args: + use_cuda (bool): Whether the target asks for CUDA. + """ + try: + import torch # type: ignore[ty:unresolved-import] + except ModuleNotFoundError: + return + if use_cuda: + torch.cuda.is_available() diff --git a/pyrit/registry/components/target_registry.py b/pyrit/registry/components/target_registry.py index cbc70433c3..1ca891f1e9 100644 --- a/pyrit/registry/components/target_registry.py +++ b/pyrit/registry/components/target_registry.py @@ -29,8 +29,10 @@ from pyrit.models import TargetIdentifier from pyrit.registry.registry import InstanceHoldingRegistry from pyrit.registry.registry_metadata import RegistryMetadata +from pyrit.registry.resolution import resolve_constructor_args if TYPE_CHECKING: + from collections.abc import Mapping from types import ModuleType from pyrit.prompt_target import PromptTarget @@ -103,3 +105,43 @@ def _identifier_type(self) -> type[TargetIdentifier]: def _metadata_class(self) -> type[TargetMetadata]: """Return ``TargetMetadata``; the base populates it from the common fields.""" return TargetMetadata + + async def create_instance_async( + self, + *, + name: str, + params: Mapping[str, object], + external_input: bool = False, + allowed_path_params: frozenset[str] = frozenset(), + ) -> PromptTarget: + """ + Build a target through its ``create_async``, so slow setup it needs runs off the calling event loop. + + The arguments are resolved as ``create_instance`` resolves them or, with ``external_input``, as + ``create_instance_from_external_input`` does, so the target gets the values its constructor will. + + Args: + name (str): The catalog name to build. + params (Mapping[str, object]): The constructor arguments. + external_input (bool): Whether ``params`` come from an external caller such as a REST request. + Defaults to False. + allowed_path_params (frozenset[str]): External parameters that can name a server file or folder but + that the caller has made safe. Defaults to none. + + Returns: + PromptTarget: The new target, not registered. + + Raises: + KeyError: If the name is not registered. + ValueError: If an argument can't be resolved or coerced for the target's constructor. + """ + cls = self.get_class(name) + resolved = resolve_constructor_args( + cls=cls, + raw_args=dict(params), + identifier_type=self._identifier_type(), + external_input=external_input, + seam_base_type=self._seam_base_type(), + allowed_path_params=allowed_path_params, + ) + return await cls.create_async(**resolved) diff --git a/tests/unit/backend/test_error_handlers.py b/tests/unit/backend/test_error_handlers.py index 86207bda56..c69c565da6 100644 --- a/tests/unit/backend/test_error_handlers.py +++ b/tests/unit/backend/test_error_handlers.py @@ -157,10 +157,10 @@ async def test_endpoint() -> dict: ) assert all(record.exc_info is None for record in caplog.records) - def test_storage_failure_log_leaves_out_a_sas_url_from_the_error_behind_it( + def test_storage_failure_log_keeps_the_error_behind_it_without_its_sas_url( self, app: FastAPI, client: TestClient, caplog: pytest.LogCaptureFixture ) -> None: - """Test that a SAS URL in the error behind a storage failure stays out of the log, even at debug level.""" + """Test that the debug log shows the error behind a storage failure, with its SAS URL left out.""" @app.get("/test") async def test_endpoint() -> dict: @@ -179,6 +179,7 @@ async def test_endpoint() -> dict: "Scenario preset storage at https://account.blob.core.windows.net/presets is unavailable: " "ServiceRequestError (GET /test)" ) in caplog.messages + assert "ServiceRequestError: https://account.blob.core.windows.net/presets" in caplog.text assert "secret-sig" not in caplog.text def test_unreadable_document_returns_503_with_the_reason(self, app: FastAPI, client: TestClient) -> None: diff --git a/tests/unit/backend/test_runtime_lifecycle.py b/tests/unit/backend/test_runtime_lifecycle.py index 94c47971ac..6b7df0d151 100644 --- a/tests/unit/backend/test_runtime_lifecycle.py +++ b/tests/unit/backend/test_runtime_lifecycle.py @@ -120,6 +120,7 @@ async def test_runtime_readiness_reports_state_async(*, runtime: RuntimeLifecycl "ready": state == "ready", "state": state if state is not None else "failed", "generation": "original" if state is not None else "", + "restore_failures": 0, } @@ -783,7 +784,12 @@ async def shutdown_async() -> None: assert runtime.status()["state"] == "stopping" readiness = await client.get("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/api/runtime") assert readiness.status_code == 200 - assert readiness.json() == {"ready": False, "state": "stopping", "generation": "original"} + assert readiness.json() == { + "ready": False, + "state": "stopping", + "generation": "original", + "restore_failures": 0, + } liveness = await client.get("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/api/health") assert liveness.status_code == 200 assert liveness.json()["status"] == "healthy" @@ -951,7 +957,12 @@ async def shutdown_async() -> None: assert runtime.status()["state"] == "stopping" readiness = await client.get("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/api/runtime") assert readiness.status_code == 200 - assert readiness.json() == {"ready": False, "state": "stopping", "generation": runtime.generation} + assert readiness.json() == { + "ready": False, + "state": "stopping", + "generation": runtime.generation, + "restore_failures": 0, + } assert (await client.get("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/api/config")).status_code == 503 release_request.set() await asyncio.wait_for(shutdown, timeout=5) @@ -1270,6 +1281,35 @@ async def test_status_lists_a_file_name_that_is_not_valid_text_async(runtime: Ru assert [item["file_name"] for item in status.json()["restore_ignored"]] == ["bad\\udcffname.json"] +async def test_everyone_sees_how_many_entries_failed_and_administrators_see_why_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe( + recipes, + kind="targets", + name="pool", + document={ + "class_module": "pyrit.prompt_target.round_robin_target", + "class_name": "RoundRobinTarget", + "params": {"targets": ["missing"]}, + }, + ) + + await _start_with_recipes_async(runtime, recipes=recipes) + + assert runtime.state == "failed" + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + readiness = await client.get("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/api/runtime") + health = await client.get("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/api/health") + status = await client.get("/api/config/runtime") + assert readiness.json()["restore_failures"] == 1 + assert "restore_failures" not in health.json() + (failure,) = status.json()["restore_failures"] + assert (failure["kind"], failure["name"], failure["reason"]) == ("targets", "pool", "missing_dependency") + assert failure["dependency"] == {"kind": "targets", "name": "missing"} + + async def test_startup_lists_ignored_files_without_blocking_readiness_async( runtime: RuntimeLifecycle, tmp_path: Path ) -> None: @@ -1368,6 +1408,48 @@ async def test_apply_from_failed_without_live_apply_says_to_restart_async( lifecycle_module.close_services_async.assert_not_awaited() +@pytest.mark.parametrize("failing_step", ["close_services", "apply", "management"]) +async def test_a_failure_after_replacement_begins_drops_the_previous_restore_report_async( + runtime: RuntimeLifecycle, tmp_path: Path, failing_step: str +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="targets", name="broken", document={"class_module": "nowhere", "class_name": "Nope"}) + _save_recipe(recipes, kind="converters", name="Not-A-Name", document={}) + await _start_with_recipes_async(runtime, recipes=recipes) + assert runtime.restore_failures + assert runtime.restore_ignored + config = await runtime._load_async() + failure = RuntimeError("replacement failed") + if failing_step == "close_services": + lifecycle_module.close_services_async.side_effect = failure + elif failing_step == "apply": + config.apply_prepared_reinitialization_async.side_effect = failure + else: + runtime._management_async.side_effect = failure # type: ignore[attr-defined] + + await apply_async(runtime) + + assert (runtime.state, runtime.outcome) == ("restart-required", "restart-required") + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + status = (await client.get("/api/config/runtime")).json() + assert (status["restore_failures"], status["restore_ignored"]) == ([], []) + + +async def test_a_failure_before_replacement_keeps_the_restore_report_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="targets", name="broken", document={"class_module": "nowhere", "class_name": "Nope"}) + await _start_with_recipes_async(runtime, recipes=recipes) + config = await runtime._load_async() + config.preflight_reinitialization_async.side_effect = ValueError("bad configuration") + + await apply_async(runtime) + + assert (runtime.state, runtime.outcome) == ("failed", "invalid-configuration") + assert [failure["name"] for failure in runtime.status()["restore_failures"]] == ["broken"] + + async def test_restore_cancellation_propagates_from_startup_async(runtime: RuntimeLifecycle, tmp_path: Path) -> None: runtime.state = "initializing" @@ -1376,3 +1458,65 @@ async def test_restore_cancellation_propagates_from_startup_async(runtime: Runti await _start_with_recipes_async(runtime, recipes=tmp_path / "recipes") assert runtime.state == "initializing" + + +_RESTORABLE_TARGET = { + "class_module": "pyrit.prompt_target.openai.openai_chat_target", + "class_name": "OpenAIChatTarget", + "auth_mode": "identity", + "params": {"endpoint": "https://contoso.openai.azure.com/openai/v1", "model_name": "gpt-4o"}, +} +_BROKEN_TARGET = {"class_module": "nowhere", "class_name": "Nope"} + + +@pytest.mark.usefixtures("patch_central_database") +async def test_fixing_the_file_and_applying_restores_the_entry_async(runtime: RuntimeLifecycle, tmp_path: Path) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="targets", name="ghost", document=_BROKEN_TARGET) + await _start_with_recipes_async(runtime, recipes=recipes) + assert [failure["name"] for failure in runtime.status()["restore_failures"]] == ["ghost"] + _save_recipe(recipes, kind="targets", name="ghost", document=_RESTORABLE_TARGET) + config = await runtime._load_async() + config.apply_prepared_reinitialization_async.side_effect = lambda **_: TargetRegistry.reset_registry_singleton() + lifecycle_module.close_services_async.side_effect = _forget_registry_services_async + + await apply_async(runtime) + + assert (runtime.state, runtime.outcome) == ("ready", "success") + assert runtime.status()["restore_failures"] == [] + assert isinstance(TargetRegistry.get_registry_singleton().instances.get("ghost"), OpenAIChatTarget) + + +async def test_readiness_counts_restore_failures_without_their_details_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="targets", name="ghost", document=_BROKEN_TARGET) + await _start_with_recipes_async(runtime, recipes=recipes) + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + readiness = await client.get("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/api/runtime") + + assert readiness.json() == { + "ready": False, + "state": "failed", + "generation": runtime.generation, + "restore_failures": 1, + } + + +async def test_administrators_see_the_failures_while_other_routes_wait_for_ready_async( + runtime: RuntimeLifecycle, tmp_path: Path +) -> None: + recipes = tmp_path / "recipes" + _save_recipe(recipes, kind="targets", name="ghost", document=_BROKEN_TARGET) + await _start_with_recipes_async(runtime, recipes=recipes) + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=runtime.app), base_url="http://test") as client: + status = await client.get("/api/config/runtime") + targets = await client.get("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/api/targets") + + assert runtime.state == "failed" + assert status.status_code == 200 + assert [failure["name"] for failure in status.json()["restore_failures"]] == ["ghost"] + assert targets.status_code == 503 diff --git a/tests/unit/backend/test_scenario_suite_routes.py b/tests/unit/backend/test_scenario_suite_routes.py index 177ad3677a..ced13e544d 100644 --- a/tests/unit/backend/test_scenario_suite_routes.py +++ b/tests/unit/backend/test_scenario_suite_routes.py @@ -40,6 +40,7 @@ from pyrit.models.catalog import ScenarioSuiteRegistryEntry from pyrit.registry import ( ScenarioPresetRegistry, + ScenarioPresetStorage, ScenarioSuiteConflictError, ScenarioSuiteExecutionNotFoundError, ScenarioSuiteLaunchConflictError, @@ -443,6 +444,38 @@ def test_get_succeeds_when_preset_storage_is_unavailable( assert "preset storage is temporarily unavailable" in response.json()["entry_statuses"][0]["issues"][0]["message"] +def test_unreadable_preset_gets_repair_advice_instead_of_a_retry(*, client: TestClient, tmp_path: Path) -> None: + """Test a preset stored as a folder is reported as that preset needing repair, and the suite still saves.""" + (tmp_path / "presets" / "nightly.json").mkdir(parents=True) + presets = ScenarioPresetRegistry(storage=ScenarioPresetStorage(source=str(tmp_path / "presets"))) + storage = ScenarioSuiteStorage(source=str(tmp_path / "suites")) + expected = [ + { + "field": "preset_name", + "message": "Scenario preset 'nightly' can't be read: Not a regular file; " + "repair or replace the preset before running this suite.", + } + ] + + with ( + patch.object(ScenarioPresetRegistry, "get_registry_singleton", return_value=presets), + patch( + "pyrit.backend.routes.scenario_suites.get_scenario_suite_service", + return_value=ScenarioSuiteService(registry=ScenarioSuiteRegistry(storage=storage)), + ), + ): + created = client.post("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/api/scenario-suites", json=_suite().model_dump(mode="json")) + listed = client.get("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/api/scenario-suites") + + assert created.status_code == 201 + assert listed.status_code == 200 + assert storage.load_suite(SUITE_NAME) is not None + for entry_status in (created.json()["entry_statuses"][0], listed.json()["items"][0]["entry_statuses"][0]): + assert entry_status["origin"] is None + assert entry_status["preset_version"] is None + assert entry_status["issues"] == expected + + def test_create_requires_admin(anonymous_client: TestClient, service: MagicMock) -> None: """Test mutation authorization.""" service.save_suite_async = AsyncMock(return_value=_response()) diff --git a/tests/unit/backend/test_scenario_suite_service.py b/tests/unit/backend/test_scenario_suite_service.py index b41e077725..3ab63da19c 100644 --- a/tests/unit/backend/test_scenario_suite_service.py +++ b/tests/unit/backend/test_scenario_suite_service.py @@ -119,15 +119,27 @@ async def test_registered_suite_is_listed_with_nullable_version( @pytest.mark.parametrize( - "error", + ("error", "message"), [ - DocumentStorageUnavailableError(label="Scenario preset", source="/srv/presets", reason="Permission denied"), - DocumentUnreadableError( - label="Scenario preset", - source="/srv/presets", - name="nightly", - file_name="nightly.json", - reason="Not a regular file", + ( + DocumentStorageUnavailableError(label="Scenario preset", source="/srv/presets", reason="Permission denied"), + ( + "Scenario preset 'nightly' could not be checked because preset storage is temporarily unavailable; " + "retry when storage is available." + ), + ), + ( + DocumentUnreadableError( + label="Scenario preset", + source="/srv/presets", + name="nightly", + file_name="nightly.json", + reason="Not a regular file", + ), + ( + "Scenario preset 'nightly' can't be read: Not a regular file; " + "repair or replace the preset before running this suite." + ), ), ], ids=["storage", "one_document"], @@ -136,6 +148,7 @@ async def test_preset_storage_failure_is_advisory_after_committed_save( service: ScenarioSuiteService, preset_registry: MagicMock, error: Exception, + message: str, ) -> None: """Test that response projection cannot turn a committed write into a failure.""" preset_registry.get_preset.side_effect = error @@ -149,15 +162,15 @@ async def test_preset_storage_failure_is_advisory_after_committed_save( assert stored is not None assert response.entry_statuses[0].origin is None assert response.entry_statuses[0].preset_version is None - assert "preset storage is temporarily unavailable" in response.entry_statuses[0].issues[0].message + assert [issue.message for issue in response.entry_statuses[0].issues] == [message] -async def test_preset_storage_failure_log_leaves_out_a_sas_url_from_the_error_behind_it( +async def test_preset_storage_failure_log_keeps_the_error_behind_it_without_its_sas_url( service: ScenarioSuiteService, preset_registry: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: - """Test that the warning names the storage without the credentials the error behind it carries.""" + """Test that the warning shows the error behind a storage failure, with its SAS URL left out.""" error = DocumentStorageUnavailableError( label="Scenario preset", source="https://account.blob.core.windows.net/presets", reason="ServiceRequestError" ) @@ -167,7 +180,9 @@ async def test_preset_storage_failure_log_leaves_out_a_sas_url_from_the_error_be with caplog.at_level("DEBUG", logger="pyrit.backend.services.scenario_suite_service"): await service.save_suite_async(suite=_suite(preset_names=("nightly",)), expected_version=None) - assert f"Could not project scenario preset 'nightly': {error}" in caplog.messages + (message,) = [message for message in caplog.messages if message.startswith("Could not project scenario preset")] + assert message.startswith(f"Could not project scenario preset 'nightly': {error}\n") + assert "ServiceRequestError: https://account.blob.core.windows.net/presets" in message assert "secret-sig" not in caplog.text diff --git a/tests/unit/backend/test_target_service.py b/tests/unit/backend/test_target_service.py index 4283a91226..18fe45bec9 100644 --- a/tests/unit/backend/test_target_service.py +++ b/tests/unit/backend/test_target_service.py @@ -543,7 +543,7 @@ async def test_create_github_copilot_target_requires_token_async( with ( patch.dict(os.environ, environment, clear=True), - patch.object(service._registry, "create_instance_from_external_input") as create_instance, + patch.object(service._registry, "create_instance_async") as create_instance, pytest.raises( ValueError, match=r"Enter GitHub Token or configure GITHUB_TOKEN for this CoPyRIT instance.*\.env/\.env\.local", @@ -788,7 +788,7 @@ async def test_create_target_rejects_non_admin_remote_code_before_construction(s service = TargetService() with ( - patch.object(service._registry, "create_instance_from_external_input") as create_instance, + patch.object(service._registry, "create_instance_async") as create_instance, pytest.raises(PermissionError, match="requires administrator access"), ): await service.create_target_async(request=self._request({"trust_remote_code": value}), is_admin=False) @@ -800,7 +800,7 @@ async def test_create_target_rejects_non_boolean_remote_code_before_construction service = TargetService() with ( - patch.object(service._registry, "create_instance_from_external_input") as create_instance, + patch.object(service._registry, "create_instance_async") as create_instance, pytest.raises(ValueError, match="trust_remote_code"), ): await service.create_target_async(request=self._request({"trust_remote_code": 1}), is_admin=False) @@ -822,7 +822,7 @@ async def test_create_target_forwards_coerced_true_to_constructor_for_admin(self stop = RuntimeError("stop after construction") with ( - patch.object(service._registry, "create_instance_from_external_input", side_effect=stop) as create_instance, + patch.object(service._registry, "create_instance_async", side_effect=stop) as create_instance, pytest.raises(RuntimeError, match="stop after construction"), ): await service.create_target_async(request=self._request({"trust_remote_code": value}), is_admin=True) @@ -835,7 +835,7 @@ async def test_create_target_forwards_coerced_false_to_constructor_for_non_admin stop = RuntimeError("stop after construction") with ( - patch.object(service._registry, "create_instance_from_external_input", side_effect=stop) as create_instance, + patch.object(service._registry, "create_instance_async", side_effect=stop) as create_instance, pytest.raises(RuntimeError, match="stop after construction"), ): await service.create_target_async(request=self._request({"trust_remote_code": value}), is_admin=False) @@ -904,7 +904,7 @@ async def test_create_target_identity_mode_requires_admin_before_construction(se service = TargetService() with ( - patch.object(service._registry, "create_instance_from_external_input") as create_instance, + patch.object(service._registry, "create_instance_async") as create_instance, pytest.raises(PermissionError, match="requires administrator access"), ): await service.create_target_async(request=self._request(auth_mode="identity"), is_admin=False) @@ -917,7 +917,7 @@ async def test_create_target_identity_mode_with_caller_sas_requires_admin(self) service = TargetService() with ( - patch.object(service._registry, "create_instance_from_external_input") as create_instance, + patch.object(service._registry, "create_instance_async") as create_instance, pytest.raises(PermissionError, match="requires administrator access"), ): await service.create_target_async( @@ -930,7 +930,7 @@ async def test_create_target_api_key_without_sas_requires_admin_before_construct service = TargetService() with ( - patch.object(service._registry, "create_instance_from_external_input") as create_instance, + patch.object(service._registry, "create_instance_async") as create_instance, pytest.raises(PermissionError, match="requires administrator access"), ): await service.create_target_async(request=self._request(), is_admin=False) @@ -943,7 +943,7 @@ async def test_create_target_without_caller_sas_requires_admin_even_with_environ service = TargetService() with ( - patch.object(service._registry, "create_instance_from_external_input") as create_instance, + patch.object(service._registry, "create_instance_async") as create_instance, pytest.raises(PermissionError, match="requires administrator access"), ): await service.create_target_async(request=self._request(), is_admin=False) @@ -955,7 +955,7 @@ async def test_create_target_with_caller_sas_reaches_construction_for_non_admin( stop = RuntimeError("stop after construction") with ( - patch.object(service._registry, "create_instance_from_external_input", side_effect=stop) as create_instance, + patch.object(service._registry, "create_instance_async", side_effect=stop) as create_instance, pytest.raises(RuntimeError, match="stop after construction"), ): await service.create_target_async(request=self._request({"sas_token": "caller-sas"}), is_admin=False) @@ -967,7 +967,7 @@ async def test_create_target_identity_mode_reaches_construction_for_admin(self) stop = RuntimeError("stop after construction") with ( - patch.object(service._registry, "create_instance_from_external_input", side_effect=stop) as create_instance, + patch.object(service._registry, "create_instance_async", side_effect=stop) as create_instance, pytest.raises(RuntimeError, match="stop after construction"), ): await service.create_target_async(request=self._request(auth_mode="identity"), is_admin=True) @@ -1079,12 +1079,14 @@ async def test_create_target_delegates_construction_to_registry(self, sqlite_ins service = TargetService() with patch.object( service._registry, - "create_instance_from_external_input", - wraps=service._registry.create_instance_from_external_input, + "create_instance_async", + wraps=service._registry.create_instance_async, ) as create: await service.create_target_async(request=CreateTargetRequest(type="TextTarget", params={})) - create.assert_called_once_with("TextTarget", params={}, allowed_path_params=frozenset()) + create.assert_awaited_once_with( + name="TextTarget", params={}, external_input=True, allowed_path_params=frozenset() + ) async def test_create_target_rejects_invalid_enum_value(self, sqlite_instance) -> None: """An invalid enum value from the JSON request raises a parameter error before target construction.""" diff --git a/tests/unit/backend/test_temporary_components.py b/tests/unit/backend/test_temporary_components.py index ab01c84e4d..c3d133f35f 100644 --- a/tests/unit/backend/test_temporary_components.py +++ b/tests/unit/backend/test_temporary_components.py @@ -4,10 +4,14 @@ """Private construction, reconstruction, lifetime, and provenance regressions.""" import asyncio +import importlib.abc +import importlib.util +import sys import threading import uuid -from collections.abc import Iterator -from types import ModuleType +from collections.abc import Iterator, Sequence +from importlib.machinery import ModuleSpec +from types import ModuleType, SimpleNamespace from typing import Any from unittest.mock import AsyncMock, patch @@ -125,6 +129,26 @@ def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) +class _TorchStandIn(importlib.abc.MetaPathFinder, importlib.abc.Loader): + """Stand in for torch, noting the thread that first imports it and the one that first checks for CUDA.""" + + def __init__(self) -> None: + self.first_threads: dict[str, threading.Thread] = {} + + def find_spec( + self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = None + ) -> ModuleSpec | None: + return importlib.util.spec_from_loader(fullname, self) if fullname == "torch" else None + + def exec_module(self, module: ModuleType) -> None: + self.first_threads.setdefault("import", threading.current_thread()) + module.cuda = SimpleNamespace(is_available=self._is_available) # type: ignore[attr-defined] + + def _is_available(self) -> bool: + self.first_threads.setdefault("cuda", threading.current_thread()) + return True + + @pytest.mark.usefixtures("patch_central_database") class TestTemporaryComponents: @pytest.mark.parametrize("register", [True, False]) @@ -132,10 +156,10 @@ async def test_hugging_face_construction_uses_request_loop_async(self, register: request_loop = asyncio.get_running_loop() constructed: list[HuggingFaceChatTarget] = [] registry = TargetRegistry.get_registry_singleton() - factory = registry.create_instance_from_external_input + factory = registry.create_instance_async - def create(name: str, *, params: Any, allowed_path_params: Any) -> HuggingFaceChatTarget: - target = factory(name, params=params, allowed_path_params=allowed_path_params) + async def create(**kwargs: Any) -> HuggingFaceChatTarget: + target = await factory(**kwargs) assert isinstance(target, HuggingFaceChatTarget) constructed.append(target) return target @@ -143,7 +167,7 @@ def create(name: str, *, params: Any, allowed_path_params: Any) -> HuggingFaceCh with ( patch.dict("sys.modules", {"torch": ModuleType("torch")}), patch.object(HuggingFaceChatTarget, "load_model_and_tokenizer_async", new_callable=AsyncMock) as load, - patch.object(registry, "create_instance_from_external_input", side_effect=create), + patch.object(registry, "create_instance_async", side_effect=create), ): response = await TargetService().create_target_async( request=CreateTargetRequest( @@ -160,6 +184,64 @@ def create(name: str, *, params: Any, allowed_path_params: Any) -> HuggingFaceCh assert response.identifier.class_name == "HuggingFaceChatTarget" assert registry.instances.get_names() == (["local-model"] if register else []) + @pytest.mark.parametrize( + ("use_cuda", "steps"), [(False, ["import"]), ("false", ["import"]), (True, ["cuda", "import"])] + ) + async def test_hugging_face_imports_torch_off_the_request_loop_async( + self, use_cuda: bool | str, steps: list[str] + ) -> None: + torch = _TorchStandIn() + with ( + patch.dict("sys.modules"), + patch.object(sys, "meta_path", [torch, *sys.meta_path]), + patch.object(HuggingFaceChatTarget, "load_model_and_tokenizer_async", new_callable=AsyncMock), + ): + sys.modules.pop("torch", None) + await TargetService().create_target_async( + request=CreateTargetRequest( + name="local-model", + type="HuggingFaceChatTarget", + params={"model_path": "test-model", "use_cuda": use_cuda, "hf_access_token": "test-only-token"}, + ) + ) + target = TargetRegistry.get_registry_singleton().instances.get("local-model") + assert isinstance(target, HuggingFaceChatTarget) + await target.load_model_and_tokenizer_task + + assert sorted(torch.first_threads) == steps + assert threading.current_thread() not in torch.first_threads.values() + assert target.load_model_and_tokenizer_task.get_loop() is asyncio.get_running_loop() + + async def test_hugging_face_without_torch_reports_the_constructor_error_async(self) -> None: + with patch.dict("sys.modules", {"torch": None}), pytest.raises(RuntimeError, match="Could not import torch"): + await TargetService().create_target_async( + request=CreateTargetRequest( + name="local-model", + type="HuggingFaceChatTarget", + params={"model_path": "test-model", "use_cuda": True, "hf_access_token": "test-only-token"}, + ) + ) + + assert TargetRegistry.get_registry_singleton().instances.get_names() == [] + + async def test_hugging_face_use_cuda_that_is_not_a_boolean_is_refused_without_a_cuda_check_async(self) -> None: + torch = _TorchStandIn() + with ( + patch.dict("sys.modules"), + patch.object(sys, "meta_path", [torch, *sys.meta_path]), + pytest.raises(ValueError, match="expects bool"), + ): + sys.modules.pop("torch", None) + await TargetService().create_target_async( + request=CreateTargetRequest( + name="local-model", + type="HuggingFaceChatTarget", + params={"model_path": "test-model", "use_cuda": "maybe", "hf_access_token": "test-only-token"}, + ) + ) + + assert "cuda" not in torch.first_threads + @pytest.mark.parametrize( ("router", "path", "payload", "registry"), [ diff --git a/tests/unit/registry/test_target_registry.py b/tests/unit/registry/test_target_registry.py index 2a4b8fddad..5fb4e720c3 100644 --- a/tests/unit/registry/test_target_registry.py +++ b/tests/unit/registry/test_target_registry.py @@ -6,13 +6,18 @@ and its introspection helpers. """ +import asyncio import re +import threading +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch import pytest from pyrit.models import ComponentIdentifier, ComponentType, Message, MessagePiece from pyrit.prompt_target import ( CopilotType, + HuggingFaceChatTarget, PlaywrightCopilotTarget, PromptTarget, RoundRobinTarget, @@ -473,3 +478,34 @@ def test_no_key_targets_accept_an_explicit_auth_mode(self, registry: TargetRegis assert target_cls.get_auth_mode_parameters(auth_mode="none") == {"auth_mode": "none"}, ( f"{name} advertises no-key support but does not forward an explicit auth_mode" ) + + +@pytest.mark.usefixtures("patch_central_database") +class TestCreateInstanceAsync: + @pytest.mark.parametrize(("use_cuda", "asks_for_cuda"), [("false", False), ("true", True)]) + async def test_hugging_face_prepares_torch_off_the_calling_loop_then_builds_on_it_async( + self, registry: TargetRegistry, use_cuda: str, asks_for_cuda: bool + ) -> None: + prepared: list[tuple[threading.Thread, bool]] = [] + torch = SimpleNamespace(cuda=SimpleNamespace(is_available=lambda: True)) + + def import_torch(*, use_cuda: bool) -> None: + prepared.append((threading.current_thread(), use_cuda)) + + with ( + patch.dict("sys.modules", {"torch": torch}), + patch.object(HuggingFaceChatTarget, "_import_torch", side_effect=import_torch), + patch.object(HuggingFaceChatTarget, "load_model_and_tokenizer_async", new_callable=AsyncMock), + ): + target = await registry.create_instance_async( + name="HuggingFaceChatTarget", params={"model_path": "test-model", "use_cuda": use_cuda} + ) + await target.load_model_and_tokenizer_task + + [(thread, cuda)] = prepared + assert thread is not threading.current_thread() + assert cuda is asks_for_cuda + assert isinstance(target, HuggingFaceChatTarget) + assert target.use_cuda is asks_for_cuda + assert target.load_model_and_tokenizer_task.get_loop() is asyncio.get_running_loop() + assert registry.instances.get_names() == []