← Inference From First Principles

Structured Outputs and Constrained Decoding

A schema compiled to a finite-state constraint over a real tokeniser, checked against the jsonschema library, Python's re and a reference implementation, and run on a 0.6-billion-parameter model: what a guaranteed-valid output costs, what it does not guarantee, and where it breaks.

A 0.6-billion-parameter model was asked to turn 200 short, synthetic order messages into JSON records. Without a decoding constraint, exactly half of its outputs (100 of 200) failed to parse as written. Every failure was a JSON object inside a Markdown code fence. Removing those fences made all 200 parse and satisfy the tested schema. With a schema-derived decoding constraint, all 200 outputs likewise parsed and validated, without requiring that lenient post-processing. The principal gain was therefore reliable structure in this experiment, rather than an independently demonstrated gain in the model’s understanding of orders.

The distinction appears when the records are compared with the messages that supplied their values. The constrained model produced 87 exactly correct records out of 200. The unconstrained model produced 80 once its fences were removed. The paired difference was +3.5 percentage points, with a 95% bootstrap interval of −0.5 to +7.5 points: the experiment does not establish a semantic-accuracy improvement over that inexpensive, lenient baseline. Of the constrained records, 113 were schema-valid but wrong. The most frequent errors were plural item names, old prices used instead of discounted prices, and 38 false gift labels changed to true for messages denying that an order was a gift. The schema constrained types and keys, not these meanings.

Two further experiments show where the contract stops. On 100 messages that never mentioned whether the order was a gift, a required boolean forced a value: every constrained output supplied false, even though the labelled ground truth for the absent fact was null. Changing the required property’s type to boolean-or-null made the constrained model write null 94 times out of 100. When generation was capped at 40 tokens, only 39 of 200 constrained outputs parsed as written, compared with five unconstrained outputs: a constraint can keep a partial sequence extendable without guaranteeing it will be finished before the token budget expires. These are separately measured outcomes, not contradictions of the validity guarantee for normally completed generations.

The model is Qwen3-0.6B, the records and expected answers come from a seeded synthetic generator, and the constrained decoder is a finite-state engine built for this chapter. Its validator, regular-expression automaton and token-index masks were checked independently against jsonschema 4.26.0, Python’s re and outlines_core 0.2.14; selected actual generations were compared as well. The exercise covers an intentionally restricted part of JSON Schema and one tokenizer on one GPU. The chapter’s plan called for schema validation, a finite-state constraint, invalid-schema cases and a contrast between structural validity and semantic accuracy. Those are the claims tested here. No provider API was called, and none of the local conformance checks certifies arbitrary JSON Schema support.

The question

There are four separate checks, not one: whether generation terminated normally, whether its text parses as JSON, whether the resulting value satisfies the schema, and whether its fields faithfully represent the source message. A system should record each outcome separately instead of calling them all “validity.”

text  ->  parses as JSON  ->  satisfies the schema  ->  says what the input said

A mask compiled from a schema restricts token choices so that the generated prefix can still become a member of a permitted language. If generation reaches an accepting state and ends normally, that yields an output in the compiler’s language; it does not prove that the output represents the source correctly. If the compiler omitted a schema keyword or if a token limit interrupts generation, even structural compliance can fail. The engineering questions are therefore: which subset of the schema does the compiler enforce, how was soundness checked, what is the mask’s compilation and per-token cost, how does termination interact with the constraint, and when should the application reject, repair or retry?

Where this sits

Chapter 5 turned logits into tokens; constrained decoding adds an eligibility mask before the sampler chooses among them. Chapter 9 measured decode-step time, so it supplies the cost denominator for mask overhead. Chapter 30 established validation, bounded retries and terminal outcomes; Chapters 31 and 34 distinguished protocol control tokens from untrusted data and demonstrated that a correct intermediate step does not imply a correct task. Chapter 33 provided this Qwen3 model, hardware and sampling settings, while Chapter 34 showed why valid JSON arguments are not sufficient authorisation to execute a tool. Here those connections become an executable chain: schema check → grammar compilation → token selection → completion check → independent validation → source-grounded correctness.

Where the starter was wrong

The starter’s FiniteStateDecoder contains one state and filters against a set of allowed strings. It can illustrate the idea that some outputs are permitted and others refused, but not the grammar’s evolving expectations after a key, colon or value. Its validate_json calls a library and reports the first problem. It has no model, tokeniser, schema compiler or handling for tokens that contain several characters and cross grammar boundaries. Its source and tests remain unchanged; no benchmark in this chapter is attributed to the starter. The new lab implements a restricted compiler and independently tests the language and the mask against reference tools.

The setup

The model and sampling. The experiments used Qwen3-0.6B (Apache-2.0), fixed at revision c1899de289a04d12100db370d81485cdf75e47ca, in float16 on a shared RTX 2060 12 GB GPU. Generation ran through Hugging Face generate, with thinking disabled, temperature 0.7, top-p 0.8, top-k 20, and an allowance of at most 160 new tokens per record. The tokenizer and model are the same as in Chapters 33–34. Those settings, rather than any generic claim about structured decoding, define the observed model behaviour; a separate 40-token cap was used only for the truncation experiment.

