Skip to content

LCORE-0000: Safety Refactor (Capabilities) - #2989

Draft
jrobertboos wants to merge 4 commits into
lightspeed-core:feature/safety-refactorfrom
jrobertboos:feature-safety
Draft

jrobertboos wants to merge 4 commits into
lightspeed-core:feature/safety-refactorfrom
jrobertboos:feature-safety

Conversation

@jrobertboos

@jrobertboos jrobertboos commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

Sorry for the huge PR!

This is a PR that aims to refactor the safety capabilities through abstraction.

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library [pyproject.toml + uv.lock]
  • Bump-up dependent library [requirements.*.txt for Konflux]
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement
  • Benchmarks improvement

Tools used to create PR

Identify any AI code assistants used in this PR (for transparency and review context)

  • Assisted-by: (e.g., Claude, CodeRabbit, Ollama, etc., N/A if not used)
  • Generated by: (e.g., tool name and version; N/A if not used)

Related Tickets & Documents

  • Related Issue #
  • Closes #

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Please provide detailed steps to perform tests related to this code change.
  • How were the fix/results from this change verified? Please provide relevant screenshots or results.

@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@jrobertboos jrobertboos changed the title LCORE-0000: Safety Refactor LCORE-0000: Safety Refactor (Capabilities) Oct 22, 2026
@jrobertboos
jrobertboos marked this pull request as ready for review October 22, 2026 20:24

@Jazzcort Jazzcort 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.

It's a huge effort there to pull this out. But honestly, I don't have a strong faith here that bring this into out repo will benefit us by a lot.

If we think of what this PR can bring us:

a. If we need to implement another output shield that's capable with streaming output, we don't have to deal with the messy streaming handling.
b. We have less boilerplate per safety capability.

For a, it can be achieved in other way. For b, outside of the streaming part is actually pretty trivial.

And what are the downsides for this new safety class?

a. Restricts developer freedom at hook points. If the chosen pattern of the abstract safety class does not fit my need, I still need to do everything on my own.
b. If we create shield from the abstract safety class, we lose the access to RunContext. The only part we can change is evaluate function. It's what make it less boilerplate but also what make it more limited.

Overall, I just don't want to trade off the flexibility here, but it's just my own opinion. If more people are leaning toward this, I'm fine with it. 😬

_SCORE_START_TAG = "<score>"
_SCORE_END_TAG = "</score>"

_JUDGE_PREAMBLE_NOTHINK = (

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.

These parts are completely copied from Ask Red Hat's GitLab repo. Even though it's a private GitLab instance hosted by Red Hat, I feel like it's still genuinely good to cite the source as a comment here. 😁

redacted = prompt
for pattern in self._compiled:
redacted = pattern.sub(replacement, redacted)
if redacted == prompt:

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.

If the redacted content has the same string length as the replaced content, it will be marked as pass but it's redacted.

PASSWORD: 1234567890 -> PASSWORD: [REDACTED]

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.

why would the string length matter? Its checking string equivalency which will be different once the redacted text is applied.

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.

you're right! my bad.

Comment thread src/safety/base.py
raise OutputBlocked(result.message)
case "replace":
return [
PartStartEvent(

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.

Why PartStartEvent for the replacement? This just create a malform streaming pattern. It might not affect our /streaming_query endpoint since it does not care about whether it's PartStartEvent or PartDeltaEvent but having this kind of malform break the framework's protocol from my point of view.

Comment thread src/safety/base.py
case "replace":
return [
PartStartEvent(
index=0, part=TextPart(content=str(result.replacement))

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.

index does not matter for our /streaming_query endpoint because we just don't care about it, but it will definitely cause problem for AG-UI.

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.

Yea this will have to be modified but as I said in another comment it will also have to be modified for all other existing capabilities.

Comment thread src/safety/base.py
if ctx.conversation_id is not None:
state = dataclasses.replace(state, conversation_id=ctx.conversation_id)
if isinstance(error, ToolBlocked):
output = error.reason or "Tool result blocked by a safety guard."

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.

I think we're planing to use StepPersistenceStore for the agent history, which means the message_history also needs to be modified with the violation message here. Otherwise, the blocked content still exists in message_history.

Same for wrap_run where only the output is modified but not the message_history

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.

Yea there are definitely things that will need to be modified with this implementation, however so will all the already existing Shields. Abstracting away the stream handling behind a single evaluate function makes it so that when things change in the future only one instance will need to be modified.



@dataclass
class GraniteGuardian(CombinedCapability[AgentDepsT]):

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.

From my understanding about CombinedCapability, it runs the capabilities in it sequentially. So, are we just giving up on the parallelism we had? This means for 5 risks we spend 5x the time than before.

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.

Yea this is something that I am working on, I have a plan for instead of each and every risk being a capability a capability will be created for each mount point e.g. Input, Tool, Output. This should allow us to maintain the parallelism.

Comment thread src/safety/base.py
"""Evaluate the buffered output once `state` is ready, and act on the verdict."""

async def release(state: OutputState) -> list[AgentStreamEvent]:
text, events = state.flush()

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.

Just noticed that neither the GraniteGuardian in pydantic_ai_lightspeed/ nor this new one implement the sliding window mechanism for the streaming check. If you go back to check my original implementation of output guardrail, you can check the details. It helps a lot with the cutting at the boundary case.

I know wrap_run re-evaluate the whole response but those were emitted during the streaming are already in the end user's hand.

@jrobertboos

Copy link
Copy Markdown
Contributor Author

@Jazzcort I do think that this would bring benefit to the project. I think that by extracting the actual agent loop hooks out into an abstract class is beneficial as by definition a shield will always be ran on a prompt and will have a prescribed list of actions that can be taken (allow, block, replace, maybe retry). Also the stream handling logic is quite complex so isolating it behind an abstract class means that whenever a new shield is added tests that test the stream handling functionality (for output and tool) will need to also be tested which will add a ton more complexity when adding a new shield.

Responding to your 2 concerns:

a. As of right now I can not think of any more hook points but if we ever do then we can extend the abstract class to offer the hook points. Also if you need more fine grained control than you can always overload the actual lifecycle hooks.

b. I chose to have the evaluate function be independent of RunContext as I can not (as of rn) think of any times where a shield would need to have access to RunContext but if that need ever arises then we can pass it to the evaluate function.

I think that while yes this is less flexible I do believe it is as flexible as a safety capability would need to be and if there is something that needs more than is offered by the evaluate interface then it might be worth reconsidering if it really is a safety capability.

@jrobertboos

jrobertboos commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@Jazzcort There is definitely a lot of small refinements that will need to be made before this is fully wired but I do think that a pattern similar to this will significantly simplify the implementation of existing safety shields as well as make the creation of new ones much easier.

I also am not a huge fan of having the actual business logic of a shield being so intertwined with the hooks offered by pydantic capability and think that the separation is the right approach.

@jrobertboos
jrobertboos requested a review from anik120 October 23, 2026 15:45
@Jazzcort

Copy link
Copy Markdown
Contributor

I totally understand the motivation here for generalizing the safety shield. It provides the convenience but also comes with the restriction that's what I want to say here. 😁 Let's see what other people thinks.

…ity, and redaction guards

Introduces `src/safety/` with an abstract safety capability base, streaming
output buffering, guardrail verdict types, and message-history helpers.
Adds concrete guards:
- `GraniteGuardian` / `GraniteGuardianRisk` for logprob-based risk checks
- `QuestionValidityCapability` for LLM-classified on-topic input filtering
- `RedactionCapability` for regex-based PII redaction on input/output
…nd typing cleanup

- Adds module docstrings to `safety/types.py` and `granite_guardian/types.py`.
- Wraps long error strings in `base.py` for readability.
- Adds missing `case _:` exhaustiveness checks for safety verdict actions in
  `AbstractSafetyCapability`.
- Replaces inline `def fn[TypeVar]` syntax with explicit `TypeVar` declarations
  in `safety/utils.py` for broader compatibility.
- Shortens a Granite Guardian docstring and adds a pylint disable comment for
  an intentional keyword argument.
- Reflows a long docstring line in `RedactionCapability`.
Comment on lines +80 to +81
"SELECT id, document, content_text, "
"embedding <=> $1::vector AS distance "
@fullsend-ai-review

fullsend-ai-review Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ❌ Failure (post-script /home/runner/work/lightspeed-stack/lightspeed-stack/.fullsend/.fullsend-cache/resources/sha256/72bc9e497d4e5e31e33c96c40908d0721bcb4566e49ce23fe37b85ee42ea03f5/scripts/post-review.sh faile…) · Started 2:11 PM UTC · Completed 2:15 PM UTC

Commit: de6ef36 · View workflow run →

Runtime: claude · Model: opus → claude-opus-4-6 · Effort: high · Cost: $0.90

@fullsend-ai-review

fullsend-ai-review Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Review

Findings

High

  • [logic-error] src/safety/base.py:186 — After the async for event in stream loop in wrap_run_event_stream exits normally, any events still buffered in OutputState (accumulated since the last state.ready() returned True) are silently dropped — they are never evaluated and never yielded to the streaming consumer. With check_tokens=50, if 48 events arrive after the last flush, the streaming caller sees the response truncated. The non-streaming path (wrap_run) re-evaluates the complete output separately, so it still sees the full text, but the streaming consumer is missing the tail. See also: [data-exposure] finding at this location.
    Remediation: After the async for event in stream loop, add a final flush for residual buffered events.

Medium

  • [logic-error] src/safety/granite_guardian/utils.py:80 — _search_tag clears the buffer when buffer.strip() does not start with <. If a single token contains both reasoning text and a closing tag (e.g. "reasoning</think>"), the tag is lost, preventing the state machine from transitioning. While current tokenizers typically emit XML tags as separate tokens, the parser is not resilient to combined tokens.
    Remediation: Replace the startswith("<") heuristic with a check that tests whether the tag appears anywhere in the buffer.

  • [logic-error] src/safety/redaction/capability.py:36 — The class docstring says "Guards both 'input' and 'output' by default" and the field docstring says "Defaults to guarding both the user's prompt and the model's streamed output", but the actual default is ["input"] only. In a safety module, this mismatch could lead operators to believe output is guarded when it is not.
    Remediation: Change the default to ["input", "output"] to match the documented behaviour, or update the docstrings to say input-only.

Low

  • [edge-case] src/safety/granite_guardian/capability.py:104 — asyncio.gather is used without return_exceptions=True. If one risk evaluation raises, the exception propagates but other concurrent tasks continue running in the background, wasting resources.

  • [missing-test] tests/unit/safety/test_base.py — No test covers the residual-buffer scenario where the output stream ends with events still in the buffer below the check_tokens threshold.

  • [injection-vuln] src/safety/redaction/capability.py:65 — Regex patterns from configuration are compiled without ReDoS guards. Operator-controlled configuration, not end-user input.

  • [data-exposure] src/safety/base.py:186 — Streaming buffer tail bypasses safety evaluation when below check_tokens threshold. The wrap_run post-check mitigates for final output but not the streaming path. See also: [logic-error] finding at this location.

  • [injection-vuln] src/safety/granite_guardian/utils.py:66 — build_guardian_block interpolates criteria into the guardian prompt template without sanitization. Operator-controlled configuration, not end-user input.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run

<!-- fullsend:review-findings-v2:eyJ2ZXJzaW9uIjoyLCJhY3Rpb24iOiJyZXF1ZXN0LWNoYW5nZXMiLCJmaW5kaW5ncyI6W3sic2V2ZXJpdHkiOiJoaWdoIiwiY2F0ZWdvcnkiOiJsb2dpYy1lcnJvciIsImZpbGUiOiJzcmMvc2FmZXR5L2Jhc2UucHkiLCJpZCI6ImZfYWM5OGVlMDhhZWQ2NGFhNiIsImxpbmUiOjE4NSwiYWN0aW9uYWJsZSI6dHJ1ZX0seyJzZXZlcml0eSI6Im1lZGl1bSIsImNhdGVnb3J5IjoibG9naWMtZXJyb3IiLCJmaWxlIjoic3JjL3NhZmV0eS9ncmFuaXRlX2d1YXJkaWFuL3V0aWxzLnB5IiwiaWQiOiJmXzUxMmI5YTEzZGIzNGJkZTMiLCJsaW5lIjo4MCwiYWN0aW9uYWJsZSI6dHJ1ZX0seyJzZXZlcml0eSI6Im1lZGl1bSIsImNhdGVnb3J5IjoibG9naWMtZXJyb3IiLCJmaWxlIjoic3JjL3NhZmV0eS9yZWRhY3Rpb24vY2FwYWJpbGl0eS5weSIsImlkIjoiZl81NmNlMzIwODUxZDUzNGE5IiwibGluZSI6MzYsImFjdGlvbmFibGUiOnRydWV9LHsic2V2ZXJpdHkiOiJsb3ciLCJjYXRlZ29yeSI6ImVkZ2UtY2FzZSIsImZpbGUiOiJzcmMvc2FmZXR5L2dyYW5pdGVfZ3VhcmRpYW4vY2FwYWJpbGl0eS5weSIsImlkIjoiZl81ZGYxMDYzMTFjNDBjNmRlIiwibGluZSI6NjksImFjdGlvbmFibGUiOnRydWV9LHsic2V2ZXJpdHkiOiJsb3ciLCJjYXRlZ29yeSI6Im1pc3NpbmctdGVzdCIsImZpbGUiOiJ0ZXN0cy91bml0L3NhZmV0eS90ZXN0X2Jhc2UucHkiLCJpZCI6ImZfNzAwMzUyZWZkNzU5Nzk4ZiIsImFjdGlvbmFibGUiOnRydWV9LHsic2V2ZXJpdHkiOiJsb3ciLCJjYXRlZ29yeSI6ImluamVjdGlvbi12dWxuIiwiZmlsZSI6InNyYy9zYWZldHkvcmVkYWN0aW9uL2NhcGFiaWxpdHkucHkiLCJpZCI6ImZfMmRkMDQzNjlkZmFmNjExYiIsImxpbmUiOjY1LCJhY3Rpb25hYmxlIjp0cnVlfSx7InNldmVyaXR5IjoibG93IiwiY2F0ZWdvcnkiOiJkYXRhLWV4cG9zdXJlIiwiZmlsZSI6InNyYy9zYWZldHkvYmFzZS5weSIsImlkIjoiZl8zNmNmNmEzZWM4ZThiOGM1IiwibGluZSI6MTg2LCJhY3Rpb25hYmxlIjpmYWxzZX0seyJzZXZlcml0eSI6ImxvdyIsImNhdGVnb3J5IjoiaW5qZWN0aW9uLXZ1bG4iLCJmaWxlIjoic3JjL3NhZmV0eS9ncmFuaXRlX2d1YXJkaWFuL3V0aWxzLnB5IiwiaWQiOiJmXzNmMDE2Njg1NzgwMTczZmQiLCJsaW5lIjo2NiwiYWN0aW9uYWJsZSI6ZmFsc2V9XX0= -->

Review

Findings

High

  • [logic-error] src/safety/base.py:185 — In wrap_run_event_stream, when 'output' is in self.type, events are appended to state and only flushed when state.ready(self.check_tokens) returns True. After the async for event in stream loop exhausts the stream, any events remaining in the buffer that did not cross the ready() threshold are silently dropped — they are never yielded to the consumer. While ready() returns True on a PartEndEvent (covering the typical case), if the stream's final events after the last PartEndEvent don't reach the threshold (e.g., trailing non-text events, or a stream that ends without a PartEndEvent), those buffered events are lost. A streaming consumer would see an incomplete response.
    Remediation: After the async for event in stream loop, add a final flush: if state.events: for released in await release(state): yield released.

Medium

  • [logic-error] src/safety/granite_guardian/utils.py:80 — _search_tag clears the buffer and returns False whenever buffer.strip() doesn't start with <. If a single token contains non-tag text followed by a tag (e.g., "reasoning</think>"), the tag is silently discarded. In the INSIDE_THINK state, this causes the parser to get stuck because the </think> close tag is lost. The code already handles split-tag scenarios, so this gap is inconsistent with the robustness level the parser aims for.
    Remediation: Instead of clearing the buffer when it doesn't start with <, scan the buffer for the tag using tag in buffer regardless of the buffer's prefix, or retain the portion starting from the last <.

  • [logic-error] src/safety/redaction/capability.py:36 — The class docstring says "Guards both 'input' and 'output' by default" and the type field docstring says "Defaults to guarding both the user's prompt and the model's streamed output", but the actual default_factory is lambda: ["input"] — input only. A user relying on the docstring would believe output is guarded by default when it is not, potentially leaving model output unscreened for PII.
    Remediation: Either change the default to lambda: ["input", "output"] to match the docstring, or fix the docstrings to say "Guards 'input' by default".

Low

  • [edge-case] src/safety/granite_guardian/capability.py:69 — GraniteGuardianRisk.__post_init__ sets self.type = self.risk.type, which aliases the same mutable list object from the Risk dataclass. frozen=True only prevents attribute reassignment — the list itself is still mutable, creating a shared-mutable-state hazard.
    Remediation: Copy the list: self.type = list(self.risk.type).

  • [missing-test] tests/unit/safety/test_base.py — No test for the scenario where an output stream ends with events still buffered below the check_tokens threshold and without a trailing PartEndEvent. Such a test would expose the unflushed-buffer bug.

  • [injection-vuln] src/safety/redaction/capability.py:65 — RedactionCapability compiles user-configurable regex patterns from configuration via re.compile() with no safeguards against catastrophic backtracking (ReDoS). Patterns come from configuration rather than direct runtime user input, limiting exploitability to configuration-level compromise.

  • [data-exposure] src/safety/base.py:186 — In wrap_run_event_stream, each buffered chunk is evaluated independently by evaluate(). Content that straddles two evaluation windows passes both individual checks and is yielded to the streaming caller. The code acknowledges this in the wrap_run docstring ('chunk-boundary blind spot').

  • [injection-vuln] src/safety/granite_guardian/utils.py:66 — build_guardian_block interpolates the criteria string directly into the Granite Guardian system prompt via an f-string. If criteria contains adversarial text, it could override the scoring schema. The criteria value originates from configuration, not runtime user input.


Labels: PR introduces a new safety capability framework with guardrails and PII redaction.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (2)

Review

Reason: token-limit

This PR was NOT reviewed. Do not count this as an approval.

Introduces `tests/unit/safety/` with test coverage for:
- `AbstractSafetyCapability` lifecycle, streaming, and guardrail verdicts
- `safety.exceptions`, `safety.types`, and `safety.utils`
- Granite Guardian risk scoring, types, and logprob parsing utilities
- Question validity classification and model binding

Includes shared test helpers for building `RunContext` and `ModelRequestContext`.
@fullsend-ai-review

fullsend-ai-review Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 2:27 PM UTC · Completed 2:44 PM UTC

Commit: 293d9d6 · View workflow run →

Runtime: pi · Model: opus → claude-opus-4-6 · Effort: high · Cost: $5.82

fullsend-ai-review[bot]

This comment was marked as outdated.

… point

- Adds `GuardrailResult.combine` to collapse multiple allow/block verdicts into one, with any block winning and block messages joined.
- Renames `GraniteGuardianRisk` to `GraniteGuardianType` and groups risks by guard point (input/output/tool), evaluating each group's risks in parallel and combining verdicts.
- Updates tests and docstrings accordingly.
@fullsend-ai-review

fullsend-ai-review Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 5:13 PM UTC · Completed 5:34 PM UTC

Commit: 092945c · View workflow run →

Runtime: pi · Model: opus → claude-opus-4-6 · Effort: high · Cost: $4.93

@fullsend-ai-review fullsend-ai-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

See the review comment for full details.

Comment thread src/safety/base.py
try:
if "output" in self.type:
state: OutputState = OutputState()
async for event in stream:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[high] logic-error

After the async for event in stream loop in wrap_run_event_stream exits normally, any events still buffered in OutputState (accumulated since the last state.ready() returned True) are silently dropped — they are never evaluated and never yielded to the streaming consumer. With check_tokens=50, if 48 events arrive after the last flush, the streaming caller sees the response truncated. The non-streaming path (wrap_run) re-evaluates the complete output separately, so it still sees the full text, but the streaming consumer is missing the tail.

Suggested fix: After the async for event in stream loop, add a final flush for residual buffered events:
if state.events:
for released in await release(state):
yield released

tag-like, or once the tag is found.

"""
if not buffer.strip().startswith("<"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] logic-error

_search_tag clears the buffer when buffer.strip() does not start with <. If a single token contains both reasoning text and a closing tag (e.g. reasoning then closing think tag), the tag is lost, preventing the state machine from transitioning. While current tokenizers typically emit XML tags as separate tokens, the parser is not resilient to combined tokens.

Suggested fix: Replace the startswith heuristic with a check that tests whether the tag appears anywhere in the buffer before deciding to clear it.

"""

type: Sequence[Literal["input", "output", "tool"]] = field(
default_factory=lambda: ["input"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] logic-error

The class docstring says Guards both input and output by default and the field docstring says Defaults to guarding both the users prompt and the models streamed output, but the actual default is input only. In a safety module, this mismatch could lead operators to believe output is guarded when it is not.

Suggested fix: Change the default to input and output to match the documented behaviour, or update the docstrings to say input-only.

return GuardrailResult.allow()
return GuardrailResult.block(message=risk.violation_message)

results = await asyncio.gather(*[evaluate_risk(risk) for risk in self.risks])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] edge-case

asyncio.gather is used without return_exceptions=True. If one risk evaluation raises, the exception propagates but other concurrent tasks continue running in the background, wasting resources.

if self.replacement is None:
self.replacement = DEFAULT_REPLACEMENT
self._compiled: tuple[re.Pattern[str], ...] = tuple(
re.compile(pattern) for pattern in self.patterns.values()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] injection-vuln

Regex patterns from configuration are compiled without ReDoS guards. Operator-controlled configuration, not end-user input.

Comment thread src/safety/base.py
try:
if "output" in self.type:
state: OutputState = OutputState()
async for event in stream:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] data-exposure

Streaming buffer tail bypasses safety evaluation when below check_tokens threshold. The wrap_run post-check mitigates for final output but not the streaming path.

"""Build Granite Guardian instructions that judge `criteria`."""
preamble = _JUDGE_PREAMBLE_THINK if think else _JUDGE_PREAMBLE_NOTHINK
return (
f"{preamble}\n\n"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] injection-vuln

build_guardian_block interpolates criteria into the guardian prompt template without sanitization. Operator-controlled configuration, not end-user input.

@tisnik
tisnik marked this pull request as draft November 25, 2026 14:10

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

enhancement New feature or request Review effort 5/5

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants