Skip to content

fix(python-sdk): accept a list of types in the schema guard - #1998

Merged
AmanAgarwal041 merged 2 commits into
openlit:mainfrom
shlokbam:fix/schema-guard-type-list
Nov 28, 2026
Merged

AmanAgarwal041 merged 2 commits into
openlit:mainfrom
shlokbam:fix/schema-guard-type-list

Conversation

@shlokbam

@shlokbam shlokbam commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: Fixes #1997

Change description:

Schema crashed with TypeError: unhashable type: 'list' when a schema used a list of types such as ["string", "null"], the usual way to write a nullable field. With the default fail_open=True the pipeline turned that crash into allow, so invalid outputs passed.

_validate_json_schema now treats type as a list of names (a single name becomes a one-item list):

  • a value passes if it matches any listed type
  • booleans still don't count as integer or number
  • required, properties and items are still checked when the list contains object or array
  • the error names every type, e.g. Expected string or null at .nickname, got int

Single-type schemas behave exactly as before.

Tests

New cases in tests/test_guard_schema.py: list types accept null and a string, deny 42, true and [], keep rejecting booleans for ["integer", "null"], check nested properties and array items, and a Pipeline with the default fail_open now denies instead of allowing.

  • On main, the 8 new tests fail (TypeError); with the fix, tests/test_guard_schema.py and tests/test_guard_pipeline.py pass (34 passed).
  • I also compared the validator with jsonschema on 4000 random schemas using type, required, properties and items, including lists of types: no disagreements (main raises on them).
  • pylint on the changed files: 10.00/10.

Checklist

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

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

Update the Python schema guard to correctly validate fields declared with multiple JSON Schema types.

Bug Fixes:

  • Support JSON Schema type arrays so nullable and union-typed fields are validated without raising errors or incorrectly allowing invalid values.

Enhancements:

  • Preserve numeric boolean exclusions and nested object and array validation for schemas using multiple types.
  • Clarify validation errors by listing all accepted types and retain existing behavior for single or unknown types.

Tests:

  • Add coverage for accepted and rejected union types, nullable fields, nested properties and array items, unknown type names, numeric booleans, and fail-open pipeline behavior.

@shlokbam
shlokbam requested review from a team and ishanjainn as code owners November 23, 2026 15:25
@sourcery-ai

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Update schema validation to accept lists of JSON Schema types, preserve numeric boolean semantics, and validate nested objects and arrays when their allowed types include those structures.

  • sdk/python/src/openlit/guard/schema.py L19-25, L36-54, L68

Tests

Add coverage for nullable and union types, unknown type names, nested validation, and pipeline denial of mismatched values.

  • sdk/python/tests/test_guard_schema.py L6, L34-110

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

Fix schema guard validation of lists of JSON types

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Accept JSON Schema type lists, including nullable fields, without raising an exception.
• Preserve nested validation and report mismatches instead of allowing invalid output through the
 fail-open pipeline.
• Test accepted and rejected values, nested schemas, and pipeline behavior.
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 changed validator and the postflight integration jointly implement one bounded behavior: validating provider output against a caller-supplied schema before returning it.
  • The integration invokes the pipeline on extracted output and raises on DENY, so the validator's result directly determines this guard-enforcement outcome.
Behavioral complexity 🟡 Medium 🧩 Compatibility cases, Interacting branches

  • Before: schema_type was treated as one scalar name, and object/array recursion was entered only when that scalar exactly equaled "object" or "array".
  • After: schema_type may be scalar or a list; known names are filtered, any known name may match, numeric booleans remain excluded, and object/array recursion is enabled when those names occur anywhere in the list.
  • New correctness condition: union validation must preserve legacy scalar behavior while correctly handling nullable and mixed object/array unions, unknown names, nested properties/items, and the distinction between JSON booleans and numeric types.
  • The branches are local and deterministic; no new concurrency, persistence, or ordering protocol is introduced.
Potential damage 🟡 Medium 🩹 Recoverable

  • A false allow can pass schema-invalid output to the caller's normal response-processing path.
  • The repository does not show persistent storage or an external side effect caused by this guard decision, so recovery is generally a request retry, caller-side validation, or correcting/reverting the guard configuration.
  • The exact downstream application response is outside this repository and is therefore an assumption.
  • Reverting the SDK restores the former scalar-type behavior, but it does not repair any caller-side interpretation already performed.
  • Recovery prerequisites are another request or explicit caller validation; no automatic repair worker or compensation path is shown.
Assessed commit 7bc3e2b
Diagram

graph TD
  A["JSON output"] --> B["Schema guard"] --> C{"Allowed type?"} -->|yes| D["Nested validation"] --> E["Guard result"] --> F["Pipeline decision"]
  C -->|no| E
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use a full JSON Schema validator
  • ➕ Provides broader standards coverage and delegates validation edge cases to an established library.
  • ➖ Adds a dependency and broadens the scope beyond this guard's deliberately minimal validator.

Recommendation: Keep the focused fix: it supports the guard's existing schema subset without adding a dependency. Consider a full validator separately if broader JSON Schema compatibility becomes a requirement.

Files changed (2) +85 / -11

Bug fix (1) +22 / -11
schema.pyValidate against any declared JSON type +22/-11

Validate against any declared JSON type

• Normalizes a single type or type list for matching, preserves the boolean-versus-number distinction, and reports all expected types on mismatch. Object and array constraints remain active when those types appear in a list.

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

Tests (1) +63 / -0
test_guard_schema.pyCover type lists and fail-open pipeline behavior +63/-0

Cover type lists and fail-open pipeline behavior

• Adds cases for nullable values, mismatched types, numeric booleans, and nested object and array validation. A pipeline test verifies that a mismatch returns DENY rather than becoming ALLOW through exception handling.

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 (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Malformed unions let invalid outputs through ✓ Resolved
Description
matches() returns True when a type-list member is unknown or is not a string, so that member
satisfies any() regardless of the output value. For {"type": ["string", "bogus"]},
Schema.evaluate("42") returns allow, and a pipeline with fail_open=False does not raise because
validation never reports an error.

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display > Comment parts

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit 7bc3e2b

#1997 Bug: Schema guard crashes on a list of types, so the default pipeline allows every output · 3 of 3 met

# Requirement Status Notes
1 Accept a value matching any type in a type list. ✅ Met The validator accepts a value when it matches any known listed type.
2 Deny a value matching none of the listed types with schema_mismatch. ✅ Met A type-list mismatch returns a validation error, which Schema.evaluate reports as schema_mismatch.
3 Ensure the default pipeline denies invalid output instead of allowing it after a validation error. ✅ Met The added pipeline test checks that a mismatched nullable field is denied with the default fail_open setting.

@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 2 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="40" />
<code_context>
+        def matches(name: Any) -> bool:
+            expected = type_map.get(name) if isinstance(name, str) else None
+            if expected is None:
+                return True
+            # In Python, bool is a subclass of int, but JSON Schema treats booleans
+            # as a separate primitive type from numbers.
</code_context>
<issue_to_address>
**Invalid schema types allow output**

When a schema type list contains an unsupported, misspelled, or non-string member, `matches` returns `True` for that member, so `any(matches(name) for name in types)` accepts values that match none of the recognized types and the schema guard allows invalid output.

Make `matches` reject unsupported or non-string type members instead of treating them as matches.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/guard/schema.py" line_range="45" />
<code_context>
+            # as a separate primitive type from numbers.
+            if name in ("integer", "number") and isinstance(data, bool):
+                return False
+            return isinstance(data, expected)
+
+        if not any(matches(name) for name in types):
</code_context>
<issue_to_address>
**Integral JSON numbers are denied**

When a value such as `1.0` is checked against a type list containing `integer`, `matches` uses `isinstance(data, int)` for `integer`, but `json.loads` parses `1.0` as a float, so the schema guard denies valid output.

Treat JSON numbers with an integral value as integers while continuing to exclude booleans.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: sdk/python/src/openlit/guard/schema.py:40, sdk/python/src/openlit/guard/schema.py:45


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

Comment thread sdk/python/src/openlit/guard/schema.py Resolved
Comment thread sdk/python/src/openlit/guard/schema.py Resolved
@shlokbam

Copy link
Copy Markdown
Contributor Author

Qodo's "Malformed unions let invalid outputs through" finding is fixed in 7bc3e2b as well: unknown or non-string names in a type list are now ignored instead of treated as a match, so {"type": ["string", "bogus"]} denies 42. Tests added.

@shlokbam

Copy link
Copy Markdown
Contributor Author

Hi @ishanjainn, gentle ping on this one when you have time. Both bot findings are addressed and the threads are resolved. Happy to change anything.

@AmanAgarwal041
AmanAgarwal041 merged commit 933cd70 into openlit:main Nov 28, 2026
5 checks passed
@github-actions

Copy link
Copy Markdown

Merged PR summary

  • Python SDK · Fixes — Python SDK schema guard now supports type lists for nullable and union-typed fields, validating them correctly and denying invalid outputs instead of allowing them under fail_open.

Generated from the merged PR description and bounded, component-scoped file evidence. Release preparation reuses this validated summary.

This branch was successfully deployed

1 active deployment
release-notes — 7bc3e2b2 Deployed Nov 28, 2026 by AmanAgarwal041 via Summarize / Merged pull request #341
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.

Bug: Schema guard crashes on a list of types, so the default pipeline allows every output

2 participants