The extraction task. The input was one of four seeded templates for an order message, with names, items, quantities, prices, destinations, delivery priority and gift wording varied. A representative message mentions a kettle formerly priced at $24.50 but now $19.99, six units, a Leeds shipping destination rather than a Cork billing address, and an explicit statement that the order is not a gift. The target record has seven fields: customer, item (singular spelling), quantity (integer), unit_price (number), city, priority (standard or express) and gift (boolean). The labelled answer is generated alongside the message, so accuracy can be measured field by field. Distractors include list prices, alternative cities and corrected quantities. Twenty development messages (seed 1) were used for harness and prompt work; the reported main evaluation used 200 different messages (seed 2). A separate set of 100 messages with no gift statement (seed 3) tested absent information. An earlier evaluation in which one item was already plural was discarded, the item list was corrected, and all affected runs were repeated; the retained results come from the corrected task definition.

Scoring. Parsed means json.loads accepts the output as written; schema-valid means schema_core.validate accepts the parsed value; exact means the record matches the seeded reference for every field, with no additional fields. A separate plural-tolerant exact measure was introduced after the first run exposed item inflection as a major error, and must not replace the prespecified exact-match measure. Normal termination is an additional, independent flag. For the unconstrained baseline, the analysis also reports a lenient parse that removes surrounding text down to the JSON braces; those records are not the same as outputs that parsed unmodified.

The validator, and how it was checked

The validator: checking conformance

schema_core.validate implements the keyword families needed by the lab: basic types, enum and const; object properties, required and additionalProperties; homogeneous array items with item bounds; string lengths and regular-expression search via pattern; numeric bounds; and anyOf, oneOf, allOf and not. It returns a list of errors with paths such as $.tags[0]. JSON semantics are easy to get wrong when writing this in Python: true is not an integer even though bool subclasses int; 3.0 can satisfy JSON Schema’s integer type; numeric equality may equate 1 and 1.0 while distinguishing either from true; minLength counts Unicode code points; and pattern is a search unless the regex anchors the text. An irrelevant keyword such as required on an array does not make that array invalid. The method assumes the schema was checked first and is a deliberately partial validator, not a general replacement for an established JSON Schema implementation.

To check the validator rather than trust its examples, the lab compared its verdicts with jsonschema 4.26.0 using the Draft 2020-12 validator. Of 661 schema–instance cases, 61 were hand-written edge cases and 600 were generated by mutating records; the library accepted 318 and rejected 343, and the two implementations agreed on every case. This is regression evidence for the covered keywords and sampled inputs, not equivalence to the full Draft 2020-12 specification. In particular, schema constructs not implemented by this validator cannot be declared supported merely because these 661 cases passed.

Invalid schemas, unsatisfiable schemas, schemas the constraint cannot express

The first gate checks that the schema itself is valid under the chosen dialect. The second asks whether any value could satisfy it. The third asks whether the chosen compiler can express the relevant constraints. A production pipeline must report these separately: an invalid schema is an authoring defect, an empty accepted language is an impossible request, and an unsupported keyword is a capability mismatch. Treating all three as a generic decoding failure makes a schema bug look like a model failure.

An invalid schema fails the Draft 2020-12 metaschema: examples include {"type": "strin"}, {"required": "a"}, {"minimum": "3"}, {"items": [...]} in the old tuple-validation form, and {"anyOf": []}. On the lab’s 49-schema corpus, its check_schema and jsonschema both identified exactly 26 invalid schemas, with no disagreement on validity. A schema such as {"minLength": 2.0} was valid because the value is mathematically an integer under the dialect. This test checks the explicitly represented cases; unsupported dialect features, unknown annotation keywords and third-party extensions still require a deliberate handling policy.

A valid but unsatisfiable schema passes metaschema validation yet has no possible instance. Examples tested include contradictory length bounds, an empty enum, an integer enum containing only a string, and a required property disallowed by additionalProperties: false. The lab compiler raises UnsatisfiableSchema when it can prove that the resulting language contains no accepted string, including by reachability of the automaton’s start state. Six of the 23 schemas valid under the lab’s checker were classified this way. This is not a complete decision procedure for arbitrary JSON Schema: compilation itself is limited, and more expressive combinations may require other solvers or a separate satisfiability check.

A valid schema unsupported by this compiler is different again. Its regular-language generator deliberately refuses unimplemented features such as pattern, format, numeric ranges, oneOf, $ref, uniqueItems, an optional property or an array without an item schema; eleven of the 23 valid test schemas were in this group. That boundary belongs to schema_to_regex, not to finite automata in general. For instance, bounded integer ranges, fixed-format dates and finite enumerations can be recognised by finite-state machines; this compiler simply has no construction for those features. Unbounded uniqueness across arbitrary JSON values and unrestricted recursion need stronger machinery or bounded approximations. Silently dropping unsupported conditions would be unsafe: if the decoder’s language is broader than the schema, structurally fluent output can still violate the schema. This lab raises UnsupportedSchema instead.

The comparison with outlines_core 0.2.14 is a low-level API experiment, not a claim about every Outlines deployment. Its build_regex_from_schema returned a regex for four of the 26 schemas the Draft 2020-12 checker rejected; it errored on the other 22. Among 23 valid schemas it raised on three and returned regexes for twenty, one of which the lab’s regex engine could not compile. Five crafted counterexamples demonstrated gaps between regex acceptance and complete schema validation, including numerical bounds, uniqueItems, an impossible requirement and a mixed-type enum. Some other keywords, such as a tested pattern, format and oneOf, were enforced. These results establish that this function, in this installed version and on these cases, can compile a language weaker than the supplied schema. They do not establish whether the public Outlines package performs additional validation, which was not exercised. A sound system either proves supported-keyword coverage for its compiler or validates the final decoded object against the original schema, preferably both.

From a schema to a mask

From a schema to a mask

A language

A decoding constraint is a language of permitted output strings. For a schema S, schema_to_regex constructs a restricted regular language L of JSON encodings that should all validate under S: L ⊆ JSON(S). It intentionally chooses one spelling for many values—fixed key order, limited whitespace and limited string escapes—so equality between the two languages is neither claimed nor required for this example. A soundness requirement is stronger than observing a few valid examples: the compiler must not omit a schema restriction, and its token mask must not permit a path outside L. The chapter checks both properties on selected schemas and paths, but does not present a universal proof. For example, the supported object schema {"type":"object","properties":{"ok":{"type":"boolean"}},"required":["ok"],"additionalProperties":false} becomes

\{[ ]?"ok"[ ]?:[ ]?(?:true|false)[ ]?\}

The generated expression admits at most one space at selected separators, fixes object key order, and encodes a restricted range of JSON strings with common backslash escapes; numeric spellings use the usual optional sign, fraction and exponent syntax. minLength, maxLength, minItems and maxItems become bounded or unbounded repetition counts, and enum/const become alternations after candidates excluded by the rest of the supported schema are removed. anyOf is implemented as alternation only in a limited form. Tests sampled 1,597 accepted strings from four automata (order record, nullable gift, bounded array, nested object); all 1,597 parsed and validated. A further 1,600 records serialised with the tested json.dumps settings were accepted. Those are reassuring checks, not a formal proof for every supported schema or all possible Unicode encodings. Many valid JSON spellings, including different spacing and some Unicode escapes, are deliberately absent from L.

An automaton

CharDFA compiles that regular expression using a small parser, Thompson’s NFA construction and subset determinisation. Instead of iterating over every Unicode code point, the implementation partitions characters at the class boundaries appearing in the pattern; the order schema needed 50 classes and produced 161 reachable DFA states. Dead-end states are pruned so a token can be rejected when no completion in the language remains. On twelve selected patterns and 5,367 strings—including valid strings and nearby edits—its full-string verdicts agreed with Python’s re.fullmatch in every case. This is a finite-sample conformance test for a limited regex syntax, not a theorem that its parser implements all of Python re, or that a DFA construction makes every JSON Schema keyword expressible.

A mask over tokens

The DFA consumes characters, while a language model selects vocabulary tokens that may contain several characters. From state s, a candidate token t with decoded text c₁…cₖ is permitted only if running all those characters leaves the DFA in a live state: M_s(t) = 1 when δ*(s, c₁…cₖ) ≠ ⊥. This matters at grammar boundaries: a token may complete a number and include a comma, or close a quoted string and begin the next property. End-of-generation is permitted only at an accepting state. Masking then zeroes the probability of disallowed tokens and renormalises the remaining candidates:

p'(t | s) = p(t) · M_s(t) / Σ_u p(u) · M_s(u)

For this tokenizer the model’s logits have shape (B, V) with V = 151,936, and the mask is applied as scores.masked_fill(~mask, -inf) before ordinary sampling controls. While decoding continues, every chosen token is constrained to keep its decoded text on a live path in the compiler’s language. Completion is guaranteed only if a terminating token is eventually selected in an accepting state; a token ceiling can stop earlier. The resulting complete-output distribution is also not generally equal to the original model distribution conditioned on eventual validity: locally normalising among feasible next tokens ignores how much valid probability mass lies in their future continuations. Grammar-Aligned Decoding (Park et al., NeurIPS 2024) studies this distributional distinction; its proposed remedy is outside this experiment. No end-to-end change in distributional fidelity was measured here.

TokenIndex builds the eligible-token mask for a DFA state on demand, using NumPy transition-table operations grouped by token-text length. Of the 151,669 tokenizer entries inspected, 150,195 could be treated by this character-level index as non-empty, self-contained Unicode text; 1,448 byte-level token fragments could not be decoded independently, and 26 added tokens were excluded. The fragment restriction is a coverage limitation: it prevents some valid non-ASCII strings whose bytes cross token boundaries. The added-token restriction is a deliberate protocol-safety choice because this tokenizer uses tags and special markers that other layers may interpret structurally. A string-position mask can admit roughly 146,000 ordinary tokens, whereas the start of the order-record language allows only { and {". These counts describe this particular tokenizer, index representation and schema; other vocabulary sizes or token encodings require rebuilding the index.

The processor

class MaskProcessor:
    def __call__(self, input_ids, scores):
        if input_ids.shape[1] > self.width:                       # not the first step
            for r, tok in enumerate(input_ids[:, -1].tolist()):   # the token just chosen, per sequence
                if self.done[r]: continue
                if tok in index.eos_ids: self.done[r] = True
                else: self.states[r] = index.advance(self.states[r], tok)
        rows = [self.masks.eos_only if (self.done[r] or s == index.dfa.dead) else self.masks.get(s)
                for r, s in enumerate(self.states)]
        return scores.masked_fill(~torch.stack(rows), float("-inf"))

There is one DFA state per active sequence. After a token is sampled, the processor advances that row through the token’s decoded text; rows that have ended are masked to allow only the end token. In the tested Hugging Face generation path, the custom processor runs before temperature, top-k and top-p, so the sampler’s top-k ranking is taken among permitted tokens, not applied first and then intersected with the grammar. A separate CPU test with a tiny randomly initialised Qwen3 and the real tokenizer checks finished outputs against the language and unfinished outputs for a still-viable prefix. These are ordering and state-transition tests of this software path; they do not establish the same ordering in vLLM, SGLang, a fused sampler or any hosted service.

Against the reference

For an independent mask implementation, the experiment used outlines_core 0.2.14, a Rust component of Outlines, with the same regular expression. It compared allowed-token sets while walking generated token paths: 6,845 positions for the order schema and 6,423 for its nullable-gift variant. The comparisons include valid-document paths and mutated paths, but not every possible DFA state and vocabulary continuation. Comparing a common regex isolates token-index behaviour; it does not test whether the two products compile arbitrary JSON Schemas to equivalent languages.

On the compared paths the lab index never allowed a token excluded by the reference index. The reverse was not true for two documented classes of tokens. First, outlines_core admitted approximately 866 more byte fragments per compared position on average, because its byte-level representation can continue multi-byte characters that this character-level index excludes. Second, the reference admitted certain added-token IDs whose printable spellings look like protocol tags or markers when inside a JSON string; the experiment counted 56,712 such allow-set differences on the order schema. This is a potential integration hazard, not proof of a successful control-token injection: a serving runtime may treat the ID as ordinary data in that position, may filter it elsewhere, or may never sample it. The lab did not run an adversarial generation showing that those IDs change role or tool control. Chapter 34 explains why any stack that does interpret them structurally must exclude or escape them at this trust boundary.

As a behavioural cross-check, the two index implementations generated identical complete text on all 200 order messages when run through this particular model, prompt and sampling configuration. That result complements—but cannot replace—the allow-set comparison: the reference permitted tokens that the model did not select in those generations. It shows equivalent observed outputs on these 200 prompts, not equivalence of the two constraints for arbitrary prompts, Unicode strings, schemas or adversarial token selections.

What it costs

What constrained decoding costs

Compiling. The order schema took approximately 0.14 ms to compile to regex and 3.6 ms to determinise (161 states, 50 character classes). Tokenising the vocabulary into candidate text strings took another 0.17 s, and building the token index took 0.36 s. Precomputing all 161 state masks cost 0.72 s, with no individual mask above 6 ms. Thus the full cold lab preparation, including tokenizer-specific work and all eager masks, is closer to 1.25 s than to the regex compiler’s millisecond times; the individual stages must not be conflated. The reference constructed its regex index in approximately 0.52 s after about 0.49 s of vocabulary loading, a different accounting boundary. Reusing a schema and tokenizer amortises the preparation, while dynamically generating a different schema for each request can destroy that saving. Anthropic’s published structured-output documentation specifies a compiled-grammar cache lasting 24 hours since last use and a 180-second compilation timeout. OpenAI’s currently published guide identifies a first-use latency penalty for fine-tuned models, not a blanket requirement that every model compiles on every first request. These are provider contracts, not latency measurements from this machine.

Applying the mask. In the saved isolated latency experiment on one shared RTX 2060, a 25-row no-processor run averaged 70.2 ms per decode step and a no-op processor 70.2 ms. The lab’s mask processor averaged 71.1 ms per step, and its Python integration of the reference index 74.0 ms. Those figures suggest modest overhead for the tested launch-bound Hugging Face path, but they are not a perfectly matched fixed-step comparison: the saved rows record 64 steps for the unconstrained/no-op conditions and 55 for the constrained conditions, and sequence-length/context effects are not eliminated. The roughly +1.0 ms and +3.8 ms arithmetic differences therefore should not be presented as universal 1.4% and 5.4% causal speed penalties. The reference timing also includes this lab’s Python/Torch integration rather than isolating the Rust library. In the full extraction runs, measured per-step times differed more (66.9 ms unconstrained versus 78.4 ms constrained), with additional prompt and stopping differences. A controlled same-context, same-step latency benchmark and a throughput-under-load test are still needed. XGrammar’s published large speedup is the paper authors’ result on their comparison, not a performance result reproduced here.

The results

Condition (200 messages) Parses Schema-valid Exact (95% interval) Exact, plural item allowed Mean generated tokens per input
unconstrained, as written 100 100 42 (15.9 to 27.2%) 69 63.2
unconstrained, braces cut out 200 200 80 (33.5 to 46.9%) 141 63.2
unconstrained, repaired 200 200 80 141 63.2
unconstrained, validate and retry (3 samples) 100 100 42 69 129.4
constrained, schema in the prompt 200 200 87 (36.8 to 50.4%) 147 49.4
constrained, schema not in the prompt 200 200 40 (15.0 to 26.1%) 46 56.6
constrained by outlines_core (same regex) 200 200 87 147 49.4

The format failures were one failure. All 100 answers that did not parse were wrapped in a code fence (```json … ```); the other 100 were bare; every one was well-formed inside. Cutting to the first and last brace turned all 100 into valid records, and the repair routine (Python literals, single quotes, bare keys, trailing commas, a truncated ending) had nothing further to do: it changed no output beyond the cut. This is the ordinary failure of an instruction-tuned model asked for JSON, and the cheapest remedy is a line of leniency in the reader. A constraint removes it too, and removes the fence’s tokens, so an answer is 49 tokens and not 63.

Validate and retry did not repair the fences. The 100 initially unparsable outputs were returned with a generic error saying that the text was not JSON and asking for only a JSON object. Under this protocol and with up to three samples per affected input, the model returned fenced output again each time; 100 of 200 inputs therefore remained unparsable as written. Mean generated tokens per original input rose from 63.2 to 129.4, counting unchanged successful inputs alongside retried ones. This is a failure of that retry message and sampling setup, not evidence that retry is intrinsically worse than lenient parsing. A targeted explanation such as “remove the Markdown code fence” was not tested. A production parser should still validate the object after stripping a fence, and should reject ambiguous multiple-object or trailing-content cases rather than cutting arbitrary braces by default.

Validity did not establish semantic accuracy. Constrained outputs scored 87/200 exact, against 80/200 for unfenced, leniently parsed unconstrained outputs: +3.5 percentage points, paired bootstrap interval −0.5 to +7.5. The much larger +22.5-point gap against raw, unparsed unconstrained text is mainly the formatting failure and should not be described as improved extraction reasoning. The comparison is paired by input message, but different decoding conditions use different token streams and random draws; one seed per condition limits attribution. A third figure, plural-tolerant exact, was introduced after seeing the outputs and is explicitly exploratory. Schema-conforming wrong records—113 of 200—are not successes for a downstream order system merely because a decoder can parse them.

  • item: 78 wrong under the primary exact criterion. Each used a plural such as kettles where the labelled task required singular kettle; the schema itself allowed any string.
  • gift: 38 wrong, all labelled false but emitted true on negated descriptions such as “it is not a gift”. The boolean type was obeyed, the sentence’s meaning was not.
  • unit_price: 15 wrong, typically choosing the list price instead of the discounted price that the customer would pay.
  • quantity: two wrong; customer: none wrong. These field-error counts can overlap within an individual record, so they must not be added as if each wrong answer had exactly one cause.

The schema allowed each of these values because it expresses field types and a two-value priority enum, not a relationship between generated values and an order message. A more specialised schema could restrict item spelling with an enum or pattern, or rule out impossible prices within a known catalogue. It still could not generally prove that a price, negation or address was correctly extracted from arbitrary prose without adding source-dependent checks. That distinction is the system-design boundary: schema validation checks admissibility; business validation and source-grounded evaluation check truth.

Keeping the schema visible to the model mattered. Removing its textual description from the prompt while leaving the identical token-level constraint reduced exactly correct records from 87/200 to 40/200, a paired-by-message difference of 23.5 points (bootstrap interval 16 to 31). Both conditions generated 200/200 schema-valid outputs, since the mask still required the keys and basic types; what changed was the model’s guidance about the fields’ intended meanings. This result is specific to this prompt, schema, model and sampling run, and the prompts differ in length and token context as well as in instructions. It does not prove that every production model must receive a full JSON Schema verbatim: concise field descriptions or examples might supply the needed semantics at lower prompt cost, but that alternative was not tested.

A field the text does not mention

The absence experiment contains 100 additional messages with no evidence either way about gift; their reference annotation is null. The original schema still required gift to be a boolean, so correct representation of this unknown state was impossible. The experiment compares that contract with a modified one in which the property remains required but can be boolean or null:

Schema, decoding Parsed gift written Entire record exact
gift is boolean, unconstrained 59 false 59 times 0
gift is boolean, constrained 100 false 100 times 0
gift is required, boolean or null, unconstrained 60 null 57, false 3 19
gift is required, boolean or null, constrained 100 null 94, false 6 48

The last column is whole-record exact match, not merely accuracy of gift, and can be lowered by unrelated errors such as plural item names. In the required-boolean condition the constrained decoder returned false for all 100 absent-gift messages and the unconstrained generator returned false in all 59 outputs that parsed; both are invented definite values relative to the labelled unknown state. In the nullable condition, constrained decoding emitted null 94 times, and 48 records were entirely correct; the unconstrained run emitted null in 57 of the 60 parsed records, of which 19 were entirely correct. This is not evidence that nullable schemas automatically make models truthful. It demonstrates that representing unknown information in the output type is a prerequisite to expressing honest uncertainty. The field may be required in the JSON object while its value is nullable; that differs from making the property optional and absent altogether.

When the answer is cut off

The same 200 order messages were generated again with a maximum of 40 new tokens, below the mean length of a normal complete record. The table separates a model stop signal, raw JSON parsing, independent schema validation and post-hoc repair:

Decoding Normal stop Raw JSON parsed Raw schema-valid Parsed after repair (newly repaired) Newly repaired and schema-valid Newly repaired and entire-record exact
Unconstrained 3 5 5 81 (76) 4 3
Constrained 19 39 39 146 (107) 23 13

A prefix mask ensures that generated text stays extendable to a legal string while decoding continues, not that the model will select a legal ending before its budget is exhausted. Here 39 of 200 constrained outputs already parsed and validated as written despite only 19 reporting a normal stop: some sequences reached a complete JSON object exactly as the limit was met. The other 161 were incomplete or otherwise unparseable as written. Heuristic repair made 107 additional constrained strings parse, but only 23 of those additional repairs satisfied the entire schema, and just 13 exactly matched the source record. For unconstrained text, repair made 76 additional strings parse, but only four of those were schema-valid and three entirely correct. The distinction between “parsed after repair” and “schema-valid after repair” is essential. The application must inspect the generation stop reason and validate independently before committing a record or executing a downstream tool. A repaired document that invents missing values should be treated as a failed extraction, not a successful recovery.

What the providers document, which was not run

The hosted providers expose documented schema-conformance contracts, not the finite-state machine implemented here, and none was called in this chapter. OpenAI distinguishes Structured Outputs in strict JSON-schema mode from JSON mode, which addresses parsing but not the full schema. Its strict subset requires an object at the root, every object property listed as required, and additionalProperties: false; a nullable union is the documented way to represent a required field whose value may be unknown. The supported subset includes anyOf, selected string patterns/formats, numeric limits and array length bounds, subject to model-specific constraints; allOf, not and conditional JSON Schema keywords are not supported in strict mode. Unsupported schemas are rejected, and an output can fall outside the schema when the model refuses or a generation is incomplete. The current OpenAI documentation qualifies first-schema latency specifically for fine-tuned models, so the original broad claim about every first request was too strong.

Anthropic documents JSON outputs via output_config.format and strict tool use via strict: true, with a different supported subset. It supports basic types, enum, const, anyOf, limited allOf, internal references and selected formats, but not arbitrary numeric bounds, recursion or arbitrary array constraints. It reports an error for unsupported schema features and documents compiled-grammar caching (24 hours since last use) and a compilation timeout (180 seconds). A refusal or max_tokens stop can produce an output that fails the schema, and the documentation warns of a string enum/const capitalization exception. Its SDK may additionally transform certain unsupported constraints before sending them and validate client-side; that behaviour must not be confused with server-side enforcement. SGLang documents interchangeable XGrammar, Outlines and llguidance backends, each with its own grammar coverage. These are provider/library claims as documented around 26 October 2026, not provider measurements. A real integration must pin API versions, validate the actual returned value, and handle refusal, incomplete generation, compile errors and downstream semantic checks as distinct outcomes.

What the numbers do not show

Synthetic extraction only. The retained order messages were generated from four templates and a limited name/item/city vocabulary, with labelled answers known by construction. This is strong for controlled error analysis but weak evidence for production extraction, where messages contain unseen formats, contradictions, irrelevant instructions, multiple orders or missing information in combinations the generator never produced.

One small model and one decoding stack. Qwen3-0.6B was run with one sampling configuration and tokenizer revision. Its plural-item and negated-gift mistakes should not be generalised to larger or instruction-tuned extraction models. A larger model may improve semantic accuracy without changing the usefulness of structural guarantees. Conversely, even a larger model can produce a wrong value that satisfies the schema.

A restricted regular compiler. The lab’s JSON output language has fixed key order and limited string encodings; it rejects recursion, numeric ranges, optional properties, general pattern, format, oneOf and $ref. Some of those omitted features are regular in suitable bounded forms and therefore possible in principle; they are simply not implemented. Unbounded nesting and richer inter-field constraints need more expressive parsing or validation. No guarantee is made for schemas rejected by this compiler, even if an upstream JSON Schema library considers them valid.

Timing is not serving performance. The GPU was shared, generation used a launch-bound Hugging Face loop, and the isolated timing samples had different effective step counts between constrained and unconstrained cases. Mask overhead in a fused engine with short decode steps, continuous batching, CPU/GPU overlap, compilation caches and diverse schemas is NOT_MEASURED. The full experiment’s tokens and per-step timings are preserved but are not a controlled throughput comparison.

One sample and a condition-dependent random stream. Each of 200 messages was evaluated under each condition, so paired problem-level correctness differences can be computed. That does not mean the conditions used identical stochastic draws: changing prompt length and the allowed token set changes the sampling trajectory. Bootstrap intervals quantify variation across these 200 synthetic inputs under the recorded runs, not uncertainty from multiple model seeds, alternative templates or repeated deployments.

A post-hoc secondary endpoint. The plural-tolerant exact-match score was added after item inflection emerged as the main constrained error. It is useful diagnostically, and its counts (147 constrained; 141 leniently parsed unconstrained) are disclosed, but it cannot replace the original strict score (87 and 80) in a prespecified performance claim. A publication-quality replication should declare both scoring policies and run on another held-out corpus.

Reference checks were narrow. jsonschema was used to cross-check a hand-selected and mutated validation corpus, re to cross-check a limited pattern corpus, and outlines_core to compare token-index sets and 200 generations. The full Outlines application, XGrammar, llguidance, SGLang and all hosted structured-output endpoints were not run. The reference’s additional allowed tag-like tokens are a potential integration issue—not a demonstrated exploit—and the library’s schema compiler gaps are measured for one low-level function/version rather than all deployments.

Inference Lab increment

examples/ch35/schema_core.py provides the standalone validator (validate), schema checker (check_schema), restricted schema-to-regex compiler (schema_to_regex, UnsupportedSchema, UnsatisfiableSchema), regex parser and deterministic character automaton (parse_regex, CharDFA), token decoding/indexing (token_texts, TokenIndex) and random valid-text generation (random_text). These are intentionally separable stages: a schema’s validity, its compiler support and the correctness of a token mask are different obligations. The regex compiler is not a general JSON Schema implementation.

examples/ch35/structured_lab.py supplies the seeded record generator (make_orders), ORDER_SCHEMA and nullable-gift variant, prompt construction, model sampling and the two token-mask processors (MaskProcessor and OutlinesProcessor). It also contains raw JSON extraction, lenient brace extraction, repair, field-level and whole-record scoring, and the run, absent, truncate and latency experiment paths. The important implementation distinction is that a successful mask or json.loads call does not count as a correct extraction without the independently generated reference record.

examples/ch35/structured_checks.py implements the offline reference checks: validator_check against the Draft 2020-12 jsonschema library, schema_check against the metaschema, regex_check against Python re, language_check for generated strings against the schema, and mask_check against outlines_core. Its fixture corpus demonstrates both supported cases and deliberate refusals. These checks were run when the saved results were produced; editing the manuscript does not rerun or extend them.

To reconstruct the chapter’s tables from the saved results and generated texts, use the committed analysis command below. Record the output’s Git commit, Python and dependency versions and raw-data hashes alongside any newly generated results, so a later run cannot silently replace this baseline:

python research/ch35/build_results.py

To run the reference checks again, use the first command below; to regenerate model outputs, use the experiment commands implemented by structured_lab.py with the recorded seeds, model revision and token caps. These operations have different cost and environment requirements: conformance checks can be much cheaper than GPU generation, while a complete run depends on a locally available model and tokenizer. A successful unittest run is not, on its own, evidence that the 200-example GPU benchmark was reproduced.

python examples/ch35/structured_checks.py all

The engineering rule is: compile the schema only within a declared supported subset; prove or test that the permitted language is a subset of schema-valid outputs; then validate both completion and the final value independently. A grammar can ensure admissible form but cannot generally verify that fields were extracted from the source correctly. A token budget can end a viable prefix before it is a document. An unsupported schema should fail closed rather than silently weaken the decoder; a missing fact should have an honest representation such as null. The model also needs enough field meaning in its prompt or examples to select the right values. In a production pipeline, treat valid JSON, schema-valid, complete, source-grounded and authorised for downstream use as separate gates.

What you should now be able to do

  • Explain the five distinct gates: normal completion, JSON parsing, schema validation, source-grounded correctness and downstream authorisation.
  • Distinguish invalid schemas, valid-but-unsatisfiable schemas, and valid schemas unsupported by a particular compiler, and identify which failure should be surfaced before generation.
  • Compile a declared JSON Schema subset to a regular language, build a DFA over character classes, and evaluate a whole tokenizer token across grammar boundaries before admitting it.
  • Explain why the token mask must participate in the model’s sampling pipeline before top-k/top-p in this implementation, and why a different serving engine must be separately verified.
  • Check a compiler with positive and negative schema fixtures, random accepted strings, independent validation and reference-index comparisons; explain why finite tests do not prove general soundness.
  • Choose between strict constraints, narrow lenient parsing, schema-aware repair and bounded retry, and identify when each can conceal missing or invented data.
  • Represent unknown values honestly in schemas, preserve the source text for field-level checking, and read the stop reason before treating an output as a completed record.
  • Benchmark cold compilation, warm mask overhead and end-to-end performance with matched token counts, context lengths and batch sizes.

Key terms

  • Schema: a contract describing admissible JSON values; it may not express every relationship between a value and the source it describes.
  • Constrained decoding: restricting candidate tokens so their decoded text remains on a path to an accepted output in a specified language.
  • Finite-state automaton (DFA): deterministic states and transitions for a regular language; in this lab, transitions operate over character classes.
  • Token mask: the per-state set of tokenizer IDs whose complete decoded contents keep a viable path alive; the end token is allowed only at acceptance.
  • Soundness: every completed output in the compiler’s language satisfies the original schema; a compiler may be sound but deliberately incomplete.
  • Completeness of generation: termination with an accepted document, not merely an extendable prefix at the token limit.
  • Structural validity: a finished output parses and meets the schema’s enforced restrictions.
  • Semantic correctness: generated values agree with the source message and task definition.
  • Unsatisfiable schema: a well-formed schema for which no value can satisfy all constraints.
  • Unsupported schema: a valid schema using keywords or constructs a particular compiler declines to encode.
  • Repair: modifying generated text to make it parse or validate; not evidence that ungenerated facts are true.
  • Compilation overhead: work to derive a grammar and tokenizer-specific indexes or masks, which may be amortised across requests.

Reader exercises

  1. Add a bounded integer range, such as 1–999, to the compiler. Generate a finite automaton for its permitted decimal spellings and compare it with both jsonschema and exhaustive integer fixtures; demonstrate why “finite-state cannot count” would be wrong.
  2. Compare a bounded-recursion representation and a pushdown grammar for nested JSON. Measure reachable states, memory and worst-case compilation time.
  3. Make the token index byte-aware so a Unicode character can span several BPE tokens, and repeat the allow-set and end-to-end output checks against outlines_core.
  4. Replace the generic retry message with a targeted code-fence correction, keeping seeds and test items independent of prompt selection. Report validation success and tokens per correct record.
  5. Remove the schema JSON from the prompt but supply field names and meanings as short descriptions. Test whether semantic accuracy can be restored with fewer prompt tokens.
  6. Add source-grounded checks for gift, item and unit_price. Evaluate both false positives and false negatives, especially messages that contain conflicting or negated statements.
  7. Run matched-length benchmarks: exactly the same prompt, sequence count, context and number of decode steps with and without a mask; separately report cold compile time, warm per-token time and throughput.
  8. Add a schema containing an unsupported keyword and prove that the application rejects it instead of emitting a best-effort result and claiming schema conformance.
  9. With an explicitly authorised budget and a fresh API schema, compare provider cold/warm latency and refusal, incompletion and strict-mode errors. Do not send a request by default; reuse the opt-in budgeting discipline of Chapters 32–33.
  10. Use Grammar-Aligned Decoding as a reading comparison: explain why greedy local masking is not identical to sampling the model conditional on the complete language, then design a tractable synthetic example that demonstrates the difference.

References

  • Efficient Guided Generation for Large Language Models — Willard and Louf (2023); presents vocabulary-indexed finite-state guided generation and the Outlines lineage. The reported efficiency findings are external research; this chapter tests its own implementation.
  • XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models — Dong et al., MLSys 2025; discusses efficient grammar execution and vocabulary preprocessing. The paper’s reported speedups were not reproduced.
  • Generating Structured Outputs from Language Models: Benchmark and Studies / JSONSchemaBench — Geng et al. (2025); evaluates constrained decoding on real-world JSON schemas, coverage, efficiency and output quality. The 10,000-schema benchmark was not run here.
  • Grammar-Aligned Decoding — Park et al., NeurIPS 2024; analyses how greedy token masking can change the distribution over completed grammatical outputs compared with the original model conditioned on the grammar. This chapter discusses the mechanism but did not evaluate the paper’s algorithm.
  • ChopChop: A Programmable Framework for Semantically Constraining the Output of Language Models — 2026 research on program-level semantic constraints and completability beyond simple syntactic grammars; relevant as a direction for source-dependent and program-invariant checking, not an engine or experiment used here.
  • OpenAI — Structured model outputs — official documentation; strict JSON Schema subset, nullable required fields, refusals, incomplete generations, and model-dependent compile-latency qualification. Checked 26 October 2026; no API requests were made.
  • Anthropic — Structured outputs — official documentation; JSON output and strict-tool contracts, subset limitations, compiled-grammar caching, refusal and token-limit exceptions. Checked 26 October 2026; no API requests were made.
  • SGLang — Structured Outputs — describes its selectable grammar backends and interfaces; not run in this chapter.
  • outlines_core 0.2.14 — Apache-2.0; the locally installed Rust core was used for direct regex-index comparison. Its higher-level package was not evaluated.
  • jsonschema 4.26.0 — Draft 2020-12 reference validator and schema checker used in the saved conformance tests.
  • Qwen3-0.6B — Apache-2.0 model revision c1899de289a04d12100db370d81485cdf75e47ca, used for local generation.

Evidence in this chapter

Claim Evidence classification and boundary
Unconstrained text parsed as written for 100/200 inputs; all 100 failures were fenced JSON and all were valid after brace extraction Book result, one synthetic corpus; lenient parsing changed the accepted text
Constrained text parsed and was schema-valid for 200/200 inputs; 87/200 were exactly correct and 113 were valid but wrong Book result, one model and schema; validity is not source-grounded correctness
After lenient parsing, unconstrained exact match was 80/200; difference from constrained was +3.5 points, paired interval −0.5 to +7.5 Book result; insufficient evidence for a semantic improvement over the lenient baseline
The constrained run made 78 plural-item errors, 38 gift-negation errors and 15 wrong-price errors Book result; field-error totals can overlap
Removing the schema’s textual description reduced exact records from 87/200 to 40/200 Book result; prompt lengths and random trajectories also differ
With the gift fact absent, a required boolean led to 100/100 invented false values; a nullable required field produced 94/100 null values Book result on a separate 100-example set; whole-record exact is a different metric
With only 40 generated tokens, 39/200 constrained outputs and 5/200 unconstrained outputs parsed as written Book result; 19 constrained normal stops do not imply that all 39 parsed outputs reported a stop token
Validator agreed with jsonschema on 661 examples; schema checks on 49 schemas; DFA agreed with re on 5,367 strings; 1,597 sampled accepted strings passed validation Book result on finite test suites, not a general proof of conformance
The lab index was a subset of outlines_core allowed tokens on compared paths; 200 outputs were identical in the two measured conditions Book result, this tokenizer and outlines_core 0.2.14; no claim of global equivalence or exploitability
Low-level outlines_core.build_regex_from_schema accepted five crafted schema-violating strings and compiled four test schemas invalid under Draft 2020-12 Book result for one function and version; not a claim about all Outlines integrations
Cold preparation consisted of regex/DFA, vocabulary, index and masks (about 1.25 s combined); isolated per-step means were 70.2 ms no processor and 71.1 ms masked Book timing on a shared GPU; 64 vs 55 steps makes the isolated step averages an imperfect causal comparison
Grammar-Aligned Decoding analyses distortion from local filtering; XGrammar and JSONSchemaBench report other methods and benchmarks External research, not reproduced
OpenAI and Anthropic document strict structured-output subsets, with refusals and incomplete generation as exceptions Current documentation, not a provider call; provider compile-latency wording differs
Arbitrary schema support, recursion, real-world extraction, other models, hosted results and production serving throughput NOT_RUN

Implementation status

  • Manuscript: content/books/inference/35-chapter.md (these changes target the Inference book, not the Embeddings book).
  • Runnable examples: examples/ch35/structured.py (unchanged starter), examples/ch35/schema_core.py (schema check, validator, regex/DFA compiler, token index), examples/ch35/structured_lab.py (seeded inputs, processors, generation, semantic scoring), and examples/ch35/structured_checks.py (library and reference-index conformance).
  • Tests: tests/test_ch35_structured.py (starter) and tests/test_ch35_structured_lab.py (32 tests recorded with the chapter: validation/schema checks, regex-DFA behaviour, compiler errors, sampled language checks, token masks and processor order, repair and scoring, seeded input generation). No tests were rerun for these editorial edits.
  • Evidence: research/ch35/sources.md, research/ch35/results.json, research/ch35/raw/, research/ch35/measurements/, research/ch35/build_results.py, research/evidence-register.md.
  • Verification command: python -m unittest discover -s tests -v; independent evidence regeneration requires the recorded GPU environment and raw data.
  • Remaining engineering gates: byte-aware indexing; strict unsupported-schema refusals across integrations; matching-length mask benchmarks; source-grounded field checks; and a held-out real-world extraction set.

This chapter is publication-oriented but its draft = false flag is not an experimental certification. The verified claims concern a particular 0.6B model, seeded synthetic order messages, a restricted regular-language compiler and saved measurements. The central result is a boundary, not a model leaderboard: structured decoding made the record reliably parsable and schema-valid, but the application still has to establish that it is complete, truthful to the source and safe to act on. Chapter 36 carries that distinction into metrics and production evaluation.