Skip to content

FEAT add CodeAttackConverter (closes #1945) - #1960

Merged
Roman Lutz (romanlutz) merged 19 commits into
microsoft:mainfrom
u7k4rs6:feat/code-attack
Aug 25, 2026
Merged

Roman Lutz (romanlutz) merged 19 commits into
microsoft:mainfrom
u7k4rs6:feat/code-attack

Conversation

@u7k4rs6

@u7k4rs6 Utkarsh Bahuguna (u7k4rs6) commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

This adds CodeAttackConverter, from the CodeAttack paper (Ren et al., ACL 2024). It turns a prompt into a code completion task by encoding it into a data structure inside a partial code template and asking the target to finish the code. It's registered as the code_attack technique on PromptSendingAttack, with no new attack class.

Two things differ from the issue, both to match the reference implementation: encoding is word by word rather than per character, and there are eight templates instead of five because the Python ones each have a verbose version. Built-in templates pick their own encoding and custom template files have to pass one. Templates are loaded and checked at construction, string literals are escaped per language so emoji and control characters still compile, and the identifier is based on the template content.

There are 88 converter tests plus technique tests, and the docs have an example with real output.

Closes #1945

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

PR Risk Summary

Quality Score: 9/10
Risk Level: low
Merge Recommendation: Safe to merge
Rationale: The changes appear to be focused on adding and refining code attack functionalities and their associated prompt converters. The review found no issues, and the changes are well-contained within the relevant modules. The addition of unit tests further strengthens the quality of this pull request.

Comment thread doc/myst.yml Resolved
@romanlutz

Copy link
Copy Markdown
Contributor

We need a references.bib update to include the paper.

Utkarsh Bahuguna (u7k4rs6) added a commit to u7k4rs6/PyRIT that referenced this pull request Jun 22, 2026
…te enum, add bib entry, docs

- Rename CodeAttackAttack -> CodeAttack (Task 1)
- Collapse language + verbose into a single CodeAttackConverter.Template enum
  modelled on BinaryConverter.BitsPerChar; custom pathlib.Path still accepted
  for caller-supplied YAML templates (Task 2)
- CodeAttack.__init__ now accepts template: CodeAttackConverter.Template | Path
  and forwards it to the converter; language/verbose params removed (Task 3)
- Add @ren2024codeattack entry to doc/references.bib after liu2024flipattack (Task 4)
- Add Code row to the attack table in 1_single_turn.py, add ## Code section
  after ## Flip mirroring the FlipAttack shape, regenerate notebook (Task 5)
- Rebase onto upstream/main (doc/code/executor/attack/ directory was removed
  upstream; old standalone code_attack.ipynb/.py deleted, content moved into
  1_single_turn.py)
- Update all unit tests for the new Template-based API; add custom-Path cases
@u7k4rs6

Copy link
Copy Markdown
Contributor Author

Roman Lutz (@romanlutz) Thanks for the thorough pass. Addressed everything:

Rebased on main; folded the docs into 1_single_turn next to Flip, removed the separate file and myst.yml entry
Added the ren2024codeattack reference and cited it in the docstrings
Renamed CodeAttackAttack to CodeAttack
Collapsed language + verbose into a single enum-typed template param (CodeAttackConverter.Template) that also accepts a custom Path
Kept the attack class but structured it like FlipAttack (system prompt via _setup_async); left the converter independently usable

Open to dropping the class for converter-only if you'd rather. Re-requesting review.

@u7k4rs6

Copy link
Copy Markdown
Contributor Author

Tracked the framing variant in #2088. Resolving.

Utkarsh Bahuguna (u7k4rs6) added a commit to u7k4rs6/PyRIT that referenced this pull request Jul 10, 2026
…te enum, add bib entry, docs

- Rename CodeAttackAttack -> CodeAttack (Task 1)
- Collapse language + verbose into a single CodeAttackConverter.Template enum
  modelled on BinaryConverter.BitsPerChar; custom pathlib.Path still accepted
  for caller-supplied YAML templates (Task 2)
- CodeAttack.__init__ now accepts template: CodeAttackConverter.Template | Path
  and forwards it to the converter; language/verbose params removed (Task 3)
- Add @ren2024codeattack entry to doc/references.bib after liu2024flipattack (Task 4)
- Add Code row to the attack table in 1_single_turn.py, add ## Code section
  after ## Flip mirroring the FlipAttack shape, regenerate notebook (Task 5)
- Rebase onto upstream/main (doc/code/executor/attack/ directory was removed
  upstream; old standalone code_attack.ipynb/.py deleted, content moved into
  1_single_turn.py)
- Update all unit tests for the new Template-based API; add custom-Path cases
Utkarsh Bahuguna (u7k4rs6) added a commit to u7k4rs6/PyRIT that referenced this pull request Aug 9, 2026
…te enum, add bib entry, docs

- Rename CodeAttackAttack -> CodeAttack (Task 1)
- Collapse language + verbose into a single CodeAttackConverter.Template enum
  modelled on BinaryConverter.BitsPerChar; custom pathlib.Path still accepted
  for caller-supplied YAML templates (Task 2)
- CodeAttack.__init__ now accepts template: CodeAttackConverter.Template | Path
  and forwards it to the converter; language/verbose params removed (Task 3)
- Add @ren2024codeattack entry to doc/references.bib after liu2024flipattack (Task 4)
- Add Code row to the attack table in 1_single_turn.py, add ## Code section
  after ## Flip mirroring the FlipAttack shape, regenerate notebook (Task 5)
- Rebase onto upstream/main (doc/code/executor/attack/ directory was removed
  upstream; old standalone code_attack.ipynb/.py deleted, content moved into
  1_single_turn.py)
- Update all unit tests for the new Template-based API; add custom-Path cases
@u7k4rs6

Copy link
Copy Markdown
Contributor Author

Roman Lutz (@romanlutz) Rebased onto current main. The branch was ~150 commits behind, so this
absorbs the PromptConverter → Converter rename from #2161 across all
three directory moves and both symbol renames, and drops the FlipAttack
and ContextComplianceAttack hunks now that those are gone upstream.

Also fixed a gap that predates the rebase: test_all_converters_are_documented
was failing because CodeAttackConverter had no entry under
doc/code/converters/. Added an example to 1_text_to_text_converters,
plus a description= on the code_attack factory so it matches the others.

Converter, docs and setup suites green, pre-commit clean. Description
updated for the new names.

@u7k4rs6

Utkarsh Bahuguna (u7k4rs6) commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor Author

hey Roman Lutz (@romanlutz) , no rush on the review itself, but #1960's CI is stuck awaiting maintainer approval so nothing has actually run on it yet. could you kick that off when you get a sec? also cleaned up the description, the attack class is gone and it's a converter + technique factory now, plus updated the bib entry to the ACL Findings version to match your #2409 pass 🙏

@u7k4rs6 Utkarsh Bahuguna (u7k4rs6) changed the title FEAT add CodeAttackConverter and CodeAttackAttack (closes #1945) FEAT add CodeAttackConverter (closes #1945) Aug 22, 2026
Comment thread doc/code/executor/1_single_turn.ipynb Resolved
Comment thread doc/references.bib Resolved
Implement CodeAttack (Ren et al., ACL 2024) as a standalone converter
and a PromptSendingAttack subclass following the FlipAttack pattern.

CodeAttackConverter encodes a natural-language prompt word-by-word into
a data-structure initialisation sequence (deque appends, list appends,
or a string assignment) and embeds it in a partial code template that
asks the model to complete the code. Five language variants are
supported: python_stack, python_list, python_string, cpp, go. The
verbose flag selects the _plus template (detailed paragraphs) for the
three Python variants; cpp and go have no plus variant upstream.

CodeAttackAttack wraps the converter in a PromptSendingAttack, prepends
a system prompt that frames the session as code completion, and forwards
language and verbose to the converter. Callers supply a scorer via
AttackScoringConfig as usual.

Files added:
  pyrit/prompt_converter/code_attack_converter.py
  pyrit/executor/attack/single_turn/code_attack.py
  pyrit/datasets/executors/code_attack.yaml
  pyrit/datasets/prompt_converters/code_attack_python_stack{,_plus}.yaml
  pyrit/datasets/prompt_converters/code_attack_python_list{,_plus}.yaml
  pyrit/datasets/prompt_converters/code_attack_python_string{,_plus}.yaml
  pyrit/datasets/prompt_converters/code_attack_cpp.yaml
  pyrit/datasets/prompt_converters/code_attack_go.yaml
  tests/unit/prompt_converter/test_code_attack_converter.py (23 tests)
  tests/unit/executor/attack/single_turn/test_code_attack.py (16 tests)
  doc/code/executor/attack/code_attack.py
  doc/code/executor/attack/code_attack.ipynb

Files modified:
  pyrit/prompt_converter/__init__.py
  pyrit/executor/attack/single_turn/__init__.py
  pyrit/executor/attack/__init__.py
  doc/myst.yml
…te enum, add bib entry, docs

- Rename CodeAttackAttack -> CodeAttack (Task 1)
- Collapse language + verbose into a single CodeAttackConverter.Template enum
  modelled on BinaryConverter.BitsPerChar; custom pathlib.Path still accepted
  for caller-supplied YAML templates (Task 2)
- CodeAttack.__init__ now accepts template: CodeAttackConverter.Template | Path
  and forwards it to the converter; language/verbose params removed (Task 3)
- Add @ren2024codeattack entry to doc/references.bib after liu2024flipattack (Task 4)
- Add Code row to the attack table in 1_single_turn.py, add ## Code section
  after ## Flip mirroring the FlipAttack shape, regenerate notebook (Task 5)
- Rebase onto upstream/main (doc/code/executor/attack/ directory was removed
  upstream; old standalone code_attack.ipynb/.py deleted, content moved into
  1_single_turn.py)
- Update all unit tests for the new Template-based API; add custom-Path cases
Correct the authors to match the ren2024codeattack bib entry:
Ren, Gao, Shao, Yan, Tan, Lam, Ma (SJTU / Shanghai AI Lab / CUHK).
Remove incorrect names (Liu, Fan, Chen, Zhong, Lu, Wen) and replace
Nanyang Technological University with Shanghai Jiao Tong University.
Remove CodeAttack attack class and its test file; wire code_attack as a
PromptSendingAttack + CodeAttackConverter entry in scenario_techniques.py.
Delete the now-orphaned executor system-prompt seed YAML. Update the
single-turn executor doc and regenerate the notebook to show the
converter-based usage pattern.
All five encoders (_encode_python_stack, _encode_python_list,
_encode_python_string, _encode_cpp, _encode_go) now use json.dumps() to
escape embedded double quotes and backslashes before interpolating into
string literals. A prompt containing a double quote no longer produces
malformed code.

Also fix the class docstring: separator normalisation on [\s\-]+ applies
only to python_stack; python_list uses str.split() and preserves hyphens.

Add tests for embedded double quotes in all five encoder paths.
…ues/core.py

Upstream (microsoft#2155) replaced initializers/components/scenario_techniques.py
with initializers/techniques/core.py and renamed strategy_tags to
technique_tags. The core group tag is now injected by build_technique_factories
rather than stored in the factory. Port the code_attack entry and its test
list update to the new layout.
Satisfies tests/unit/docs/test_converter_documentation.py, which requires
every converter in pyrit.converter.__all__ to appear in a notebook under
doc/code/converters/. The example lives in its own cell so the existing
section 1.2 cell (which contains non-deterministic converters) keeps its
stored output untouched.

The converter is template-based and runs offline, so the new cell carries
real executed output like every other cell on the page.
Every other factory in techniques/core.py carries a description; code_attack
was the only one without. Matches the sibling register: single sentence,
third-person present, states the mechanism.
…stable identifier

Addresses review feedback on microsoft#1960.

Escaping: every encoder used json.dumps() with the default ensure_ascii=True,
so a non-BMP character became a surrogate pair ("😀"). Python
evaluates that to two lone surrogates and Go and C++ reject surrogate escapes
outright, so emoji input produced code that would not compile. All five
encoders now route through one module-level _escape_string_literal() helper
that emits literal UTF-8 and escapes only backslash, double quote and control
characters. C++ uses three-digit octal for control characters because its hex
escapes consume an unbounded run of hex digits and would swallow a following
literal digit; Python and Go use two-digit hex, which their grammars bound.
Verified by compiling the generated C++ and Go under -Wall -Wextra -Werror and
go vet, then asserting byte-identical round-trips for emoji, newline, tab,
backslash, double quote, control and DEL characters.

Template loading: SeedPrompt.from_yaml_file() moved from convert_async into
__init__ and cached on the instance, so a missing or malformed custom file now
fails at construction instead of on first use. Construction also rejects a
template whose body never references wrapped_input, which previously rendered
a constant string and silently discarded the objective.

Identifier: _build_identifier() no longer embeds an absolute template path,
which was machine-dependent and did not change when a custom file's contents
changed. It now reports the stable enum name, a sha256 prefix of the loaded
template value and the encoding, matching TemplateSegmentConverter's shape.

Encoding: a custom pathlib.Path template was forced to python_string, so a
caller could not supply a custom stack, list, C++ or Go wrapper. Adds a
separate Encoding enum, maps each Template member to its Encoding, and
requires an explicit encoding= for Path templates rather than defaulting
silently. The Template enum and the PYTHON_STACK_VERBOSE default are
unchanged, so existing callers are unaffected.

Docstring: the separator-normalisation section claimed normalisation was
python_stack only. python_list also collapses whitespace runs via str.split();
the stack-specific part is that it additionally consumes hyphens and reverses
order. Rewritten per encoding so a caller can tell what round-trips losslessly.

Tests: 31 -> 64. Adds a real render parameterized over every Template member,
exact decoded-literal assertions in place of escaped-substring matching,
identifier stability across paths and sensitivity to content and encoding,
non-BMP round-trips per encoding, control-character round-trips, custom
template validation (missing file, malformed YAML, no wrapped_input, Path
without encoding) and a focused code_attack factory-wiring test.

Two existing tests changed because the behaviour they asserted is the bug
being fixed: test_custom_path_template_constructs and
test_custom_path_template_renders both relied on a Path template silently
defaulting to python_string, and now pass encoding= explicitly.
Adds @ren2024codeattack to the citation-key list in doc/bibliography.md,
keeping the list alphabetical (between @promptfoo2025ccp and
@robustintelligence2024bypass). The bib entry already existed; it was not
listed, so the citation did not render.

Regenerates the modality table in doc/code/converters/0_converters.ipynb,
whose stored output jumped from CharacterSpaceConverter straight to
CodeChameleonConverter. CodeAttackConverter now appears at row 36. Only that
cell was executed; the cells that need a live target were left untouched.
…literal

Coverage audit against the six review asks turned up two gaps.

The factory-wiring test was in the converter test file, but the repo keeps
core technique factory tests in tests/unit/setup/techniques/test_core_techniques.py
next to the flip technique. Moved it there as TestCodeAttackTechnique,
matching TestFlipTechnique's shape: one test for the factory wiring (attack
class, tags, description, the single wired CodeAttackConverter and its
template and encoding) and one that the wired converter actually encodes the
objective. Updated that module's docstring, which claimed it covered flip only.

Seven assertions in the round-trip and edge-case tests still extracted
literals with a ([^"]+) regex and compared the escaped form, which is exactly
what the review asked to stop doing and which silently breaks on any escape.
They now go through _decode_literals/_decode_assignment like the rest, so they
compare the value the target language would actually see. The three superseded
_extract_* helpers are gone, along with a duplicated _write_template.

No behaviour change; converter test file 64 -> 63 tests because the factory
test moved, core techniques 3 -> 5.
@u7k4rs6

Copy link
Copy Markdown
Contributor Author

Roman Lutz (@romanlutz) Addressed all of these. The substantive ones: language-aware escaping so non-BMP input survives Go and C++, eager template load with wrapped_input validation, content-hash identifier, and a new Encoding enum so custom Path templates aren't locked to python_string. Tests went 31 to 63 in the converter file plus 2 in core techniques.

One I can't close: the 1_single_turn cell needs a live target and I don't have credentials. Left options on that thread.

Also, CI still hasn't run on this PR at all. All five workflows are stuck awaiting maintainer approval, so none of this has been verified upstream yet. Could you kick that off?

…ect unknown template vars

Addresses the second review round on microsoft#1960.

Encoding/template mismatch. A built-in Template accepted an encoding=
override, so Template.PYTHON_STACK + Encoding.PYTHON_LIST rendered a wrapper
that declares my_stack, wrote the objective into my_list, and then decoded
from the still-empty my_stack. The objective was silently lost with no error.
Each built-in ships a wrapper that only works with its mapped encoding, so
there is no valid override; encoding= is now rejected outright for a Template
member rather than accepted and validated. The ValueError names the template,
its mapped encoding and the one passed. A pathlib.Path still requires an
explicit encoding=, so the rule is: enum implies the encoding, Path demands it.

Unknown template variables. Construction only checked that wrapped_input was
present, so a custom template like "{{ wrapped_input }} {{ suffix }}" passed
construction and then failed on the first conversion with an undefined
suffix. The same validation now compares the full undeclared-variable set
against wrapped_input and raises at construction, naming every offending
variable.

Both rules are stated in the class docstring, the Encoding enum docstring and
the __init__ Args and Raises sections rather than left implied.

Tests 63 -> 88. Mismatched pairings are parameterized over six
template/encoding combinations, a matching pairing is asserted to raise too
since the parameter is rejected rather than validated, every Template member
is asserted to still construct without encoding=, and custom templates cover
one extra variable, several extra variables, and the supported single-variable
case still rendering.

test_explicit_encoding_overrides_builtin_template_default asserted the old
override behaviour and is replaced; it was the only call site anywhere passing
a Template together with encoding=. The technique factory and both docs
notebooks pass template= alone and are unaffected.
@u7k4rs6

Copy link
Copy Markdown
Contributor Author

No valid use case, you're right to reject it. Reproduced exactly what you described: my_stack declared and never filled, objective written into my_list, decode() handed the empty deque.

Rather than validate the pairing I now reject encoding= outright when a built-in Template is passed, since each built-in ships a wrapper that only works with its mapped encoding. So the rule is: enum implies the encoding, Path demands one. The ValueError names the template, its mapped encoding, and what was passed.

Worth flagging that one existing test asserted the override worked, so the bug was codified. Replaced with rejection tests parameterized over six mismatched pairings, plus matching pairings across all 8 members (also rejected, since the parameter is refused rather than validated), plus all 8 constructing correctly with no encoding=. No production caller passed both.

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

Copilot-Session: 6561decf-13a3-4982-ab09-0d06a8d646ee
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 6561decf-13a3-4982-ab09-0d06a8d646ee
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 6561decf-13a3-4982-ab09-0d06a8d646ee
@romanlutz
Roman Lutz (romanlutz) added this pull request to the merge queue Aug 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Aug 24, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 6561decf-13a3-4982-ab09-0d06a8d646ee
@romanlutz
Roman Lutz (romanlutz) added this pull request to the merge queue Aug 25, 2026
Merged via the queue into microsoft:main with commit ae55de7 Aug 25, 2026
54 checks passed
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.

FEAT CodeAttack

4 participants