Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions sdk/python/src/openlit/guard/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@
def _validate_json_schema(
data: Any, schema: Dict[str, Any], path: str = ""
) -> Optional[str]:
"""Minimal recursive JSON schema validator (type, required, properties)."""
"""Minimal recursive JSON schema validator (type, required, properties).

``type`` may be a single name or a list of names, such as
``["string", "null"]`` for a nullable field.
"""
schema_type = schema.get("type")
types = schema_type if isinstance(schema_type, list) else [schema_type]
if schema_type:
type_map = {
"object": dict,
Expand All @@ -28,18 +33,25 @@ def _validate_json_schema(
"boolean": bool,
"null": type(None),
}
expected = type_map.get(schema_type)
# In Python, bool is a subclass of int, but JSON Schema treats booleans
# as a separate primitive type from numbers.
is_boolean_for_numeric = (
schema_type in ("integer", "number") and isinstance(data, bool)
)
if expected and (is_boolean_for_numeric or not isinstance(data, expected)):

# Unknown or non-string names are ignored. When none are known, the type
# is not checked, as for a single unknown type.
known = [name for name in types if isinstance(name, str) and name in type_map]

def matches(name: str) -> bool:
# In Python, bool is a subclass of int, but JSON Schema treats booleans
# as a separate primitive type from numbers.
if name in ("integer", "number") and isinstance(data, bool):
return False
return isinstance(data, type_map[name])

if known and not any(matches(name) for name in known):
return (
f"Expected {schema_type} at {path or 'root'}, got {type(data).__name__}"
f"Expected {' or '.join(known)} at {path or 'root'}, "
f"got {type(data).__name__}"
)

if schema_type == "object" and isinstance(data, dict):
if "object" in types and isinstance(data, dict):
for field_name in schema.get("required", []):
if field_name not in data:
return f"Missing required field '{field_name}' at {path or 'root'}"
Expand All @@ -53,7 +65,7 @@ def _validate_json_schema(
if err:
return err

if schema_type == "array" and isinstance(data, list):
if "array" in types and isinstance(data, list):
items_schema = schema.get("items")
if items_schema:
for i, item in enumerate(data):
Expand Down
78 changes: 78 additions & 0 deletions sdk/python/tests/test_guard_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest

from openlit.guard._base import GuardAction
from openlit.guard._pipeline import Pipeline
from openlit.guard.schema import Schema


Expand Down Expand Up @@ -30,3 +31,80 @@ def test_boolean_schema_accepts_boolean():
result = Schema(schema={"type": "boolean"}).evaluate("true")

assert result.action == GuardAction.ALLOW


# OpenAI strict structured outputs write an optional field as a union with null.
NULLABLE_SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string"},
"nickname": {"type": ["string", "null"]},
},
"required": ["name", "nickname"],
}


@pytest.mark.parametrize(
"text", ['{"name": "Ada", "nickname": null}', '{"name": "Ada", "nickname": "A"}']
)
def test_type_list_accepts_any_listed_type(text):
"""A value matching any type in a list of types passes."""
result = Schema(schema=NULLABLE_SCHEMA).evaluate(text)

assert result.action == GuardAction.ALLOW


@pytest.mark.parametrize("value", ["42", "true", "[]"])
def test_type_list_rejects_other_types(value):
"""A value matching none of the listed types is denied, not raised."""
text = f'{{"name": "Ada", "nickname": {value}}}'
result = Schema(schema=NULLABLE_SCHEMA).evaluate(text)

assert result.action == GuardAction.DENY
assert result.classification == "schema_mismatch"
assert "string or null at .nickname" in result.explanation


def test_type_list_still_rejects_boolean_for_numbers():
"""Booleans stay out of numeric types inside a list of types."""
result = Schema(schema={"type": ["integer", "null"]}).evaluate("true")

assert result.action == GuardAction.DENY


def test_type_list_checks_nested_objects_and_arrays():
"""Properties and items are still checked when the type is a list."""
schema = {
"type": ["object", "null"],
"properties": {"tags": {"type": ["array", "null"], "items": {"type": "string"}}},
}

assert Schema(schema=schema).evaluate("null").action == GuardAction.ALLOW
assert Schema(schema=schema).evaluate('{"tags": ["a"]}').action == GuardAction.ALLOW
result = Schema(schema=schema).evaluate('{"tags": ["a", 1]}')
assert result.action == GuardAction.DENY
assert "at .tags[1]" in result.explanation


def test_pipeline_denies_type_list_mismatch_instead_of_failing_open():
"""With the default fail_open, the guard must deny rather than raise and allow."""
result = Pipeline(guards=[Schema(schema=NULLABLE_SCHEMA)]).evaluate(
'{"name": "Ada", "nickname": 42}', phase="postflight"
)

assert result.action == GuardAction.DENY


@pytest.mark.parametrize(
"schema_type, value, action",
[
(["strng", "null"], "42", GuardAction.DENY),
(["strng", "null"], "null", GuardAction.ALLOW),
(["strng"], "42", GuardAction.ALLOW),
],
)
def test_type_list_ignores_unknown_names(schema_type, value, action):
"""Unknown names never match; with no known name left the type is not checked."""
result = Schema(schema={"type": schema_type}).evaluate(value)

assert result.action == action
Loading