Skip to content

fix: honor Schema guard json_mode flag - #2001

Open
feiiiiii5 wants to merge 1 commit into
openlit:mainfrom
feiiiiii5:feiiiiii5/issue-contract-openlit-jsonmode
Open

feiiiiii5 wants to merge 1 commit into
openlit:mainfrom
feiiiiii5:feiiiiii5/issue-contract-openlit-jsonmode

Conversation

@feiiiiii5

@feiiiiii5 feiiiiii5 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: #1999

Change description:

The Schema guard docstring documented json : bool but the actual parameter was json_mode, stored and never read: evaluate() always applied schema validation, and the documented keyword raised TypeError. The docstring now matches the parameter, and json_mode=True returns a clean ALLOW after successful JSON parsing (invalid JSON is still rejected). Default behavior is 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 new ALLOW case; with the fix test_guard_schema.py is 14 passed and the full guard suite is 81 passed. Ruff findings are pre-existing on base. Provider live tests were not run (no credentials); this is an offline guard-unit fix.

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

Fix Schema guard JSON-only mode so it validates parseability without enforcing a schema.

Bug Fixes:

  • Honor json_mode=True in the Schema guard by allowing valid JSON without applying schema validation, while continuing to reject invalid JSON and preserving default schema validation behavior.

Enhancements:

  • Correct the Schema guard documentation to name the json_mode parameter.

Tests:

  • Add coverage for JSON-only mode, invalid JSON rejection, and unchanged schema-mismatch behavior.

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

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Document the actual json_mode parameter and make successful JSON parsing bypass schema validation when that mode is enabled.

  • sdk/python/src/openlit/guard/schema.py L87, L121-123

Tests

Cover JSON-only mode, invalid JSON rejection, and unchanged default schema validation.

  • sdk/python/tests/test_guard_schema.py L111-137

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

Honor Schema guard json_mode when validating JSON output

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 Less than 10 minutes

Grey Divider

AI Description

• Allow parseable JSON when json_mode=True, even if it does not match the supplied schema.
• Continue rejecting invalid JSON and validating schemas by default.
• Correct the parameter documentation and test all three behaviors.
Merge Risk 🟢 Low

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed behavior is one bounded postflight guard capability: deciding whether model output is accepted based on JSON parseability and, when enabled, schema conformance.
  • The test contract confirms the same end-to-end acceptance behavior rather than an independent consumer capability.
Behavioral complexity 🟢 Low 🧩 Straightforward

  • Before, successful JSON parsing always proceeded to configured schema validation.
  • After, the new json_mode branch returns immediately after parsing.
  • The new correctness condition is that json_mode must bypass only schema checks while invalid JSON still follows the existing denial path and default mode still validates schemas.
  • This is a direct conditional using the existing parsing and validation pipeline, without new state, ordering, transformation, or coordination.
Sources

sdk/python/tests/test_guard_schema.py[112-119]

def test_json_mode_allows_parseable_json_even_on_schema_mismatch():
    """json_mode=True skips schema checks once output parses as JSON."""
    result = Schema(
        action="deny", json_mode=True, schema={"type": "integer"}
    ).evaluate('"hello"')

    assert result.action == GuardAction.ALLOW
    assert result.classification == ""
Potential damage 🟡 Medium 🩹 Recoverable

  • If json_mode is incorrectly used where schema conformance is required, parseable but structurally mismatched output can pass this guard.
  • No repository evidence shows persistence or external side effects; downstream handling could reject or mishandle that output, but recovery would consist of correcting configuration/code and retrying the request.
  • Reverting the guard restores schema enforcement for future evaluations; any already-accepted output would need to be revalidated or replayed if a consumer relied on the schema.
Sources

sdk/python/tests/test_guard_schema.py[112-119]

def test_json_mode_allows_parseable_json_even_on_schema_mismatch():
    """json_mode=True skips schema checks once output parses as JSON."""
    result = Schema(
        action="deny", json_mode=True, schema={"type": "integer"}
    ).evaluate('"hello"')

    assert result.action == GuardAction.ALLOW
    assert result.classification == ""
Assessed commit 5cb16aa
Diagram

graph TD
  A["Output text"] --> B["Parse JSON"] --> C{"Valid JSON?"} -->|yes| D{"JSON mode?"} -->|no| E{"Schema matches?"} -->|yes| F["Allow"]
  C -->|no| G["Configured action"]
  D -->|yes| F
  E -->|no| G
Loading
High-Level Assessment

The early return after parsing is the simplest way to honor the existing flag. It preserves invalid-JSON rejection and leaves default schema validation unchanged; a separate JSON-only guard would add unnecessary API complexity.

Files changed (2) +32 / -1

Bug fix (1) +4 / -1
schema.pyHonor json_mode after successful JSON parsing +4/-1

Honor json_mode after successful JSON parsing

• Returns a clean ALLOW result before schema validation when json_mode is enabled, while retaining invalid-JSON rejection and default schema checks. Corrects the docstring parameter name from json to json_mode.

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

Tests (1) +28 / -0
test_guard_schema.pyCover JSON-only mode and unchanged validation behavior +28/-0

Cover JSON-only mode and unchanged validation behavior

• Adds tests confirming that JSON-only mode allows a schema mismatch but rejects invalid JSON. A third test confirms that default mode still rejects a schema mismatch.

sdk/python/tests/test_guard_schema.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 (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Schema checks are silently skipped when json_mode is set 🐞 Bug ≡ Correctness
Description
evaluate() returns a bare ALLOW as soon as self._json_mode is true, before the `if
self._schema: branch runs, so a Schema built with both json_mode=True and a schema` dict never
validates the structure. Any output that parses as JSON is allowed, including outputs that violate
the schema the caller explicitly supplied.
Code

sdk/python/src/openlit/guard/schema.py[R109-110]

+        if self._json_mode:
+            return GuardResult(guard_name=self.name)
Evidence
The early return is added ahead of the schema check, so the schema branch is unreachable whenever
json_mode is true. The PR's own test test_json_mode_allows_parseable_json_even_on_schema_mismatch
encodes this skip for a case with schema={"type": "integer"}, but the ticket's expected behavior
describes only the JSON-parse check passing, not schema validation being dropped.

sdk/python/src/openlit/guard/schema.py[106-116]
sdk/python/tests/test_guard_schema.py[35-42]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
Issue description: In `Schema.evaluate` in sdk/python/src/openlit/guard/schema.py, the new `if self._json_mode: return GuardResult(guard_name=self.name)` returns ALLOW before the schema check, so a caller passing both json_mode=True and a schema gets no schema validation.
Fix Focus Areas:
- sdk/python/src/openlit/guard/schema.py[106-116]
- sdk/python/tests/test_guard_schema.py[35-42]
Recommended Fix: Only skip schema validation when no schema was provided, e.g. `if self._json_mode and not self._schema: return GuardResult(guard_name=self.name)`, or keep the early return and reject the combination in `__init__` with a ValueError. Update the test so a json_mode=True plus schema call is either validated or rejected, and keep a separate test for json_mode=True alone returning ALLOW.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


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 3 issues

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

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/guard/schema.py" line_range="109-110" />
<code_context>
                 explanation=f"Output is not valid JSON: {exc}",
             )

+        if self._json_mode:
+            return GuardResult(guard_name=self.name)
+
         if self._schema:
</code_context>
<issue_to_address>
**String false bypasses schema checks**

When `json_mode` comes from an unparsed configuration value such as the environment string `"false"`, `self._json_mode` is truthy for the string `"false"`, so `evaluate()` returns ALLOW without checking the schema and accepts schema-mismatched output.

Validate that `json_mode` is a boolean at construction, or explicitly parse supported string values before storing it.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/guard/schema.py" line_range="109-110" />
<code_context>
                 explanation=f"Output is not valid JSON: {exc}",
             )

+        if self._json_mode:
+            return GuardResult(guard_name=self.name)
+
         if self._schema:
</code_context>
<issue_to_address>
**Invalid JSON passes the guard**

When JSON-only mode receives `NaN`, `Infinity`, or `-Infinity`, `json.loads` accepts these non-standard constants, so `evaluate()` reaches the JSON-mode ALLOW return and callers see invalid JSON pass the guard.

Reject non-standard constants during JSON parsing before returning ALLOW.
</issue_to_address>

### Comment 3
<location path="sdk/python/src/openlit/guard/schema.py" line_range="109" />
<code_context>
                 explanation=f"Output is not valid JSON: {exc}",
             )

+        if self._json_mode:
+            return GuardResult(guard_name=self.name)
+
</code_context>
<issue_to_address>
**Valid JSON is denied on schema mismatch**

When a TypeScript caller enables `jsonMode` and supplies parseable JSON that does not match the schema, typeScript `Schema.evaluate()` still validates `_schema` instead of returning ALLOW after parsing, so callers see a schema-mismatch denial.

Make TypeScript `Schema.evaluate()` return ALLOW after successful parsing when `jsonMode` is enabled, before validating the schema.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: sdk/python/src/openlit/guard/schema.py:110, sdk/python/src/openlit/guard/schema.py:110, sdk/python/src/openlit/guard/schema.py:109


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

Comment on lines +109 to +110
if self._json_mode:
return GuardResult(guard_name=self.name)

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.

🟡 Medium · String false bypasses schema checks

When json_mode comes from an unparsed configuration value such as the environment string "false", self._json_mode is truthy for the string "false", so evaluate() returns ALLOW without checking the schema and accepts schema-mismatched output.

Validate that json_mode is a boolean at construction, or explicitly parse supported string values before storing it.

Prompt for AI agents
In `sdk/python/src/openlit/guard/schema.py` at lines 109-110:

**String false bypasses schema checks**

When `json_mode` comes from an unparsed configuration value such as the environment string `"false"`, `self._json_mode` is truthy for the string `"false"`, so `evaluate()` returns ALLOW without checking the schema and accepts schema-mismatched output.

Validate that `json_mode` is a boolean at construction, or explicitly parse supported string values before storing it.

Comment on lines +109 to +110
if self._json_mode:
return GuardResult(guard_name=self.name)

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.

🟡 Medium · Invalid JSON passes the guard

When JSON-only mode receives NaN, Infinity, or -Infinity, json.loads accepts these non-standard constants, so evaluate() reaches the JSON-mode ALLOW return and callers see invalid JSON pass the guard.

Reject non-standard constants during JSON parsing before returning ALLOW.

Prompt for AI agents
In `sdk/python/src/openlit/guard/schema.py` at lines 109-110:

**Invalid JSON passes the guard**

When JSON-only mode receives `NaN`, `Infinity`, or `-Infinity`, `json.loads` accepts these non-standard constants, so `evaluate()` reaches the JSON-mode ALLOW return and callers see invalid JSON pass the guard.

Reject non-standard constants during JSON parsing before returning ALLOW.

Comment thread sdk/python/src/openlit/guard/schema.py Resolved
@feiiiiii5
feiiiiii5 force-pushed the feiiiiii5/issue-contract-openlit-jsonmode branch from 103a705 to 5cb16aa Compare November 29, 2026 14:23

This branch was previously deployed

1 inactive (outdated) deployment
release-notes — 103a705c Deployed Nov 23, 2026 by feiiiiii5 via Normalize / Conventional title #891
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