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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
254 changes: 254 additions & 0 deletions .alta/plans/2026-11-17-jsontron-spec-js-python.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
---
title: Jsontron spec, conformance suite, and JS + Python ports
status: in-progress
created: 2026-11-17
summary: Rename src/ to dotnet/, extract a language-neutral spec and shared JSON conformance suite that .NET runs first, then add reference implementations for JavaScript (Ajv + jq-wasm) and Python (jsonschema + jq) in this repo.
---

# Jsontron spec, conformance suite, and JS + Python ports

## Goal

Jsontron today is one .NET package whose semantics live in `readme.md` and the C# code.
This plan makes the semantics portable and ships two more implementations that plug into
the most used JSON Schema library of their language, the way the .NET one plugs into
JsonSchema.Net:

| Language | Host library | jq engine | Package | Folder |
|---|---|---|---|---|
| .NET (exists) | JsonSchema.Net 9 | Devlooped.JQSharp | NuGet `Jsontron` | `dotnet/` (renamed from `src/`) |
| JavaScript / TypeScript | Ajv 8 | `jq-wasm` (jq 1.8.2) | npm `ajv-jsontron` | `js/` |
| Python | `jsonschema` 4 | `jq` (libjq 1.8.2) | PyPI `jsontron` | `python/` |

## Decisions already made

- **JS jq engine**: `jq-wasm` now, behind an engine interface. A native TypeScript engine is a
later phase and replaces the default once it passes the conformance suite.
- **Error shape**: one error per failed assert/report, in every language. .NET changes from its
`"; "`-joined string to match.
- **Go and Rust**: upstream first. Their leading libraries (santhosh-tekuri/jsonschema v6, the
`jsonschema` crate) do not give a custom keyword the root document. Ask for a root accessor;
no wrapper API in the meantime.
- **Scope of this plan**: spec + suite + JS + Python. Java (networknt + jackson-jq) gets its own plan.
- **Layout**: one repo, one folder per language; `src/` becomes `dotnet/`.
- **Rename details**: the snk stays skipped (it is already absent); `includes.yml` is marked
`skip` in `.netconfig` and edited locally.

## Assumptions to confirm at review

- **Package names**: npm `jsontron` is taken, so the npm package is `ajv-jsontron` (free, and
follows the `ajv-formats` / `ajv-keywords` convention). PyPI `jsontron` is free.
- **Versions in lockstep**: one GitHub release publishes NuGet, npm and PyPI with the same
version. Simplest to explain ("0.3 everywhere implements spec 0.2"); the cost is a release of
all three for a fix in one.
- **Reference jq**: jq 1.8 is the reference for the portable profile, since JS and Python both
run real jq 1.8.2. Where JQSharp differs, that is a JQSharp bug to fix upstream, not a
profile exclusion, unless the fix is out of reach.
- **Spec version stays 0.2**: the keyword syntax does not change, so the meta-schema
`schemas/jsontron-0.2.json` and its SchemaStore id are untouched.

## Design

### Spec (`spec/jsontron.md`)

Normative text for what the readme describes informally:

- Keyword shapes (`rules`, `assert`, `report`, `let`), by reference to the meta-schema.
- Normalization: sugar forms, and the merge of sibling `assert` / `report` / `let` into the
`context: "."` rule.
- Evaluation: `.` at the schema location's instance, `$root`, `let` order, scope and shadowing,
first-result-or-null binding, jq truthiness for assert and report.
- Messages: implicit quoting of plain text, the `[rule-id][assert-id][flag=value] ` prefix,
non-string results, and an empty message when the message expression fails.
- Errors: each failed assert or report is one error at the instance location of the schema
object carrying the keyword. A jq runtime error in `context`, `let` or `test` fails the
keyword with one error carrying the engine's text (the text is not normative).
- Build time: invalid shape or invalid jq must fail when the schema is compiled.
- **Reference lowering**: a rule set compiles to one jq program that takes `{root, node}` and
returns the array of failure messages. It defines the semantics precisely and is what
engines without evaluation-time variables run. An implementation may evaluate differently
(as .NET does) if it passes the suite.
- **Portable jq profile**: the jq 1.8 features schema authors can rely on in every
implementation, with the known exclusions listed.

### Conformance suite (`tests/`)

JSON files in the style of the JSON-Schema-Test-Suite, one per area (rules, assert sugar,
report, let, merge, severity and ids, nested locations, applicators, build errors, jq profile):

```json
[
{
"description": "report fails when the test is truthy",
"schema": { "report": { "test": ".total < 0", "message": "negative total" } },
"tests": [
{ "description": "positive total", "data": { "total": 5 }, "valid": true },
{ "description": "negative total", "data": { "total": -1 }, "valid": false,
"errors": [ "negative total" ] }
]
},
{ "description": "invalid jq fails at build", "schema": { "assert": ".a |" }, "buildError": true }
]
```

`errors` is compared as a sorted list of messages, so it does not depend on the order in which
a host walks schema locations. A `tests/schema.json` validates the suite files themselves.

### JavaScript (`js/`, npm `ajv-jsontron`)

- `const addJsontron = await loadJsontron(); addJsontron(ajv)`: loading is async because the
wasm module is; everything after is synchronous, as Ajv requires.
- `rules` is a compiled Ajv keyword (`compile(schema, parentSchema)`), which gives the sibling
keywords for the merge and a build-time step. `assert` / `report` / `let` are registered too;
when `rules` is absent, `assert` (else `report`) owns the evaluation.
- Root comes from Ajv's `dataCxt.rootData`. It is passed to jq only when the lowered program
references `$root`, because each call serializes its input.
- Keyword values are validated against the meta-schema definitions, so Ajv strict mode stays on.
- Engine interface `{ check(program), run(program, input) }` with `jq-wasm` as the default.
- TypeScript, ESM + CJS, Node 20+, and the browser through `jq-wasm/inline`.

Spike numbers to keep in mind: about 0.6 ms per jq call, 3.4 ms with a 2,000-item root. A
per-item rule that reads `$root` over 2,000 items took 6.8 s. The readme must say so, and the
TypeScript engine (later phase) is the fix.

### Python (`python/`, PyPI `jsontron`)

- `JsontronValidator = validators.extend(Draft202012Validator, {...})`, used like any
`jsonschema` validator class; also `jsontron.extend(SomeValidator)` for other drafts.
- Keyword callbacks get the parent schema, which gives the sibling keywords for the merge.
- Root: `iter_errors` on the extended class records the top-level instance in a
`contextvars.ContextVar` when none is set, so nested `descend` calls see it.
- `jsonschema` has no per-keyword compile step: lowered programs are compiled on first use and
cached per schema object; `check_schema` is overridden to also compile every jq expression,
so invalid jq fails before the first instance.
- `jq` binds variables at compile time, so `$root` travels in the input (the lowering).
- Python 3.10+, typed, `pyproject.toml` with hatchling, pytest.

Spike numbers: about 1.7 ms per call with a 2,000-item root; same note in the readme.

## Steps

### 1. Rename `src/` to `dotnet/`

- [x] `git mv src dotnet`; update both paths in `Jsontron.slnx`.
- [x] `.netconfig`: re-key `src/Directory.Build.props`, `src/Directory.Build.targets` and
`src/nuget.config` to `dotnet/...` with the same `url`, `sha`, `etag`.
- [x] `.netconfig`: add `skip` entries at the three old `src/` paths, and keep the existing
`src/kzu.snk` skip. The repo-wide `[file] url = https://github.com/devlooped/oss` entry
expands upstream at its default paths and matches by path; without these the nightly sync
recreates `src/`.
- [x] `.netconfig`: add `skip` to `.github/workflows/includes.yml`; change its line 41 to
`dotnet/Directory.Build.props`.
- [x] `_config.yml`: exclude `dotnet/`, `js/`, `python/`, `spec/`, `tests/` instead of `src/`.
It is synced from upstream: mark it `skip` as well.
- [x] Verify: `dotnet build`, `dnx --yes retest`, and `dotnet file changes` shows no file about
to be written under `src/`.
- [x] Commit on a new branch `feature/ports`.

