Skip to content

MAINT: Document TargetSendContext as a supported send hook - #4825

Open
Adrian Gavrila (adrian-gavrila) wants to merge 3 commits into
microsoft:mainfrom
adrian-gavrila:adrian-gavrila-target-send-context-hook
Open

Adrian Gavrila (adrian-gavrila) wants to merge 3 commits into
microsoft:mainfrom
adrian-gavrila:adrian-gavrila-target-send-context-hook

Conversation

@adrian-gavrila

@adrian-gavrila Adrian Gavrila (adrian-gavrila) commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Description

A caller that keeps a conversation outside PyRIT memory can pass send_context to PromptTarget.send_prompt_async to choose the history a send uses, but TargetSendContext was internal and its contract wasn't written down. This makes it a supported hook. The Co-PyRIT Agent pane, in a follow-up PR, keeps its conversations in their own tables and sends them this way.

  • Export TargetSendContext from pyrit.prompt_target.
  • Document what a context provides: select_history returns a new list the target appends the request to, and target_invocation_count tells the normalizer whether a failed send raises or is saved.
  • Stop calling it internal in PromptTarget, PromptNormalizer, and the targets docs.
  • Test a context that supplies a send's whole history while nothing is saved to memory.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 3, 2026 20:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Three existing TargetSendContext imports still violate check-public-imports after the export change, leaving CI failing until they use the public import path.

1 open issue
What changed in this PR

Makes TargetSendContext a supported public hook for callers that manage conversation history outside PyRIT memory, without changing send behavior.

Changes:

  • Exports TargetSendContext through the public target package.
  • Documents history selection and send lifecycle semantics.
  • Adds a test for caller-supplied history without memory persistence.
File Description
tests/​unit/​prompt_target/​target/​test_prompt_target.py Tests caller-owned history and no persistence.
pyrit/​prompt_target/​common/​target_send_context.py Documents the supported context contract.
pyrit/​prompt_target/​common/​prompt_target.py Updates send-context parameter documentation.
pyrit/​prompt_target/​__init__.py Adds the public lazy export.
pyrit/​prompt_normalizer/​prompt_normalizer.py Uses the public import and updates documentation.
doc/​code/​targets/​11_message_normalizer.py Removes the protocol’s internal-only description.
doc/​code/​targets/​11_message_normalizer.ipynb Mirrors the documentation wording change.
doc/​code/​targets/​0_prompt_targets.md Describes the supported history-selection hook.

Review effort: Balanced

Comment thread pyrit/prompt_target/__init__.py Resolved
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

@behnam-o Behnam (behnam-o) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Adrian, this looks good! Here are a few small non-blocking comments.

