Repository navigation
LCORE-0000: Safety Refactor (Capabilities) - #2989
jrobertboos wants to merge 4 commits into
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
Jazzcort
left a comment
There was a problem hiding this comment.
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 = ( |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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]
There was a problem hiding this comment.
why would the string length matter? Its checking string equivalency which will be different once the redacted text is applied.
| raise OutputBlocked(result.message) | ||
| case "replace": | ||
| return [ | ||
| PartStartEvent( |
There was a problem hiding this comment.
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.
| case "replace": | ||
| return [ | ||
| PartStartEvent( | ||
| index=0, part=TextPart(content=str(result.replacement)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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." |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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]): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| """Evaluate the buffered output once `state` is ready, and act on the verdict.""" | ||
|
|
||
| async def release(state: OutputState) -> list[AgentStreamEvent]: | ||
| text, events = state.flush() |
There was a problem hiding this comment.
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.
|
@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. |
|
@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. |
|
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`.
12c30d6 to
de6ef36
Compare
| "SELECT id, document, content_text, " | ||
| "embedding <=> $1::vector AS distance " |
|
🤖 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: Runtime: claude · Model: opus → claude-opus-4-6 · Effort: high · Cost: $0.90 |
ReviewFindingsHigh
Medium
Low
Next steps:
Previous run<!-- fullsend:review-findings-v2:eyJ2ZXJzaW9uIjoyLCJhY3Rpb24iOiJyZXF1ZXN0LWNoYW5nZXMiLCJmaW5kaW5ncyI6W3sic2V2ZXJpdHkiOiJoaWdoIiwiY2F0ZWdvcnkiOiJsb2dpYy1lcnJvciIsImZpbGUiOiJzcmMvc2FmZXR5L2Jhc2UucHkiLCJpZCI6ImZfYWM5OGVlMDhhZWQ2NGFhNiIsImxpbmUiOjE4NSwiYWN0aW9uYWJsZSI6dHJ1ZX0seyJzZXZlcml0eSI6Im1lZGl1bSIsImNhdGVnb3J5IjoibG9naWMtZXJyb3IiLCJmaWxlIjoic3JjL3NhZmV0eS9ncmFuaXRlX2d1YXJkaWFuL3V0aWxzLnB5IiwiaWQiOiJmXzUxMmI5YTEzZGIzNGJkZTMiLCJsaW5lIjo4MCwiYWN0aW9uYWJsZSI6dHJ1ZX0seyJzZXZlcml0eSI6Im1lZGl1bSIsImNhdGVnb3J5IjoibG9naWMtZXJyb3IiLCJmaWxlIjoic3JjL3NhZmV0eS9yZWRhY3Rpb24vY2FwYWJpbGl0eS5weSIsImlkIjoiZl81NmNlMzIwODUxZDUzNGE5IiwibGluZSI6MzYsImFjdGlvbmFibGUiOnRydWV9LHsic2V2ZXJpdHkiOiJsb3ciLCJjYXRlZ29yeSI6ImVkZ2UtY2FzZSIsImZpbGUiOiJzcmMvc2FmZXR5L2dyYW5pdGVfZ3VhcmRpYW4vY2FwYWJpbGl0eS5weSIsImlkIjoiZl81ZGYxMDYzMTFjNDBjNmRlIiwibGluZSI6NjksImFjdGlvbmFibGUiOnRydWV9LHsic2V2ZXJpdHkiOiJsb3ciLCJjYXRlZ29yeSI6Im1pc3NpbmctdGVzdCIsImZpbGUiOiJ0ZXN0cy91bml0L3NhZmV0eS90ZXN0X2Jhc2UucHkiLCJpZCI6ImZfNzAwMzUyZWZkNzU5Nzk4ZiIsImFjdGlvbmFibGUiOnRydWV9LHsic2V2ZXJpdHkiOiJsb3ciLCJjYXRlZ29yeSI6ImluamVjdGlvbi12dWxuIiwiZmlsZSI6InNyYy9zYWZldHkvcmVkYWN0aW9uL2NhcGFiaWxpdHkucHkiLCJpZCI6ImZfMmRkMDQzNjlkZmFmNjExYiIsImxpbmUiOjY1LCJhY3Rpb25hYmxlIjp0cnVlfSx7InNldmVyaXR5IjoibG93IiwiY2F0ZWdvcnkiOiJkYXRhLWV4cG9zdXJlIiwiZmlsZSI6InNyYy9zYWZldHkvYmFzZS5weSIsImlkIjoiZl8zNmNmNmEzZWM4ZThiOGM1IiwibGluZSI6MTg2LCJhY3Rpb25hYmxlIjpmYWxzZX0seyJzZXZlcml0eSI6ImxvdyIsImNhdGVnb3J5IjoiaW5qZWN0aW9uLXZ1bG4iLCJmaWxlIjoic3JjL3NhZmV0eS9ncmFuaXRlX2d1YXJkaWFuL3V0aWxzLnB5IiwiaWQiOiJmXzNmMDE2Njg1NzgwMTczZmQiLCJsaW5lIjo2NiwiYWN0aW9uYWJsZSI6ZmFsc2V9XX0= --> ReviewFindingsHigh
Medium
Low
Labels: PR introduces a new safety capability framework with guardrails and PII redaction. Next steps:
Previous run (2)ReviewReason: 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`.
de6ef36 to
293d9d6
Compare
|
🤖 Finished Review · ✅ Success · Started 2:27 PM UTC · Completed 2:44 PM UTC Commit: Runtime: pi · Model: opus → claude-opus-4-6 · Effort: high · Cost: $5.82 |
… 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.
|
🤖 Finished Review · ✅ Success · Started 5:13 PM UTC · Completed 5:34 PM UTC Commit: Runtime: pi · Model: opus → claude-opus-4-6 · Effort: high · Cost: $4.93 |
| try: | ||
| if "output" in self.type: | ||
| state: OutputState = OutputState() | ||
| async for event in stream: |
There was a problem hiding this comment.
[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("<"): |
There was a problem hiding this comment.
[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"] |
There was a problem hiding this comment.
[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]) |
There was a problem hiding this comment.
[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() |
There was a problem hiding this comment.
[low] injection-vuln
Regex patterns from configuration are compiled without ReDoS guards. Operator-controlled configuration, not end-user input.
| try: | ||
| if "output" in self.type: | ||
| state: OutputState = OutputState() | ||
| async for event in stream: |
There was a problem hiding this comment.
[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" |
There was a problem hiding this comment.
[low] injection-vuln
build_guardian_block interpolates criteria into the guardian prompt template without sanitization. Operator-controlled configuration, not end-user input.
Description
Sorry for the huge PR!
This is a PR that aims to refactor the safety capabilities through abstraction.
Type of change
pyproject.toml+uv.lock]requirements.*.txtfor Konflux]Tools used to create PR
Identify any AI code assistants used in this PR (for transparency and review context)
Related Tickets & Documents
Checklist before requesting a review
Testing