Skip to content

Latest commit

 

History

History
422 lines (363 loc) · 22.2 KB

ARCHITECTURE.md

File metadata and controls

422 lines (363 loc) · 22.2 KB

ata Architecture

ata-validator is a JSON Schema validator with two faces: a runtime Validator that compiles schemas on demand, and an ahead-of-time (AOT) compiler that turns schemas into standalone, zero-dependency JavaScript modules at build time. Types are inferred from plain JSON Schema, with no builder DSL. The native C++ engine (simdjson) is optional and only powers the buffer and batch paths; core validate() runs on pure JS and works in the browser.

This document describes the architecture as of 1.7.2.

Design principles

  • Pure JS by default, native by opt-in. Nothing in the core validate path requires the native addon. Native accelerates buffer/NDJSON workloads only.
  • Compile, do not interpret (where it pays). Hot schemas are turned into specialized JavaScript functions. A small interpreter (tier 0) covers trivial schemas without paying codegen cost, and the schemas the code generator declines are compiled into a closure tree rather than walked.
  • Declining to compile must never mean accepting. A code generation path that cannot represent a shape hands the schema to an engine that can. An empty emitted program is a bug, not a valid schema.
  • Plain JSON Schema is the source of truth. Types, runtime validation, and AOT output all derive from the same plain schema literal.
  • Zero-eval, shippable output. The AOT path emits static modules with no Function/eval, safe under strict CSP and on the edge.

Component map

flowchart TD
  subgraph Authoring
    JS[Plain JSON Schema]
    DEF[defineSchema / JSONSchema type]
  end

  subgraph Frontend["Schema front-end"]
    NORM[draft7.js: normalize draft-07 + nullable]
    CLS[shape-classifier.js: classify]
  end

  subgraph Strategies["Execution strategies"]
    T0[tier0.js: fast-path interpreter]
    CG[js-compiler.js: JS codegen]
    INT[interpreter.js: schema walker]
    PC[plan-compiler.js: closure tree]
    NAT[Native C++ + simdjson]
  end

  subgraph Output["Outputs"]
    RT[Runtime Validator]
    AOT[AOT modules .mjs + .d.ts]
    STD[Standalone / bundles]
  end

  JS --> NORM
  DEF --> NORM
  NORM --> CLS
  CLS --> T0
  CLS --> CG
  CG -. declines .-> INT
  INT --> PC
  PC --> RT
  CG --> RT
  CG --> AOT
  CG --> STD
  T0 --> RT
  NAT -. buffer / batch only .-> RT
Loading

Packaging and entry points

File Role
index.js CommonJS entry. Loads the optional native addon, exposes Validator, validate, compile, bundles.
index.mjs ESM entry (re-exports the CJS core).
index.browser.mjs Browser build. No native addon, pure JS codegen only.
index.d.ts Public types: Validator<T>, Infer<S>, defineSchema, JSONSchema, Standard Schema.
build.js / build.mjs / build.d.ts Programmatic AOT build API (build, watch, expandGlobs, bundleStandalone, bundleCompact, toStandaloneModule).
t.js / t.mjs / t.d.ts Chainable builder (t.object, t.string, t.union, …) that emits plain JSON Schema literals; the TypeBox migration target.
compat.js / compat.mjs / compat.d.ts Drop-in shim for the default validator's API.
bin/ata.js CLI: ata compile, ata build, ata validate.

Runtime validation: three-tier dispatch

new Validator(schema) normalizes the schema once, then chooses an execution strategy per call. The cheapest strategy that fits the schema and the input wins.

flowchart TD
  NEW["new Validator(schema)"] --> N["draft7.js: normalize<br/>(definitions to $defs, nullable)"]
  N --> C["compile codegen fns<br/>(bool, combined, errors)"]

  C --> M{"Which method?"}

  M -->|isValidObject| CL{"shape-classifier: tier 0 eligible?"}
  CL -->|yes| T0["tier0Validate<br/>(no codegen)"]
  CL -->|no| BOOL["codegen boolean fn"]

  M -->|validate| ERR["codegen combined / error fn"]
  ERR --> EN["enrich errors"]
  EN --> RES["ValidationResult"]

  M -->|isValid Buffer / countValid / isValidParallel| NAT["Native C++ + simdjson"]
  NAT -.->|addon missing| THROW["throws: use validate / isValidObject"]

  M -->|codegen declined the schema| INT["interpreter.js<br/>compiled to a closure tree"]
Loading
  • Tier 0 (lib/tier0.js): a small interpreter for trivial shapes, built lazily on the first isValidObject call so cold start stays cheap.
  • JS codegen (lib/js-compiler.js and lib/js-compiler-errors.js): the core. Emits specialized functions:
    • compileToJSCodegen — boolean fast path (js-compiler.js)
    • compileToJSCombined — the one-pass function, returns the { valid, data, errors } result shape (js-compiler-errors.js)
    • compileToJSCodegenWithErrors — error-collecting path (js-compiler-errors.js)
    • compileToJS — closure-array fallback when codegen cannot represent a shape
    • The two error generators live in their own module, read on the first call that compiles a validator's errors, so a process that only answers verdicts never parses them. They reach the verdict generator's helpers through module.exports._internal of js-compiler.js, which is not part of the package's interface.
    • lib/branch-collapse.js folds redundant conditionals; lib/safe-regex.js routes pattern/patternProperties/propertyNames and built-in formats through a linear-time engine (ReDoS-safe). lib/regex-linear.js decides which patterns the platform RegExp may take instead, at three to five times the engine's speed per character: those with one unbounded quantifier on a single character, anchored, and those deterministic around their loops on the Glushkov construction (disjoint first and follow sets, one route to each follower, no empty loop body, anchored). tests/test_regex_native_linear.js holds both engines to the same answers and the RegExp to linear time on adversarial probes.
  • Interpreted engine (lib/interpreter.js): the answer for every schema the code generator declines, and the reference implementation the other engines are diffed against. It plans each schema node once (Plan), then walks it. unevaluatedProperties/unevaluatedItems, $id/$anchor/$dynamicAnchor scoping and cross-document $ref live here.
  • Closure-tree compiler (lib/plan-compiler.js): compiles those plans into a tree of specialized closures. No source generation and no new Function, so it runs under a strict CSP and on the edge, but every keyword branch is decided once at compile time and every child call is a direct call, which is the code generator's advantage without the codegen. What the walker decides per call from the schema path is decided here once: the base URI, the dynamic scope for $dynamicRef, whether anyone reads a node's annotations, and whether the schema can recurse at all (an acyclic schema drops the cycle guard). Each node compiles to a pair: a collecting function whose error output is byte-for-byte the walker's, and a verdict function that builds no paths and no error objects and returns on the first failure. tests/test_plan_compiler.js diffs the two over the official suite and is part of npm test.
  • Custom keywords (lib/keywords.js): new Validator(schema, { keywords }) registers validate, compile or macro definitions. A schema that uses one is routed to the interpreted engine before any of the paths above are tried (the code generator, the tier-0 plan and the compile cache are all bypassed, and lib/buffer-gate.js sends the buffer APIs through validate()), because none of those engines know the keyword and each would accept what the interpreter rejects. The plan records the custom checks per node; macro output is applied in place like an allOf branch and adds the keyword's own error when it fails. The AOT emitters refuse such schemas: a standalone module cannot carry a function.
  • Native C++ (src/ata.cpp, binding/ata_napi.cpp, deps/simdjson): powers isValid(Buffer), countValid, isValidParallel and validateAndParse. lib/buffer-gate.js routes the shapes the native walker gets wrong back through validate(). Loaded via lib/native-load.js, which resolves the per-platform @ata-validator/native-* optional package (falling back to a local dev build); absent native, the buffer/batch methods throw and everything else keeps working on JS.

Generated code stays small enough to optimize

V8 does not optimize a function past its bytecode budget (about 60 KB of bytecode), and a schema of a few hundred properties compiled to one function of a megabyte or more that ran in the interpreter for its whole life, 7 to 10 times slower than the same checks in functions of their own. All three generators therefore hoist a large property subschema into a function in the preamble (the verdict's _pf<n>, the error collector's _pe<n>, the one-pass function's _pc<n>) and call it where the property is checked. The decision is made on the schema's own size before any code is written, so nothing is generated twice, and once a function holds a budget of inline code smaller properties move out as well. A property function is generated against its real schema path, so its errors keep the precise ordinal keys the sorter uses; a property inside a shared definition's body, whose placeholder path is substituted after the fact, stays inline. tests/test_generated_function_split.js holds the bound and the agreement with the interpreted engine. The scanner splits the same way (SPLIT_MIN, SPLIT_OBJECT in lib/scan-compiler.js).

Validating from the text: the scanner

Measured end to end on a real request, JSON.parse is about three quarters of the cost and structural validation is under two percent. A caller that only wants a verdict pays most of its time building a document it then throws away.

lib/scan-compiler.js generates, per schema, a function that reads the JSON text directly and answers from it. Nothing is materialised: object keys are matched against the raw span in the text, numbers are accumulated out of their digits, and a subtree the schema does not constrain is stepped over by lib/scan-runtime.js rather than built. A rejection can stop at the byte that caused it instead of parsing the rest of a document that is already refused.

It is wired into isValidJSON, and into validateJSON under abortEarly, where there are no errors to produce. Paths that must report errors keep parsing: scanning a document that turns out to be invalid is work thrown away there. It is not used when a preprocess pass is configured, because coercion, removal and defaults rewrite the document before it is judged and the scanner reads what arrived.

Being a second JSON reader is the risk. Three rules contain it:

  • Decline by default. compileScanner returns null for any schema outside a supported core: type, properties, required, additionalProperties, items, prefixItems, the length, size and range keywords, pattern, format, const, enum, plus $ref and allOf as described below. What needs backtracking or annotations declines, which is anyOf, oneOf, not, if/then/else, contains, patternProperties, propertyNames, unevaluated* and the dependency keywords, and so does anything unrecognised. compileScanner(schema, {onDecline}) reports the reason, so what to widen next is measured rather than guessed. A compiled scanner also returns BAIL at runtime for a document shape it cannot answer. Either way the caller parses, as before.
  • A reference is inlined, narrowly. Only a fragment pointer into the document being compiled. A reference carrying any sibling that bears on the verdict declines, because draft 7 lets $ref override its siblings and 2020-12 applies both, and reading it under one rule while compiling under the other is how this goes wrong quietly. So does one that re-enters a reference already being expanded, and any $id or $anchor below the root, which is base-URI resolution the scanner does not implement.
  • An intersection becomes one schema before anything is emitted. The subtle keyword there is additionalProperties: a branch applies its own to the names its own properties does not list, which is not the set the merged properties does not list. Taking the union of the properties and keeping one additionalProperties accepts documents every branch rejects, so a name in the merged set takes, from every branch, either that branch's subschema for it or that branch's additionalProperties.
  • Whatever needs the value gets the value. format, pattern, const and enum are answered by the same compiled check validate() runs, over that one materialised scalar. A string carrying escapes is decoded by JSON.parse of its own span. So those rules cannot drift from the validator: they are the validator.
  • A duplicate name is the parser's to resolve. JSON allows a name to repeat and JSON.parse keeps the last one, so a member that fails is not the end of the scan: the failure is recorded, the value is stepped over, and scanning continues. A repeat of any name already seen bails. An object that reaches its closing brace with a recorded failure and no repeat is invalid.

tests/test_scanner_differential.js holds the scanner and validate() to the same verdict on the same text over the whole official suite, a malformed-JSON corpus, and generated documents with single-character corruptions. It counts disagreements, not bails, and the count must stay at zero.

AOT build pipeline

ata build/ata compile and the programmatic build() API compile schemas to standalone modules at build time. No validator dependency is shipped.

flowchart LR
  G["globs / schema files"] --> EX["aot-build.js: expandGlobs"]
  EX --> P["parseSchemaFile"]
  P --> NM["draft7.js: normalize"]
  NM --> CG["js-compiler.js: codegen"]
  CG --> MJS["write *.validator.mjs<br/>(zero imports)"]
  CG --> TS["ts-gen.js: write *.d.mts"]
  MJS --> RPT["cache + report<br/>(compiled / cached / skipped / failed)"]
  TS --> RPT
Loading

Standalone and bundle output

The same codegen backs three in-process emitters on Validator:

Method Output
toStandalone() Module string that still imports ata-validator.
toStandaloneModule() Fully self-contained module, zero dependency.
Validator.bundleStandalone() Multiple schemas, one zero-dep module.
Validator.bundleCompact() Bundle with shared template de-duplication.

All of them build from the compiled schema alone, so they must refuse any validator that enforces more than its schema carries. Two things do that, and each is declared rather than guessed at: the constructor's keywords option sets _usesKeywords, and a wrapper that replaces an instance's entry points, such as withKeywords() from @ata-project/keywords, sets _externalChecks. Core cannot detect the second on its own, because it installs its own entry points as own properties on the instance and so cannot read "something replaced these" as a signal. A wrapper that does not declare itself gets a module that silently drops its checks, which is why the flag is part of the contract rather than an implementation detail.

Error enrichment pipeline

Raw codegen errors are enriched into compiler-grade diagnostics, then rendered.

flowchart LR
  RAW["raw validation errors"] --> EN["enrich-error.js"]
  EN --> CODES["error-codes.js<br/>(stable ATA#### codes)"]
  EN --> POS["data-positions.js + source-positions.js<br/>(payload + schema frames)"]
  EN --> SUG["suggestions.js + levenshtein.js<br/>(did-you-mean)"]
  CODES --> R{render-shared.js}
  POS --> R
  SUG --> R
  R --> PRETTY["render-pretty.js"]
  R --> COMPACT["render-compact.js"]
  R --> JSON["render-json.js"]
Loading

Specification output format

Errors come back in ata's own shape, which is what consumers and the compat entry expect. The specification also defines an output format of its own, with keywordLocation, absoluteKeywordLocation and instanceLocation, and the official suite carries tests for it under tests/suite/output-tests/, separate from the validation tests. toOutput(validator, data, { format }) produces it.

flag and basic are implemented, for draft 2019-09 and 2020-12. detailed and verbose are not: they need the applicator tree including the subschemas that passed, which no engine keeps. The v1 list format is not implemented; it is still changing and v1's own output schema does not define it yet. tests/test_output_format.js runs what exists.

This is the part of the specification that says how a validator explains itself, and almost nothing tests it. The first case in the 2020-12 set is a property key ~a/b that has to be reported as /~0a~1b, which is a bug this repo had and fixed by hand; the suite had a test for it the whole time.

Holding the engines together

Several engines answer the same question, so the thing that has to be tested is that they answer it the same way. Two differentials do that, each running the whole corpus twice in separate processes, once with new Function blocked, because which engine answers is a property of the realm and not something a single process can switch:

Test Compares
tests/test_engine_differential.js verdicts, including values JSON cannot carry and the options matrix
tests/test_error_shape_differential.js the errors themselves: keyword, instancePath, schemaPath, params

The second exists because a wrong error is invisible to the first: both engines reject, the verdict matches, and only the report differs. That gap held a property key whose / was never escaped into a JSON Pointer, an additionalProperties: false that came back as not on one engine, and an abortEarly that returned real errors where the documented contract promises a stub. tests/test_plan_compiler.js covers a third pair, the interpreter's fast plan against its generic evaluator, over the whole suite.

Together with tests/test_ajv_parity.js, which pins the compat entry to the reference implementation, this reaches an environment the reference cannot: the reference needs code generation to compile at all, so it can never be consulted under a strict CSP. Codegen matches the reference, the interpreter matches codegen, so the interpreter matches the reference by transitivity.

TypeScript type system

Two distinct, independent paths produce TypeScript types. Do not confuse them.

flowchart TD
  S["plain JSON Schema literal"]
  S --> INF["Infer&lt;S&gt; (index.d.ts)<br/>compile-time, type-level only"]
  S --> GEN["ts-gen.js<br/>emits .d.ts text at AOT build"]

  INF --> V["new Validator(schema): Validator&lt;Infer&lt;S&gt;&gt;<br/>result.data narrows in handlers"]
  GEN --> F["*.validator.d.mts beside the compiled module"]
Loading
  • Infer<S> (index.d.ts): a recursive, type-level mapping evaluated by tsc. Resolves primitives, const/enum, objects (required vs optional), arrays, prefixItems (tuples), anyOf/oneOf (unions), allOf (intersections), and $ref into local #/$defs or #/definitions (recursive refs included). It threads the root defs map down the recursion so refs can be resolved. External/unresolvable refs degrade to unknown, never an error.
  • ts-gen.js: generates .d.ts source text during the AOT build, paired with each compiled .mjs. It also encodes runtime-only constraints (minLength, format, ranges) as JSDoc tags on the emitted types.

Native layer

flowchart TD
  IDX["index.js"] -->|native-load.js| PKG["@ata-validator/native-&lt;platform&gt;<br/>(optional package, 6 platforms)"]
  PKG --> ADDON["native addon (.node)"]
  ADDON --> NAPI["binding/ata_napi.cpp"]
  NAPI --> CORE["src/ata.cpp + src/ata_c.cpp"]
  CORE --> SIMD["deps/simdjson"]
Loading

The native addon is optional and only required for the buffer and batch APIs. Prebuilt binaries ship for the supported platforms, so installation does not require a local toolchain. When the addon is unavailable, ata transparently runs the JS path.

Module reference

Module Responsibility
lib/js-compiler.js Core schema to JavaScript codegen: the verdict generator, the closure compiler, the shared helpers.
lib/js-compiler-errors.js The error-collecting generator and the one-pass generator, read on the first error compile.
lib/aot-build.js AOT build orchestration: globbing, parsing, caching, reporting.
lib/draft7.js Draft-07 normalization and OpenAPI nullable handling.
lib/shape-classifier.js Classifies a schema to pick the execution strategy.
lib/tier0.js Fast-path interpreter for trivial schemas.
lib/interpreter.js Schema walker: the engine for everything codegen declines, and the reference the others are diffed against.
lib/plan-compiler.js Compiles interpreter plans into a closure tree, no eval, verdict and collecting variants.
lib/buffer-gate.js Routes buffer-API shapes the native walker gets wrong back through validate().
lib/scan-compiler.js Generates a per-schema scanner that answers the verdict from JSON text without parsing it.
lib/scan-runtime.js Helpers every scanner shares: the strict value skipper and span decoding.
lib/keywords.js Custom keyword definitions: normalization and the schema scan that routes a schema to the interpreter.
lib/compat-errors.js Shapes validate() errors the way the reference class reports them for ata-validator/compat: evaluation order, branch and wrapper errors, the allErrors: false group.
lib/branch-collapse.js Codegen optimization: collapse redundant branches.
lib/safe-regex.js Linear-time, ReDoS-safe regex and built-in formats.
lib/ts-gen.js Emits .d.ts source text for AOT outputs.
lib/enrich-error.js Turns raw errors into coded, framed diagnostics.
lib/error-codes.js Stable ATA#### error code registry.
lib/data-positions.js, lib/data-position-cache.js Maps payload byte offsets to line/col.
lib/source-positions.js Maps schema elements to source frames.
lib/suggestions.js, lib/levenshtein.js Typo and format suggestions.
lib/render-pretty.js, lib/render-compact.js, lib/render-json.js, lib/render-shared.js Error renderers.
src/ata.cpp, src/ata_c.cpp, binding/ata_napi.cpp Native engine and N-API bindings.
deps/simdjson Vendored simdjson for the native fast path.