Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions frontend/src/hooks/useScenarioRunProgress.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,64 @@ describe('useScenarioRunProgress', () => {
unmount()
})

it('replaces held results with a terminal reset page before stopping', async () => {
jest.useFakeTimers()
mockGetRunProgress
.mockResolvedValueOnce(makePage({
results: [makeResult('attempt-1'), makeResult('attempt-3')],
next_cursor: 'cursor-1',
}))
.mockResolvedValueOnce(makePage({
run: { ...makePage().run, status: 'COMPLETED', completed_at: '2026-01-01T00:01:00Z' },
results: [makeResult('attempt-1'), makeResult('attempt-2'), makeResult('attempt-3')],
next_cursor: 'cursor-reset',
reset: true,
}))

const { result, unmount } = renderHook(() => useScenarioRunProgress('run-1'))
await act(async () => Promise.resolve())
await act(async () => {
await jest.advanceTimersByTimeAsync(SCENARIO_RUN_POLL_INTERVAL_MS * 3)
})

expect(result.current.state.results.map((item) => item.attack_result_id)).toEqual([
'attempt-1',
'attempt-2',
'attempt-3',
])
expect(mockGetRunProgress).toHaveBeenNthCalledWith(
2,
'run-1',
{ since: 'cursor-1', limit: 500 },
expect.any(AbortSignal),
)
expect(mockGetRunProgress).toHaveBeenCalledTimes(2)
unmount()
})

it('drops the stale cursor when a reset page has no results', async () => {
jest.useFakeTimers()
mockGetRunProgress
.mockResolvedValueOnce(makePage({ results: [makeResult('attempt-1')], next_cursor: 'cursor-1' }))
.mockResolvedValueOnce(makePage({ next_cursor: null, reset: true }))
.mockResolvedValueOnce(makePage({ next_cursor: null }))

const { result, unmount } = renderHook(() => useScenarioRunProgress('run-1'))
await act(async () => Promise.resolve())
await act(async () => {
await jest.advanceTimersByTimeAsync(SCENARIO_RUN_POLL_INTERVAL_MS * 2)
})

expect(result.current.state.results).toEqual([])
expect(mockGetRunProgress).toHaveBeenNthCalledWith(
3,
'run-1',
{ limit: 500 },
expect.any(AbortSignal),
)
unmount()
})

it('aborts a stale request when the route ID changes', async () => {
const signals: AbortSignal[] = []
mockGetRunProgress.mockImplementation(
Expand Down
6 changes: 4 additions & 2 deletions frontend/src/hooks/useScenarioRunProgress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,12 @@ export function useScenarioRunProgress(scenarioResultId: string): UseScenarioRun
return
}

const appliedCursor = page.next_cursor ?? since
const reset = since === null || page.reset === true
// A reset page restarts from the first result, so a stale cursor must not be kept.
const appliedCursor = page.next_cursor ?? (reset ? null : since)
cursorRef.current = appliedCursor
retriedRef.current = false
dispatch({ type: 'apply-page', page, fresh: since === null })
dispatch({ type: 'apply-page', page, fresh: reset })

if (page.has_more) {
const nextCursor = page.next_cursor
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2589,6 +2589,8 @@ export interface ScenarioRunProgress {
next_cursor?: string | null
has_more: boolean
plan_complete: boolean
/** The request cursor was stale; this page restarts from the first result and replaces held results. */
reset?: boolean
active_conversations?: ScenarioActiveConversation[]
recorded_conversations?: ScenarioActiveConversation[]
}
Expand Down
8 changes: 8 additions & 0 deletions pyrit/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,14 @@ produced the attack (`null` for attacks outside a scan). Scan progress
result and hierarchy node `score` summarizes the objective score: `scorer_name`,
`score_type`, `status`, `score_value`, `score_rationale`, and `score_category`.

Scan progress (`GET /api/scenarios/runs/{scenario_result_id}/progress`) pages results
in ascending creation order with an opaque `since` cursor. Concurrent attacks can
save a result after a later-created one, so it may sort before a cursor the client
already holds. The cursor records how many results the client holds through it; when
storage has more, the response sets `reset: true` and restarts from the first result
with the plan. The client then replaces, rather than merges, its held results. Cursors
from earlier server versions are also answered with a reset page.

The attack service reads running attacks through a read-only lookup
(`LiveAttackLookup`) that the scenario run service provides; it does not import
scenario scheduling.
Expand Down
57 changes: 51 additions & 6 deletions pyrit/backend/services/scenario_progress_read_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,8 @@ async def get_snapshot_async(
"""
async with self._refresh_run_async(scenario_result_id=scenario_result_id):
entry = self._get_cache_entry(scenario_result_id=scenario_result_id, plan=plan, terminal=terminal)
first_new_index = len(entry.results)
deltas_updated = await self._hydrate_new_deltas_async(
scenario_result_id=scenario_result_id,
entry=entry,
terminal=terminal,
max_deltas=max_deltas,
entry, first_new_index, deltas_updated = await self._refresh_cache_entry_async(
scenario_result_id=scenario_result_id, entry=entry, terminal=terminal, max_deltas=max_deltas
)
scorer_metrics = (
await asyncio.to_thread(
Expand Down Expand Up @@ -325,6 +321,55 @@ def _build_snapshot(
has_more=entry.has_more,
)

async def _refresh_cache_entry_async(
self, *, scenario_result_id: str, entry: _ProgressCacheEntry, terminal: bool, max_deltas: int | None
) -> tuple[_ProgressCacheEntry, int, bool]:
"""
Hydrate new deltas, rebuilding the entry once when storage holds rows the cursor skipped.

Returns:
tuple[_ProgressCacheEntry, int, bool]: The current entry, the first result index
to map, and whether any delta changed.
"""
first_new_index = len(entry.results)
deltas_updated = await self._hydrate_new_deltas_async(
scenario_result_id=scenario_result_id, entry=entry, terminal=terminal, max_deltas=max_deltas
)
if await self._cache_matches_storage_async(scenario_result_id=scenario_result_id, entry=entry):
return entry, first_new_index, deltas_updated
entry = _ProgressCacheEntry(plan_signature=entry.plan_signature)
self._cache[scenario_result_id] = entry
await self._hydrate_new_deltas_async(
scenario_result_id=scenario_result_id, entry=entry, terminal=terminal, max_deltas=max_deltas
)
return entry, 0, True

async def _cache_matches_storage_async(self, *, scenario_result_id: str, entry: _ProgressCacheEntry) -> bool:
"""
Check that storage holds no results behind the cache cursor that the cache never read.

Result timestamps record creation, so a concurrent attack can commit a row
ordered before a cursor that already passed it. Comparing the stored count
through the cursor with the cached count detects such late commits and deletions.

Returns:
bool: Whether the cached deltas match storage through the cursor.
"""
if entry.cursor is None:
return True
stored_count = await self._memory.get_scenario_attack_result_count_async(
scenario_result_id=scenario_result_id, through=entry.cursor
)
if stored_count == len(entry.deltas):
return True
logger.info(
"Scenario run %s has %d stored results through the progress cursor but %d cached; rebuilding.",
scenario_result_id,
stored_count,
len(entry.deltas),
)
return False

async def _hydrate_new_deltas_async(
self,
*,
Expand Down
76 changes: 56 additions & 20 deletions pyrit/backend/services/scenario_run_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@

_DEFAULT_MAX_CONCURRENT_RUNS = 1
_MAX_OVERLOAD_EVENTS = 500
_PROGRESS_CURSOR_VERSION = 2
_MAX_OVERLOAD_ROLES = 16
_MAX_TERMINAL_ERRORS = 100
_SCHEDULER_RETRY_INITIAL_SECONDS = 0.05
Expand Down Expand Up @@ -268,6 +269,15 @@ class _ActiveRunSnapshot:
active_scenario_result_id: str | None = None


@dataclass(frozen=True, slots=True)
class _ProgressCursor:
"""A decoded client progress bookmark and the number of results the client holds through it."""

keyset: AttackResultKeysetCursor
# None for version 1 cursors, which predate the count and are always treated as stale.
seen: int | None


class ScenarioRunService:
"""
Service for managing scenario run lifecycle.
Expand Down Expand Up @@ -3035,7 +3045,7 @@ def _build_progress_response(
scenario_result_id: str,
since: str | None,
limit: int,
cursor: AttackResultKeysetCursor | None,
cursor: _ProgressCursor | None,
terminal: bool,
queue_position: int | None,
active_scenario_result_id: str | None,
Expand All @@ -3046,24 +3056,24 @@ def _build_progress_response(

for delta in progress_snapshot.deltas:
overload_events.extend(delta.retry_events)
# Use binary search to locate the bookmark in results sorted by timestamp and ID.
start = (
bisect_right(
progress_snapshot.deltas,
(cursor.timestamp, uuid.UUID(cursor.attack_result_id)),
key=lambda delta: (delta.timestamp, uuid.UUID(delta.attack_result_id)),
)
if cursor is not None
else 0
)
start = self._progress_page_start(progress_snapshot=progress_snapshot, cursor=cursor)
# A result that committed late can sort before the client's bookmark. The client then
# holds fewer results through that bookmark than storage does, so it must start over.
# An edited result moves past the bookmark instead and is re-sent on this page.
reset = cursor is not None and (cursor.seen is None or start > cursor.seen)
if reset:
start = 0
end = start + limit
deltas = progress_snapshot.deltas[start:end]
results = list(progress_snapshot.results[start:end])
has_more = end < len(progress_snapshot.deltas)
response_plan = progress_snapshot.plan if since is None else None
next_cursor = (
self._encode_progress_cursor(scenario_result_id=scenario_result_id, delta=deltas[-1]) if deltas else since
)
response_plan = progress_snapshot.plan if since is None or reset else None
if deltas:
next_cursor: str | None = self._encode_progress_cursor(
scenario_result_id=scenario_result_id, delta=deltas[-1], seen=start + len(deltas)
)
else:
next_cursor = None if reset else since
scenario_identifier = header_result.scenario_identifier
target, datasets_used, scenario_parameters = self._safe_run_metadata(scenario_identifier=scenario_identifier)
if plan is not None:
Expand Down Expand Up @@ -3105,15 +3115,34 @@ def _build_progress_response(
next_cursor=next_cursor,
has_more=has_more,
plan_complete=plan is not None,
reset=reset,
)

@staticmethod
def _encode_progress_cursor(*, scenario_result_id: str, delta: ScenarioAttackResultDelta) -> str:
def _progress_page_start(*, progress_snapshot: ScenarioProgressSnapshot, cursor: _ProgressCursor | None) -> int:
"""
Locate the first snapshot delta after the client's bookmark.

Returns:
int: The number of snapshot deltas ordered at or before the bookmark.
"""
if cursor is None:
return 0
# Use binary search to locate the bookmark in results sorted by timestamp and ID.
return bisect_right(
progress_snapshot.deltas,
(cursor.keyset.timestamp, uuid.UUID(cursor.keyset.attack_result_id)),
key=lambda delta: (delta.timestamp, uuid.UUID(delta.attack_result_id)),
)

@staticmethod
def _encode_progress_cursor(*, scenario_result_id: str, delta: ScenarioAttackResultDelta, seen: int) -> str:
payload = {
"v": 1,
"v": _PROGRESS_CURSOR_VERSION,
"run": scenario_result_id,
"timestamp": delta.timestamp.isoformat(),
"attack_result_id": delta.attack_result_id,
"seen": seen,
}
return base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode().rstrip("=")

Expand All @@ -3122,7 +3151,7 @@ def _decode_progress_cursor(
*,
since: str | None,
scenario_result_id: str,
) -> AttackResultKeysetCursor | None:
) -> _ProgressCursor | None:
if since is None:
return None
try:
Expand All @@ -3132,7 +3161,8 @@ def _decode_progress_cursor(
raise ValueError("Malformed scenario progress cursor.") from exc
if not isinstance(payload, dict):
raise ValueError("Malformed scenario progress cursor.")
if payload.get("v") != 1 or payload.get("run") != scenario_result_id:
version = payload.get("v")
if version not in (1, _PROGRESS_CURSOR_VERSION) or payload.get("run") != scenario_result_id:
raise ValueError("Cursor does not belong to this scenario run.")
try:
timestamp = datetime.fromisoformat(payload["timestamp"])
Expand All @@ -3141,7 +3171,13 @@ def _decode_progress_cursor(
raise ValueError("Malformed scenario progress cursor.") from exc
if timestamp.tzinfo is None:
raise ValueError("Cursor timestamp must include a timezone.")
return AttackResultKeysetCursor(timestamp=timestamp, attack_result_id=attack_result_id)
# Version 1 cursors carry no result count, so they are always treated as stale.
seen = payload.get("seen") if version == _PROGRESS_CURSOR_VERSION else None
if version == _PROGRESS_CURSOR_VERSION and (type(seen) is not int or seen < 0):
raise ValueError("Malformed scenario progress cursor.")
return _ProgressCursor(
keyset=AttackResultKeysetCursor(timestamp=timestamp, attack_result_id=attack_result_id), seen=seen
)

async def _get_hierarchy_aggregate_async(
self, *, scenario_result_id: str, plan: ScenarioRunPlan | None
Expand Down
Loading
Loading