### 2. Spec

- [x] Write `spec/jsontron.md` as described under Design, taking each rule from the C# code
(`RuleSetCompiler.cs`, `JqEvaluation.cs`) rather than from the readme where they differ.
- [x] Write the reference lowering as an algorithm with one worked example.
- [x] List every behaviour the code has that the readme does not state, and decide each one in
the spec (for example: a jq runtime error in a test, a non-string message result).

### 3. Conformance suite, run by .NET

- [x] Create `tests/*.json`, `tests/schema.json` and `tests/readme.md` (120 groups, checked against jq 1.8.2
where the rule set is at the root).
- [x] Port the existing xUnit cases the suite does not cover yet.
- [x] Add cases the xUnit tests lack: jsontron inside `if`/`then`/`else`, `not`, `anyOf`,
`$ref`; `$root` from nested locations; the jq profile features one by one.
- [x] Add a data-driven xUnit theory in `dotnet/Tests` that runs every suite file; keep only
the C# tests that cover .NET-specific API (`MetaSchemas.Register`, dialect, vocabulary).
- [x] One error per failure in .NET. `KeywordEvaluation` has a single `Error` string, so find
how JsonSchema.Net lets one keyword report several (its `Details` sub-results are the
candidate). If it cannot, stop and report: the fallback is a documented separator plus a
helper that splits, and that is a decision for the user.
- [x] Fix any other divergence the suite shows in .NET.
- [ ] File the JQSharp issue: `Jq.Parse` accepts undefined variables (`$x`), jq rejects them at
compile time. Four build-error cases are skipped in the .NET runner's known-gaps list
until then. Proposed as a follow-up task.

### 4. JavaScript port

- [x] Scaffold `js/` (TypeScript, tsup or equivalent for ESM + CJS, vitest).
- [x] Normalization and merge, the lowering, message preparation: pure functions with unit tests.
- [x] Engine interface and the `jq-wasm` engine, with the build-time check.
- [x] Ajv keywords and `loadJsontron`; meta-schema copied from `schemas/` at build, never
duplicated in the source tree.
- [x] Suite runner over `../tests`; all cases pass under Ajv strict mode with `allErrors`.
- [x] `js/readme.md`: quick start mirroring the .NET one, the async load, the performance note.

### 5. Python port

- [x] Scaffold `python/` (`pyproject.toml`, `src/jsontron`, pytest, ruff).
- [x] Normalization, lowering and message preparation, with unit tests. Same algorithm as JS;
the suite is what keeps the two equal.
- [x] `JsontronValidator`, `extend`, root capture, program cache, `check_schema`.
- [x] Suite runner over `../tests`; all cases pass on Windows.
- [ ] Linux and macOS: covered by the `python.yml` matrix, which has not run yet (nothing is pushed).
- [x] `python/readme.md`: quick start, the performance note.

### 6. CI, publishing, docs

- [x] `.github/workflows/js.yml` and `python.yml`: build and run the suite on push and pull
request. New files, because `build.yml` and `publish.yml` are synced from upstream.
- [x] Publishing on release, in the same new workflows: npm and PyPI trusted publishing (OIDC),
as the NuGet publish already does. The user sets up the trusted publishers on npm and PyPI.
- [x] Root `readme.md`: an implementations table and links; the .NET content stays as is.
- [x] `AGENTS.md` at the root (the repository guidance asks for it): layout, spec and suite as
the source of truth, the lowering, per-language integration, how to add a language.
- [x] ~~`changelog.md` entry~~: the file is generated on release from merged pull requests, so
the error-shape change belongs in the pull request title/description instead.

### 7. Go and Rust upstream requests

- [x] Draft the two issues (root instance accessor for custom keywords), each with the Jsontron
use case and the smallest API that would do. Show them to the user; file only after
their approval.

## Deviations and findings during execution

- **Message wrapping changed in the spec** (section 4). Real jq rejects `\"` inside `\(...)`, so
the old rule (escape every `"`) made plain-text messages such as
`order \(.id // "?")`, which the root readme uses, a build error in JS and Python. JQSharp
accepts it, which hid this in .NET. Interpolations are now copied unchanged and a backslash
keeps the next character; implemented in all three, with suite cases.
- **Default message is literal** (decided while writing the spec): an item without `message`
reports its `test` text as is. Before, .NET evaluated that text as a jq string, which broke
on tests containing quotes or `\(`.
- **.NET one error per failure** works: each keyword evaluates a private subschema once per
failure, so failures are child results (`Details`) at `<schema path>/<keyword>`.
- **Python root document** uses a registry of validators (weak references) filled by
`iter_errors` and `evolve()`, not a context variable: `iter_errors` is a generator, so a
context variable would leak into an interleaved validation.
- **Lowering**: each expression is followed by two newlines, not one, because jq 1.8 continues
a comment that ends in a backslash onto the next line.
- **Results on Windows**: .NET 238 passed, 4 skipped (JQSharp gap); JS 276 passed; Python 329
passed.

## Verification

- `dnx --yes retest`, `dotnet format whitespace` and `dotnet format style` for .NET.
- `npm test` in `js/` and `pytest` in `python/`, each running every file under `tests/`.
- The three implementations report the same validity and the same sorted messages for every
suite case; CI fails if any suite file is not run by all three.

## Risks

- **.NET cannot emit several errors per keyword**: handled as a stop-and-ask in step 3.
- **JQSharp differs from jq 1.8** on profile features: each difference is either fixed in
JQSharp or excluded from the profile, case by case.
- **Performance of per-item rules** in JS and Python: documented, not solved here.
- **`jsonschema` internals**: replacing `iter_errors` on the extended class relies on current
behaviour of `descend` / `evolve`; pinned by a test and a minimum version.
- **Synced files**: three more files become local-only (`includes.yml`, `_config.yml`, and the
renamed paths). Upstream changes to them no longer arrive.

## Later, not in this plan

- Native TypeScript jq engine for `ajv-jsontron`.
- Java: networknt json-schema-validator + jackson-jq.
- Go and Rust ports, once the root accessor exists upstream.
2 changes: 1 addition & 1 deletion .github/workflows/includes.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jobs:
shell: pwsh
run: |
$file = "osmfeula.txt"
$props = "src/Directory.Build.props"
$props = "dotnet/Directory.Build.props"
if (-not (test-path $file) -or -not (test-path $props)) {
exit 0
}
Expand Down
80 changes: 80 additions & 0 deletions .github/workflows/js.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Builds and tests the JavaScript implementation (js/) against the conformance suite,
# and publishes it to npm when a release is published.
# Publishing uses npm trusted publishing (OIDC): configure the trusted publisher for the
# @devlooped/jsontron package on npmjs.com with repository devlooped/Jsontron and workflow js.yml.

name: js
on:
workflow_dispatch:
push:
branches: [ main, 'feature/*', 'rel/*' ]
paths: [ 'js/**', 'tests/**', 'schemas/**', '.github/workflows/js.yml' ]
pull_request:
paths: [ 'js/**', 'tests/**', 'schemas/**', '.github/workflows/js.yml' ]
release:
types: [released]

defaults:
run:
working-directory: js

jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ ubuntu-latest, windows-latest, macos-latest ]
node: [ 20, 22, 24 ]
steps:
- name: 🤘 checkout
uses: actions/checkout@v4

- name: ⚙ node
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: js/package-lock.json

- name: 📦 install
run: npm ci

- name: 🔍 typecheck
run: npm run typecheck

- name: 🙏 build
run: npm run build

- name: 🧪 test
run: npm test

publish:
needs: test
if: github.event_name == 'release'
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- name: 🤘 checkout
uses: actions/checkout@v4

- name: ⚙ node
uses: actions/setup-node@v4
with:
node-version: 24
registry-url: https://registry.npmjs.org

- name: 📦 install
run: npm ci

- name: 🏷 version
env:
TAG: ${{ github.event.release.tag_name }}
run: npm version "${TAG#v}" --no-git-tag-version --allow-same-version

- name: 🙏 build
run: npm run build

- name: 🚀 publish
run: npm publish --provenance --access public
Loading
Loading