Skip to content

state_exec: load the stdlib modules in every environment, with a per-call allocation limit - #660

Merged
transfix merged 6 commits into
masterfrom
feat/state-exec-stdlib-modules
Oct 17, 2026
Merged

transfix merged 6 commits into
masterfrom
feat/state-exec-stdlib-modules

Conversation

@transfix

@transfix transfix commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

Why

src/cvc/state/state_exec/stdlib.cpp registers the string, bytes, math and collections modules, including the Unicode-aware string.length/char-at/substring and string.encode/bytes.decode from the SE-1/SE-3 work. None of it was reachable from a DSL program. Only stdlib.cpp and two tests referenced stdlib_registry, and builtins::make_default_environment() didn't import it. So on master, (string.length "x") fails with unknown function or special form: string.length on the sync and async schedulers, in Ariadne's program lanes and predicates, in pycvc's Exec and in cvc exec.

The stdlib arrived with the engine in #93 and was never wired in. CVCGL-UI-DSL-ROADMAP.md §7.3 had already decided on "full stdlib by default" for the predicate and action envs.

What

Always loaded, shared, not copied.

  • stdlib_registry::standard() is the built-in registry, built once.
  • stdlib_registry::shared_scope() is one frozen environment holding every stdlib function, also built once.
  • make_default_environment() links that scope as its outer, so every host gets the modules from one place without copying them.
  • All names are module-qualified, so nothing clashes with builtins (length, range, slice are unchanged).

Frozen scopes.

  • environment::frozen: set() throws on a frozen scope.
  • set_existing() binds in the outermost unfrozen scope instead of writing into a frozen one. It is now a loop rather than recursion.
  • So a program's (set string.length 42) or (defun string.upper ...) shadows the name for that program only. Nothing writes the shared scope, so threads can read it concurrently.

Ariadne predicates (kAllowed) get the pure, bounded subset, where the result is a scalar or no bigger than the argument:

  • string.length, byte-length, char-at, substring, upper, lower, trim, starts-with, ends-with, contains;
  • bytes.length and byte-at;
  • every math.* function except math.random, which would make a predicate nondeterministic.

The materializers (string.join/replace/split/encode, bytes.slice/concat/decode, collections.*) stay out of predicates until they run as scheduled, sliced work: the executor-jobs follow-up. The init, action and resident lanes get everything.

Per-call allocation limit. A native call builds its whole result inside one step. max_memory is checked between steps and counts only state-tree writes, so it couldn't see a call like (collections.range 1000000000).

  • eval_alloc_guard and eval_alloc_check() sit next to eval_deadline_guard in types.h.
  • Both schedulers arm the guard around each step with the tighter of two limits:
    • the tree setting limits.max_alloc_bytes, resolved like max_pending_messages: state_exec.schedulers.<id>.limits.max_alloc_bytes, then state_exec.defaults.limits.max_alloc_bytes, then 16 MiB. 0 means no limit of its own.
    • what's left of the process's max_memory.
  • The sync scheduler resolves the setting in load_settings() and publishes the effective value. The async scheduler (the app's exec scheduler and pycvc's Exec) reads the defaults key on every submission.
  • With no guard armed (a bare evaluator, or a direct C++ call) the limit is the 16 MiB default.
  • These functions estimate their result size and throw, naming themselves, before allocating:
    • string.split, string.join, string.replace, bytes.concat;
    • collections.range, collections.zip, collections.flatten, collections.dict-merge;
    • the builtins str-concat and collect.

Ariadne action budget. kActionMaxBytes was a fixed 256 KiB. It's now the tree setting ariadne.limits.action_max_memory, read on every submission. The default is 4 MiB, and 0 means no limit. Since the per-step allocation limit takes what's left of max_memory, keeping 256 KiB would have capped every native call in an action at 256 KiB too. docs/ARIADNE.md has the new table. Test: AriadneStdlib.ActionMemoryBudgetIsATreeSetting checks the default, a 64 KiB budget, 0, and an unparsable value.

Step guard cost (86ac286). An unconditional per-step guard cost a memory-tracker lookup and thread-local writes every step, making a plain loop about 6-8% slower. The schedulers now arm it only for a process with a memory budget or a non-default limits.max_alloc_bytes; for everything else the default applies unarmed, with the same limit.

Fixes found along the way.

  • collections.range counts its elements in unsigned arithmetic. The old loop had signed overflow (UB) near INT64_MAX/INT64_MIN.
  • string.replace builds its result in one pass with the same non-overlapping, left-to-right semantics. The old version did an in-place replace per match, which is O(n·k).
  • collections.unique and collections.dict-merge are quadratic, so they now poll the evaluation deadline.

Docs. The developer guide's §11 is rewritten: how the modules load, shadowing, the allocation limit, the predicate subset, and per-module examples. §7's settings table gets the new key. Every ;; => example in §11 was evaluated through pycvc against this build and matches. The old examples had several mistakes:

  • the collections.map argument order was wrong, and it showed lambdas, which aren't accepted;
  • substring was documented as (start, end) instead of (start, length);
  • floor/ceil/round were shown returning floats;
  • booleans were shown as true rather than #t.

Tests

  • New state_exec_stdlib_test (20 cases):
    • reach through the sync scheduler, the async scheduler and an explicit make_default_environment() env;
    • every module, and builtins keeping their short names;
    • the shared scope is linked and not copied;
    • set, defun and set_existing shadow; writing a frozen scope throws;
    • the default limit; max_memory tightening it; tree resolution per scheduler and then defaults, including a bad value and the published value; 0 = none; guard nesting;
    • each growing result is checked under a tight limit;
    • replace/split/join semantics, and range at the int64 ends.
  • ariadne_runtime_test (127): the predicate subset is shown, the materializers and math.random are hidden and reported, the init and action lanes reach the whole stdlib, and an action over limits.max_alloc_bytes is killed and reported, then succeeds once the limit fits.
  • test_pycvc_exec.py: the modules are loaded in Exec, shadowing is per program, and the limit comes from the app tree.
  • state_exec_intrinsics_test: StdlibRegistryTest.ImportAll and ImportSpecific now use a bare environment, since a default one already reaches the stdlib.

Local results (MSVC 14.38 Release, Windows, deps from the cvcpkg prefix):

  • On master, the new reach tests fail with unknown function or special form: string.length on both schedulers. With this change:
    • all 21 state_exec, Ariadne, async_lane and state_list suites pass, 1309 tests in all (ariadne_runtime 126, state_exec_intrinsics 156, state_exec_stdlib 20, ...);
    • pycvc (CVC_BUILD_PYCVC=ON, SWIG 4.4.1, Python 3.11 from the prefix): test_pycvc_exec, _exec_async, _exec_coro, _ari and _state give 41 passed;
    • cvc exec -e '(string.length "café")' prints 4, and (collections.range 1000000000) exits 1 with the allocation-limit error;
    • CvcCliTest: 171/173 pass, including every Exec* case. The two failures are Vol2ImgExportsSlices and Img2VolImportsSlices: ImageMagick's CoderModulesPath registry lookup fails on this box, which is unrelated;
    • check_test_targets.py is OK, and clang-format 18 is clean.
    • After merging master (gl: physics bodies are drawn at their pose anywhere in the scene hierarchy #654-world: one world_geometry for render, physics and nav; the city bundle loader (G3a) #656, which brings PEGTL): rebuilt, and the same suites plus state_exec_pegtl_test pass (22 suites, 1313 tests); pycvc still gives 41 passed.

Not in this PR

  • Scheduled, sliced versions of the materializers, so a long string.join or collections.sort runs a slice per step against max_steps/max_time and can join the predicate subset. This is the resumable-job mechanism planned under "deep-data work on the executor" (stacked on state_exec: read submitted scripts inside the process, a slice per step #653 and state_exec: free, print, compare, copy and snapshot deep values without native recursion #657).
  • collections.map, filter and reduce still take only native functions ((collections.map xs math.sqrt) works, a DSL lambda doesn't). Calling a closure from a native needs the same job mechanism.
  • The allocation check is a pre-allocation bound per call. Live in-process values still aren't charged to max_memory.
  • The snapshot codec encodes the frozen stdlib scope as an empty scope (it skips native bindings, as before). No production path decodes evaluator states today.

Conflicts

This touches lines that #649/#653 (scheduler.cpp/async_scheduler.cpp settings and submit) and #657 (environment::set_existing, now a loop in both) also change. Whichever merges second rebases; each conflict is a few lines.

…call allocation limit

The string, bytes, math and collections modules in stdlib.cpp were never
reachable from DSL programs: nothing outside tests referenced
stdlib_registry, so (string.length "x") failed with "unknown function"
on both schedulers, in Ariadne and in pycvc's Exec.

- stdlib_registry::shared_scope() builds one frozen scope with every
  stdlib function, once per process. builtins::make_default_environment()
  links it as its outer scope, so every host reaches the modules without
  copying them into each environment.
- environment::frozen: set() refuses a frozen scope, and set_existing()
  binds in the outermost unfrozen scope instead of writing into it. A
  program's (set string.length ...) or (defun string.upper ...) shadows
  the name for that program only, and threads can share the scope.
- Ariadne predicates get the pure, bounded subset: string.length,
  byte-length, char-at, substring, upper, lower, trim, starts-with,
  ends-with, contains; bytes.length, byte-at; every math.* except
  math.random. The materializers stay out until they run as scheduled,
  sliced work.
- Per-call allocation limit. A native call builds its result inside one
  step, where max_memory (between steps, state-tree writes only) cannot
  see it. New eval_alloc_guard/eval_alloc_check, next to the evaluation
  deadline: the schedulers arm it per step with the tighter of the tree
  setting limits.max_alloc_bytes (state_exec.schedulers.<id>, then
  state_exec.defaults; default 16 MiB, 0 = none of its own) and what is
  left of max_memory. string.split/join/replace, bytes.concat,
  collections.range/zip/flatten/dict-merge, str-concat and collect check
  their result size before allocating.
- collections.range counts its elements in unsigned arithmetic, so it no
  longer overflows at the int64 ends. string.replace builds its result in
  one pass. collections.unique and dict-merge poll the deadline.
- Developer guide section 11 rewritten: how the modules load, the
  allocation limit, the predicate subset, and corrected examples.
…lib-modules

# Conflicts:
#	src/cvc/tests/CMakeLists.txt
A full-file clang-format realigned an untouched include comment, which the
changed-lines check then flagged.
kActionMaxBytes (a fixed 256 KiB) becomes ariadne.limits.action_max_memory,
read on every submission (bytes; 0 = no limit; a missing or unparsable value
keeps the 4 MiB default). With the per-step allocation limit taking what is
left of max_memory, 256 KiB would also have capped every native call in an
action at 256 KiB.
…mething

With no memory budget and the default limits.max_alloc_bytes, an armed guard
gives the same limit as none (the default applies unarmed), but cost a
memory-tracker lookup and thread-local writes every step: a plain counting
loop ran about 6-8% slower. The schedulers now arm it only for a process
with a budget or a non-default limit.
…lib-modules

# Conflicts:
#	src/cvc/state/state_exec/types.cpp
#	src/cvc/tests/CMakeLists.txt
@transfix
transfix merged commit 4908c65 into master Oct 17, 2026
15 checks passed
transfix added a commit that referenced this pull request Oct 18, 2026
…c-data-steps

#653's branch picked up #660 (stdlib modules in every environment, with a
per-call allocation limit). Conflicts:

- scheduler.cpp load_settings(): data.step_nodes and
  limits.max_alloc_bytes, both resolved and both published.
- types.cpp: the release backlog and the allocation guard, side by side.
- builtins.cpp str-concat: #658's sliced path for list/dict arguments,
  then #660's checked fast path.

The sliced path built its string in a concat job without #660's check,
so passing the same big string many times next to one list would get
past the limit. The concat job now checks every append against
eval_alloc_check (the guard is armed around each scheduler step, data
steps included), naming the builtin (str-concat, print):
make_concat_job() takes it. New DataJob.ConcatChecksTheAllocationLimit.
transfix added a commit that referenced this pull request Oct 18, 2026
…final #660)

#665 carried an older cherry-pick of #660 (811c954). For the files #665
changes, the merge applies what #660 changed after that copy (three-way,
with 811c954 as the base). Every other file is #658's. The diff against
#658 is #665's own 17 files.
transfix added a commit that referenced this pull request Oct 18, 2026
transfix added a commit that referenced this pull request Oct 18, 2026
…671)

* state_exec: grammar spec, conformance cases and parse corpus (grammar P0)

Declare the state_exec s-expression grammar in docs/STATE_EXEC_GRAMMAR.md
(W3C EBNF, Unicode source rules, literal tables, and a table of every
intentional change from the hand-written parser, tagged by phase P2-P4).
The parser itself is unchanged; later phases build it from this grammar.

state_exec_grammar_test tags each case with the phase it holds from:
landed cases must hold, pending cases must still differ, the doc's EBNF
must be closed, and every production needs a case. state_exec_corpus_test
pins how the 597 DSL scripts the repo carries parse today
(state_exec_corpus/, regenerated with gen_state_exec_corpus.py and
CVC_UPDATE_GOLDENS=1).

Also correct parser.h (no quasiquote) and the developer guide (false and
#f read as nil, bytes literals exist).

* state_exec grammar: make the nesting limit configurable (default 256)

Spec only: parse_options::max_depth on parse()/parse_all()/parser and execute_options::max_parse_depth for submitted scripts, both from P2. Records why the limit exists (the reader recurses on the native stack; the evaluators are stackless) and the corpus's real depths (max 13, median 2).

* state_exec grammar: parser settings live on the state tree

Spec only. max_depth resolves from state_exec.schedulers.<id>.parser.max_depth, then state_exec.defaults.parser.max_depth, then 256, matching scheduler::load_settings(); parse_options remains for callers without a tree. Drops the execute_options::max_parse_depth idea so the tree is the single source.

* state_exec: parser settings on the state tree, with a nesting limit (grammar P1b)

The parser now stops at parser.max_depth nested lists and quotes (default
256) with a parse_error, instead of recursing until the native stack
overflows. Like the scheduler's other settings, the limit lives on the
state tree: state_exec.schedulers.<id>.parser.max_depth, then
state_exec.defaults.parser.max_depth, then 256; a missing, malformed or
zero value is skipped.

- parser: parse_options (max_depth) on parse()/parse_all()/parser, a
  depth guard on lists and quotes, and parse_options_from_state().
- scheduler: load_settings() resolves parser.* and publishes the
  effective value under state_exec.schedulers.<id>.parser.max_depth;
  execute() parses with it.
- async_scheduler (the app's exec scheduler) reads the defaults key on
  every submit; Ariadne predicates read it from the app tree.
- stackless evaluators: create_state(script, env, parse_options).

The grammar test moves from a numeric kLandedPhase to named phases; the
257-deep case is P1b and holds now. Tests cover the default, a custom
depth, quotes, 100000 open parens, the error position, tree resolution,
bad values, and both schedulers.

* state_exec: make the parser stackless (explicit frame stack, resumable read)

Lists and quotes were parsed by native recursion, so input depth was
bounded by the thread's stack. The parser now keeps open lists and quotes
on a heap stack of frames and reads in a loop: native stack depth is
constant however deeply the input nests (a test reads a million open
parens and reports the unclosed list instead of crashing).

The loop is a resumable read(out, budget): it reads up to `budget` tokens
and returns datum / end / more, carrying open frames between calls, so a
scheduler can parse a script a slice at a time. parse() and parse_all()
call it with no budget.

Output is unchanged, quirks included (a stray top-level `)` still reads
as a symbol until P2): the conformance cases, the 597-script corpus and
the evaluator suites all pass. parser.max_depth stays on the state tree;
it now bounds parsed data for the code that still walks values
recursively (list destruction, the snapshot codec, to_string) rather
than the parser's own stack. parse_fib20_expr: about 3.4 us vs 3.1 us
for the recursive parser (median of 6, MSVC Release, loaded machine).

* state_exec: read submitted scripts inside the process, a slice per step

The stackless parser's state is an input position plus a heap stack of
open frames, so it can pause anywhere. New setting parser.step_tokens
(on the state tree, resolved like parser.max_depth; default 0) lets a
scheduler parse a submitted script inside the new process instead of at
submit: each scheduler step reads N tokens, and the step that reaches the
end sets up evaluation exactly as parsing up front would have.

- Reading steps are process steps: they count against max_steps and
  max_time and interleave with other processes.
- A syntax error surfaces like a runtime error: the async scheduler kills
  the process with it as the exit error; the sync scheduler throws it
  from step()/run(). With step_tokens = 0, execute() still throws.
- Signals and watch events wait until the script is read (their
  handlers run on the evaluation stack, which doesn't exist yet).
- The snapshot codec stores a mid-read process's source and settings and
  re-reads it after a restore.

Adds parse_options::step_tokens, script_reader (owns its source and
drives parser::read() a budget at a time) and evaluator_state::reading;
stackless_evaluator::step() reads until the script is read. Tests cover
the reader, the evaluator, the codec and both schedulers (results,
syntax errors, max_steps, deferred signals).

* state_exec: the app's exec scheduler reads scripts in steps (1024 tokens)

app::exec_scheduler(), which runs Ariadne's actions and residents, now
defaults parser.step_tokens to 1024, so it parses submitted scripts
inside their processes. async_scheduler gains set_parser_defaults(): the
built-in values under its watch root's state_exec.defaults.parser.* keys.
A plain async_scheduler (pycvc's Exec) and the sync scheduler stay at 0,
so they still report syntax errors at submit.

Why 1024: every script the repo carries reads in one slice (the largest
is 159 tokens, .ari scripts at most 24), so a normal action pays one
extra step of its 5000; a slice costs about 80 us at the parser's
measured ~80 ns/token, so a pathologically large script is spread over
steps and frames instead of stalling a drain.

Ariadne now says why a process died: a killed action's warning carries
its exit error, and the per-frame sweep reports a killed resident (a
syntax error in its body, a runtime error, its per-step cap) once,
instead of letting it vanish silently.

* pycvc: give Exec the same state_exec defaults as the app's exec scheduler

pycvc's Exec runs programs on a private async_scheduler that already
watches the app's state tree, but its built-in parser defaults were
plain parse_options{} while app::exec_scheduler() read scripts in
1024-token steps. Both now take async_scheduler::host_parser_defaults(),
one definition (with the reasoning for 1024) for every libcvc host, and
the app tree's state_exec.defaults.parser.* keys override both.

Exec.run() still raises a RuntimeError with the parse error's message:
from the killed process's exit error when the script is read in steps,
or from execute() when the tree sets step_tokens to 0.

Tests: test_pycvc_exec.py checks the parse error's message and that
max_depth / step_tokens on the app tree configure Exec; the integration
test pins the app scheduler to host_parser_defaults().

* pycvc: expose the state_exec parser-settings surface under its C++ names

pycvc's state_exec surface was only Exec; the parser settings these PRs
add had no Python counterpart, so the defaults weren't even observable.
In pycvc's direct-wrap style (the real C++ types, no facade):

- pycvc.parse_options: the real cvc::state_exec::parse_options struct
  (max_depth, step_tokens), C++ defaults included.
- pycvc.async_scheduler.host_parser_defaults(): the real static, declared
  to SWIG on its own (async_scheduler isn't wrapped yet, so no
  constructor).
- pycvc.parse_options_from_state(app, scheduler_id="", base=...): the C++
  resolver, taking the app where C++ takes the root (pycvc's convention).
- Exec.parser_defaults() / Exec.set_parser_defaults(): the same calls as
  the async_scheduler Exec wraps.

test_pycvc_exec.py covers each against the C++ behaviour; the README
gains a state_exec section. Built locally (SWIG 4.4.1, Python 3.11):
exec, exec_async, exec_coro and ari tests, 26 passed.

* pycvc: parse_options_from_state takes the State root, as in C++

Wrap the real cvc::state_exec::parse_options_from_state(state&, id, base)
instead of a pycvc adapter that took the app: Python passes the tree root,
pycvc.State.instance(app), exactly as C++ passes cvc::state&. This is the
first decision of the pycvc/C++ parity approach (C++ cvc::state& parameters
take a pycvc.State in Python).

* pycvc: state_exec parity part 1 (values, parsing, parse_error, value codec)

Start bringing pycvc's state_exec API to the C++ surface under the C++
names (docs/PYCVC_STATE_EXEC_PARITY.md: the audit of all 20 state_exec
headers, the agreed approach, and the PR plan).

- One strict value_t <-> Python conversion (pycvc_value.h), used by every
  API and by Exec: native types for data, pycvc.symbol (the real struct)
  for symbols, and pycvc.value (the real value_t, opaque) for closures,
  native fns, data objects and generators, which convert back unchanged.
  Non-str dict keys and unsupported types raise TypeError, ints beyond 64
  bits OverflowError, and nesting past 1000 levels or a cycle ValueError.
  This replaces the lossy converter (symbols became str, closures
  "<closure>", anything else str(obj)), which could also put a null item
  in a list on invalid UTF-8 and leave an OverflowError pending.
- pycvc.parse / parse_all, pycvc.parse_error (a RuntimeError with .line
  and .col), pycvc.script_reader, to_string, values_equal, and the value
  codec encode_value / decode_value on a State node.
- Exec.run raises pycvc.parse_error for a syntax error whether the script
  was parsed at submit or read inside the process (it re-parses a killed
  process's script to recover the position).
- The pycvc README's Status/Design sections described a v0 facade; they
  now describe the direct-wrap design.

test_pycvc_state_exec.py (13 tests) covers each against the C++
behaviour. Locally: those plus pycvc's exec, async, coro, ari, state and
core suites pass (87), except test_volume_rawiv_roundtrip, which fails
the same way on the unmodified build (a Windows temp-file lock).

* pycvc: state_exec parity part 2 (environments, builtins, schedulers)

Wrap the scheduler surface of cvc::state_exec under the C++ names:

- environment (shared, as environment_ptr) and builtins:
  make_default_environment, and register_fn taking a Python callable
  or a pycvc.value holding a native fn.
- execute_options (on_complete is a Python callable, signal_handlers a
  dict), process_info, scheduler_stats, percent_encode/percent_decode.
- process_status and scheduling_policy as enum.IntEnum classes; an enum
  argument must be a member, so to_string(process_status) and
  to_string(value_t) keep their shared name.
- scheduler and async_scheduler as real classes with their
  non-coroutine members. run/step and sync_run/sync_step release the
  GIL; Python callbacks retake it.
- Exec.scheduler() returns Exec's async_scheduler, which keeps the Exec
  alive.

Empty optionals are None, except for values: get_result,
pop_pending_message and environment.lookup raise KeyError, since None
is nil. The value_t typecheck now runs last, so execute(str) picks the
script overload.

test_pycvc_state_exec_sched.py repeats the C++ scheduler tests on both
classes. The parity doc and README are updated.

* Rerun CI on master (the merge push ran while the PR still targeted #653's branch)

* pycvc: environment.frozen (#660), and the set_existing note now that its comment is fixed
transfix added a commit that referenced this pull request Oct 18, 2026
…nsics) (#675)

* state_exec: grammar spec, conformance cases and parse corpus (grammar P0)

Declare the state_exec s-expression grammar in docs/STATE_EXEC_GRAMMAR.md
(W3C EBNF, Unicode source rules, literal tables, and a table of every
intentional change from the hand-written parser, tagged by phase P2-P4).
The parser itself is unchanged; later phases build it from this grammar.

state_exec_grammar_test tags each case with the phase it holds from:
landed cases must hold, pending cases must still differ, the doc's EBNF
must be closed, and every production needs a case. state_exec_corpus_test
pins how the 597 DSL scripts the repo carries parse today
(state_exec_corpus/, regenerated with gen_state_exec_corpus.py and
CVC_UPDATE_GOLDENS=1).

Also correct parser.h (no quasiquote) and the developer guide (false and
#f read as nil, bytes literals exist).

* state_exec grammar: make the nesting limit configurable (default 256)

Spec only: parse_options::max_depth on parse()/parse_all()/parser and execute_options::max_parse_depth for submitted scripts, both from P2. Records why the limit exists (the reader recurses on the native stack; the evaluators are stackless) and the corpus's real depths (max 13, median 2).

* state_exec grammar: parser settings live on the state tree

Spec only. max_depth resolves from state_exec.schedulers.<id>.parser.max_depth, then state_exec.defaults.parser.max_depth, then 256, matching scheduler::load_settings(); parse_options remains for callers without a tree. Drops the execute_options::max_parse_depth idea so the tree is the single source.

* state_exec: parser settings on the state tree, with a nesting limit (grammar P1b)

The parser now stops at parser.max_depth nested lists and quotes (default
256) with a parse_error, instead of recursing until the native stack
overflows. Like the scheduler's other settings, the limit lives on the
state tree: state_exec.schedulers.<id>.parser.max_depth, then
state_exec.defaults.parser.max_depth, then 256; a missing, malformed or
zero value is skipped.

- parser: parse_options (max_depth) on parse()/parse_all()/parser, a
  depth guard on lists and quotes, and parse_options_from_state().
- scheduler: load_settings() resolves parser.* and publishes the
  effective value under state_exec.schedulers.<id>.parser.max_depth;
  execute() parses with it.
- async_scheduler (the app's exec scheduler) reads the defaults key on
  every submit; Ariadne predicates read it from the app tree.
- stackless evaluators: create_state(script, env, parse_options).

The grammar test moves from a numeric kLandedPhase to named phases; the
257-deep case is P1b and holds now. Tests cover the default, a custom
depth, quotes, 100000 open parens, the error position, tree resolution,
bad values, and both schedulers.

* state_exec: make the parser stackless (explicit frame stack, resumable read)

Lists and quotes were parsed by native recursion, so input depth was
bounded by the thread's stack. The parser now keeps open lists and quotes
on a heap stack of frames and reads in a loop: native stack depth is
constant however deeply the input nests (a test reads a million open
parens and reports the unclosed list instead of crashing).

The loop is a resumable read(out, budget): it reads up to `budget` tokens
and returns datum / end / more, carrying open frames between calls, so a
scheduler can parse a script a slice at a time. parse() and parse_all()
call it with no budget.

Output is unchanged, quirks included (a stray top-level `)` still reads
as a symbol until P2): the conformance cases, the 597-script corpus and
the evaluator suites all pass. parser.max_depth stays on the state tree;
it now bounds parsed data for the code that still walks values
recursively (list destruction, the snapshot codec, to_string) rather
than the parser's own stack. parse_fib20_expr: about 3.4 us vs 3.1 us
for the recursive parser (median of 6, MSVC Release, loaded machine).

* state_exec: read submitted scripts inside the process, a slice per step

The stackless parser's state is an input position plus a heap stack of
open frames, so it can pause anywhere. New setting parser.step_tokens
(on the state tree, resolved like parser.max_depth; default 0) lets a
scheduler parse a submitted script inside the new process instead of at
submit: each scheduler step reads N tokens, and the step that reaches the
end sets up evaluation exactly as parsing up front would have.

- Reading steps are process steps: they count against max_steps and
  max_time and interleave with other processes.
- A syntax error surfaces like a runtime error: the async scheduler kills
  the process with it as the exit error; the sync scheduler throws it
  from step()/run(). With step_tokens = 0, execute() still throws.
- Signals and watch events wait until the script is read (their
  handlers run on the evaluation stack, which doesn't exist yet).
- The snapshot codec stores a mid-read process's source and settings and
  re-reads it after a restore.

Adds parse_options::step_tokens, script_reader (owns its source and
drives parser::read() a budget at a time) and evaluator_state::reading;
stackless_evaluator::step() reads until the script is read. Tests cover
the reader, the evaluator, the codec and both schedulers (results,
syntax errors, max_steps, deferred signals).

* state_exec: the app's exec scheduler reads scripts in steps (1024 tokens)

app::exec_scheduler(), which runs Ariadne's actions and residents, now
defaults parser.step_tokens to 1024, so it parses submitted scripts
inside their processes. async_scheduler gains set_parser_defaults(): the
built-in values under its watch root's state_exec.defaults.parser.* keys.
A plain async_scheduler (pycvc's Exec) and the sync scheduler stay at 0,
so they still report syntax errors at submit.

Why 1024: every script the repo carries reads in one slice (the largest
is 159 tokens, .ari scripts at most 24), so a normal action pays one
extra step of its 5000; a slice costs about 80 us at the parser's
measured ~80 ns/token, so a pathologically large script is spread over
steps and frames instead of stalling a drain.

Ariadne now says why a process died: a killed action's warning carries
its exit error, and the per-frame sweep reports a killed resident (a
syntax error in its body, a runtime error, its per-step cap) once,
instead of letting it vanish silently.

* pycvc: give Exec the same state_exec defaults as the app's exec scheduler

pycvc's Exec runs programs on a private async_scheduler that already
watches the app's state tree, but its built-in parser defaults were
plain parse_options{} while app::exec_scheduler() read scripts in
1024-token steps. Both now take async_scheduler::host_parser_defaults(),
one definition (with the reasoning for 1024) for every libcvc host, and
the app tree's state_exec.defaults.parser.* keys override both.

Exec.run() still raises a RuntimeError with the parse error's message:
from the killed process's exit error when the script is read in steps,
or from execute() when the tree sets step_tokens to 0.

Tests: test_pycvc_exec.py checks the parse error's message and that
max_depth / step_tokens on the app tree configure Exec; the integration
test pins the app scheduler to host_parser_defaults().

* pycvc: expose the state_exec parser-settings surface under its C++ names

pycvc's state_exec surface was only Exec; the parser settings these PRs
add had no Python counterpart, so the defaults weren't even observable.
In pycvc's direct-wrap style (the real C++ types, no facade):

- pycvc.parse_options: the real cvc::state_exec::parse_options struct
  (max_depth, step_tokens), C++ defaults included.
- pycvc.async_scheduler.host_parser_defaults(): the real static, declared
  to SWIG on its own (async_scheduler isn't wrapped yet, so no
  constructor).
- pycvc.parse_options_from_state(app, scheduler_id="", base=...): the C++
  resolver, taking the app where C++ takes the root (pycvc's convention).
- Exec.parser_defaults() / Exec.set_parser_defaults(): the same calls as
  the async_scheduler Exec wraps.

test_pycvc_exec.py covers each against the C++ behaviour; the README
gains a state_exec section. Built locally (SWIG 4.4.1, Python 3.11):
exec, exec_async, exec_coro and ari tests, 26 passed.

* pycvc: parse_options_from_state takes the State root, as in C++

Wrap the real cvc::state_exec::parse_options_from_state(state&, id, base)
instead of a pycvc adapter that took the app: Python passes the tree root,
pycvc.State.instance(app), exactly as C++ passes cvc::state&. This is the
first decision of the pycvc/C++ parity approach (C++ cvc::state& parameters
take a pycvc.State in Python).

* pycvc: state_exec parity part 1 (values, parsing, parse_error, value codec)

Start bringing pycvc's state_exec API to the C++ surface under the C++
names (docs/PYCVC_STATE_EXEC_PARITY.md: the audit of all 20 state_exec
headers, the agreed approach, and the PR plan).

- One strict value_t <-> Python conversion (pycvc_value.h), used by every
  API and by Exec: native types for data, pycvc.symbol (the real struct)
  for symbols, and pycvc.value (the real value_t, opaque) for closures,
  native fns, data objects and generators, which convert back unchanged.
  Non-str dict keys and unsupported types raise TypeError, ints beyond 64
  bits OverflowError, and nesting past 1000 levels or a cycle ValueError.
  This replaces the lossy converter (symbols became str, closures
  "<closure>", anything else str(obj)), which could also put a null item
  in a list on invalid UTF-8 and leave an OverflowError pending.
- pycvc.parse / parse_all, pycvc.parse_error (a RuntimeError with .line
  and .col), pycvc.script_reader, to_string, values_equal, and the value
  codec encode_value / decode_value on a State node.
- Exec.run raises pycvc.parse_error for a syntax error whether the script
  was parsed at submit or read inside the process (it re-parses a killed
  process's script to recover the position).
- The pycvc README's Status/Design sections described a v0 facade; they
  now describe the direct-wrap design.

test_pycvc_state_exec.py (13 tests) covers each against the C++
behaviour. Locally: those plus pycvc's exec, async, coro, ari, state and
core suites pass (87), except test_volume_rawiv_roundtrip, which fails
the same way on the unmodified build (a Windows temp-file lock).

* pycvc: state_exec parity part 2 (environments, builtins, schedulers)

Wrap the scheduler surface of cvc::state_exec under the C++ names:

- environment (shared, as environment_ptr) and builtins:
  make_default_environment, and register_fn taking a Python callable
  or a pycvc.value holding a native fn.
- execute_options (on_complete is a Python callable, signal_handlers a
  dict), process_info, scheduler_stats, percent_encode/percent_decode.
- process_status and scheduling_policy as enum.IntEnum classes; an enum
  argument must be a member, so to_string(process_status) and
  to_string(value_t) keep their shared name.
- scheduler and async_scheduler as real classes with their
  non-coroutine members. run/step and sync_run/sync_step release the
  GIL; Python callbacks retake it.
- Exec.scheduler() returns Exec's async_scheduler, which keeps the Exec
  alive.

Empty optionals are None, except for values: get_result,
pop_pending_message and environment.lookup raise KeyError, since None
is nil. The value_t typecheck now runs last, so execute(str) picks the
script overload.

test_pycvc_state_exec_sched.py repeats the C++ scheduler tests on both
classes. The parity doc and README are updated.

* Rerun CI on master (the merge push ran while the PR still targeted #653's branch)

* pycvc: environment.frozen (#660), and the set_existing note now that its comment is fixed

* pycvc: state_exec parity part 3 (evaluators, processes, policy, intrinsics)

Wrap the rest of cvc::state_exec's public surface under the C++ names:

- stackless_evaluator and evaluator, with evaluator_state, eval_frame,
  eval_phase (an IntEnum) and evaluation_stats; evaluation_interrupted
  and evaluation_timeout as RuntimeError subclasses. The evaluators
  release the GIL while they evaluate, so another thread can interrupt,
  pause or resume them. on_complete is a Python callable.
- The process struct (shared, as process_ptr), watch_event and
  watch_handler_entry, make_process, and the scheduler calls that take
  them: current_process() and queue_watch_event(). scheduler_base is
  the common base of the two schedulers.
- encode_/decode_environment and encode_/decode_evaluator_state.
- resource_policy (mode as an IntEnum), process_limits, validate_limits.
- intrinsics_context, channel_policy, register_intrinsics, apply_chroot,
  resolve_channel_key, make_future, future_channel_of. Every function
  register_intrinsics adds keeps its context alive, and the context
  keeps the scheduler and channel policy assigned to it.
- From #660: kDefaultMaxAllocBytes, eval_alloc_limit, eval_alloc_check,
  alloc_bytes, scheduler.max_alloc_bytes(), max_alloc_bytes_from_state.

A reference into an object (evaluator_state.stats, evaluator.stats(),
process.state) keeps its owner alive; other members read and write as
copies. evaluator_state is move-only, so it is moved into Python.

test_pycvc_state_exec_eval.py repeats the C++ tests. The parity doc,
whose inventory now includes what landed on master since the audit, and
the README are updated.
transfix added a commit that referenced this pull request Oct 18, 2026
…y-depth values) (#679)

* state_exec: grammar spec, conformance cases and parse corpus (grammar P0)

Declare the state_exec s-expression grammar in docs/STATE_EXEC_GRAMMAR.md
(W3C EBNF, Unicode source rules, literal tables, and a table of every
intentional change from the hand-written parser, tagged by phase P2-P4).
The parser itself is unchanged; later phases build it from this grammar.

state_exec_grammar_test tags each case with the phase it holds from:
landed cases must hold, pending cases must still differ, the doc's EBNF
must be closed, and every production needs a case. state_exec_corpus_test
pins how the 597 DSL scripts the repo carries parse today
(state_exec_corpus/, regenerated with gen_state_exec_corpus.py and
CVC_UPDATE_GOLDENS=1).

Also correct parser.h (no quasiquote) and the developer guide (false and
#f read as nil, bytes literals exist).

* state_exec grammar: make the nesting limit configurable (default 256)

Spec only: parse_options::max_depth on parse()/parse_all()/parser and execute_options::max_parse_depth for submitted scripts, both from P2. Records why the limit exists (the reader recurses on the native stack; the evaluators are stackless) and the corpus's real depths (max 13, median 2).

* state_exec grammar: parser settings live on the state tree

Spec only. max_depth resolves from state_exec.schedulers.<id>.parser.max_depth, then state_exec.defaults.parser.max_depth, then 256, matching scheduler::load_settings(); parse_options remains for callers without a tree. Drops the execute_options::max_parse_depth idea so the tree is the single source.

* state_exec: parser settings on the state tree, with a nesting limit (grammar P1b)

The parser now stops at parser.max_depth nested lists and quotes (default
256) with a parse_error, instead of recursing until the native stack
overflows. Like the scheduler's other settings, the limit lives on the
state tree: state_exec.schedulers.<id>.parser.max_depth, then
state_exec.defaults.parser.max_depth, then 256; a missing, malformed or
zero value is skipped.

- parser: parse_options (max_depth) on parse()/parse_all()/parser, a
  depth guard on lists and quotes, and parse_options_from_state().
- scheduler: load_settings() resolves parser.* and publishes the
  effective value under state_exec.schedulers.<id>.parser.max_depth;
  execute() parses with it.
- async_scheduler (the app's exec scheduler) reads the defaults key on
  every submit; Ariadne predicates read it from the app tree.
- stackless evaluators: create_state(script, env, parse_options).

The grammar test moves from a numeric kLandedPhase to named phases; the
257-deep case is P1b and holds now. Tests cover the default, a custom
depth, quotes, 100000 open parens, the error position, tree resolution,
bad values, and both schedulers.

* state_exec: make the parser stackless (explicit frame stack, resumable read)

Lists and quotes were parsed by native recursion, so input depth was
bounded by the thread's stack. The parser now keeps open lists and quotes
on a heap stack of frames and reads in a loop: native stack depth is
constant however deeply the input nests (a test reads a million open
parens and reports the unclosed list instead of crashing).

The loop is a resumable read(out, budget): it reads up to `budget` tokens
and returns datum / end / more, carrying open frames between calls, so a
scheduler can parse a script a slice at a time. parse() and parse_all()
call it with no budget.

Output is unchanged, quirks included (a stray top-level `)` still reads
as a symbol until P2): the conformance cases, the 597-script corpus and
the evaluator suites all pass. parser.max_depth stays on the state tree;
it now bounds parsed data for the code that still walks values
recursively (list destruction, the snapshot codec, to_string) rather
than the parser's own stack. parse_fib20_expr: about 3.4 us vs 3.1 us
for the recursive parser (median of 6, MSVC Release, loaded machine).

* state_exec: read submitted scripts inside the process, a slice per step

The stackless parser's state is an input position plus a heap stack of
open frames, so it can pause anywhere. New setting parser.step_tokens
(on the state tree, resolved like parser.max_depth; default 0) lets a
scheduler parse a submitted script inside the new process instead of at
submit: each scheduler step reads N tokens, and the step that reaches the
end sets up evaluation exactly as parsing up front would have.

- Reading steps are process steps: they count against max_steps and
  max_time and interleave with other processes.
- A syntax error surfaces like a runtime error: the async scheduler kills
  the process with it as the exit error; the sync scheduler throws it
  from step()/run(). With step_tokens = 0, execute() still throws.
- Signals and watch events wait until the script is read (their
  handlers run on the evaluation stack, which doesn't exist yet).
- The snapshot codec stores a mid-read process's source and settings and
  re-reads it after a restore.

Adds parse_options::step_tokens, script_reader (owns its source and
drives parser::read() a budget at a time) and evaluator_state::reading;
stackless_evaluator::step() reads until the script is read. Tests cover
the reader, the evaluator, the codec and both schedulers (results,
syntax errors, max_steps, deferred signals).

* state_exec: the app's exec scheduler reads scripts in steps (1024 tokens)

app::exec_scheduler(), which runs Ariadne's actions and residents, now
defaults parser.step_tokens to 1024, so it parses submitted scripts
inside their processes. async_scheduler gains set_parser_defaults(): the
built-in values under its watch root's state_exec.defaults.parser.* keys.
A plain async_scheduler (pycvc's Exec) and the sync scheduler stay at 0,
so they still report syntax errors at submit.

Why 1024: every script the repo carries reads in one slice (the largest
is 159 tokens, .ari scripts at most 24), so a normal action pays one
extra step of its 5000; a slice costs about 80 us at the parser's
measured ~80 ns/token, so a pathologically large script is spread over
steps and frames instead of stalling a drain.

Ariadne now says why a process died: a killed action's warning carries
its exit error, and the per-frame sweep reports a killed resident (a
syntax error in its body, a runtime error, its per-step cap) once,
instead of letting it vanish silently.

* pycvc: give Exec the same state_exec defaults as the app's exec scheduler

pycvc's Exec runs programs on a private async_scheduler that already
watches the app's state tree, but its built-in parser defaults were
plain parse_options{} while app::exec_scheduler() read scripts in
1024-token steps. Both now take async_scheduler::host_parser_defaults(),
one definition (with the reasoning for 1024) for every libcvc host, and
the app tree's state_exec.defaults.parser.* keys override both.

Exec.run() still raises a RuntimeError with the parse error's message:
from the killed process's exit error when the script is read in steps,
or from execute() when the tree sets step_tokens to 0.

Tests: test_pycvc_exec.py checks the parse error's message and that
max_depth / step_tokens on the app tree configure Exec; the integration
test pins the app scheduler to host_parser_defaults().

* pycvc: expose the state_exec parser-settings surface under its C++ names

pycvc's state_exec surface was only Exec; the parser settings these PRs
add had no Python counterpart, so the defaults weren't even observable.
In pycvc's direct-wrap style (the real C++ types, no facade):

- pycvc.parse_options: the real cvc::state_exec::parse_options struct
  (max_depth, step_tokens), C++ defaults included.
- pycvc.async_scheduler.host_parser_defaults(): the real static, declared
  to SWIG on its own (async_scheduler isn't wrapped yet, so no
  constructor).
- pycvc.parse_options_from_state(app, scheduler_id="", base=...): the C++
  resolver, taking the app where C++ takes the root (pycvc's convention).
- Exec.parser_defaults() / Exec.set_parser_defaults(): the same calls as
  the async_scheduler Exec wraps.

test_pycvc_exec.py covers each against the C++ behaviour; the README
gains a state_exec section. Built locally (SWIG 4.4.1, Python 3.11):
exec, exec_async, exec_coro and ari tests, 26 passed.

* pycvc: parse_options_from_state takes the State root, as in C++

Wrap the real cvc::state_exec::parse_options_from_state(state&, id, base)
instead of a pycvc adapter that took the app: Python passes the tree root,
pycvc.State.instance(app), exactly as C++ passes cvc::state&. This is the
first decision of the pycvc/C++ parity approach (C++ cvc::state& parameters
take a pycvc.State in Python).

* pycvc: state_exec parity part 1 (values, parsing, parse_error, value codec)

Start bringing pycvc's state_exec API to the C++ surface under the C++
names (docs/PYCVC_STATE_EXEC_PARITY.md: the audit of all 20 state_exec
headers, the agreed approach, and the PR plan).

- One strict value_t <-> Python conversion (pycvc_value.h), used by every
  API and by Exec: native types for data, pycvc.symbol (the real struct)
  for symbols, and pycvc.value (the real value_t, opaque) for closures,
  native fns, data objects and generators, which convert back unchanged.
  Non-str dict keys and unsupported types raise TypeError, ints beyond 64
  bits OverflowError, and nesting past 1000 levels or a cycle ValueError.
  This replaces the lossy converter (symbols became str, closures
  "<closure>", anything else str(obj)), which could also put a null item
  in a list on invalid UTF-8 and leave an OverflowError pending.
- pycvc.parse / parse_all, pycvc.parse_error (a RuntimeError with .line
  and .col), pycvc.script_reader, to_string, values_equal, and the value
  codec encode_value / decode_value on a State node.
- Exec.run raises pycvc.parse_error for a syntax error whether the script
  was parsed at submit or read inside the process (it re-parses a killed
  process's script to recover the position).
- The pycvc README's Status/Design sections described a v0 facade; they
  now describe the direct-wrap design.

test_pycvc_state_exec.py (13 tests) covers each against the C++
behaviour. Locally: those plus pycvc's exec, async, coro, ari, state and
core suites pass (87), except test_volume_rawiv_roundtrip, which fails
the same way on the unmodified build (a Windows temp-file lock).

* pycvc: state_exec parity part 2 (environments, builtins, schedulers)

Wrap the scheduler surface of cvc::state_exec under the C++ names:

- environment (shared, as environment_ptr) and builtins:
  make_default_environment, and register_fn taking a Python callable
  or a pycvc.value holding a native fn.
- execute_options (on_complete is a Python callable, signal_handlers a
  dict), process_info, scheduler_stats, percent_encode/percent_decode.
- process_status and scheduling_policy as enum.IntEnum classes; an enum
  argument must be a member, so to_string(process_status) and
  to_string(value_t) keep their shared name.
- scheduler and async_scheduler as real classes with their
  non-coroutine members. run/step and sync_run/sync_step release the
  GIL; Python callbacks retake it.
- Exec.scheduler() returns Exec's async_scheduler, which keeps the Exec
  alive.

Empty optionals are None, except for values: get_result,
pop_pending_message and environment.lookup raise KeyError, since None
is nil. The value_t typecheck now runs last, so execute(str) picks the
script overload.

test_pycvc_state_exec_sched.py repeats the C++ scheduler tests on both
classes. The parity doc and README are updated.

* Rerun CI on master (the merge push ran while the PR still targeted #653's branch)

* pycvc: environment.frozen (#660), and the set_existing note now that its comment is fixed

* pycvc: state_exec parity part 3 (evaluators, processes, policy, intrinsics)

Wrap the rest of cvc::state_exec's public surface under the C++ names:

- stackless_evaluator and evaluator, with evaluator_state, eval_frame,
  eval_phase (an IntEnum) and evaluation_stats; evaluation_interrupted
  and evaluation_timeout as RuntimeError subclasses. The evaluators
  release the GIL while they evaluate, so another thread can interrupt,
  pause or resume them. on_complete is a Python callable.
- The process struct (shared, as process_ptr), watch_event and
  watch_handler_entry, make_process, and the scheduler calls that take
  them: current_process() and queue_watch_event(). scheduler_base is
  the common base of the two schedulers.
- encode_/decode_environment and encode_/decode_evaluator_state.
- resource_policy (mode as an IntEnum), process_limits, validate_limits.
- intrinsics_context, channel_policy, register_intrinsics, apply_chroot,
  resolve_channel_key, make_future, future_channel_of. Every function
  register_intrinsics adds keeps its context alive, and the context
  keeps the scheduler and channel policy assigned to it.
- From #660: kDefaultMaxAllocBytes, eval_alloc_limit, eval_alloc_check,
  alloc_bytes, scheduler.max_alloc_bytes(), max_alloc_bytes_from_state.

A reference into an object (evaluator_state.stats, evaluator.stats(),
process.state) keeps its owner alive; other members read and write as
copies. evaluator_state is move-only, so it is moved into Python.

test_pycvc_state_exec_eval.py repeats the C++ tests. The parity doc,
whose inventory now includes what landed on master since the audit, and
the README are updated.

* pycvc: state_exec parity part 4 (data jobs, heap, stdlib registry, any-depth values)

- The value conversion walks with an explicit stack instead of recursing, so a value
  nested any depth crosses both ways (the parser's max_depth default is going to
  100000). A list or dict shared within a value converts to one object, both ways:
  sharing survives the trip, a shared structure converts in time proportional to its
  size, and a DSL list that holds itself becomes a Python list that holds itself. A
  Python value that holds itself still raises ValueError.
- The deep-data jobs (#658, #665): data_job, the make_*_job factories,
  run_to_completion, run_data_job (a Python callable as `then`), call_function,
  is_compound, count_data_nodes, kDataNodeBytes. A job is handed to Python owned
  (std::unique_ptr); `who` is kept for good, as C++ holds the pointer.
- The heap (#667): heap_options and its tree settings, measure_heap_share,
  make_heap_share_job, heap_remeasure_bytes, and the per-thread cycle collector;
  the heap fields on process and process_info, evaluator_state.heap_measured,
  stackless_evaluator.global_env(), eval_alloc_note.
- stdlib_registry: standard() (a copy), shared_scope(), register_function (a Python
  callable or a pycvc.value native), list_*, import_module, lookup_qualified (KeyError
  where C++ returns nullptr).
- SWIG_STD_MOVE moves on MSVC too (it reports __cplusplus 199711L without
  /Zc:__cplusplus), so a unique_ptr argument can be passed.

test_pycvc_state_exec_data.py covers the new calls, and test_pycvc_state_exec.py the
any-depth, sharing conversion. The parity doc and README are updated.

* pycvc: wrap #682/#683's call_function continuation, make_generator_job and the native nesting limits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant