Skip to content

fix: redact toxicity as well as profanity - #2002

Open
feiiiiii5 wants to merge 5 commits into
openlit:mainfrom
feiiiiii5:feiiiiii5/issue-contract-openlit-moderation
Open

feiiiiii5 wants to merge 5 commits into
openlit:mainfrom
feiiiiii5:feiiiiii5/issue-contract-openlit-moderation

Conversation

@feiiiiii5

@feiiiiii5 feiiiiii5 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: #2000

Change description:

Moderation(action="redact") replaced only profanity; toxicity was classified but left in the text with transformed_text=None, so the pipeline forwarded the toxic string unchanged. Toxicity patterns are now compiled once and substituted into the text alongside profanity, producing a populated transformed_text with no toxic phrase. Classification, scoring and other actions are unchanged.

Checklist

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked for other open Pull Requests for the same change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented

Base fails the two toxicity cases; with the fix test_guard_pipeline.py is 19 passed. Ruff findings are pre-existing on base. Provider live tests were not run (no credentials); offline guard tests cover the change.

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Summary by Sourcery

Redact toxic phrases alongside profanity across the moderation guards.

Bug Fixes:

  • Ensure moderation redaction removes detected toxicity as well as profanity and forwards the sanitized text to downstream guards.

Enhancements:

  • Preserve toxicity classification, scoring, overlap handling, and unscanned text while applying combined redaction across Python and TypeScript SDKs.

Tests:

  • Add Python and TypeScript coverage for toxicity redaction, overlapping matches, suffix preservation, and pipeline propagation.

@feiiiiii5
feiiiiii5 requested review from a team and ishanjainn as code owners November 23, 2026 16:33
@sourcery-ai

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Compile toxicity patterns for redaction and merge toxicity and profanity spans in one pass, prioritizing toxicity while preserving unscanned text.

  • sdk/python/src/openlit/guard/moderation.py L44-51, L58-80 (+2 small edits)
  • sdk/typescript/src/guard/moderation.ts L22-60, L99

Tests

Cover toxicity and profanity redaction, overlap priority, scan-tail preservation, and forwarding redacted text through the pipeline.

  • sdk/python/tests/test_guard_pipeline.py L20-34, L218-285 (+2 small edits)
  • sdk/typescript/src/guard/__tests__/pipeline.test.ts L112-129

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Redact toxic phrases in moderation guard output

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Redact detected toxic phrases alongside profanity so pipelines do not forward them unchanged.
• Preserve existing classification, scoring, and non-redaction behavior.
• Add guard and pipeline tests for toxicity, profanity, and clean text.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The Python and TypeScript implementations provide the same bounded moderation-redaction behavior.
  • Their outputs feed the corresponding guard pipelines and automatic provider wrappers, so these are implementation and integration hops of one end-to-end capability rather than independent capabilities.
Sources

sdk/python/src/openlit/guard/moderation.py[58-78]

def _redact_spans(text: str, profanity_re: re.Pattern) -> str:
    spans: List[Tuple[int, int, str]] = []
    for match in _TOXICITY_RE.finditer(text):
        spans.append((match.start(), match.end(), "[REDACTED:toxicity]"))

    toxic_spans = [(start, end) for start, end, _ in spans]
    for match in profanity_re.finditer(text):
        start, end = match.span()
        if any(start < toxic_end and end > toxic_start for toxic_start, toxic_end in toxic_spans):
            continue
        spans.append((start, end, "[REDACTED:profanity]"))

    spans.sort(key=lambda span: span[0])
    parts: List[str] = []
    cursor = 0
    for start, end, replacement in spans:
        parts.append(text[cursor:start])
        parts.append(replacement)
        cursor = end
    parts.append(text[cursor:])
    return "".join(parts)

sdk/typescript/src/guard/moderation.ts[22-59]

const TOXICITY_REDACTION_SOURCE = TOXICITY_PATTERNS.map(
  (pattern) => `(?:${pattern.source})`,
).join('|');

interface RedactionSpan {
  start: number;
  end: number;
  replacement: string;
}

function redactModeration(text: string, profanityRe: RegExp): string {
  const spans: RedactionSpan[] = [];
  const toxicityRe = new RegExp(TOXICITY_REDACTION_SOURCE, 'gi');
  for (const match of text.matchAll(toxicityRe)) {
    const start = match.index ?? 0;
    spans.push({ start, end: start + match[0].length, replacement: '[REDACTED:toxicity]' });
  }

  const toxicSpans = spans.map(({ start, end }) => ({ start, end }));
  const customRe = new RegExp(profanityRe.source, 'gi');
  for (const match of text.matchAll(customRe)) {
    const start = match.index ?? 0;
    const end = start + match[0].length;
    const overlapsToxicity = toxicSpans.some((span) => start < span.end && end > span.start);
    if (!overlapsToxicity) {
      spans.push({ start, end, replacement: '[REDACTED:profanity]' });
    }
  }

  spans.sort((a, b) => a.start - b.start);
  let transformed = '';
  let cursor = 0;
  for (const span of spans) {
    transformed += text.slice(cursor, span.start) + span.replacement;
    cursor = span.end;
  }
  return transformed + text.slice(cursor);
}
Behavioral complexity 🟡 Medium 🧩 Interacting branches, Data transformation

  • Before: redact mode replaced every profanity match using one direct regular-expression substitution, while toxicity was classified but not redacted.
  • After: the implementation collects toxicity and profanity spans, gives toxicity precedence on overlap, sorts replacements, reconstructs the text, and preserves the uncapped suffix through the existing run path.
  • New correctness conditions: all matched spans must be non-overlapping in reconstruction, toxicity must suppress overlapping profanity without exposing text, ordering must preserve untouched segments, and capped scans must retain the unscanned suffix.
  • The TypeScript and Python implementations must preserve these same conditions.
  • The span merging and precedence logic are newly interacting behavior; the existing pipeline forwarding is an unchanged consumer mechanism.
Sources

sdk/python/src/openlit/guard/moderation.py[58-78]

def _redact_spans(text: str, profanity_re: re.Pattern) -> str:
    spans: List[Tuple[int, int, str]] = []
    for match in _TOXICITY_RE.finditer(text):
        spans.append((match.start(), match.end(), "[REDACTED:toxicity]"))

    toxic_spans = [(start, end) for start, end, _ in spans]
    for match in profanity_re.finditer(text):
        start, end = match.span()
        if any(start < toxic_end and end > toxic_start for toxic_start, toxic_end in toxic_spans):
            continue
        spans.append((start, end, "[REDACTED:profanity]"))

    spans.sort(key=lambda span: span[0])
    parts: List[str] = []
    cursor = 0
    for start, end, replacement in spans:
        parts.append(text[cursor:start])
        parts.append(replacement)
        cursor = end
    parts.append(text[cursor:])
    return "".join(parts)

sdk/typescript/src/guard/moderation.ts[22-59]

const TOXICITY_REDACTION_SOURCE = TOXICITY_PATTERNS.map(
  (pattern) => `(?:${pattern.source})`,
).join('|');

interface RedactionSpan {
  start: number;
  end: number;
  replacement: string;
}

function redactModeration(text: string, profanityRe: RegExp): string {
  const spans: RedactionSpan[] = [];
  const toxicityRe = new RegExp(TOXICITY_REDACTION_SOURCE, 'gi');
  for (const match of text.matchAll(toxicityRe)) {
    const start = match.index ?? 0;
    spans.push({ start, end: start + match[0].length, replacement: '[REDACTED:toxicity]' });
  }

  const toxicSpans = spans.map(({ start, end }) => ({ start, end }));
  const customRe = new RegExp(profanityRe.source, 'gi');
  for (const match of text.matchAll(customRe)) {
    const start = match.index ?? 0;
    const end = start + match[0].length;
    const overlapsToxicity = toxicSpans.some((span) => start < span.end && end > span.start);
    if (!overlapsToxicity) {
      spans.push({ start, end, replacement: '[REDACTED:profanity]' });
    }
  }

  spans.sort((a, b) => a.start - b.start);
  let transformed = '';
  let cursor = 0;
  for (const span of spans) {
    transformed += text.slice(cursor, span.start) + span.replacement;
    cursor = span.end;
  }
  return transformed + text.slice(cursor);
}
Potential damage 🟡 Medium 🩹 Incorrect results

  • If the changed transformation regresses, flagged toxicity or profanity could remain in text, be replaced incorrectly, or alter surrounding content.
  • The affected behavior is bounded to moderation redaction and the guarded pipeline/provider content that consumes its transformed value.
  • A code revert stops future incorrect transformations, but text already sent to an external provider or returned to a caller cannot be recalled; repair or compensation is therefore needed for such effects.
  • Future behavior is restored by reverting the code.
  • Previously submitted or returned text requires external handling if the failure exposed or altered it; no automatic repair path is established by the inspected sources.
Sources

sdk/python/src/openlit/guard/moderation.py[58-78]

def _redact_spans(text: str, profanity_re: re.Pattern) -> str:
    spans: List[Tuple[int, int, str]] = []
    for match in _TOXICITY_RE.finditer(text):
        spans.append((match.start(), match.end(), "[REDACTED:toxicity]"))

    toxic_spans = [(start, end) for start, end, _ in spans]
    for match in profanity_re.finditer(text):
        start, end = match.span()
        if any(start < toxic_end and end > toxic_start for toxic_start, toxic_end in toxic_spans):
            continue
        spans.append((start, end, "[REDACTED:profanity]"))

    spans.sort(key=lambda span: span[0])
    parts: List[str] = []
    cursor = 0
    for start, end, replacement in spans:
        parts.append(text[cursor:start])
        parts.append(replacement)
        cursor = end
    parts.append(text[cursor:])
    return "".join(parts)

sdk/typescript/src/guard/moderation.ts[22-59]

const TOXICITY_REDACTION_SOURCE = TOXICITY_PATTERNS.map(
  (pattern) => `(?:${pattern.source})`,
).join('|');

interface RedactionSpan {
  start: number;
  end: number;
  replacement: string;
}

function redactModeration(text: string, profanityRe: RegExp): string {
  const spans: RedactionSpan[] = [];
  const toxicityRe = new RegExp(TOXICITY_REDACTION_SOURCE, 'gi');
  for (const match of text.matchAll(toxicityRe)) {
    const start = match.index ?? 0;
    spans.push({ start, end: start + match[0].length, replacement: '[REDACTED:toxicity]' });
  }

  const toxicSpans = spans.map(({ start, end }) => ({ start, end }));
  const customRe = new RegExp(profanityRe.source, 'gi');
  for (const match of text.matchAll(customRe)) {
    const start = match.index ?? 0;
    const end = start + match[0].length;
    const overlapsToxicity = toxicSpans.some((span) => start < span.end && end > span.start);
    if (!overlapsToxicity) {
      spans.push({ start, end, replacement: '[REDACTED:profanity]' });
    }
  }

  spans.sort((a, b) => a.start - b.start);
  let transformed = '';
  let cursor = 0;
  for (const span of spans) {
    transformed += text.slice(cursor, span.start) + span.replacement;
    cursor = span.end;
  }
  return transformed + text.slice(cursor);
}
Assessed commit 05555e7
Diagram

graph TD
  A["Input text"] --> B["Moderation guard"] --> C{"Redaction needed?"}
  C -- "Yes" --> D["Profanity replacement"] --> E["Toxicity replacement"] --> F["Pipeline output"]
  C -- "No" --> F
Loading
High-Level Assessment

Keep the separate redaction passes. They reuse the existing profanity matcher and toxicity patterns while leaving detection, classification, and scoring unchanged; a combined matcher would add complexity without a clear benefit for this small pattern set.

Files changed (2) +53 / -1

Bug fix (1) +10 / -1
moderation.pyReplace toxic phrases during moderation redaction +10/-1

Replace toxic phrases during moderation redaction

• Compiles an alternation of the existing toxicity patterns for redaction. Redact mode now substitutes toxic phrases after profanity, while detection and scoring continue to use the original patterns.

sdk/python/src/openlit/guard/moderation.py

Tests (1) +43 / -0
test_guard_pipeline.pyCover moderation redaction and pipeline output +43/-0

Cover moderation redaction and pipeline output

• Adds tests for toxicity-only redaction, existing profanity redaction, unchanged clean text, and the pipeline returning redacted toxicity instead of the original phrase.

sdk/python/tests/test_guard_pipeline.py

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Custom word flags leave threats in output ✓ Resolved
Description
Moderation.evaluate replaces custom profanity matches before applying the toxicity regex, so an
overlapping profanity match breaks the toxic phrase before it can be redacted. With
custom_words=["I'll"] and input "I'll kill you", the result classifies the original text as
toxic but returns "[REDACTED:profanity] kill you", which the pipeline forwards to later guards and
provider requests.

Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai sourcery-ai Bot 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.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/guard/moderation.py" line_range="102" />
<code_context>
         if self._action.value == "redact":
-            transformed = self._profanity_re.sub("[REDACTED:profanity]", text)
+            redacted = self._profanity_re.sub("[REDACTED:profanity]", text)
+            transformed = _TOXICITY_RE.sub("[REDACTED:toxicity]", redacted)

         return GuardResult(
</code_context>
<issue_to_address>
**Toxic text passes through**

When a TypeScript caller uses redact mode on toxicity-only text, `Moderation.evaluate` substitutes only profanity, so `transformedText` stays null and the pipeline forwards the toxic text unchanged.

Add toxicity redaction to the TypeScript moderation implementation, matching Python.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/guard/moderation.py" line_range="101-102" />
<code_context>
         transformed: Optional[str] = None
         if self._action.value == "redact":
-            transformed = self._profanity_re.sub("[REDACTED:profanity]", text)
+            redacted = self._profanity_re.sub("[REDACTED:profanity]", text)
+            transformed = _TOXICITY_RE.sub("[REDACTED:toxicity]", redacted)

         return GuardResult(
</code_context>
<issue_to_address>
**Toxic phrase remains visible**

When a configured custom word matches part of a detected toxicity phrase, `Moderation.evaluate` replaces the custom word before applying `_TOXICITY_RE`, breaking the toxicity match and leaving the rest of the phrase visible to downstream guards.

Apply toxicity redaction before custom-word redaction so a custom-word replacement cannot break the toxicity match.
</issue_to_address>

### Comment 3
<location path="sdk/python/src/openlit/guard/moderation.py" line_range="102" />
<code_context>
         if self._action.value == "redact":
-            transformed = self._profanity_re.sub("[REDACTED:profanity]", text)
+            redacted = self._profanity_re.sub("[REDACTED:profanity]", text)
+            transformed = _TOXICITY_RE.sub("[REDACTED:toxicity]", redacted)

         return GuardResult(
</code_context>
<issue_to_address>
**Long input loses its suffix**

When the input exceeds `max_scan_length` and a toxicity match occurs within the scanned prefix, `Guard.run` passes only the capped prefix to `Moderation.evaluate`, which returns it as `transformed_text`; `Pipeline.evaluate` and provider integrations then replace the full input with that prefix, dropping the suffix.

Preserve the unscanned suffix when returning the redacted text so the capped scan does not truncate the input.
</issue_to_address>

### Comment 4
<location path="sdk/python/tests/test_guard_pipeline.py" line_range="218" />
<code_context>
+
+    def test_pipeline_forwards_redacted_toxicity(self):
+        """The pipeline no longer forwards toxic text to later guards."""
+        pipeline = Pipeline(guards=[Moderation(action="redact")])
+        result = pipeline.evaluate("kill yourself", phase="preflight")
+
</code_context>
<issue_to_address>
**Downstream receives toxic text**

When the pipeline passes the original text to later guards while preserving the first guard’s redacted text as its final result, when the pipeline keeps the original input for later guards but still returns the first guard’s redacted result, `test_pipeline_forwards_redacted_toxicity` passes: line 218 configures only `Moderation`, so no later guard observes what text it receives, and lines 221–224 check only the aggregate result.

Add a second guard that records or asserts the text it receives, and verify that it sees the redacted toxicity placeholder rather than the original phrase.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: sdk/python/src/openlit/guard/moderation.py:102, sdk/python/src/openlit/guard/moderation.py:102, sdk/python/src/openlit/guard/moderation.py:102, sdk/python/tests/test_guard_pipeline.py:218


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread sdk/python/tests/test_guard_pipeline.py Resolved
sourcery-ai[bot]
sourcery-ai Bot previously approved these changes Nov 28, 2026

@sourcery-ai sourcery-ai Bot 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.

Sourcery assessment

Approved.

feiiiiii5 and others added 5 commits November 29, 2026 06:35
Give toxicity priority over custom profanity matches on the original text,
preserve unscanned suffixes, and mirror the behavior in TypeScript.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@feiiiiii5
feiiiiii5 force-pushed the feiiiiii5/issue-contract-openlit-moderation branch from 528d4d0 to 05555e7 Compare November 29, 2026 14:41

This branch was previously deployed

1 inactive (outdated) deployment
release-notes — 2a1d159d Deployed Nov 23, 2026 by feiiiiii5 via Normalize / Conventional title #892
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant