Skip to content

No thread markers: core's thread pools and state_exec keep nothing per thread [4.0, breaking] - #1217

Merged
transfix merged 12 commits into
masterfrom
p0a/no-thread-markers-state-exec
Nov 15, 2026
Merged

transfix merged 12 commits into
masterfrom
p0a/no-thread-markers-state-exec

Conversation

@transfix

Copy link
Copy Markdown
Owner

Removes the 37 per-thread markers left after #1203: core's thread pools 10, state_exec 27. A thread_local isn't per process, but every app and object running on a thread shares it, so two apps (or two pools, two evaluators) on one thread saw each other's markers. The allowlist drops from 59 to 22. 4.0, breaking.

This branch contains #1203 (it starts from #1203's head, aa01bda). Merge #1203 first, then this; once #1203 is on master, this PR's diff shrinks to its own five commits. Please merge with a merge commit.

What replaced them

  • state_exec: what running work has in force now lives in an exec_context, handed down explicitly. That covers deadlines, the allocation guard, the cycle registry, math.random's stream, the exec group, the data step, native nesting, the await slot, step depth, parking, the stack bound, the scope cache and the frame vectors. Each scheduler and evaluator owns one, and a native gets it through call_args::context().
  • Exec pool: while pump_all holds a group, the group points at its own entry in that call, which records the thread pumping it. Whatever has the group can ask whether this thread is the one pumping it. The host-body and deferred-callback flags live on the call.
  • Thread pool: each pool keeps its workers' ids (fixed at construction) and lock-free slots for callers running their own posted jobs. A fan-out context belongs to one pool.
  • Async lane: each lane knows its worker's id and which thread is draining it.
  • App: poolDropReason() is per app.

No new thread_local, static or global anywhere. ratchet.py against #1203's allowlist passes, and no thread_local is left in src/cvc/core, inc/cvc/core or state_exec.

API changes (4.0)

  • Natives: native_fn takes call_args (the arguments plus the context); natives declared with std::span still convert. There is a new exec_context class.
  • Evaluators and schedulers: context() on the evaluators, step(state, ctx), step_now(state, ctx), and evaluation_context() on both schedulers.
  • Take the context: the deadline and allocation guards and checks, run_to_completion, run_data_job, call_function, count_data_nodes, async_host::call, generator_next, the parking calls, and the decode_* functions (optional).
  • Heap: collect_cycles(ctx) and cycle_registry_id(...) replace the thread's registry calls. Gone: cycle_registry_scope, bound_cycle_registry_id, collect_cycles_at_thread_exit, and the no-argument collect_cycles, tracked_objects, cycle_collection_due and note_process_exit.
  • Groups: exec_group::current(ctx) and pumping_here() replace current().
  • Gone: random_stream_scope, data_step_scope::current(), backlog_scope and native_nesting::depth().
  • Exec pool: pump_all returns the groups it failed; failed_groups() and in_pump_all() are gone. run_on_host(group, fn) takes the group, and so do cvc::detail's worker_pool, defer_on_complete and run_on_host_waiting.
  • Thread pool: fanout_context_scope(pool, ctx) takes the pool, and pool.fanout_context_here() replaces current_fanout_context().
  • async_host: its inline constructor takes an optional fan-out pool. A host with an app charges kernel fan-outs on the app's compute pool.
  • pycvc: register_fn(..., with_context) hands Python natives a pycvc.call_context, which the eval_alloc_* and data-job calls take. The cycle-registry calls are stackless_evaluator and Exec methods.

Behaviour changes to review

  • No per-thread cycle registry. A bare evaluator or scheduler has its own, collected when it goes. Objects that outlive their registry are no longer handed over to anything, so a host that keeps a function past its group must break that cycle itself. pump_all's deferred on_complete callbacks run with no registry bound.
  • Kernels: an async kernel may now run an evaluator of its own (before, that was refused; the test that asserted the refusal is changed). A kernel's thread mark belongs to the kernel's scheduler, so only that scheduler's entry points refuse it.
  • Frees: slicing-step frees are routed explicitly. A value dropped inside a native's own code is freed inline rather than a slice at a time. The pinned step counts still match.
  • Fan-outs: one nested inside an inline fan-out (n = 1 or max_par = 1) may now post instead of running inline. It can't deadlock, since a caller always runs its own indices.
  • A new evaluator costs about 15-20 µs on first use, because its registry, frame vectors and scope cache used to be warm per-thread pools. Production code makes evaluators once per lane or group (Ariadne's read lane, each exec group's scheduler), so only tiny short-lived runs notice. stdlib_dict_merge_per_node, which times 10 nodes, roughly doubles.

Tests

  • Same thread, two apps:
    • StateExecNestsAcrossAppsOnOneThread: app B's group runs inside a native of app A's, on one thread, in both creation orders. Each side sees its own group, registry, allocation limit, random stream and context.
    • AKernelsMarkIsItsSchedulersOnly: inside app A's inline kernel, A's scheduler refuses kill and B's takes it.
    • In exec_pool_test, one thread pumps two apps' pools in both orders, and one app's pool is pumped from inside another app's group.
    • In thread_pool_test, nested fan-outs cross two pools on one thread, and re-entrancy is per pool. In async_lane_test, lanes on one thread drain each other.
  • Multi-app workload: new core_threads and state_exec_contexts parts, each checked alone, at once on threads, and reversed.
  • Existing tests: many were rewritten onto explicit contexts.

Benchmarks (Windows, MSVC Release, a shared machine, so noisy)

  • Pool dispatch got faster:
    • parallel_for n = 8, max_par 1: 110 → 48 ns;
    • pump_all, 8 groups with 3 busy workers: 105 → 76 µs;
    • every other shape was flat or faster.
    • A first version that locked to detect nested callers was 20 % slower nested; the lock-free slots fixed it.
  • state_exec: per-step and per-node paths are within about 5 %, or faster.
    • eval_fib15: 2.46 → 2.23 ms.
    • scheduler_500_procs: 556 → 468 µs.
    • eval_nest_list_2000: +3.9 %.
    • native_call_apply: +4.9 %.
    • sched.single.tail_rec: +6 %, inside its 9.6 % noise.

Testing

  • Windows (MSVC Release), full tree (pycvc and cvcGL included), built with no errors.
    • 36 C++ suites pass: every state_exec suite, plus exec_pool, thread_pool, async_lane, app, multi_app_integration, ariadne_registries, ariadne_runtime and the bench test. Stress, soak and benchmark cases were left out, as on PR runs.
    • 21 pycvc ctests pass on the merged tree. All 52 passed on core's part alone, before the merge.
  • GCC/Clang code path: the 52 changed sources that Windows builds pass a clang syntax check with the GCC/Clang coroutine trampoline forced on. wasm_engine.cpp builds only for wasm: its three call sites were checked against the new signatures by hand, and CI's wasm lanes compile it.
  • clang-format: clean on changed lines against No singletons: libcvc's process-wide state per app, per object or gone [4.0, breaking] #1203's head.
  • Not run locally: Linux, macOS, wasm and the sanitizers. CI covers them.

Left (22 lines)

  • Signal-handler state (3): approved.
  • Process resources set up once by the library (6): curl, ImageMagick, HDF5's library lock, Jolt.
  • Our own process state (10): the CUDA device manager 2, raycast.cu's __constant__ tables 7, the process nice level 1.
  • state_exec (3): the scope-serial counter (scope_mark relies on unique low-32-bit serials) and the built-in exception classes (identified by address).

Also not scanned: the executables' globals (ari/arigl g_wasm, arisrv's g_stop and its benchmark tool's settings), ariadne_python's script_engine(), and cvcGL's Clipboard_mac.mm buffer (macOS only; the scan runs on Linux).

…p nothing per thread

A thread_local is shared by every app and object on its thread, so two apps' pools (or lanes) run
by one thread saw each other's markers. Core's ten go; the allowlist loses 10 lines (cvc 57 -> 47).

exec_pool (t_worker, t_caller, t_defer, t_callback, t_failed and its __tls_guard):
- A pump_all holding a group points the group's pool_link().call at its own entry, which records
  the thread pumping it now. Code that has the group finds its call and whether the calling
  thread is the worker pumping it: detail::worker_pool(group), detail::defer_on_complete(group,
  cb), run_on_host(group, fn), detail::run_on_host_waiting(pool, group, fn), purge_host_calls.
- Whether the caller runs a host body or a deferred callback is its call's flag;
  detail::in_pool_callback(app) reads the app's pool (a threaded call stays listed until its
  deferred callbacks have run).
- pump_all returns the groups it failed (failed_groups() is gone). in_pump_all() is gone.

thread_pool (t_active_pool, t_fanout_context):
- Re-entrancy is the pool's own: its workers' ids (an immutable list) and the callers running a
  posted job's indices (slots written under its mutex, read lock-free, each thread looking for
  its own id). A fan-out nested in a max_par 1 or n 1 fan-out may now post (never a deadlock).
- fanout_context_scope(pool, ctx) sets the context on one pool (kept by thread, under its mutex);
  pool.fanout_context_here() replaces current_fanout_context(). A worker running chunks under a
  context keeps it in its own slot.
- async_host charges a kernel's fan-outs on its fan-out pool: the app's compute pool, or one given
  to an inline host (async_host(sched, fanout_pool)).

async_lane (t_running_top): the lane knows its worker's id and the thread running its drain.

app (t_poolDropReason): poolDropReason() is a member: the app keeps its drops under way by thread
(app::PoolDropScope). launch_pool_task's and the async host's tasks hold their app.

Call sites in state_exec's files, updated minimally: exec_group.cpp (worker_pool(group),
defer_on_complete(group, ...), run_on_host(group, ...), run_on_host_waiting(pool, group, ...),
in_pool_callback(app)); async_host.h/.cpp (run_kernel takes the fan-out pool, kernel_task holds
the app and the pool, the inline constructor takes an optional fan-out pool);
state_exec_groups_test.cpp, state_exec_bench.cpp (pump_all's failed groups);
state_exec_async_calls_test.cpp (its inline hosts name the compute pool).

Tests: one thread pumping two apps' exec pools in turn (each returns and calls back only its
own), a nested pump of one app's pool inside another app's group (each group's natives see only
their own pool), nested fan-outs across two thread pools on one thread (contexts and
re-entrancy per pool), pools on threads at once, lanes on one thread draining each other, and
multi_app_integration_test's core_threads part. Dispatch benchmarks (disabled tests, best of 3x5
runs, before -> after): parallel_for n=1 9.8 -> 7.4 ns, n=8 max_par 1 110 -> 48 ns, n=4 1167 ->
980 ns, n=64 5562 -> 5316 ns, nested 4x4 1409 -> 1231 ns; pump_all of 8 groups at 0 workers idle
2.01 -> 1.72 us, busy 186 -> 149 us, at 3 workers idle 2.43 -> 2.04 us, busy 105 -> 76 us.
What state_exec work has in force (deadlines, the allocation guard, the
cycle registry, math.random's stream, the group a pump runs, the data
step, native nesting, the await slot, step depth, parking, the stack
bound, the scope cache and the frame vectors) is an exec_context, handed
from whoever runs the work to what it calls: the schedulers' and the
evaluators' own contexts, a data job's bound context, and a native's
call_args::context(). Nothing of it is kept per thread.

- native_fn takes call_args (the arguments and the call's context); a
  native declared with std::span still converts.
- Releases steal a value's unshared parts into a local queue, and the
  evaluator hands what a slicing step drops to its backlog explicitly.
- The scope cache, serial runs and frame vectors live in the context.
- A scheduler marks the threads running its kernels
  (scheduler_base::kernel_thread_scope), and its entry points refuse
  them; a kernel reports allocations to its call (async_call::alloc_check).
- exec_group::current(ctx) and pumping_here() replace the thread's group.
- Ariadne's script slices and wasm guests carry their step's context.
…the state_exec part

Conflicts, resolved with the state_exec design:
- async_host: run_inline takes the call's context, run_kernel the fan-out
  pool; a kernel's thread is marked on its scheduler and reports what it
  allocates to the call, its fan-out chunks on fanout_pool().
- exec_group: begin_external(ctx, ...) and the call_args proxy, with the
  group-taking worker_pool(group) and run_on_host(group, fn).
- exec_pool's run_for_group keeps the in_callback flag and binds nothing.
…allowlist down 27

Builds on the merge of core's part. What is left of state_exec's per-thread
state goes, and its 27 allowlist lines with it (data_job, exec_group, heap,
native_stack, stackless_evaluator, stdlib, types; g_next_serial_run and the
exception classes stay).

- A scheduler's evaluation context is parkable (exec_context::parkable): a
  nested evaluator, with a context of its own, can't park its caller's
  process.
- A slicing step's backlog takes what it frees as before: a release lets
  go of a shared part in order, so the holder of the last reference hands
  it over (take_or_let_go), and a finished job hands over its inputs
  (data_job::release_inputs).
- msg-recv keeps its call's context when it awaits a future.
- The lock_enter test hook gets the step's context.
- pycvc: a Python function registered with_context gets a
  pycvc.call_context, which eval_alloc_*, run_data_job, call_function,
  run_to_completion and count_data_nodes take; a bare stackless_evaluator
  collects its own registry; ExecPool.close asks the groups whether they
  are pumped or run a kernel here.
- Tests: no thread registry to collect at exit; the registry, stream,
  deadline, allocation-limit, scope-cache and kernel-mark tests run on
  explicit contexts; multi_app_integration_test nests app B's group inside
  a native of app A's on one thread (both orders), checks a kernel's mark
  is its scheduler's only, and adds the contexts to the workload.
- Docs: STATE_EXEC_EXCEPTIONS 3.7, the developer guide's pump scope and
  cycle registry, THREADED 4.1 and 4.7, LOCKS, and the pycvc parity table.
@transfix
transfix enabled auto-merge November 13, 2026 06:38
…rkers

Master's new code on the context, as the rest of the branch:
- script_engine: the pure exports' run_pure takes the calling native's
  context (exec_context): the eval's deadline (eval_deadline_check(ctx)),
  its data step for the slices' charge, and the slice's context for
  call_now, in place of the thread's. Its ScriptSlice keeps both
  context() and the new may_wait().
- Runtime::ReadFunction takes call_args (a function taking a span of
  arguments still fits), so export_pure hands run_pure the eval's context;
  the read lane binds it as a call_args native.
- wasm_engine's pure calls reach the data calls' allocation checks through
  the slice's context, as its other calls do.
…ntrol block; RX01's new name in CI

- take_part takes a class's natives' parts out too (a constructor's class
  dict, an inherited method's superclass dict, an evaluator method's
  closure: what heap.cpp's value_edges finds in them), so freeing a long
  class chain, each class holding the next through its natives, runs in
  the release's own loop. The per-thread release loop used to absorb that
  nesting; StateExecNativeNesting.InheritedInitUpALongChain and
  FreeingALongClassChain overflowed the stack without it. take_owner counts
  a dict's elements as a list's.
- kControlBytes is 40 with libc++, whose shared_ptr counts are long: the
  control block holds block_allocator's slot pointer too.
- ci.yml's tsan required cases name Groups.RX01_ABareSchedulersCyclesGoWithIt.
…rkers

No conflicts. Master's new net code (#925's started ws-open and ws-recv,
settle_started, the app's WsTable) registers async work through the same
async_work marshals and start lambdas, which take no context; nothing it
calls changed in this branch, so it merges as it is.
…tries past their envs

LeakSanitizer found reference cycles in three suites at 499371d. No
thread registry is left to adopt what outlives a registry, so a
registry's last collection must come after everything holding its cycles
has let go.

- The evaluators' own registry (stackless, recursive, coroutine) is now
  their first member, so it goes last: after the evaluator has let go of
  its global environment. Before, a bare evaluator's last collection saw
  its own global environment as live, and a defun bound there was never
  freed. CycleRegistryTest.ABareEvaluatorsCyclesGoWithIt checks it
  without a leak checker (it fails with the old order).
- The tests that keep an environment past its scheduler or evaluator do
  what a host does (pycvc's Exec): give them a registry that outlives the
  environment (CycleCollectorTest.LiveDataIsNeverFreed and
  DoesNothingInsideAStep, StacklessCallee.ARewiredChainIsLookedUpAgain),
  or let go of the environment before the group goes (group_world, for
  GR01, GR03 and DT01). The solo runs check each group's environment is
  freed with its world.
- The developer guide states the contract.
LeakSanitizer still found cycles at f495fdb, all from
Groups.DT02_ThreadsZeroEqualsBareSchedulers. Its bare_world keeps its
environment past its scheduler, and the scheduler had no registry of the
host's, so its evaluator's own registry did its last collection while
the environment was still held, and the cycles its programs left there
(the kept closures, the defuns) were never freed.

bare_world now does what a group does: a registry of its own, made first
so it goes last, given to its scheduler. That also configures the bare
scheduler as a group's is (it collects when idle), and its runs still
equal the pooled ones.

DT-2 now checks each bare world's environment is freed with it, as the
solo runs do for groups, so the leak shows without a leak checker: the
check fails for all 8 bare worlds without the registry.
Master gained #1203 (this branch's base), #1192 (state_exec Stage S,
several steps a pick) and ten others.

Conflicts, both #1192's run code against this branch's registry work:
- async_scheduler.cpp: the slice setters from #1192, set_cycle_registry
  from here (it also gives the evaluator the registry). The cycle check
  takes the registry in the evaluation context (the one given, else its
  evaluator's own) where #1192 fell back to the thread's own, which this
  branch removes; collect_cycles_if_due now takes a registry. A run's
  steps go through the same context as its first; step_run's drain check
  is check_not_in_kernel, as step_once's is.
- state_exec_groups_test.cpp: OC01's caller-pumped case keeps #1192's one
  step a pick and this branch's watched group. The file's note on leaks no
  longer speaks of a thread's own registry.

Semantic, not textual:
- #1192's Slices tests: SL04's spin-step and SL08's heavy take call_args
  and reach their context through it (eval_deadline_check(a.context()),
  a.context()->data), as this branch's other natives do.
- cvc-cli's trace command (#1168) takes its app, and #1180's three
  rich-text tests pass theirs to load_string. Both landed after #1203's
  last master merge and still used what #1203 removed, so master does not
  build at 7ead20e or 69c7091; #1225 makes the same change there.

Checked on Windows (MSVC Release): full build; groups 28/28; Slices and
run-budget tests 19/19; rich text and heap 10/10; the cycle collector and
registry tests, pycvc_ariadne, CvcCliTest.TraceInfoAndVerifyReplayASession
and state_exec_async_test_slice256, 20/20.
transfix added a commit that referenced this pull request Nov 14, 2026
Conflicts, all master's #1216 and #1177 against this branch's embedded
Python:
- python_engine.cpp: _arihost stays made at boot by install_arihost (no
  inittab entry); its docstring takes #1216's name for the host,
  pycvc.ari.Host().
- ARIADNE_SCRIPTING_HOSTS.md: the same, in the roadmap's words.
- arigl/main.cpp: the conference camera keeps this branch's kWalkKeys
  comment and gains master's setMouseLookOrbits(true).

Nothing master added calls what this branch removed (g_python, g_wasm,
lent(), script_engine(), the inittab module, the CUDA manager's
instance(), the load bench's globals).

Checked on Windows (MSVC Release): full build; ratchet ok against
#1217's allowlist (22 lines) and master's (59), 13 here; the scan's own
tests; format clean; the host, Python and multi-app ctests, 24 pass and
18 skip (FTXUI and matplotlib, absent here), pycvc_ari and
pycvc_ariadne_harness among the passes.
CI at 9d002d1 built it on master as of 09:28, after #1197 added
ariadne_wasm_browser_test.cpp with register_script_engine calls that
predate #1203 (all three package-linux lanes and wasm-guests failed to
compile it). Master fixed that in #1229, and the load_string calls
#1169 left in the loader and chart tests in #1190. This merge takes
master as it is now, so CI builds on those fixes. No conflicts.

Master's new natives (#1190's file-pick and http-upload, #1195's
py_console, #1169's chart) build against this branch's call_args
context as they are.

Checked on Windows (MSVC Release): full build; the Ariadne, net, HTTP,
state_exec, groups, slices, async-call, cycle-registry and multi-app
ctests, 1336/1336. ariadne_wasm_browser_test is not built here (it needs
wasmtime or Emscripten); master's CI builds it.
transfix added a commit that referenced this pull request Nov 14, 2026
One conflict, master's #1195 (py_console) in the class this branch
reworked, python_engine.cpp's PythonScriptEngine:
- load_block keeps master's order (the block's object lives on for
  consoles_for) with this branch's take_error(helper); unload comes in
  beside the engine's private EngineState pointer.
- export_console's natives described their own errors through the
  process-wide g_helper this branch removed. export_console now takes
  the helper and its natives hold a reference of their own, let go as
  their consoles are; unload passes none.
- The engine's constructor describes a console that fails to load with
  st.helper, which is up by then.

Checked on Windows (MSVC Release): full build; format clean on changed
lines; the host, Python and multi-app ctests with master's console
tests, 47/47 (skips as before: no FTXUI or matplotlib here), among them
arix_engine_test, which reloads documents with and without a console.
transfix added a commit that referenced this pull request Nov 14, 2026
Joe's answer on executables (roadmap 9 item 5, 2026-11-14): "Only
OS-forced globals (Recommended)". The hosts were done; the examples,
which the scan does not cover, still kept state of their own:

- The demo menu (examples/common/demos_menu.cpp) kept how to open each
  demo and whether one was started in two file-scope globals, and the
  program's directory in a static. Its state is now an app slot:
  demos_menu(app, slug) and demo_switch_requested(app), in all ten
  demos.
- terrain_lab: the size-following extents (world half, water grid,
  cloud slab) are an Extents main owns and passes to the water and sky
  builders; spans are labelled with the app's world_units() (SI, one
  unit a metre, as the global was); the sun angles are constants; and
  the building library, cached in a static that kept the first app's,
  is loaded once by main.
- nav_city_drive and nav_city_swarm: eight function statics each (the
  panel's fps tick and chase toggle, the world being rebuilt, the far
  skyline flag, the render profile) are locals of the panel callback's
  and the loop's scope. A second run in one process (the demo switch)
  no longer starts from the first's.

The allowlist: each group says why it stays. scan.py's WHY_IT_STAYS
holds the reasons and render_allowlist writes them above each file's
lines, so a regenerated list keeps them; a scan test fails a line with
no reason. The header, the scan README and roadmap 9 item 5 quote
Joe's four answers, and the roadmap notes what is still open: the CUDA
volume cache is one per app, keyed by device, not one per device.

Checked on Windows: the examples build (ImGui on), terrain_lab renders
offscreen (--capture orbit --frames 3); scan tests 18/18 (one skipped
without nm); ratchet ok against master, #1217 and 50561e2.
@transfix
transfix merged commit eddaaf9 into master Nov 15, 2026
28 checks passed
@transfix
transfix deleted the p0a/no-thread-markers-state-exec branch November 15, 2026 03:03
transfix added a commit that referenced this pull request Nov 15, 2026
Master's #1217 keeps nothing per thread in state_exec: a native's context (call_args::context())
carries its group, registry and stream, async_host::call and begin_external take it, and the pool
drops in_pump_all() and the one-argument run_on_host.

- async_host.h: begin_external takes the context, as on master, and keeps this branch's note that
  a call is finished through the host it was made on.
- script_engine.cpp: the sliced form finds the calling program's group from the call's context
  (exec_group::current(ctx)), else group 0, and reads its data step from the context.
- ariadne.cpp: file-pick opens its picker through run_on_host for the group its verbs were bound
  for (the env's, as its host is), and inline in group 0 and the init lane.
- exec_pool: in_pump_all() is back, for the host-thread calls' debug assertion and
  ScriptLane::run's refusal, read from the pool's calls (their callers' and pumpers' thread ids)
  under its mutex rather than from thread-locals.
- ariadne_runtime_test: the init lane's cycles test no longer compares against the calling
  thread's own registry, which master removed; it is AriadneInit.RunsAScriptThatLeavesCycles.
- ci.yml: the sanitizer's required list names the test by its new name.
- STATE_EXEC_THREADED.md: B29-B31 and the file-pick and sliced-call notes name the context-based
  calls.
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