"""
The number of sends that reached target-specific execution.
The prompt normalizer compares it before and after a send: a send that failed before reaching

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FINDING 1 (P1): target_invocation_count makes every caller implement a counter that only PromptNormalizer reads, and this sentence doesn't match what the normalizer does.

  • Only the normalizer reads it (prompt_normalizer.py#L191-L212). If the caller's count didn't rise, a failure raises Error normalizing prompt and nothing is saved. Every implementation repeats the same counter: PrependedHistorySendContext (whose own logic uses _target_invocation_marked), _MessageSendContext, _TargetInvocationContext, the new test helper, and FEAT: Add an Agent pane to Co-PyRIT #4838's _AgentSendContext. The last one calls the target directly, so its counter is never read.
  • A wrong implementation loses records with no error. I checked locally with a context whose count never rises: the provider was called, nothing was saved, and the error said Error normalizing prompt. With correct counting, the request and a processing error are saved. On cancellation, a request the target already received isn't saved either.
  • A send that reached the target is saved with an error response and then still raises Error sending prompt (L233). Only an empty response returns instead of raising.

Suggestion: have the normalizer track this itself by wrapping whatever context the caller passes in its own per-send tracker, and drop this member before it becomes public. If it stays, document the caller's obligation (go up once per mark_target_invoked, never reset) and the real outcome (saved, then raises).

"""
Return the history this send uses, before the new message.
Return a new list: the target appends the new message to it, and normalization stamps the

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FINDING 2 (P2): "Return a new list" protects the list but not the messages in it, and the target could make the rule unnecessary.

  • The target appends the request to the returned list (prompt_target.py#L889-L898). Normalization only copies the list (list(messages) in ConversationNormalizationPipeline.normalize_async), not the messages, so the stamping at L898 rewrites conversation_id on the caller's own pieces. I checked: a context that returned its own list got the request appended (2 → 3 messages), and its pieces' conversation_id changed.
  • _TargetInvocationContext and _MessageSendContext already return messages itself. That's only safe because that list belongs to the target.
  • This is the same for every target, tool loops included: it happens in the shared base method, and run_tool_loop_async works on its own copy.

Suggestion: use conversation = [*send_context.select_history(messages=persisted_messages), message] in the target, drop the rule here, and say plainly that the target sets the send's conversation ID on every piece it receives.

Caller-owned history and lifecycle for one ``PromptTarget.send_prompt_async`` call.
Pass one as ``send_context`` to choose the history a send uses: the target loads the
conversation from memory, then sends what ``select_history`` returns, followed by the new

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FINDING 3 (P2): This says every target sends the selected history, but only targets that resend history each turn do. WebSocketCopilotTarget sends only the current message, and it reads memory itself to decide isStartOfSession (websocket_copilot_target.py#L668), so a conversation kept outside memory always looks new to it. OpenAIRealtimeTarget uses the history only to find the system prompt. #4838 is fine, because agent targets must run a local tool loop and those all resend history.

Suggestion: say the selected history is what the target's normalization pipeline receives, and that targets that keep their own session state may not send it.

)
from pyrit.prompt_target import CapabilityName
from pyrit.prompt_target.common.target_send_context import TargetSendContext
from pyrit.prompt_target import CapabilityName, TargetSendContext

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FINDING 4 (P2): Further down this file, NormalizerRequest's docstring (L49) still calls send_context an "Optional internal target-send coordination contract". Use the same wording as PromptNormalizer.send_prompt_async. Everything else is consistent.

Comment on lines +1166 to +1167
assert context.target_invocation_count == 1
assert await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id) == []

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FINDING 5 (P2): The main check is the right one: the selected history, including the system message, reaches the target ahead of the request for a conversation that isn't in memory. Existing tests only pick history from memory. These two asserts add little:

  • The empty-memory check can't fail: send_prompt_async never writes to memory, and _send_prompt_to_target_async is mocked.
  • target_invocation_count == 1 repeats what the normalizer and integration tests already check.

Suggestion: drop both, and drop saves_nothing from the test name. If FINDING 2's fix lands, assert that the caller's history list is unchanged instead.

Comment thread pyrit/prompt_target/__init__.py Outdated
"TargetCapabilities": "pyrit.prompt_target.common.target_capabilities",
"TargetConfiguration": "pyrit.prompt_target.common.target_configuration",
"TargetRequirements": "pyrit.prompt_target.common.target_requirements",
"TargetSendContext": "pyrit.prompt_target.common.target_send_context",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DESIGN 1: Does this need to be exported?

  • Every consumer is in-tree. _MessageSendContext already implements the protocol by importing it from its module, and FEAT: Add an Agent pane to Co-PyRIT #4838 already imports the unexported filter_non_replayable_messages the same way. In-tree tests catch any break in the same PR, so "supported" only matters to callers outside PyRIT, and none has been named.
  • Exporting it commits PyRIT to all six members, their call order and the normalizer's save behavior. Targets call every member, so adding a hook later would break outside implementations.

Keeping it internal and shipping just the corrected docstrings and the test would be the smallest change. It's also easier to decide before the export ships than to narrow it afterwards.

Makes FINDING 4 moot, plus FINDING 1's public-API concern (its doc sentence still needs fixing).

target_class(auth_mode="none", **kwargs)


class _CallerHistoryContext:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DESIGN 2: If it should be public, consider publishing just this class rather than the protocol.

  • A small concrete context, e.g. ProvidedHistorySendContext(conversation_id=..., history=[...]), would return a copy of history from select_history and do nothing in the lifecycle methods. That's what this helper already is.
  • The lifecycle protocol and the invocation counting would stay internal.
  • FEAT: Add an Agent pane to Co-PyRIT #4838's _AgentSendContext would become a function that builds the list, since its select_history ignores messages and uses only its constructor inputs.
  • The public commitment shrinks to one constructor.

Makes FINDING 1 and FINDING 4 moot (moving the count into the normalizer becomes an optional internal cleanup), plus FINDING 2 for callers that use the class.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants