Skip to content

FIX: Require ordered template parameters in LLMGenericTextConverter - #3928

Merged
Richard Lundeen (richlundeen) merged 7 commits into
microsoft:mainfrom
samrudhi03:fix/llm-template-set-identifiers-3841
Nov 17, 2026
Merged

Richard Lundeen (richlundeen) merged 7 commits into
microsoft:mainfrom
samrudhi03:fix/llm-template-set-identifiers-3841

Conversation

@samrudhi03

@samrudhi03 Samrudhi (samrudhi03) commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #3841.

LLMGenericTextConverter rendered set and frozenset template parameters in Python’s iteration order, which for strings depends on PYTHONHASHSEED. The same configuration could therefore produce different prompts and identifiers across processes.

Following review, this PR uses an explicit ordered-input contract:

  • Set and frozenset template parameters, including empty values and subclasses, are rejected at construction with an actionable ValueError.
  • Validation reuses the existing parameter traversal. It also rejects sets encountered inside lists, tuples, dictionary keys and values, defaultdict, dataclass fields, and object attributes.
  • Callers prepare ordered values before constructing the converter. Lists and tuples are not reordered.
  • The existing identifier calculation for accepted inputs is preserved, including the caller-provided order used during rendering.

The earlier ordered-set classes, forward/reflected set-operation wrappers, and custom cyclic-container copier are removed.

Breaking change: previously accepted set and frozenset template parameters now raise ValueError. Callers must move template-side set operations into Python and pass ordered results. This is intentionally not behaviourally equivalent to the previous implementation.

Migration

The error identifies the offending parameter and suggests sorted(values) or sorted(values.difference(exclusions)). If several parameters contain sets, convert all of them.

Direct set input

source_words = {"gamma", "alpha", "beta"}
template = SeedPrompt(
    value="{{ objective }} Use one of these tones: {{ tones }}",
    parameters=["objective"],
)

# Before: now raises ValueError
LLMGenericTextConverter(
    converter_target=target,
    user_prompt_template_with_objective=template,
    tones=source_words,
)

# After
LLMGenericTextConverter(
    converter_target=target,
    user_prompt_template_with_objective=template,
    tones=sorted(source_words),
)

{{ tones }} now renders a list rather than a set. Use {{ tones|join(', ') }} for comma-separated text.

Set operations inside templates

source_words = {"gamma", "alpha", "beta"}
exclusions = {"beta"}

# Before: now raises ValueError
LLMGenericTextConverter(
    converter_target=target,
    user_prompt_template_with_objective=SeedPrompt(
        value="{{ objective }}{% for word in tones.difference(exclusions) %} {{ word }}{% endfor %}",
        parameters=["objective"],
    ),
    tones=source_words,
    exclusions=exclusions,
)

# After: perform the set operation in Python
LLMGenericTextConverter(
    converter_target=target,
    user_prompt_template_with_objective=SeedPrompt(
        value="{{ objective }}{% for word in allowed %} {{ word }}{% endfor %}",
        parameters=["objective"],
    ),
    allowed=sorted(source_words.difference(exclusions)),
)

Use sorted(...) or another explicit ordering. list(source_words) alone preserves the set’s iteration order, which is not guaranteed to be consistent across processes. Parameters should remain static after construction.

DenylistConverter expects list[str] | None. On the upstream base, a set denylist already failed when its identifier was built; it now fails earlier with the actionable constructor error.

Tests and Documentation

  • Added constructor-level rejection tests for sets, frozensets, empty values, a set subclass, and nested values reached by the existing traversal.
  • Added checks for actionable error messages and rejection of a set denylist.
  • Added rendering tests for caller-prepared sorted values and set differences.
  • Verified that caller-provided list order is preserved in prompts and that different orders produce different identifiers.
  • Added a two-process regression using different PYTHONHASHSEED values to check identical expected prompts and identifiers for explicitly ordered inputs.
  • Updated existing set-based tests to use ordered inputs and removed tests for the discarded wrapper/copying implementation.
  • Updated the constructor documentation and included migration guidance above.

Validation

Local validation used macOS Intel and Python 3.14, with upstream main at 986c8902 merged.

On 318d0e953:

  • Full unit suite (make unit-test): 38,324 passed, 463 skipped, 3 xfailed.
  • Converter and registry suites: 4,775 passed, 58 skipped, 3 xfailed.
  • Generic converter tests and the registry identifier contract under six PYTHONHASHSEED values: 436 passed, 5 skipped, 3 xfailed for each seed.
  • Converter module statement coverage: 100% (102 statements).

The follow-up commit 6896625eb only removes an assertion requiring two hash seeds to produce different set orders and its unused output field. On that revision:

  • Generic converter test file: 74 passed.
  • Cross-process regression also passed independently.
  • Formatting, lint, direct type checking, and applicable pre-commit hooks passed.
  • The full unit suite was not rerun after this test-only adjustment.

The full ty-check pre-commit hook could not run locally because its dependency setup requires a PyTorch version without an Intel macOS wheel. Direct type checks passed for the changed files. Whole-package ty check pyrit without the optional extras reported 51 diagnostics, identical to unmodified upstream main.

Replace the rejection of set and frozenset template parameters with a
reproducible ordering. Sets keep being accepted, as before, but are
copied into set subclasses that iterate, and therefore render, in an
order that does not depend on PYTHONHASHSEED. Sets nested in lists,
tuples and dictionaries are ordered too. The identifier is computed from
the same ordered values that are rendered, so equal configurations get
the same prompt and identifier in every process, while values that
render differently still get different identifiers.

Strings and integers are sorted by value; other items are sorted by
their template-value description. Set subclasses and sets held inside
other objects are left unchanged.

Restore the set coverage that the rejection removed, assert that equal
sets with different insertion orders now render the same prompt and
share an identifier, and add a set-valued keyword sample to the
registry identifier contract so its cross-process check covers sets.

Fixes microsoft#3841
Copilot AI balanced review requested due to automatic review settings November 4, 2026 10:43

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

Recursive containers still produce hash-seed-dependent rendering and hashes, while inherited set operations can render equal parameters differently despite identical hashes.

2 open issues
What changed in this PR

This PR addresses #3841 by normalizing set-valued template parameters in LLMGenericTextConverter, extending #3387’s identifier tracking so rendering and identifiers use the same reproducible ordering.

Changes:

  • Introduces ordered set wrappers and normalization for supported nested containers.
  • Adds rendering, set-behavior, and identifier regression tests.
  • Adds a set-valued sample to the cross-process identifier contract.
File Description
tests/​unit/​registry/​converter_identifier_samples.py Adds set-valued parameters to cross-process identifier checks.
tests/​unit/​converter/​test_generic_llm_converter.py Tests deterministic rendering, set behavior, and identifier distinctions.
pyrit/​converter/​llm_generic_text_converter.py Normalizes sets before rendering and hashing; documents the behavior.

Review effort: Balanced

…nces

Set operations such as copy(), union(), intersection(), difference(),
symmetric_difference() and the -, |, &, ^ operators returned plain sets
from the ordered set wrappers. A template using them could render equal
sets in different orders while their identifiers matched, and render
differently in each process. These operations now return ordered sets
of the same kind, and invalid operands still raise TypeError.

Self-referencing lists, tuples and dictionaries that hold a set were
copied so that their back-references still pointed to the originals,
leaving the original unordered set reachable. That changed the rendered
structure and kept the prompt and identifier dependent on
PYTHONHASHSEED. Containers are now copied once each, so self-references
and shared references point to the copies, and render as before with
the sets ordered. Values without sets are still passed through
unchanged.

Add regression tests for set-operation templates, the set operators,
self-referencing lists, dictionaries and tuple cycles, and shared
references.
@samrudhi03

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

@samrudhi03

Copy link
Copy Markdown
Contributor Author

Hi Roman Lutz (@romanlutz), thanks for assigning me #3841. I've submitted the fix in #3928 and addressed the initial review comments. Would you be able to take a look when you get a chance?

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.

Please narrow this to an explicit ordered-input contract rather than a partial deterministic-set implementation. Stable prompts and identifiers are worth fixing, but the inspected production callers pass strings or lists; the ordered-set classes, forward/reflected set-operation wrappers, and cyclic-container copier add a substantial compatibility surface without a demonstrated caller needing it. The framework asks us to reuse configuration, avoid speculative machinery, and fail fast. A smaller alternative is to reject unordered set/frozenset parameters at construction with an actionable message, reuse the existing parameter traversal, and have callers prepare sorted(source_words) or sorted(source_words.difference(exclusions)) before rendering. That intentionally drops template-side set methods and changes previously accepted inputs; it is not behaviorally equivalent, so include migration guidance and focused public-interface/cross-process regressions. If preserving set methods or cyclic object graphs is required, please show the operator workflow that prepared ordered data cannot adequately support. Hash-only canonicalization would not be sufficient because identity must stay aligned with rendered behavior.

This is an inclusion/scope recommendation for 309391f, not source-readiness approval. Implementation review and automatic repairs have stopped at this gate.

…ng sets

Narrow the fix for microsoft#3841 to an explicit ordered-input contract, as
recommended in review. LLMGenericTextConverter now rejects set and
frozenset template parameters at construction, including inside lists,
tuples, dictionaries, dataclass fields and object attributes, with an
error that names the parameter and shows how to prepare ordered data,
such as sorted(values) or sorted(values.difference(exclusions)).

The check runs in the existing traversal that builds the identifier, so
the values that can reach the identifier are the values that are
checked. Lists and tuples are not reordered, so a caller's chosen order
still reaches the prompt and the identifier.

Remove the ordered set classes, their set-operation wrappers and the
container copying, and the tests that depended on them. Previously
accepted set and frozenset parameters now raise ValueError.

Add tests for construction-time rejection, the error message, rendering
of caller-prepared ordered values, preserved list order, and matching
prompts and identifiers across processes with different PYTHONHASHSEED
values. Remove the set-valued registry identifier sample.
…ss test

Different PYTHONHASHSEED values do not guarantee different set iteration
orders, so asserting that two seeds iterate the source set differently
could fail spuriously. The test still runs two processes with different
seeds and checks that prepared values give the same prompt and identifier.
@samrudhi03 Samrudhi (samrudhi03) changed the title FIX: Render set template parameters in a reproducible order in LLMGenericTextConverter FIX: Require ordered template parameters in LLMGenericTextConverter Nov 16, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@richlundeen

Copy link
Copy Markdown
Contributor

review:5925289947

The scope recommendation is satisfied at da78a09: the converter rejects unordered parameters through its existing traversal, with an actionable ordered-input error; the deterministic-set classes, operator wrappers and cyclic copier are gone. The PR documents the intentional compatibility loss and caller-side sorted/set-difference migration. Renewed independent inclusion and implementation review found no remaining supported source concerns. The original converter/identifier checks passed (436 passed, 5 skipped, 3 xfailed); the main integration only updates the Bicep workflow and its contract test. This does not claim remote CI passed or authorize merging.

Verified on published commit da78a09309d13bfbec15c878daeb22f87494e2d9.

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.

Automated review completed. No blocking concerns remain. This review records source coverage; merging is handled separately.

@richlundeen
Richard Lundeen (richlundeen) added this pull request to the merge queue Nov 17, 2026
Merged via the queue into microsoft:main with commit ba2a68e Nov 17, 2026
65 of 67 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.

BUG: LLMGenericTextConverter identifier changes between processes for set-valued template parameters

3 participants