interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / seed / json / README.md

356 lines · 22100 bytes Raw Blame History Rendered
1# seed/json: strict JSON reader and writer in seeded Omega
2
3These units are part of omega-mv #788 (bounded HTTP/JSON for the private owner assistant). They are a
4strict RFC 8259 reader and writer written in seeded Omega (`.om`). No host
5implementation, generated code, heap, global or host word is used. They
6are written for the compiler pinned at `befb8199db8c4bca188a494dfaac2a6f0ee5c36fcea11188c75666c55fce8a1d`
7(omega-mv `19f014f2`).
8
9Status: EXERCISED on the host (Linux AArch64, DGX Spark) on 2026-10-26. `tests/gate-json.sh` printed
10`JSONGATE PASS rows=8758 mutants=5` against compiler `befb8199…a1d`; see "Evidence" below. That is
11host evidence only. It is not a merge, a deployment, or qualification of any HTTP gateway.
12
13| File | Contents |
14|---|---|
15| `json.om` | Reader: tokenizer and validator, tape accessors, string decoding, exact integers |
16| `jsonw.om` | Writer: checked JSON construction, escaping, lexeme-preserving numbers (needs `json.om`) |
17| `jsonf.om` | Optional exact binary64 conversion and shortest float text (needs both above) |
18| `tests/jsdrv.om` | Test driver program |
19| `tests/gen.py` | Deterministic corpus and CPython oracle (test harness only) |
20| `tests/gate-json.sh` | Gate: parity, refusals, limits, mutants |
21| `tests/big.om`, `tests/growing.py` | Above-old-limit reader/writer/formatter driver and independent CPython oracle |
22| `tests/field.py` | Native function-mode sparse uint-field edges, escape-end scans and guarded reads (test instrument) |
23| `tests/consumers.py` | Compile compatibility of documented repository compositions; optional --base comparison |
24
25## Composition
26
27The units contain no `om2` line, no `global`, no `text` and no host word. The caller composes
28them into one OM-2 program unit:
29
30```sh
31{ printf 'om2\n'; cat seed/json/json.om seed/json/jsonw.om [seed/json/jsonf.om] seed/net/http.om seed/net/notls.om app.om; } > app.full.om
32nice -n 19 seed/out/omc < app.full.om > app
33```
34
35Arrays are caller-owned OM-2 unsized parameters (`view uchar *`, `edit uint *`). A global cannot be
36passed as an argument, so the input, tape and output must be locals of the caller or arrays that
37the caller received. The 4 MiB local-array limit of `omc` applies. For example, a 300 KiB body, a
3865532-token tape and a 1 MiB writer buffer together use about 2.3 MiB.
39
40Names: functions are `js_*`, constants `js*`. Locals are short lowercase names. A unit
41composed with these files must not define functions, globals or constants whose names collide
42with those names. Its own function names should also be longer than three characters.
43
44Two limits of omc at pin `befb8199` affect composition. Both were reported to the compiler owner
45(OmegaNext):
46
47- Any `const` makes a function-mode unit fail with error 9 at end of input. OmegaNext reports the
48 fix as omega-mv PR #806. Until it lands, the library compiles only into a program (`fn main`);
49 the gate checks it with an empty `main`.
50- A `const` defined after any `fn` makes a later signature that names an earlier const as an
51 array length fail with error 16. Composed after `jsonf.om`, a unit that defines constants must
52 therefore not write `fs edit long jsfs` in its own signatures. Pass the array to the `js_*`
53 functions from the function that declares it (`fs = new long jsfs 0`), or write the length 2464
54 directly, as `tests/jsdrv.om` does.
55
56## Limits
57
58| Limit | Value | Where |
59|---|---|---|
60| Input bytes per parse | 1 .. 4294967295 (`jsmaxn`, the 32-bit offset cell of the tape), chosen per tape at `js_init` | refusal 5 |
61| Nesting depth | 1 .. 65535 (`jsdcap`), chosen at `js_init` | refusal 4 |
62| Tokens | `(len tape - 16) / 4`, at most 16777215 | refusal 11 |
63| Writer nesting | 1024 | writer refusal 25 |
64| Writer output | `len ob - 1040` bytes | writer refusal 21 |
65
66Until 2026-11-12 the input bound was 983040 bytes, chosen so that every loop bound stayed under the old
67limit 999999 of `while ... bound N`. omc now takes N up to 2^63 - 1, so the loops use that bound and the
68proof is unchanged: each parser step uses at least one distinct input byte, so the steps number at most
69n + 1. The input bound is now the tape format's 32-bit offset cell. What a caller can hold is set by omc:
70the input and tape are caller arrays (locals, at most 4 MiB per function, or parameters), because a global
71or a run-time pool cannot be passed as an argument (OMEGESE 9.15, error 19 / 7).
72
73**Remaining boundary for runtime input held by an Omega caller today:** a source local can contain
74at most 4194304 bytes (the compiler's 4 MiB local-array allowance per function). Put input, tape and output in separate
75call frames if their sum exceeds that allowance; their combined live frames must still fit the
76compiler's 8 MiB program stack. Passing a pool as a view is not implemented here and remains Drake's
77decision. The 4294967295-byte tape-field boundary is therefore not a reachable all-Omega input-size
78promise. tests/field.py independently exercises actual sparse 4 GiB source views through the documented
79native function-mode pointer/length slots: that is host-ABI evidence, not a new Omega caller facility.
80Static text or native-supplied views are different constructions, not growing runtime input pools.
81The native test checks the inclusive field edge and refusal immediately beyond it, without scanning 4 GiB of bytes.
82
83Sizes are checked before narrowing into the tape. A size refusal invalidates previous success/tokens
84and records error 5 at the configured limit, rather than trapping on the uint conversion. The internal
85number scanner and position-returning escape scanners use zero for failure: successful next/end
86positions are nonzero, so position 4294967295 is never confused with jsnone. Both writer loops consume the
87admitted span and stop immediately on sticky output failure, including before another source read.
88The decimal exponent is accumulated exactly until its magnitude exceeds the mantissa displacement
89plus the binary64 range; early exponent saturation cannot erase long-mantissa cancellation.
90
91## Reader API (`json.om`)
92
93```
94js_init tape edit uint * slim ulong dlim ulong to long 0, or -13 (bad limits, tape < 20 cells)
95js_parse src view uchar * tape edit uint * n ulong to long token count, or -code (tape then empty)
96```
97
98`js_init` sets up the 16-cell header and the limits once. After that, `js_parse` may be called
99on the same tape any number of times. It parses `src[0 .. n)` as exactly one JSON text,
100optionally surrounded by whitespace. After a refusal, `js_err` and `js_epos` give the code and
101the byte position, and no token is visible.
102
103Accessors take `tape view uint *` and return 0, or `jsnone` (4294967295), on a refused or
104uninitialised tape or an out-of-range token:
105
106| Function | Result |
107|---|---|
108| `js_ok tape` | bool: the last parse succeeded |
109| `js_ntok tape` | token count |
110| `js_err tape`, `js_epos tape` | refusal code and byte offset |
111| `js_maxdep tape` | deepest nesting seen |
112| `js_dtotal tape`, `js_dmax tape` | decoded bytes of all keys and strings, and of the longest one |
113| `js_type tape t` | 1 `{`, 2 `}`, 3 `[`, 4 `]`, 5 key, 6 string, 7 number, 8 true, 9 false, 10 null |
114| `js_off tape t`, `js_span tape t` | source byte offset and length. A container spans from its bracket to its closing bracket; a string includes its quotes; a number is its lexeme |
115| `js_match tape t` | for a bracket, the index of the matching bracket |
116| `js_nkids tape t` | members of an object or elements of an array |
117| `js_slen tape t` | decoded byte length of a key or string |
118| `js_nflags tape t` | number flags: 1 minus sign, 2 fraction, 4 exponent |
119| `js_last tape t` | last token of the value at `t` |
120| `js_first tape t` | first key or element of a non-empty container, else `jsnone` |
121| `js_mnext tape k` | the key after member key `k`, else `jsnone`. The value of key `k` is `k + 1` |
122| `js_enext tape e` | the element after array element `e`, else `jsnone` |
123
124Each token occupies 4 cells starting at 16 + 4t. Cell 0 holds the type, the flags shifted left
125by 4 and the child count shifted left by 8. Cell 1 is the offset, cell 2 the span, and cell 3
126holds the match for a bracket or the decoded length for a string. Tokens appear in source
127order. Duplicate member names are kept, in order. RFC 8259 section 4 leaves their meaning to
128the application.
129
130Strings from the source:
131
132```
133js_sget src view uchar * off ulong ob edit uchar * to long decode the string at src[off]; bytes or -code (-13 short ob)
134js_streq src view uchar * off ulong key view uchar * to bool decoded string equals key bytes exactly
135```
136
137`js_slen`, or `js_dmax` for every string at once, gives the buffer size needed. Decoding
138writes UTF-8: escapes are resolved and a surrogate pair becomes one 4-byte code point.
139
140Integers are exact. Nothing is ever rounded silently:
141
142```
143js_ilex src off 0 not an integer lexeme, 1 integer with |v| <= 2^64-1, 2 larger
144js_isu / js_tou fits ulong (no minus sign) / its value (0 when not)
145js_isl / js_tol fits long / its value (0 when not); "-0" is 0
146```
147
148Any other number keeps its lexeme. A caller can copy it, compare it, or write it back
149unchanged (`js_wlex`). Conversion to binary64 is an explicit opt-in (`jsonf.om`).
150
151## Reader refusals
152
153`js_parse` returns minus the code. `js_epos` is the byte offset where the refusal was found.
154
155| Code | Name | Meaning |
156|---|---|---|
157| 1 | `jseeof` | input ended inside a value (also empty input) |
158| 2 | `jsesyn` | unexpected byte, including a byte-order mark, a trailing comma, a missing `:` |
159| 3 | `jsetrl` | bytes after the root value |
160| 4 | `jsedep` | an opening bracket would exceed the depth limit |
161| 5 | `jsesiz` | n is over the size limit (position = the limit) |
162| 6 | `jseutf` | ill-formed UTF-8 inside a string (RFC 3629 section 4: overlong, surrogate, > U+10FFFF, stray or missing continuation) |
163| 7 | `jsesur` | a `\u` surrogate that is not one high-then-low pair |
164| 8 | `jsectl` | a raw byte below 0x20 inside a string |
165| 9 | `jseesc` | an unknown escape or a non-hex `\u` digit |
166| 10 | `jsenum` | number grammar (leading zero, `1.`, `-`, `1e`) |
167| 11 | `jsetok` | the tape is full |
168| 12 | `jselit` | a misspelled `true`, `false` or `null` |
169| 13 | `jsearg` | bad arguments (n > len src, tape not initialised, limits out of range) |
170
171Outside strings only the four RFC whitespace bytes and the grammar's ASCII are accepted, so
172any non-ASCII byte there is refused as code 2. Strings are validated during the parse, and
173`js_sget` checks them again: it never trusts the offset it is given.
174
175## Writer API (`jsonw.om`)
176
177The caller passes one `ob edit uchar *` array. Its first 1040 bytes are the writer state, and
178the JSON text is `ob[1040 .. 1040 + js_wlen ob)`.
179
180```
181js_winit ob reset, 0 or -26 (ob <= 1040 bytes)
182js_wobj / js_wobje / js_warr / js_warre ob
183js_wnull ob, js_wbool ob b, js_wulong ob v, js_wlong ob v
184js_wnumb ob s off n s[off..off+n) must be exactly one RFC 8259 number lexeme; copied unchanged
185js_wlex ob src off the lexeme of a parsed number token at src[off], unchanged
186js_wsbuf ob s off n a string from raw UTF-8 bytes (validated, escaped)
187js_wsbeg ob / js_wsb ob c / js_wsend ob the same, streamed one byte at a time
188js_wsrc ob src off re-encode the parsed key or string at src[off]
189js_wtok ob src type off write one parsed token (rewriting a whole tape in order reproduces the value)
190js_wdone ob text length if exactly one complete value was written, else -code
191js_wlen ob, js_werr ob
192```
193
194A string is written as a member key when the innermost open container is an object that is
195waiting for a key. Otherwise it is written as a value. Commas and colons are inserted
196automatically. Every call checks the state, so the writer can only produce RFC 8259 text.
197The first refused call records its code, and every call after it writes nothing.
198
199Escaping follows RFC 8259 section 7 exactly as CPython `json.dumps(..., ensure_ascii=False)`
200does. `"` and `\` are escaped. `\b \f \n \r \t` use their short forms. The other bytes below
2010x20 become `\u00xx` with lowercase hex. Everything else, including `/`, DEL and all non-ASCII
202UTF-8, is copied unchanged.
203
204| Code | Name | Meaning |
205|---|---|---|
206| 21 | `jswesp` | output array full |
207| 22 | `jswest` | call not valid in this state (a value where a key is due, a second root, a key without a value, a mismatched close, an unfinished string, nothing written) |
208| 23 | `jsweut` | ill-formed UTF-8 in string bytes |
209| 24 | `jswenm` | not a number lexeme; infinity and NaN, which JSON cannot represent |
210| 25 | `jswedp` | nesting over 1024 |
211| 26 | `jswearg` | bad array or slice |
212| 27 | `jswesrc` | `js_wsrc` offset is not a well-formed source string |
213
214## Optional floats (`jsonf.om`)
215
216```
217js_f64 src off fs -> f64 nearest binary64, ties to even; overflow +-inf, underflow +-0
218js_f64st fs -> ulong 0 finite, 1 overflowed to infinity, 2 no number lexeme at off (NaN returned)
219js_fmt64 fs x -> long shortest round-trip text at fs[2416 ..], or -1 for inf/NaN
220js_fmtch fs i -> uchar byte i of that text
221js_wf64 ob x fs write it (inf/NaN refused with 24)
222```
223
224`fs` is a caller `long` array of `jsfs` = 2464 cells, about 19 KiB. The method is the
225arbitrary-precision decimal of Go `strconv`: `decimal.go` with its shifts, `atof.go` `floatBits`,
226and `ftoa.go` `roundShortest`. It uses 800 digits plus a truncation flag and is exact for every
227lexeme, including more than 800 significant digits and exact halfway cases. The text uses
228Python `repr` layout. Fixed notation is used when the decimal exponent x satisfies -4 <= x < 16,
229with `.0` added to whole numbers. Otherwise the layout is `d.ddde+XX`.
230
231This is deliberately **not** the numeric contract of `serde_json` 1.0.151. Its default float
232parser is not correctly rounded. Cortex's `/tmp/cxo/cortex/om/f64.om` replicates that behavior
233for Cortex parity and needs about 230 MB of pools. Neither its numeric contract nor its
234allocation is used here.
235
236## Tests
237
238```sh
239nice -n 19 sh seed/json/tests/gate-json.sh
240```
241
242The gate needs Linux AArch64, python3 >= 3.11, and the pinned `seed/out/omc`. If any of these
243is missing, it prints `JSONGATE NOT_RUN` and exits 3. It runs these steps:
244
2451. It checks that the library has no `global`, `text`, `om2` line or host word, and that it
246 compiles on its own with an empty `main`.
2472. It builds the driver `tests/jsdrv.om`. `tests/gen.py` writes a deterministic corpus (seed 788)
248 containing the following inputs:
249 - hand-written valid and invalid cases;
250 - 39 refusals whose code and position are pinned (36 listed in `PINNED`, plus depth, capacity and gateway size);
251 - the size and depth boundaries, both inclusive;
252 - token capacity;
253 - a 307200-byte (300 KiB) gateway chat request, which must be accepted at limit 307200 and
254 refused at 307199;
255 - about 1,900 float lexemes, including exact binary64 midpoints, midpoints plus or minus
256 10^-900 relative (more than 800 digits), subnormals and overflow;
257 - 700 random documents with random escaping and whitespace;
258 - 900 byte-level mutants of them;
259 - 150 surrogate-escape documents;
260 - writer scripts.
2613. Every parse case runs in four modes. The two token modes, the flat token stream and the walk
262 through the navigation API, must both match CPython `json.loads`. That parse uses the C
263 scanner with `parse_int`/`parse_float` hooks receiving exact lexemes and `object_pairs_hook`
264 to keep order and duplicates. Every span, match, flag and decoded length is also self-checked.
265 The f64 mode must match CPython `float()`, `repr()` and its bits, and the integer accessors
266 must match `int()`. The rewrite must be byte-identical to a serializer built from
267 `json.encoder.c_encode_basestring` with lexemes kept. Writer scripts must match pinned bytes
268 and refusal codes.
2694. A driver input larger than its array exits 93. The 4 MiB driver distinguishes EOF, read error
270 (90), and overflow (93), including an invalid byte appended to the full valid workflow fixture.
271 Growth cases exercise reader, raw-string writer, number writer, token rewrite and float formatting
272 beyond 983040 bytes. CPython `float`, binary64 bits and `repr` independently check balanced
273 million-digit mantissas/exponents and randomized long numbers. Native sparse views check both
274 uint-field edges and number consumers at the maximum end offset; guard pages prove exhausted
275 output stops before reading another source byte. Escape probes also scan a real field-width string
276 ending in a simple/Unicode escape and compare its closed control; a sparse valid writer string
277 crosses the same next-position edge. Growth/field mutants restore each defect.
2785. Five mutants must each be caught:
279 - an overlong E0 sequence accepted;
280 - raw 0x1F accepted;
281 - the depth limit off by one;
282 - 0x1F written unescaped;
283 - halfway cases rounded up instead of to even.
284
285The oracle differs from CPython in four documented places. CPython accepts all of them, and RFC
2868259 or the limits require refusing them:
287- lone surrogate escapes (RFC 8259 section 8.2: strings must be Unicode text);
288- `NaN`, `Infinity` and `-Infinity`, which CPython accepts by default (`parse_constant` refuses);
289- depth over the limit;
290- size or tape capacity over the limit.
291
292CPython is a test-only referee, fixture generator and driver. The original corpus oracle writes no
293compiled implementation. The growth/field instruments compose the hand-written Omega driver/wrappers
294and explicit source mutants; all JSON implementation and conversion remains seeded Omega.
295All acceptance and mutant checks use explicit failure branches, not Python assertions. Test execution,
296including mprotect in the native guard probes, is never removed by PYTHONOPTIMIZE. Each Python gate
297accepts --wrong-expectation to make one expected result deliberately wrong; running that control
298with PYTHONOPTIMIZE=1 must fail. The existing corpus generator and local evidence instruments use
299the same unconditional-check rule. Long balanced exact midpoint cases straddle zero/min-subnormal,
300subnormal/normal and finite/overflow rounding thresholds, with both signs and both mantissa forms.
301Fixed-size callers must use a constant for their own allocation and signatures, not jsmaxn (the
302library format ceiling). The Node acceptance drivers use their own ndjsz declared in nodedrv.om.
303consumers.py compiles each concrete documented composition, including the Node drivers, benchmark
304chat/fake-model, agent, library variants and native probes. JSON_COMPAT_BASE=REF adds base/head
305compile-status parity; its manifest records exact inputs, citations and any new test application
306held identical across both library versions. Three width mutants must be compile refusal 23.
307The gate prints `SOURCE`, compiler/source hashes, and a final PASS naming the checkout head; retain
308that output from a clean committed tree as the exact-head receipt.
309
310Driver modes and the writer-script language are documented at the top of `tests/jsdrv.om`. A
311writer script has one operation per line:
312
313- `o O a A`: object or array open and close;
314- `s<hex>`: a string from bytes;
315- `S`, `b<hh>`, `E`: a streamed string;
316- `n<lexeme>`: a number lexeme;
317- `u<dec>`, `l<dec>`: unsigned and signed integers;
318- `t f z`: true, false, null;
319- `d<16 hex>`: f64 bits.
320
321Numeric constants were checked with WolframLanguageEvaluator:
322- `{2^64-1, Quotient[2^64-1,10], Mod[2^64-1,10], 2^63}` -> `{18446744073709551615, 1844674407370955161, 5, 9223372036854775808}`;
323- surrogate bounds `FromDigits[{"D800","DBFF","DC00","DFFF"},16]` -> `55296, 56319, 56320, 57343`;
324- UTF-8 lead and continuation bytes `80 C2 E0 ED F0 F4 A0 9F 90 8F BF` -> `128 194 224 237 240 244 160 159 144 143 191`;
325- `2^52-1 -> 4503599627370495`, `2^53 -> 9007199254740992`;
326- the quiet NaN `FromDigits["7FF8000000000000",16] -> 9221120237041090560`;
327- the scratch layout `16+3*800 -> 2416`, `+48 -> 2464`.
328
329## Evidence
330
331This run was on 2026-10-26, on Linux aarch64 (DGX Spark host), with Python 3.12.3. The tree was
332omega-mv `58d6fb6a2f72b1ab02c0eb0c01afe141303c968d` with these units uncommitted on top.
333
334```
335ionice -c3 nice -n 19 sh seed/json/tests/gate-json.sh -> exit 0
336COMPILER befb8199db8c4bca188a494dfaac2a6f0ee5c36fcea11188c75666c55fce8a1d
337SRC 456254fc754ea35103ced480407b24fc1a3896d094b90ae0e9623e7b6594e2d2 seed/json/json.om
338SRC 464f649e8207495f5d67fe8795d31e42ea3ccebd9ed547274dab802d4f7c5f21 seed/json/jsonw.om
339SRC bade33cef4b7edcc834c436d8499810aa573e02a97fb0dafded3736744e67a29 seed/json/jsonf.om
340SRC 2f2f8ac522db876db55bca464060ab6e1071447180f51c4e53051d4ce3ddd710 seed/json/tests/jsdrv.om
341gen.py 6e8169151790a07e1cca57505e0bbdce729b5b8db9ab121adbd2c0041f835985
342DRIVER 15e928704eb5be7f078712c77e536940053541e245018472d58d9f9259c13778
343GEN cases=2764 rows=8758
344JSONGATE PASS rows=8758 mutants=5
345```
346
347Of the 2003 parse cases checked in mode `t`, 1094 were compared byte for byte and 909 were
348refusals checked by their `ERR ` prefix. Pinned refusals are compared exactly. All five mutants
349made the parity run fail. If any of the hashes above change, this record no longer applies; rerun
350the gate.
351
352Re-verified 2026-10-26 after refresh onto main `c5d981041` with reseeded `seed/out/omc` `189ada82e00bb440cb41351bd252cc68c54a1b1050051cc42a1df700081c3b54`: `JSONGATE PASS rows=8758 mutants=5`; gate pin updated.
353
354Re-verified 2026-10-26 on `integ/omc-batch2` with the batch 2 `seed/out/omc` `2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f`: `JSONGATE PASS rows=8758 mutants=5`; gate pin updated. Negative controls: the 189ada82 compiler, and the old pin given through `JSON_OMC_PIN`, both end in `JSONGATE FAIL ... differs from pin` (exit 1).
355
356Re-verified 2026-10-27 on `build/omc-batch3-896-897-898-903` with the batch 3 `seed/out/omc` `397346de169d78e8a5ce53dce6cf9f0ca56a8f527128165bbfb4fb62a335f93e`: `JSONGATE PASS rows=8758 mutants=5`; gate pin updated. Negative control: the 2c824805 compiler ends in `JSONGATE FAIL ... differs from pin` (exit 1).