Repository navigation
state_exec: json-parse, json-encode and state-set-tree, so documents can read REST replies - #883
Merged
Merged
Conversation
…can read REST replies
Ariadne documents get HTTP bodies as raw text. Nothing in state_exec read general JSON:
state-json and state-from-json only handle cvc::state's flat, path-keyed document, and
state-from-json collapses arrays into their parent node.
- (json-parse text): JSON text, or bytes such as a reply's body, to values. An object is a dict
in document order, an array a list, null nil. A number without a fraction or exponent is an
int when it fits in 64 bits, and otherwise a float (as JavaScript reads it); one too large
for a float is an error. A repeated key keeps its first place and takes its last value, as
JSON.parse and json.loads do. Invalid UTF-8 and lone surrogates become U+FFFD. Malformed text
is a ValueError naming the line and column, with `line`, `col` and `offset` fields.
- (json-encode value [indent]): compact, or `true` for 2 spaces, or 1 to 10. Dict order is
kept; a float always has a point or exponent, so it reads back as a float. A type JSON lacks
is a TypeError; nan, a string that isn't UTF-8 and a self-containing list or dict are
ValueErrors.
- (state-set-tree path value): a parsed value as the subtree at `path`, so binds and `repeat:`
can show it. Keys and indices name children, and a list's node holds its length, so
`repeat: (state-get "feed.items")` and `bind: feed.items.{i}.text` render an array. It
replaces the subtree, removing children the value doesn't name, skips nodes whose text is
unchanged, and checks the whole value before writing anything.
No new dependency. All three are data jobs, so a large reply runs a slice per scheduler step
against max_steps and max_time, and what they build is held to the allocation limit; a library
parser would run the whole text inside one step. Lists and dicts nest at most 512 levels
(kJsonMaxDepth), checked without recursion. Parser and encoder are json.cpp (about 700 lines),
standard C++ only, so it builds wherever libcvc does, wasm included.
Also:
- state::childNames(): a node's direct children (children() lists every descendant).
- json-parse and json-encode are on the reactive lane's allowlist.
- pycvc wraps make_json_parse_job, make_json_encode_job, kJsonMaxDepth and kJsonMaxIndent.
- examples/ariadne/documents/json_feed.ari parses a JSON literal and renders it with repeat:,
and ariadne_ftxui_test renders it.
- Docs: STATE_EXEC_DEVELOPER_GUIDE.md §2 "JSON" and §5, ARIADNE.md §10.3,
STATE_EXEC_GRAMMAR.md, PYCVC_STATE_EXEC_PARITY.md.
…ri in both terminal backends FTXUI leaves the cell after a full-width glyph (CJK, an emoji) empty, since the glyph covers it. render_to_string's plain text printed that cell as a space, so every wide glyph pushed the rest of its line a column right and a window's right edge went ragged. Screen::ToString() (--ansi, and the live terminal) leaves the cell out; now the plain text does too. The tvision desktop already did: it skips the empty cell when it blits a hosted window. json_feed.ari gets a fourth post written with JSON \u escapes: accented letters, CJK and a surrogate-pair emoji. Tests: - WideGlyphsTakeTwoColumnsInTheTextSnapshot: CJK, an emoji, combining and composed accents in a window; every row ends in the same column. It fails without the fix. - JsonFeedDocumentRepeatsOverAParsedArray: what `ari snapshot` prints of the example, every row the same width. It fails without the fix. - JsonFeedDocumentFillsItsHostedWindow: the example through TvisionBackend's hosted layout, the cells the tvision desktop blits: a cell per column, each wide glyph followed by the cell it covers.
…tmux `ari snapshot` always lays out with FTXUI, so nothing checked what the tvision desktop, or the live FTXUI screen, puts on a terminal. run_in_tmux_test.sh runs `ari run --backend B` in a 100x30 tmux pane on a server of its own, waits for the document, and compares the text inside the window's borders with tests/json_feed.rows. Each row there ends in '|' where the right border is, so a wide glyph (the CJK and emoji row) that took the wrong number of columns fails it. ari_run_json_feed_ftxui and ari_run_json_feed_tvision are registered on Linux when tmux is found. A backend this ari lacks is skipped (77). Both pass locally with cvcpkg's tvision and ncurses, and fail when the expected row is one column off.
…MSVC)
MSVC's traditional preprocessor reads a raw string inside a macro's arguments as an ordinary
string, so R"("\"\\\/\b\f...")" in EXPECT_EQ failed to compile (C2017 illegal escape, then
C2065/C2146), and R"("\ud83d")" was a surrogate universal-character-name (C3850). The windows
recipe lane (run 40988493178) failed on them. The JSON texts are now named constants; the
assertions compare against those.
# Conflicts: # src/ari/CMakeLists.txt
…took §10.3 #888 added §10.3 (the host's allowlist and credentials) beside this branch's §10.3, so the merge left two. The JSON section is now §10.4, its links follow, and its http-get example says the host has to allow the origin.
This was referenced Oct 30, 2026
transfix
added a commit
to cy-pca/cypkg
that referenced
this pull request
Oct 30, 2026
…est logic .github/workflows/test.yml builds a stock ari from libcvc master with transfix/libcvc#883 and #896 merged on top (skipping any that have merged), with libcvc's dependencies from cvcpkg as libcvc's CI gets them, and runs every test layer. The built ari is cached by its libcvc source tree. A daily job runs the contract check against cvcpkg.org. tests/logic.sh runs 17 ari test tests (tests/logic.tests.yaml) on a copy of main.ari pointed at the fixture registry. Each drives main.ari's real on_tick the way the views do and asserts on the state they read. main.ari counts finished requests (search.seq, pkg.seq) so a test can wait for one.
# Conflicts: # src/cvc/tests/state_exec_builtins_test.cpp
…ts in full #885 made state-set write a float in its shortest round-trip form, as state-set-tree already did, so the comment, the developer guide and a test note no longer call that a difference.
transfix
pushed a commit
that referenced
this pull request
Oct 30, 2026
…her order #883 adds a JSON section right after Type Conversion and edits the builtin list's String line and ARIADNE.md's value-allowlist bullet. These edits touched the lines next to those, so whichever PR merged second would conflict: the Surprises list now sits before Type Conversion, the Logic line is left as it was (and/or are still functions as values; the special forms table says so), and §2.1's gate list changes only its second line.
This was referenced Oct 30, 2026
This was referenced Oct 31, 2026
Merged
transfix
added a commit
that referenced
this pull request
Oct 31, 2026
…) (#926) * Ariadne: WebSocket client verbs (ws-open, ws-send, ws-poll, ws-recv, ws-close) A document can follow a server that pushes changes instead of polling it. cvc::net gets a WebSocket client (ws_client.h) with two backends: libcurl's WebSocket API natively, so wss:// has the same TLS and proxy handling as https://, and the browser's WebSocket under Emscripten. Messages arrive whole in a queue; ws-poll takes what is there without waiting, for on_tick loops, and ws-recv waits on the background pool. The host's policy checks a ws(s) URL as its http(s) twin, and auth/headers/credential values work as for the HTTP verbs (natively; a browser WebSocket sends no headers). Documented in ARIADNE.md 10.5, with client tests against a Beast server and verb tests in ariadne_runtime_test. * ws client tests: a Beast close code is an enum; copy the handshakes before looping over them * ws client: build on MSVC (windows.h's min macro broke std::min) * ws verbs: clang-format the changed lines * ws client: close before queueing the oversized-message error The reader queued the Error event and then closed, so a recv on another thread could take the error while open() was still true; NetWsClient. AnOversizedMessageIsAnError failed about one run in five. Closing first matches the peer-close path, which clears open_ before it queues. * Ariadne: ws-send carries a credential the host puts in A browser's WebSocket can't send request headers, so a document in the wasm page could only authenticate a live feed by holding the token and sending it in a message, and documents never see tokens. Now (ws-send H MESSAGE) sends a dict or list as JSON (json-encode, compact), and a (dict "credential" NAME) anywhere in it goes out as the host's token for NAME, a JSON string: (ws-send h (dict "type" "hello" "token" (dict "credential" "txwtf"))) - The token is fetched for the origin the connection was opened and checked as (its URL's http(s) twin, now kept in the handle table), so credential bindings apply as for HTTP. It is put in on the host just before the send, with room reserved so no replace leaves a copy in a freed buffer, then wiped; a send error is redacted. - A name with no token at that origin, or a credential value on a host that keeps no credentials, is an error and sends nothing. - Each connection remembers the credentials it has sent (handshake auth and header values too), and ws-recv / ws-poll blank them to [redacted] in what they return, as perform() does for an HTTP reply, should the server echo one. - A string message is sent as it is, as before. Tests: AriadneNetHost.WsSendPutsInTheHostsTokenThatNoValueHolds checks, against LocalWsServer, that the server gets the substituted token while no state node, error or warning holds it, that an echo comes back redacted and that a missing credential sends nothing; the round-trip test checks plain JSON and a host without credentials. Spec: docs/ARIADNE.md section 10.5. Merges master for #883's builtin_json_encode. --------- Co-authored-by: nicotina-ci <[email protected]>
This was referenced Oct 31, 2026
transfix
added a commit
that referenced
this pull request
Nov 6, 2026
* Ariadne L4: requests in single-threaded wasm don't stall the frame loop
In a browser build without threads the background pool's jobs run on the page's main thread,
so an http verb's kernel ran inside the frame pump and spun on emscripten_sleep(0) until the
reply came: nothing drew or took input for the whole request (100-300 ms, up to the 30 s
timeout).
- cvc::net: start(req[, policy], done) -> HttpTransfer (abort()), and http_starts_async().
The browser fetch backend issues an emscripten_fetch and returns; onsuccess/onerror deliver
the reply from the event loop. It reports a timeout as one, enforces the 64 MiB cap as the
body arrives, and aborts cleanly (no callback after abort). Elsewhere start() sends in place.
The policy check follows redirects hop by hop, as send(req, policy) does (shared next_hop).
- state_exec: async_work {kernel, start} and a register_async_fn overload. Where the call can
park, start() begins the work and the call is an external one with the registration's
timeout and charging; the work settles and posts it. async_call::on_cancel(stop) is how a
kill, a timeout or the host's shutdown stops it. Elsewhere the kernel runs as before.
- The net verbs (http-get, http-request) return an async_work when the transport starts
requests without blocking: credentials go in and captures come out in C++ around the
started request (perform split into prepare/complete). fetch of an http(s) URI uses the
http handler's new non-blocking form (register_uri_async_handler / resolve_async); a host's
own handler for the scheme drops it.
- AppRuntime::idle() counts the scheduler's calls in flight (started ones included), and
settle() yields to the browser's event loop in wasm, so ari snapshot waits for the reply.
Tests: AsyncCalls started-call cases (park, timed await slices, errors, kill, timeout,
shutdown, kernel fallback), NetStart (in place, later, policy hop by hop, abort),
AriadneNetL4 (frames go on while a program is parked on a request, await slices, teardown
aborts, credentials and capture on the started path, policy refusal, fetch). CI: the wasm
ari's node job runs tests/l4_frames.ari against a 1 s endpoint and fails unless frames ran
while the request was out (218 here; 0 with the blocking path).
Docs: ARIADNE.md 10.2, STATE_EXEC_EXCEPTIONS.md 3.12.
* Ariadne: WebSocket client verbs (ws-open, ws-send, ws-poll, ws-recv, ws-close)
A document can follow a server that pushes changes instead of polling it.
cvc::net gets a WebSocket client (ws_client.h) with two backends: libcurl's
WebSocket API natively, so wss:// has the same TLS and proxy handling as
https://, and the browser's WebSocket under Emscripten. Messages arrive whole
in a queue; ws-poll takes what is there without waiting, for on_tick loops,
and ws-recv waits on the background pool. The host's policy checks a ws(s)
URL as its http(s) twin, and auth/headers/credential values work as for the
HTTP verbs (natively; a browser WebSocket sends no headers).
Documented in ARIADNE.md 10.5, with client tests against a Beast server and
verb tests in ariadne_runtime_test.
* ws client tests: a Beast close code is an enum; copy the handshakes before looping over them
* ws client: build on MSVC (windows.h's min macro broke std::min)
* Ariadne: ws-open and ws-recv don't stall the frame loop in single-threaded wasm
#923's browser WebSocket waited in loops on emscripten_sleep(10): WebWsConnection::wait_open
inside ws_connect (up to the 15 s connect timeout) and recv (up to ws-recv's seconds). Without
-pthread those kernels run on the pump thread, so ws-open and ws-recv froze the page, as http-get
did before #914. This moves them onto #914's path.
- cvc::net: ws_start(url, opts, done) and WsConnection::recv_async(timeout, done), plus
ws_starts_async() and a set_ws_connector seam (WsConnector), as set_http_client is for HTTP.
The browser backend in a build without threads answers from the WebSocket's own callbacks
(on_open / on_error / on_close / on_message) and emscripten_set_timeout timers; the returned
stop function abandons a connect (closing the socket, a connecting one too) or drops a wait.
Elsewhere both wait in place, as before.
- ws-open and ws-recv return a state_exec async_work (#914) when ws_starts_async(): the program
parks, frames go on, and the callbacks post the reply; a killed or timed-out call abandons its
connect or drops its wait (on_cancel). ws-open's checks, credentials and handle table are
shared by the kernel and the started path (build / prepare / finish_ws_open).
- WebWsConnection::close sends 1000 for a code a page may not send (WebSocket.close throws on
anything but 1000 and 3000-4999, the 1001 and 1013 this file uses included).
Tests: AriadneNetL4.WebSocketOpenAndRecvAreStartedWhileFramesGoOn and
ATornDownDocumentAbandonsItsConnectAndItsWait (a deferred connector and connection the test
answers between frames; forcing ws-open back to its kernel fails both). CI: the wasm ari's node
job runs tests/l4_ws.ari against tests/ws_probe_server.py (stdlib; a 1 s handshake, then a
message 1 s later) and fails unless 20 frames ran during each wait: 354 and 374 here, 0 and 0
with the blocking path.
Docs: ARIADNE.md 10.5.
* ws verbs: clang-format the changed lines
* ws client: close before queueing the oversized-message error
The reader queued the Error event and then closed, so a recv on another
thread could take the error while open() was still true; NetWsClient.
AnOversizedMessageIsAnError failed about one run in five. Closing first
matches the peer-close path, which clears open_ before it queues.
* Ariadne: ws-send carries a credential the host puts in
A browser's WebSocket can't send request headers, so a document in the wasm
page could only authenticate a live feed by holding the token and sending it
in a message, and documents never see tokens. Now (ws-send H MESSAGE) sends a
dict or list as JSON (json-encode, compact), and a (dict "credential" NAME)
anywhere in it goes out as the host's token for NAME, a JSON string:
(ws-send h (dict "type" "hello" "token" (dict "credential" "txwtf")))
- The token is fetched for the origin the connection was opened and checked
as (its URL's http(s) twin, now kept in the handle table), so credential
bindings apply as for HTTP. It is put in on the host just before the send,
with room reserved so no replace leaves a copy in a freed buffer, then
wiped; a send error is redacted.
- A name with no token at that origin, or a credential value on a host that
keeps no credentials, is an error and sends nothing.
- Each connection remembers the credentials it has sent (handshake auth and
header values too), and ws-recv / ws-poll blank them to [redacted] in what
they return, as perform() does for an HTTP reply, should the server echo one.
- A string message is sent as it is, as before.
Tests: AriadneNetHost.WsSendPutsInTheHostsTokenThatNoValueHolds checks, against
LocalWsServer, that the server gets the substituted token while no state node,
error or warning holds it, that an echo comes back redacted and that a missing
credential sends nothing; the round-trip test checks plain JSON and a host
without credentials. Spec: docs/ARIADNE.md section 10.5.
Merges master for #883's builtin_json_encode.
* Ariadne: ws-open offers subprotocols, and a credential as one
A browser's WebSocket can send no request headers, but it can offer
subprotocols, so a credential there is the one handshake auth a document in the
wasm page can use. ws-open takes two new options:
- "protocols": a list of subprotocols to offer (Sec-WebSocket-Protocol), each an
HTTP token.
- "auth_protocol": (dict "credential" NAME ["prefix" P] ["encoding" "raw"|
"base64url"]) offers the host's token for NAME, fetched for the URL's origin as
for auth, as one more subprotocol: P then the token, or its unpadded base64url
(a token68's '/' or '=' can't be in a subprotocol), as Kubernetes does with
"base64url.bearer.authorization.k8s.io.".
cvc::net: WsOptions::protocols is sent natively as a Sec-WebSocket-Protocol line
and in the browser through createAttributes.protocols, in both the blocking and
the started connect. Both fail the connect unless the server picks one of the
offered subprotocols, as browsers do (RFC 6455 4.1; natively from the 101's
headers, which libcurl files under CURLH_1XX). An invalid or repeated
subprotocol is refused, with no error quoting one, and the joined strings are
wiped. ws_valid_protocol is public for the option checks.
The token is wiped after the connect, and errors are redacted of it and of its
base64url spelling. The connection records the name, so ws-recv and ws-poll
blank either spelling if the server echoes it.
Tests: NetWsClient covers offering, a server that picks none or another
subprotocol, and invalid subprotocols. AriadneNetHost.
WsOpenOffersTheHostsTokenAsASubprotocol checks the handshake line, the
redacted echo, a raw token with '/' that is refused without connecting, and that
no state node holds the token. LocalWsServer can pick a subprotocol. The wasm
file compiles with em++, with and without threads. Spec: docs/ARIADNE.md
section 10.5.
---------
Co-authored-by: nicotina-ci <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Ariadne documents get HTTP bodies as raw text, and nothing in state_exec read general JSON.
state-jsonandstate-from-jsononly handle cvc::state's flat, path-keyed document, andstate-from-jsoncollapses arrays into their parent node. This adds three verbs, so a document can read a REST reply and render it:This is item L3 of cy-pca/nicotina's ROADMAP.md (the TX.WTF client written as
.aridocuments).The verbs
(json-parse text)reads a string, or bytes such as a reply'sbody.true/false/null1e999) is an error.JSON.parseandjson.loadsdo.ValueErrorwhose message names the line and column, withline,colandoffsetfields.(json-encode value [indent])writes compact JSON, or indented JSON withtrue(2 spaces) or 1 to 10.TypeError.nan, a string that isn't UTF-8 and a self-containing list areValueErrors.(state-set-tree path value)writes a value as the subtree atpath.repeat:.., a space at either end), callables, cycles and an empty path are refused.state-setprints a dict into one node.state-from-jsoncollapses arrays.state-childrenlists every descendant's full path, so it can't count a list. The newstate::childNames()lists a node's direct children.Design
parse()would run the whole text inside one evaluator step, and converting its DOM tovalue_twould be a second walk. All three verbs are data jobs instead: a large reply runs a slice per step againstmax_stepsandmax_time, and what they build is held to the allocation limit, asstrandstate-from-jsonalready are.kJsonMaxDepth) both ways, checked with a heap stack, not recursion.json-parseandjson-encodeare pure, so they're on its allowlist.test_pycvc_state_exec_data.py.Example, in both terminal backends
examples/ariadne/documents/json_feed.ariparses a JSON literal and renders it withrepeat:. Its last post is written with JSON\uescapes: accented letters, CJK and a surrogate-pair emoji.ari snapshot(plain and--ansiagree):Fix included (second commit): before it,
ari snapshot's plain text printed a space in the cell a wide glyph covers, so│zoë: café 日 本 🎉 │ran past the window's edge. FTXUI's ownScreen::ToString()(--ansiand the live terminal) and the tvision blitter already skipped that cell; now the plain text does too.ariadne_ftxui_testrenders the example asari snapshotdoes and checks every row ends in the same column.WideGlyphsTakeTwoColumnsInTheTextSnapshotpins the fix with CJK, an emoji, and composed and combining accents. Both fail without the fix.render_window).JsonFeedDocumentFillsItsHostedWindowruns the example throughTvisionBackendand checks those cells: one per column, each wide glyph followed by the cell it covers.ari snapshotalways lays out with FTXUI, sosrc/ari/tests/run_in_tmux_test.shrunsari run --backend ftxui|tvisionin a 100x30 tmux pane and compares the text inside the window's borders withsrc/ari/tests/json_feed.rows. Each expected row ends in|at the border, so a wide glyph that takes the wrong number of columns fails.ari_run_json_feed_ftxuiandari_run_json_feed_tvisionpass locally with cvcpkg's tvision and ncurses, and fail when a row is one column off. They're registered only on Linux where tmux is found. CI had no tmux; cvcpkg now packages it (recipe(tmux, libevent): tmux 3.8 against cvcpkg's ncurses; libevent 2.1.13 (cvc.1) cy-pca/cvcpkg#509), and ci: tmux from cvcpkg on the Linux lanes, so the ari tmux tests run #901 installs it in CI, to merge after this PR.The tvision desktop as
ari run --backend tvisiondraws it (tmux capture):Tests
Local runs are Linux, GCC 13, Debug.
state_exec_builtins_test(16 new): every value kind, int/float rules, 64-bit edges, repeated keys (scanned and indexed), escapes and surrogate pairs, U+FFFD replacement, 23 malformed inputs with their line and column, the depth cap (a million[refused without recursion), encode compact and indented, escapes, shortest floats, everything encode refuses, round trips, and 3,000 seeded mutations of a document (each parses or is aValueError; what parses round-trips).state_exec_intrinsics_test(5 new):state-set-treewriting, replacing, skipping unchanged nodes, refusing before writing, writing through a writable link.state_exec_data_steps_test(6 new): sliced runs match whole runs for any slice; the allocation limit; throughasync_schedulerat 64 nodes a step, with a parse error caught bytryafter 5,000 lines;state-set-treeof a 300-item reply and its replacement; a bad key found after 3,000 elements, before anything is written.ariadne_ftxui_test(3 new): the example under FTXUI and tvision's hosted layout, and the wide-glyph fix.test_pycvc_state_exec_data.py: the factories, and the verbs inside a program.ari checkof the example.Not done here
r#"…"#, grammar phase P4) are in STATE_EXEC_GRAMMAR.md but haven't landed, so the example escapes its quotes.state-setused to write a float with 6 significant digits. state_exec: state-set stores a float in its shortest round-trip form #885 (merged) fixed that, sostate-set-treeandstate-setnow write scalars the same way.