Skip to content

json-schema: prevent out-of-bounds and stack overflow in regex parsing for GBNF - #22606

Open
AryanGold wants to merge 1 commit into
ggml-org:masterfrom
AryanGold:fix-gbnf-regex-bounds
Open

AryanGold wants to merge 1 commit into
ggml-org:masterfrom
AryanGold:fix-gbnf-regex-bounds

Conversation

@AryanGold

Copy link
Copy Markdown

Overview

By experimenting with structured outputs, I noticed that llama-server crashes via Segfault if it receives a malformed regex pattern in a JSON schema (e.g., pattern: "^+[a-z]$" or pattern: "^{2}times$").

The crash happens in common_schema_converter::_visit_pattern because the quantifier branches evaluate before ensuring the seq vector has elements, leading to seq.back() accessing unallocated memory. Additionally, deeply nested parentheses can cause the recursive transform lambda to exhaust the call stack.

Changes in this PR:

  • Added if (seq.empty()) bounds checks for *, +, ?, and { branches, returning a descriptive error.

  • Added a depth parameter to the recursive transform() lambda, capping nesting at 100 to gracefully return an error instead of overflowing the stack.

Additional information

Reproduction Script

This Python script consistently crashes the unpatched server by passing a malformed regex in the response_format JSON schema. With this patch, the server gracefully returns a 400 error indicating the pattern is invalid.

import requests
import json

payload = {
    "model": "local-model",
    "messages":[{"role": "user", "content": "Extract the street name"}],
    "response_format": {
        "type": "json_schema",
        "json_schema": {
            "name": "geocoding_extraction",
            "schema": {
                "type": "object",
                "properties": {
                    "street_name": {
                        "type": "string",
                        "pattern": "^+[a-zA-Z0-9 ]$"  # The trigger
                        #"pattern": "^{2}times$"      # Another payload
                    }
                }
            }
        }
    }
}

try:
    requests.post("http://127.0.0.1:8080/v1/chat/completions", json=payload)
    print("Request processed successfully.")
except requests.exceptions.ConnectionError:
    print("Server crashed.")

After patching, the server returns error messages for wrong payloads:

"^+[a-zA-Z0-9 ]$"

operator (): got exception: {"error":{"code":400,"message":"JSON schema conversion failed:\nQuantifier '+' appears without preceding token","type":"invalid_request_error"}}

"^{2}times$"

operator (): got exception: {"error":{"code":400,"message":"JSON schema conversion failed:\nQuantifier '{2}' appears without preceding token","type":"invalid_request_error"}}

Tested on Windows 10 x64, Gemma-4 model.

Requirements

  • I have read and agree with the contributing guidelines

  • AI usage disclosure: NO - The core fix was authored by a human contributor. AI was used to double-check that everything was fixed, and for grammar suggestions on the PR description.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant