O que faz
- O subconjunto do JSON Schema 2020-12 que os provedores e o MCP usam, em modo estrito ou leniente
- Validação sem DOM, com o JSON Pointer de cada erro
- Validação em streaming: cada pedaço responde viável, completo ou inválido, no primeiro byte que decide
- Schema, decode e encode gerados de uma struct C++
- Conferência de dialeto: o que Anthropic, OpenAI estrito e MCP recusariam
- Extração e reparo auditado da saída do modelo, que nunca inventa valor
Medido
- Validação de uma vez: 496 MB/s num documento de 1 MiB (GCC), 410 MB/s (MSVC)
- Zero alocação depois do aquecimento
- Chamadas de ferramenta típicas (75 bytes em média): 141 MB/s. Meta de 500 MB/s não cumprida
- Decode de 5 campos para uma struct: 356 ns no p50. Meta de 150 ns não cumprida
Limites conhecidos
- Um subconjunto do JSON Schema 2020-12: sem if/then/else, patternProperties, propertyNames, contains, dependent*, unevaluated*, $anchor nem $dynamicRef
- Só $ref e $defs locais
JSON Schema for the tools and structured outputs of language models (Ethereal::Ai::Schema). It compiles a schema into a flat program, validates JSON against it without a DOM (whole or in pieces, saying after each piece whether the document can still be valid), writes the schema of a C++ type and decodes JSON straight into the struct, checks what each provider accepts, and extracts and repairs the JSON a model wrote. It is built on the JSON reader of [serialization](serialization.md) and on the [regex](regex.md) module.
The module is optional: -DETHEREAL_AI_SCHEMA=ON (off by default). It needs only the core, and no other option. ETHEREAL_AI_LLM requires it.
#include <ethereal/cpp/ai/schema/schema_inc.hpp>
namespace S = Ethereal::Ai::Schema;
S::CSchema Schema; // immutable, shared between threads
S::SSchemaError Err;
if( S::CSchema::Compile( sSchemaJson, S::SCompileOptions{}, &Schema, &Err ) != S::EStatus::eOk )
return; // Err.aPointer and Err.pMessage say where and why
S::CValidator Validator; // one per thread, no allocation once warm
S::SValidationReport Report;
Validator.Validate( Schema, sJson, Report ); // Report.bValid, Report.aErrors[ i ].aPointer
// The output of a model, piece by piece: stop as soon as it went wrong.
S::EPrefixState eState;
Validator.Begin( Schema );
Validator.Feed( sPiece, false, &eState ); // eInvalid: Validator.PrefixError() says what
Validator.Feed( {}, true, &eState );
Validator.End( Report );Always include schema_inc.hpp: it brings in the entire module in the right order. The SDK ships a complete program in examples/modules/schema.cpp: it compiles a schema, repairs what a model wrote (single quotes and a trailing comma) and validates it, printing the JSON Pointer of the error.
---
What it reads
The subset of JSON Schema 2020-12 that the providers and MCP use:
| Group | Keywords |
|---|---|
| Structure | type, properties, required, additionalProperties, items, prefixItems |
| Values | enum, const |
| Combinators | anyOf, oneOf, allOf, not |
| References | $ref, $defs (and definitions, the draft 7 name, read the same way) |
| Numbers | minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf |
| Strings | minLength, maxLength (in code points), pattern (ECMA-262), format |
| Arrays | minItems, maxItems, uniqueItems |
| Annotations | title, description, default, examples. $schema and $id at the root only. $comment, deprecated, readOnly and writeOnly are accepted and dropped |
Formats (EFormat): date-time, date, time, duration, email, hostname, uri, uuid, ipv4 and ipv6.
Two modes (EMode). In eStrict (the default) a keyword outside the subset is an error, eUnsupportedKeyword. In eLenient it is ignored and recorded as a warning (CSchemaDocument::Warnings). What would change the meaning of the rest of the document (a remote $ref, $id below the root) is an error in both modes. Keywords outside the subset include patternProperties, propertyNames, contains, if, then, else, unevaluatedProperties, unevaluatedItems, minProperties, maxProperties and dependentRequired.
---
The API
| Piece | What it does |
|---|---|
CSchema::Compile( text, SCompileOptions, &schema, &error ) | reads and compiles a schema. Movable, not copyable |
CSchema::Compile( CSchemaDocument &&, ... ) | compiles a schema already read |
IsEmpty(), Reset(), Document(), AssertsFormat() | queries and release |
CSchemaDocument::Parse( text, SParseOptions, &error ) | the schema as a flat model: Root, Node, NodeCount, PointerOf, Resolve, Warnings |
CValidator::Validate( schema, json, report ) | validates a whole document |
CValidator::Begin / Feed / End | validates in pieces of any size, one byte included. Same report as Validate |
CValidator::PrefixState() / PrefixError() | whether the pieces so far can still be valid, and the first break |
Validate( schema, json, report, options ) | free function with a validator of its own (allocates on each call) |
CheckDialect( schema, EDialect, report ) | lists what a provider would refuse in the schema |
SchemaOf< T >() / SchemaOf< T >( EDialect ) | the schema of a described C++ type |
CDecoder::Decode( json, value, report, pArena ) / Decode(...) | JSON straight into the struct, checked as it reads |
Encode( value, span, &written ) | the struct as compact JSON into a buffer of the caller |
Extract( text, &begin, &end ) | the first JSON object or array of a text |
Repair( input, ERepairMode, span, &written, log ) | a limited, audited repair of almost valid JSON |
StatusName, KeywordName, FormatName, DialectName, RepairEditName | names for messages |
Result codes
| Code | When |
|---|---|
eOk | success, or a validation that ran to a verdict (valid or not: bValid says which) |
eInvalidArgument | a null, empty or out of range argument |
eJsonSyntax | the text is not valid JSON (SSchemaError::eJson, or SValidationReport::Json) |
eInvalidSchema | valid JSON but not a valid schema: a value of the wrong type, a repeated property, an empty anyOf, a pattern that is not ECMA-262 |
eUnsupportedKeyword | strict mode: a keyword outside the subset. SSchemaError::aKeyword names it |
eUnsupportedFeature | a remote $ref, a $ref to an anchor, $id below the root, $schema of another draft, a pattern with lookaround or a backreference, and in strict mode a format outside the list or items as an array |
eRefNotFound | a $ref whose target is not a schema of the document |
eRefCycle | a cycle of $ref or combinators that reads no data |
eDepthLimit | nesting deeper than the options allow |
eLimitExceeded | more nodes, frames or bytes than the options allow |
eOutOfMemory | the allocator returned null |
eBufferTooSmall | the buffer of Encode or Repair is short. The size needed is reported |
eNotLicensed | the library is not licensed (see [licensing](licensing.md)) |
Reports
SValidationReport holds the verdict (bValid), the status, and up to SValidateOptions::uMaxErrors errors (1 by default, at most 16). Each SValidationError has the keyword broken (eKeyword), the schema node, the byte offset in the instance, the JSON Pointer of the place (aPointer), what the keyword asked for when it helps to fix the value (sDetail: the missing property, the limit, the pattern, the format) and a short English message that a model can read. bStoppedEarly says that the rest of the instance was not checked.
Validation in pieces
Each Feed says eViable, eComplete or eInvalid. eInvalid is certain: no rest of the document can make it valid. eViable is not a promise. A break is found at the first byte that decides it:
type, andenumorconstwith no candidate of that type: the first byte of the value.- a property that
additionalProperties: falserefuses: the first byte of the key that no property name continues. maxLength: the code point that passes it.enumorconstof strings: the first byte that no candidate string continues.maxItems, and an item thatitemsorprefixItemsrefuse: the first byte of the item.anyOfandoneOf: as soon as every branch is certain to fail.- the rest (
minLength,pattern,format, the numbers,required,minItems,uniqueItems,not): when the value is complete.
The report of End does not depend on how the document was cut.
C++ types as schemas
A struct described with the [meta](meta.md) module, plus the schema attributes of this module, gives its schema, a decoder and an encoder. The three agree by construction: the decoder checks exactly what SchemaOf writes, with the keywords and JSON Pointers the validator would give.
enum class EUnit { eCelsius, eFahrenheit };
ETL_META_ENUM( EUnit, eCelsius, eFahrenheit ); // "celsius", "fahrenheit"
struct SWeatherArgs { char sCity[ 64 ]; EUnit eUnit; ETL_INT32 iDays; };
ETL_META_DESCRIBE( SWeatherArgs,
ETL_META_FIELD( sCity, Meta::Description( "City name" ), Schema::MinLength( 1 ) ),
ETL_META_FIELD( eUnit, Meta::Description( "Temperature unit" ) ),
ETL_META_FIELD( iDays, Meta::Range( 1, 14 ) ) );
std::string_view sSchema = S::SchemaOf< SWeatherArgs >(); // properties "city", "unit", "days"
SWeatherArgs Args{};
S::SValidationReport Report;
S::Decode( sToolInput, Args, Report ); // Report.aErrors[ 0 ] on failure- Attributes:
MinLength,MaxLength,Pattern,Format,MinItems,MaxItems,UniqueItems,Minimum,Maximum,ExclusiveMinimum,ExclusiveMaximum,MultipleOfandTitle, next toMeta::Description,Meta::Range,Meta::Optional,Meta::DefaultandMeta::Skip. - Types:
bool, integers of 8 to 64 bits,float,double, enums described withETL_META_ENUM,char[N],std::string_view, described structs,Containers::CFixedVector,std::array,T[N],std::spanandstd::optional. Field and enumerator names lose their Hungarian prefix and become snake_case (eMetersPerSecondis"meters_per_second"). - The schema: a struct is an object with
additionalProperties: false, and every field withoutMeta::Optional,Meta::Defaultorstd::optionalis required. Nested structs go to$defsand are reached by$ref. Integers carry the bounds of their type,char[N]amaxLengthof N - 1. The text is written on the first call and kept for the life of the process. Thread safe. - The decoder stops at the first error. A
std::string_viewpoints into the input, or into theMemory::CMemoryArenagiven when the text had escapes, and the items of a span go to the arena.SDecodeOptions::bIgnoreUnknownFieldsskips fields the struct does not have, for models that add their own.
Provider dialects
CheckDialect lists what a destination would refuse, each with its rule (EDialectRule), its severity (eError when the provider documents the refusal, eWarning when it only recommends against it) and the JSON Pointer of the node. SchemaOf< T >( eDialect ) writes the schema in the shape the dialect accepts, and moves the constraints it leaves out to the end of the description, as the providers' SDKs do.
| Dialect | Rules checked |
|---|---|
eGeneric | none beyond the subset. Reports only keywords that lenient mode ignored |
eAnthropic | the input_schema of a tool without strict |
eAnthropicStrict | structured outputs and strict tool use: no numeric or length constraints, minItems only 0 or 1, additionalProperties: false on every object, no recursion, simple patterns |
eOpenAIStrict | strict: true: the root an object without anyOf, every property required (optional is a union with null), additionalProperties: false, no allOf or not, the size limits |
eMcp | the inputSchema of an MCP tool (revision 2026-07-28) |
eMcpElicitation | the requestedSchema of MCP form mode: a flat object of primitive properties |
Extraction and repair
Extract finds the first object or array in a text, past prose and Markdown fences. A brace counts only when what follows looks like JSON. Repair then fixes, in one pass and without allocating, only these defects: a truncated document (open strings and containers closed, a dangling comma dropped), a trailing comma, single quotes, unquoted keys, // and /* */ comments, the Python literals True, False and None, invalid escapes and raw control characters, and a byte order mark. It never invents content. A value missing after :, a key or literal cut in the middle, a number that ended in -, . or e, NaN, Infinity, a hexadecimal number, a lone surrogate or a missing colon or comma fails with eJsonSyntax. Every change goes to SRepairLog with its kind (ERepairEdit), offset and length. Repairing the output again changes nothing. ERepairMode::eStrict accepts no change at all.
---
Limits and behavior
Schemas come from outside the program (a provider, an MCP server, a file) and are treated as untrusted input. A hostile schema gives an error, never a crash, a deep recursion or a huge allocation.
| Option | Default |
|---|---|
SParseOptions::uMaxDepth | 64 schemas inside schemas (up to 1,024) |
SParseOptions::uMaxCombinatorDepth | 16 |
SParseOptions::uMaxJsonDepth | 256 (up to 1,024) |
SParseOptions::uMaxNodes | 65,536 |
SParseOptions::uMaxDocumentBytes | 4 MiB |
SCompileOptions::uMaxPatternBytes | 1 MiB per compiled pattern |
SValidateOptions::uMaxDepth | 256 |
SValidateOptions::uMaxFrames | 65,536 schemas applied at the same time |
SValidateOptions::uMaxDocumentBytes | 64 MiB |
- **
formatis checked by default**, as the providers do in structured outputs. JSON Schema 2020-12 treats it as an annotation.SCompileOptions::bAssertFormat = falsefollows the standard. - Equality (
const,enum,uniqueItems): numbers by value without going throughdouble(1equals1.0), and objects without regard to key order. - References are local only (
#and JSON Pointers into the document). A recursive schema (a tree, a list) is allowed and bounded by the depth of the data. A cycle that reads no data iseRefCycle. - Threads. A
CSchemais immutable afterCompileand can be shared by several threads. ACValidatorand aCDecoderbelong to one thread and keep their memory from one document to the next: after the first documents, they do not allocate. - Out of scope: remote
$ref, custom JSON Schema vocabularies, grammars for constrained decoding.
---
C layer
Header ethereal/c/ai/schema.h. Two opaque handles (ETLC_Schema, ETLC_SchemaValidator), the ETLC_STATUS return shared by every C layer, and four codes of the AI pillar in ethereal/c/ai/ai.h: ETLC_AI_INVALID_SCHEMA, ETLC_AI_UNSUPPORTED_KEYWORD, ETLC_AI_REF_NOT_FOUND and ETLC_AI_REF_CYCLE. Every struct carries its size in the first field (iStructSize), and zero or a size smaller than the one of this version is refused. Zero in an options field means the default of that field, so a struct cleared by memset keeps every defense on.
ETLC_Schema h = NULL;
ETLC_SchemaValidationReport R;
memset( &R, 0, sizeof( R ) );
R.iStructSize = sizeof( R );
if( ETLC_SchemaCompile( pSchema, strlen( pSchema ), NULL, &h, NULL ) == ETLC_OK &&
ETLC_SchemaValidate( h, pJson, strlen( pJson ), NULL, &R ) == ETLC_OK && !R.bValid )
printf( "%s at '%s': %s\n", R.aErrors[ 0 ].pKeyword, R.aErrors[ 0 ].aPointer, R.aErrors[ 0 ].pMessage );
ETLC_SchemaDestroy( h );It covers compile, whole and streaming validation with the prefix state (ETLC_SchemaValidatorFeed, ETLC_SchemaValidatorPrefixError), ETLC_SchemaExtract and ETLC_SchemaRepair. Schemas are JSON text only: the C++ descriptors (SchemaOf, Decode, Encode) and the dialect checker stay in C++. The layer is tested as C11 and C17 without extensions.
---
What was verified
- The official JSON-Schema-Test-Suite,
draft2020-12withoptional: the 213 groups and 1,290 cases inside the subset pass through three paths (the freeValidate, a reusedCValidatorwith 16 errors, and three pieces), on GCC, Clang and MSVC. Every document of the suite cut in two at every byte gives the same report as the whole document, and the prefix state is nevereInvalidon a valid document. - **The schemas
SchemaOfwrites**, in every dialect, are valid against the official 2020-12 metaschema (checked with the Pythonjsonschema4.19.2). - Repair: a corpus of 280 malformed model outputs, each with the expected class and value, 100%.
- One hour of libFuzzer per parser with ASan and UBSan, no finding. Line coverage 93.3%.
---
Throughput
i7-6700, one thread, quiet machine. Whole document validation, MB/s, median:
| Document | GCC 15.2 | MSVC |
|---|---|---|
| Search result, 1 MiB | 496 | 410 |
| Search result, 64 KiB | 491 | 406 |
| Product (146 bytes) | 285 | 228 |
| Order of 16 lines (884 bytes) | 124 | 102 |
| 65 tool calls (75 bytes on average) | 141 | 117 |
Decode of 5 fields (146 bytes): 356 ns at p50 (GCC). Zero allocation after warmup.
Targets not met: 500 MB/s on typical tool calls, 150 ns for the 5 field decode, and 2x against decoding through a DOM plus a copy. On small documents almost all of the time goes to the fixed cost of each validation.