Repository navigation
state_exec async: persistent background pool, cheaper async calls, concurrent compute fan-outs - #843
Merged
Merged
Conversation
…s and async calls A standalone executable (plain main(), `--smoke` CTest entry) with about 80 scenarios. They time the recursive and the stackless evaluators bare, and the sync and async schedulers under floods of small, large and mixed programs. They also cover async functions on the background pool, a lane and inline; compute fan-outs; messaging; native and state-tree calls; per-process footprint; armed limits; deep-data work; and parsing. Each record is a JSONL line with: - wall time, driver-thread and process CPU; - steps by kind and ns/step; - latency percentiles; - peak working set and private bytes; - allocation counts; - thread and handle counts, including the app's pooled threads. The driver pins itself to a performance core, and every scenario checks its programs' results. tools/bench/state_exec_bench.py runs one process per scenario with repetitions and compares two runs against their noise. docs/STATE_EXEC_BENCH.md describes every scenario, the metrics, how to get stable numbers, and the pathologies the first runs exposed: - scheduler steps that cost O(P log P); - the background pool's thread per call, kept alive with its result until ~app; - the step rate re-read from the state tree on every charge; - busy-spinning sleepers; - unreaped floods.
…x64) WPR and VSDiagnostics need elevation, so the bench samples itself. A sampler thread suspends the driver about every millisecond and unwinds its stack in place with RtlVirtualUnwind into a preallocated ring, with no allocation, locks or DbgHelp while the driver is suspended. A watchdog resumes it if a sample holds it over 50 ms. Waits and other system calls are told apart by the ntdll/win32u stub they sit in. After the run, DbgHelp, loaded on demand, symbolizes the samples into folded stacks (speedscope, flamegraph.pl) and top self/inclusive/line tables. Only the first measured rep is sampled, so the other reps' timings stay clean; records name the sample files. Elsewhere --sample says it is unsupported and points at perf.
… workers parallel_for held one job slot behind _post_mtx, so a second caller blocked until the first fan-out drained, and every post notify_all'd the whole pool, even for a fan-out capped at two participants. Jobs now go on a FIFO list. A free worker joins the oldest job with room under its cap and indices left; the caller unlinks its job (no joins after) before waiting for the workers that did join. A post wakes min(idle, enlisted) workers. Chunks still run under the poster's fanout_context, one run_chunks per joined worker, so async_host's per-call charge accounts are unchanged. Tests: two capped fan-outs that each wait to see the other running; three posters sharing six workers, each chunk under its own context, at most the cap's workers inside a context at once.
…the pool size The background pool created a boost::thread per task, registered it in _threads until ~app (so each task's functor and captures, an async call's result included, lived until then), probed uniqueThreadKey from 0 under a mutex and rebuilt the thread-key sets over every thread ever started. The hang: tasks queued while the pool was full all got the same key, so a worker starting the next one interrupted and timed_joined the thread holding that key. tryStartWorker unlocked _threadPoolMutex by hand around threads(key, ...), whose interruption points (its top, hasThread, the timed_join) then threw thread_interrupted in a worker another worker had just interrupted. The caller's scoped_lock unlocked the mutex a second time; on Windows that flips boost::mutex's lock bit back on with no owner, and every later locker blocks forever. Confirmed with a probe on the old code: the throw fired in each failing run, followed by "did not stop in 5s" stalls, stranded tasks (14 of 1000 done after 10 s) or a hard hang. Now: - anonymous tasks (wait=false, and the new submitPooled) run on persistent workers, started on demand up to the pool size and joined by ~app; no key, no _threads entry, destroyed on the worker before they count as done; - one queue ordered by priority, then submission (FIFO within a priority); - keyed tasks (wait=true) keep their contract: a thread of their own, registered under the key before they run (synchronously when the pool has room), the entry kept after they end; a finishing keyed thread starts the next queued keyed task itself, so join-then-lookup chains still work; - the pool mutex is only released by the RAII lock that took it, and workers and registrations run with interruption disabled (only tasks are interruptible; a stale request is dropped before the next task); - wait_for_threads() interrupts the running pooled tasks and waits up to 5 s for the pool to drain; ~app interrupts running tasks, drops queued ones and joins the workers; - compute_async submits anonymously. Tests: a 1000-task flood on 4 workers (hung or stranded before), worker reuse and no thread-map entries, FIFO within a priority, no retention after a task ends, wait() waits for the pool, and ~app with a full queue returns promptly and releases the dropped tasks.
Per call, on the scheduler thread:
- the {"function": name} error-field vectors (call, outcome, begin_external)
are built only on the way to a throw;
- the reply channel string is made only for a call that parks or returns a
future (a transparent inline call has neither);
- check_open reads an atomic instead of taking the host lock;
- shared_state::add prunes expired weak_ptrs when the list has doubled since
the last prune (amortized O(1)) instead of scanning every live call;
- the kernel goes into the executor's task itself (no shared_ptr holder), and
that task is submitted anonymously with app::submitPooled (no key string,
no uniqueThreadKey probing, no thread per call) or moved to the lane;
- run_inline no longer reads the step rate up front: cancelled() reads it on
first need for a step budget, and the final charge reads it as before (so a
change still applies to the next charge).
run_kernel destroys the kernel on its thread before the host's count goes
down, as the holder did. launch_pool_task submits to the background pool
directly instead of compute_async(1, ...), which also built the compute pool.
Tests: 40 calls on a 2-worker pool all complete on at most 2 threads with no
thread-map entries; a finished call keeps neither its kernel's captures nor
itself (its result) alive; shutdown still cancels the call in flight after
300 finished ones.
A worker started for a queued task takes it and wakes or starts the next one before it waits, so while one is still starting, a new submission doesn't start another. A burst of short tasks now starts workers only as fast as they are needed (async.flood.noop n=10 started 19 threads per fresh app; the old pool started 10, one per task).
Creating a thread can take milliseconds on a loaded machine, and the worker was created with _threadPoolMutex held, so every submitter (the scheduler thread among them) and every finishing worker waited behind it: in async.flood.noop n=10 the completions of a burst arrived together, 1-30 ms late. tryStartWorker now only asks for a worker; whoever called it creates the thread once it has let the mutex go (startRequestedWorkers), and a worker created while ~app stops the pool is joined by its creator.
The list of calls to cancel at shutdown held a weak_ptr per call until a batch prune, and a weak_ptr keeps a make_shared object's storage (the whole async_call) allocated: async.pool_retention where=lane kept ~270 bytes per call. Each call now records its index in the list, and leaves in O(1) (the last entry moves into its slot) when its kernel ends, or, for an external call, when finish() posts its outcome. The batch prune stays for calls that die without leaving. The shutdown test makes 100 calls first instead of 300 (each costs a pump period).
…ter the fixes STATE_EXEC_BENCH.md: what changed for the thread-per-call executor, the stall and hang past the pool size (its cause, now confirmed), the serialized compute fan-outs and the per-call overhead, with the A/B numbers; --bg-oversubscribe now only matters for older builds.
… its workers at once Review fixes for the persistent background pool. - A keyed startThreadPooled (wait=true) with room in the pool for it and for every task already queued now starts on the submitting thread, so it is in threads() when startThreadPooled returns even right behind an anonymous task still waiting for its worker. Before, it was registered only if it was at the head of the queue, and the documented pattern `if (hasThread(k)) threads(k)->join();` silently skipped it. - poolKickLocked() gives every queued task that may start a worker on its way: a signalled or starting one, else an idle one to wake, else a new one up to the pool size. A burst of N tasks on a fresh app now starts min(N, pool size) workers at once instead of one at a time, and a signalled worker that has not woken yet is no longer counted as idle. - Workers wait on a std::condition_variable_any (boost's makes and closes a semaphore per wait on Windows) and are signalled after the pool mutex is released. Threads are created after it is released too, and with no extra lock round trip when nothing was asked for. - Workers are interrupted only under the pool mutex (wait_for_threads, ~app), with a generation count: a worker clears a stale request, under the mutex, before it takes its next task, and an interrupt sent after the take is that task's. One that reached a worker between taking a task and starting it used to be cleared as stale, and ~app then waited 5 s for a task that never stopped. Tests: a keyed task behind anonymous ones on a fresh and a warm pool is registered on return and joined by the hasThread/join pattern; ~app right after submitting interrupts every task taken (64 delays); a burst of 8 mutually waiting tasks runs at once on a fresh and a warm pool.
…ss key on first post - run_kernel decides the timeout, settles and posts the completion when the kernel ends, and only then frees the kernel. Freeing its captures (a large buffer, a Python callable's last reference under the GIL) had been counted against the call's timeout, turning a call that returned in time into a TimeoutError. The kernel is still freed on its thread before the host's count drops. Test: a kernel that returns at once with a 0.2 s timeout and captures taking 0.4 s to free returns its value. - The "<name>.progress" channel key is built on the first post() (most kernels never post), from the process's root path kept on the call.
… registration - THREAD_POOL.md's many-small-tasks example waits on the tasks' own completion, and says that app.wait() interrupts running tasks and gives up after 5 s. - THREAD_POOL(_API).md: when a keyed task is registered before startThreadPooled returns, and that a burst starts its workers at once. - Comments that still described one fan-out at a time per compute pool (raycaster, VOLREN_API, lod tiles, producer_thread, a volren test) and launch_pool_task starting a thread per call (async_lane.h) now describe fan-outs running side by side on shared workers and the background pool's persistent workers.
- The baseline's pool aging is load-dependent (about 3-17x, median 12 at k=3000), retention is a few hundred bytes per call after the fix, and the baseline's oversubscribe hang is intermittent. - A burst gets its workers at once; the worker wake's cost after the move to std::condition_variable_any. - Concurrent saturating fan-outs: all of them finish 23-25 % sooner, and a single one's stretch at m=4 moves with load. - Allocation savings quoted from the inline points (-15 to -23 %) and the poll1ms background point (-22 %), with a note that spin-driven threaded points mostly count idle pump iterations.
- wait_for_threads() and ~app interrupt the workers in _poolWorkers, but a worker started by applyPoolKick could take and start a task before its creator had put it there. The interrupt then missed that task: wait() waited it out (up to 5 s), and in ~app the creator, seeing the stop, joined the worker with no interrupt and no time limit, or ~app gave up on the creator and freed the app while the worker still ran. - A new worker now waits at a gate (PoolWorkerGate, guarded by the pool mutex) until its creator has registered it, or has seen the stop; one that is not registered ends without taking a task, and its creator interrupts it and joins it with a 5 s bound, with interruption disabled. - A worker clears any interrupt sent before its first task, as it already did before each later one. - Tests, through a protected test seam that holds the creator between the worker's start and its registration: wait() interrupts the task such a worker took (before: missed, wait() took 4 s), and a stop in that window leaves the task unrun and the creator not held up (before: the worker ran the task).
- Once ~app has stopped the pool, a task submitted to it, or still in its
queue, was destroyed without running and without any signal. An async
call whose kernel was dropped stayed unsettled, its process parked, and
its host's count of calls in flight never went down, so shutdown()
waited for good; launch_pool_task never posted its one value, and
compute_async never called back.
- submitPooled returns false when it drops a task (it returned void), and
stopThreadPool destroys the queued tasks before it joins the workers.
- async_host: a threaded call's task holds a kernel_task that ends the
call exactly once: run_kernel when it runs, or, refused (submitPooled
false, a stopped lane) or destroyed unrun, RuntimeError "<name>: not
run: ...", its kernel freed and the host's count lowered. The task's
one capture fits std::function's buffer, so a call still allocates one
block for it.
- launch_pool_task posts on_error("not run: the app's background pool has
stopped") for a dropped task.
- compute_async gains an on_error overload that calls exactly one of
on_done and on_error, also for a throw and a dropped job; the old form
calls neither for a dropped job and releases both.
- Tests: a call made after the stop and one still queued at it raise
RuntimeError and leave the host; a pool task dropped either way resumes
its process with on_error's value; submitPooled reports a late submit
and frees the task; compute_async's on_error form for a throw, a late
submit and a queued drop.
…rruptible - STATE_EXEC_EXCEPTIONS.md 3.5: async kernels, compute_async and launch_pool_task use app::submitPooled (it said startThreadPooled); 3.6: a kernel its executor never runs ends its call with RuntimeError. - THREAD_POOL(_API).md: wait() and ~app interrupt a task a worker took a moment after it started; a dropped task is destroyed unrun, submitPooled returns false after the stop, and what a task captured can report it.
…able - The drop guards (async_host's kernel_task, launch_pool_task's pool_task_post, compute_async's compute_job) were shared objects that each task captured by shared_ptr. MSVC and libc++ keep that one capture in std::function's buffer, but libstdc++ keeps only a trivially copyable callable there, so on Linux each threaded async call, launch_pool_task and compute_async allocated two blocks (the guard and the std::function's copy of the lambda) where they used to allocate one. - Each guard is now the std::function's target itself, holding its state by value, with a flag that a move takes over: one heap block on every standard library, and no shared_ptr counts. Destroyed unrun, it ends the call, posts on_error's value or calls on_error, as before. std::function needs a copy constructor; no executor copies its task, and a copy takes the task over as a move does, so one object alone can end it. - async_host::submit no longer settles a refused call itself: the task, destroyed unrun inside the lane's submit() or submitPooled(), does. A lane refusal still raises "<name>: lane '<lane>' is stopped" (the task points at the lane's key in the host); a kernel still queued when the pool stops now says "<name>: not run: the app's background pool has stopped", as a late submit does (it said "not run: its executor stopped"). - Tests: a call to a stopped lane raises RuntimeError naming the lane and leaves the host; the queued-drop test checks the whole message.
…eir state - STATE_EXEC_EXCEPTIONS.md 3.6 grouped a kernel a stopped lane refuses with the pool's dropped kernels under "name: not run: ...". A lane refusal raises "name: lane 'lane' is stopped"; the pool's say "name: not run: the app's background pool has stopped". A lane runs every kernel it accepted before it stopped. - THREAD_POOL(_API).md: a task reports its drop from its own destructor; the in-tree ones hold that state by value, since a shared_ptr capture adds a heap block per task under libstdc++.
Conflicts in inc/cvc/core/app.h and src/cvc/core/app.cpp, between perf/async's background pool (anonymous tasks on persistent workers, keyed tasks on threads of their own) and two master changes: - #827 (fb3fccc) made a wait=false pooled job run under a reserved unique key and had finishing pooled workers reap finished ones (reserveThreadKey, retirePooledThread, reapFinishedPooledThreads, finished_pooled_thread, reap_when_done), closed the pool in ~app (_poolClosed) and swept the thread map again for threads started while ~app was joining. - #825 (4cd69ad) null-checks threads(key) in startThreadPooled and holds interruption off in thread_info, thread_feedback and hdf5_utils::library_lock so an interrupt stays pending. Resolution, keeping perf/async's pool design: - The reap machinery and key reservation are dropped: an anonymous task has no key and never enters threads(), and its worker destroys it as soon as it ends, so there is nothing to reserve or reap. _poolClosed is perf/async's _poolStopping, set by stopThreadPool(). - ~app: stopThreadPool() (no queued task starts, later submissions are dropped, running tasks interrupted, workers joined), then master's bounded re-sweep of the thread map, which still catches a keyed pool thread that registers its successor after the first snapshot. - uniqueThreadKey keeps master's single-lock search, without the reserved-key set. - A keyed task is destroyed with interruption held off, as master's pooled worker did and perf/async's anonymous workers do. - The threads(key) null check and the disable_interruption bookkeeping (thread_info, thread_feedback, library_lock) and hdf5_io's per-call app come over as master has them. - Docs and comments (app.h, THREAD_POOL.md, THREAD_POOL_API.md, tf/overlay_tasks) describe the merged behaviour. Master's app_test tests that pin the reap mechanism are adapted in the next commit.
…n anonymous tasks #827's four tests pinned the reap mechanism (a wait=false job's reserved key, its thread-map entry, a later worker reaping it). On perf/async a wait=false job or compute_async call is an anonymous pool task with no key and no entry, so each test now checks the same user-visible guarantee directly: - ComputeAsyncReapsFinishedWorkerThreads -> ComputeAsyncCallsDoNotGrowTheThreadMap: threads() stays at its starting size right after every one of 60 on_done calls (it allowed 4 stragglers once reaping caught up), and once the pool is idle every call's fn/on_done captures are released. - QueuedComputeAsyncCallsKeepDistinctKeysAndAreReaped -> QueuedComputeAsyncCallsEachRunOnceUninterrupted: 100 calls queued behind a pool of 2 still each run on_done exactly once, none interrupted; threads() does not grow while they queue or after, and no finished call holds its captures. - ReapingLeavesARunningPooledThreadListed -> ComputeAsyncChurnLeavesRunningPooledJobsAlone: with 20 compute_async calls going through, a long wait=false job is not listed, keeps its captures while it runs, is never interrupted and releases them once it ends; a long keyed (wait=true) job, the listed kind, keeps its entry, stays joinable, reports "Processing: <key>", and keeps its entry once it has ended. - DestroyingAnAppWithComputeAsyncInFlightIsClean: same body, comments for the persistent workers, and every job ~app ran or dropped has released its captures when ~app returns.
…keep interrupts pending Review of the master merge into perf/async found three behaviours the merged pool got wrong. compute_async no longer reported a thread it couldn't start. On master it threw when creating a job's thread failed, and a threaded tf overlay task caught that and carried on cooperatively (#827). On perf/async a failed worker creation was swallowed and the job left queued, so with no worker running the overlay process parked on a chunk nothing would run until an unrelated submission started a worker. Now enqueuePoolTask can hand an anonymous task back when the worker its call asked for could not be created and the pool has none, running or starting; compute_async then throws boost::thread_resource_error, having released fn and on_done (and on_error) uncalled, and nothing is left queued. With a worker running, the job still just waits for it. A submitPooled task keeps waiting in the queue (its drop message names a stopped pool). The overlay_tasks comments say so again, and _poolWorkerSpawnHook is a test seam that makes worker creation fail. ~app joined the pool's workers before it interrupted the threads in threads(). A pool task waiting, with no interruption point, on something a keyed or startThread thread held got no help from it for the 5 s join and then outlived the app. stopThreadPool() is split into closeThreadPool() (close, interrupt, drop the queue) and joinPoolWorkers(); ~app interrupts the first sweep of the thread map between the two, as master interrupted everything before joining anything. Some waits and drops swallowed an interrupt, the pattern #825 removed from thread_info, thread_feedback and library_lock: wait_for_threads' joins and pool wait, the destructors of dropped tasks (compute_job's on_error, pool_task_post's on_error and post, kernel_task's drop), the pool's destruction of a refused or queued task, the joins in stopThreadPool and ~app. Each now holds interruption off, so an interrupt sent to the thread doing it stays pending. app.h, THREAD_POOL.md and THREAD_POOL_API.md describe all three; the overlay_tasks.h paragraph is reflowed, and its threaded mode is on the background pool, not the compute pool. Tests (app_test): AppPoolSpawnFailure.ComputeAsyncThrowsWhenNoWorkerCanBeStarted, AppPoolSpawnFailure.ComputeAsyncQueuesTheJobWhenAWorkerIsRunning, AppPoolTeardown.DestroyingTheAppInterruptsTheThreadMapBeforeJoiningThePool, AppPoolTeardown.WaitKeepsAnInterruptSentToItsCallerPending, AppPoolTeardown.DroppingATaskKeepsAnInterruptPendingOnTheDroppingThread; (tf_overlay_tasks_test) TfOverlayTasksNoThreads.ThreadedTaskCarriesOnCooperativelyWhenNoWorkerCanStart.
- state_exec_bench: --bg-oversubscribe's rationale and skip message described tasks sharing a thread key, which no current build does; the skip now keeps runs comparable with builds before the persistent-worker pool, as docs/STATE_EXEC_BENCH.md says. - THREAD_POOL_API.md's batch example used a thread_feedback with no app (it doesn't compile) and keyed feedback in an anonymous task; it now counts finished batches itself. - tf_binding.h: overlay chunks run on the app's background pool, not the compute pool.
5acc14d moved the pool-worker join into sweep 0, after its snapshot of the thread map, but still broke out of the loop on that snapshot being empty. A thread a worker registers while ~app joins it (a keyed task the worker took just before the pool closed, or a thread a pool task starts once it is interrupted) was then never interrupted or joined, and ran on into the freed app. Sweep 0 now goes on to the next sweep whenever it joined workers, even with an empty snapshot. Test: AppPoolTeardown.AThreadRegisteredWhileTheAppJoinsThePoolIsJoinedToo.
compute_async threw only when its own worker creation failed and the pool's thread count was zero at that moment. Another call's creation still under way counted as a worker on its way, so when that one failed too, after the look, the job stayed queued with no worker running or starting and its caller was never told. A call that made no creation of its own (a pool of 1, another call's creation already under way) never looked at all. The pool now counts the creations under way (_creatingWorkers: claimed by poolKickLocked, until registered or given up). A call whose task, at its kick, had no running worker and only creations under way waits (bounded) for those to succeed or fail, then hands the task back if the pool has no worker (poolHasNoWorkerLocked). With a worker running, nothing changes and nothing waits. Test: AppPoolSpawnFailure.ComputeAsyncThrowsWhenTheWorkerItReliedOnFailsLater (both cases: a creation of its own that fails first, and none of its own).
…r can start 5acc14d brought back master's throw for compute_async only. The other two background-pool users, the exec async host (state_exec async functions) and launch_pool_task, still queued their task when no worker could be started and the pool had none. The calling process stayed parked, and ~app never returned: it first waits, with no bound, in async_host::shutdown() for a kernel no worker would run, and only the later closeThreadPool() would have dropped it. - app::trySubmitPooled (PoolSubmit is now public): submitPooled, but a task no worker can be started for is handed back unrun (no_worker). compute_async now goes through it. - async_host::submit drops a handed-back kernel with RuntimeError "<fn>: not run: no background worker could be started", ending the call. - launch_pool_task posts on_error("not run: no background worker could be started") for a handed-back task. - ~app closes a pool that has no worker (none could be created) before the async host's shutdown, so a kernel queued behind keyed threads whose end-of-task kick then failed is dropped instead of waited for. Docs: app.h, async_task.h, THREAD_POOL.md, STATE_EXEC_EXCEPTIONS.md. Tests (state_exec_async_calls_test): AsyncCalls.ACallNoWorkerCanBeStartedForRaisesAndLeavesTheHost, AsyncCalls.APoolTaskNoWorkerCanBeStartedForPostsOnErrorsValue, AsyncCalls.DestroyingTheAppEndsACallQueuedOnAPoolWithNoWorker.
… be created On base, a keyed task whose thread couldn't be created made startThreadPooled throw boost::thread_resource_error. Since the persistent-worker pool, startKeyedPoolThread dropped the task silently and startThreadPooled returned as if the task were registered under its key, so `if (hasThread(k)) threads(k)->join();` went on at once (or found the old, already-joined thread) and the caller read results that were never computed. A keyed task started later from the queue was dropped without a word as well. startKeyedPoolThread now reports the failure. enqueuePoolTask throws boost::thread_resource_error when it is the caller's own keyed task; a keyed task started for another submission, by a worker, or by the previous keyed thread's tail is logged as dropped. Keyed-thread creation goes through the _poolWorkerSpawnHook test seam too. Docs: app.h (wait=true), THREAD_POOL.md, THREAD_POOL_API.md. Test: AppPoolSpawnFailure.AKeyedTaskWhoseThreadCantBeCreatedThrowsOrIsLogged.
5acc14d held interruption off for ~app's body only. An interrupt pending on the thread destroying the app then outlived the body and was thrown at the first interruption point in a member destructor (the state tree in _data joining a handler thread, a user object in the data or in a slot that joins one), out of a noexcept destructor: std::terminate. Before that commit, the first interruptible join in the body happened to absorb it whenever ~app had something to join. The hold is now a member, _teardownHold (a std::optional of disable_interruption), declared before every other member so that it is destroyed after all of them, and engaged first thing in ~app. The interrupt is still pending for the caller once the app is gone. Test: AppPoolTeardown.AnInterruptPendingOnTheThreadDestroyingTheAppOutlivesIt.
…errupt The split of stopThreadPool into closeThreadPool and joinPoolWorkers left two comments naming stopThreadPool as where ~app sets _poolStopping and destroys the queue. THREAD_POOL.md said wait() "isn't interruptible itself", but an interrupt already pending when it is called is thrown at its first line (threads() is an interruption point); only one sent once it has begun stays pending. Say so there and in app.h.
Its hooks counted 1 ms sleeps, which take a timer tick (~15 ms) each on Windows, so its two 300 ms windows took 4.7 s apiece. Wait on a steady_clock deadline instead: the test now takes about 0.6 s.
When a keyed task that waited in the queue couldn't get a thread of its own as its turn came, startKeyedPoolThread freed its slot (counting it out of _activeWorkers and signalling an idle pool), ran the pool's kick, and only then logged the drop. Anyone who saw the pool idle in that gap, wait() or a poll of the counts, could read the log before the line was in it: AppPoolSpawnFailure.AKeyedTaskWhoseThreadCantBeCreatedThrowsOrIsLogged failed about 1 run in 100 on this box (1/100 with the AppPoolSpawnFailure and AppPoolTeardown filter, 3/60 and 4/40 in earlier runs). The drop is now logged first, still outside _threadPoolMutex and with interruption held off, and the slot freed after it, so an idle pool implies the drop is logged. The test now also records, from a dataChanged slot on its log key, what the pool's counts were while log() ran. On the old order they were 0 every time (logged after the slot was freed), so it fails deterministically instead of 1 run in 100. Test: AppPoolSpawnFailure.AKeyedTaskWhoseThreadCantBeCreatedThrowsOrIsLogged.
… worker ed4d3df made trySubmitPooled hand a task back when the worker creations it relied on failed, but only for creations under way while it was submitting. A task can also be queued with no worker running or being created: keyed tasks, on threads of their own, hold every slot of a pool that has never started a worker, so the submission asks for no worker. When the last of them ended, its tail kick asked for one, and if that creation failed, applyPoolKick's rollback only adjusted the counts. The task stayed queued with nothing to run it until a later submission or ~app: an async call's process stayed parked, launch_pool_task never posted, compute_async never called on_done or on_error, and a host bound to the app that shuts down before ~app (a pycvc Exec's) waited in shutdown() for its kernel. ~app's early close only covered the app's own exec host. Tasks queued through trySubmitPooled are now marked (ThreadPoolTask:: handBack, which fits in the struct's padding). Wherever a failed creation leaves the pool with no worker, running or being created, and the pool is not stopping (applyPoolKick's rollback, and a worker that couldn't be recorded), takeUnstartableLocked takes the marked tasks out of the queue and dropPoolTasks destroys them unrun once the mutex is released, on the thread whose creation failed. A trySubmitPooled call still waiting for the creations its own task relies on is counted in _handBackChecks; while one is, nothing else drops marked tasks, so it still takes its own task back and returns no_worker (compute_async throws, as before), and it drops the rest when it is done. submitPooled tasks stay queued, as documented. The drop reason reaches the guards in other translation units (async_host's kernel_task, async_task's pool_task_post, compute_job) through app::poolDropReason(), a thread-local that the pool sets with a scope while it destroys tasks unrun: kPoolNoWorker for these drops, kPoolStopped for ~app's and for a submission refused once the pool has stopped (also the answer where no drop is under way, so a guard destroyed any other way says what it said before). The guards read it in their destructors before calling out. A field or hook on the task record would not reach them: the pool holds only a std::function, a callable's address inside it is not stable across the moves and swaps the queue does, and a second callable per task would cost an allocation on every submission. The thread-local costs the normal path nothing; the only additions there are one bool store per queued task, and a counter update on the path that already waits for creations. startKeyedPoolThread's failure handling moved out of its catch block, since the kick there may now drop tasks whose destructors call out. Docs: app.h (trySubmitPooled, poolDropReason, compute_async), async_task.h (launch_pool_task). Tests: AppPoolSpawnFailure.ComputeAsyncJobsLeftWithNoWorkerAreDroppedAndReported, AsyncCalls.ACallLeftQueuedOnAPoolWithNoWorkerRaisesAndLeavesTheHost, AsyncCalls.APoolTaskLeftQueuedOnAPoolWithNoWorkerPostsOnErrorsValue. AsyncCalls.DestroyingTheAppEndsACallQueuedOnAPoolWithNoWorker asserted the old state (the kernel still queued after the failed creation); it now covers ~app's early close with the keyed thread still running when ~app begins, the case that close is still for.
…drops compute_async's doc still said it never blocks the caller, and launch_pool_task's that it returns immediately, but since f425247 a trySubmitPooled submission made while the pool has no worker running yet, only creations under way, waits in poolHasNoWorkerLocked (up to 5 s) for them to succeed or fail; trySubmitPooled's own doc didn't say so either. That covers compute_async, an async call on the exec scheduler's thread and launch_pool_task. Say so in app.h, async_task.h, THREAD_POOL.md and STATE_EXEC_EXCEPTIONS.md 3.6. THREAD_POOL_API.md's Shutdown item said ~app closes the pool first "after only the async host". It now says that ~app shuts down its own exec host first while the pool stays open, and closes the pool before that instead when the pool has no worker; that it sweeps the thread map again after joining the pool's workers, even when the first sweep found it empty; and that ~app holds interruption off until its last member is destroyed. A new item covers thread creation failures (the hand-back, its wait, and the later no-worker drop), and the Notes list trySubmitPooled with PoolSubmit, and poolDropReason. The no-worker drop of the previous commit is in THREAD_POOL.md and STATE_EXEC_EXCEPTIONS.md 3.6 as well, and a keyed task's drop being logged before its slot is freed in THREAD_POOL.md and THREAD_POOL_API.md.
…is left c81166c dropped every task queued through trySubmitPooled once a failed worker creation left the pool with no worker running or being created. compute_async's four-argument form submits through it too, but its job has no on_error, so the drop called nothing and its caller was never told. The threaded tf overlay task is such a caller: its chunk's on_done posts the reply the task's process waits on. When a keyed thread held the only slot of a pool with no worker and the worker asked for as it ended couldn't be created, the chunk was dropped and the task waited for good, even after a later submission started a worker. Before c81166c the chunk stayed queued and ran then. trySubmitPooled's body is now submitPooledHandingBack(task, priority, dropIfNoWorker), and the task flag ThreadPoolTask::handBack is renamed dropIfNoWorker, since it now says only whether a queued task is dropped, not whether the call hands it back. compute_async sets it only when on_error is set. A four-argument job is still handed back, and compute_async still throws, when no worker can be started for it while it is submitted; once queued, it waits for a later submission to start a worker, as a submitPooled task does. The on_error form is unchanged. Test: AppPoolSpawnFailure.ComputeAsyncJobsLeftWithNoWorkerAreDroppedOrWaitForOne, which replaces ...AreDroppedAndReported (that test asserted the silent drop). On the unfixed build it fails: the four-argument job's captures were released, one task was pending instead of two, and the job never ran once a worker started.
…h no worker A threaded overlay task launches each chunk with compute_async and parks on the reply that the chunk's on_done posts. Suppose the pool is left with no worker after the chunk is queued: a keyed thread held the only slot of a pool with none, and the worker asked for as it ended couldn't be created. With the four-argument form the chunk then waits in the queue until a later submission starts a worker (as before c81166c, and again since the previous commit), or, under c81166c, it was dropped without a reply. Either way the task stopped advancing, though overlay_tasks.h says a task carries on cooperatively when no thread can be started. launch_chunk now uses compute_async's on_error form. When the pool drops the chunk with app::kPoolNoWorker, on_error marks the chunk's reply no_worker and posts #f to it, unless the task has let go of the chunk. The next (tf-overlay-step) sees the mark and switches the task to cooperative slices, as it does when compute_async throws. A chunk dropped as ~app stops the pool, or interrupted, still posts nothing, as the four-argument form's did. Test: TfOverlayTasksNoThreads.AThreadedTaskWhoseChunkIsLeftWithNoWorkerCarriesOnCooperatively, which holds the slot with a keyed task, queues a chunk behind it, fails the worker creation as the keyed task ends, and waits for the task with no later submission. It fails both on the build before this series (wait_overlays timed out: the chunk was dropped without a reply) and with the previous commit alone (timed out with the chunk still queued); its rescue then starts a worker so the test ends.
…bout its own task A trySubmitPooled call that finds a keyed task at the head of the queue, with the slot free, starts that task on the calling thread. That state arises once the pool drops anonymous tasks queued ahead of keyed ones for want of a worker (c81166c), or when a worker creation fails after a queued keyed task's own start failed. If the keyed task's thread then couldn't be created, nor the worker asked for as it freed its slot, that failed creation dropped the call's own task inside the call: _handBackChecks counted only calls relying on creations already under way, and this one relied on none. compute_async returned as though its job were queued. The on_error form's on_error ran inside the call instead of the documented boost::thread_resource_error, and the four-argument form's job was lost without a word (since the previous commit, it is left queued instead, still without the throw). Such a call is now counted in _handBackChecks too while it starts the keyed task. When a failed creation leaves the pool with no worker while a check is pending, takeUnstartableLocked sets _poolDropOwed rather than only returning. Having started the keyed task, the call hands its own task back if a drop is owed and the pool still has no worker running or being created; and the last deciding call to finish does the owed drop of the other dropIfNoWorker tasks (a call relying on creations decides as before, and does that drop too). A keyed thread that started leaves the call's task queued behind it, as any task queued behind a keyed thread holding the slot is. Only a call that starts a keyed task while no worker is running is counted, so a submission with a worker running takes no second lock and pays only a branch. Test: AppPoolSpawnFailure.ComputeAsyncThrowsWhenAQueuedKeyedTaskItStartsLeavesNoWorker (the reviewer's scenario: a job dropped ahead of two keyed tasks, then one call in each form, each starting a keyed task whose thread can't be created). On the unfixed build neither call threw, and the on_error form's job got "not run: no background worker could be started" inside its own call.
…mitPooled call While a trySubmitPooled call waits on a worker creation that its own task relies on, a failed creation that leaves the pool with no worker doesn't drop anything itself: it leaves the drop to that call (_poolDropOwed), which hands its own task back first. Nothing tested that half. Removing the call's takeUnstartableLocked left every test passing, though a job queued earlier then waited for a worker nothing would start. AppPoolSpawnFailure.AJobLeftWithNoWorkerWhileACallWaitsOnTheCreationIsDroppedByThatCall queues job A behind a keyed task holding the only slot, holds the creation asked for as the keyed task ends until call B waits on it (probe_app::handBackChecks, new), and then fails it. A's on_error gets "not run: no background worker could be started" on B's thread, B's compute_async throws, and nothing is left queued. With the call's drop removed, A is never reported and the test fails; its rescue then starts a worker so that it ends.
The docs for c81166c's no-worker drop said a queued trySubmitPooled task is dropped when the worker asked for as the LAST keyed thread ends can't be created, on the thread whose creation failed. The code drops it once any worker creation fails and leaves the pool with no worker running or being created, also while other keyed threads still hold their slots. Waiting for the last of them would leave the task stuck behind a long-lived keyed thread, the state c81166c set out to end, so the docs now give the code's rule. The drop does not always run on the thread whose creation failed. When a trySubmitPooled call is still deciding about its own task (waiting on that creation, or, since the commit before last, starting a keyed task queued ahead of it), the failed creation leaves the drop to that call. It runs there before the call returns, so another submitter's report of the drop (an async call's RuntimeError, launch_pool_task's post, compute_async's on_error) can run inside a compute_async call, an async call made on the scheduler's thread or launch_pool_task. The docs say so, and they cover the two changes earlier in this series: compute_async's form without on_error has its job wait for a worker rather than be dropped, and a call that starts a queued keyed task hands its own task back when that leaves the pool with no worker. Updated: app.h (trySubmitPooled, compute_async's on_error form), async_task.h (launch_pool_task), THREAD_POOL.md (thread creation failures), THREAD_POOL_API.md (item 6, trySubmitPooled in Notes), STATE_EXEC_EXCEPTIONS.md 3.6, the change history in app.cpp, and the comments in the drop guards (compute_job, pool_task_post, kernel_task) and in one state_exec_async_calls_test comment.
… raised A trySubmitPooled call that decides what becomes of its own task raises _handBackChecks before it kicks the pool and starts a keyed task, and lowers it only once it has decided. If applyPoolKick or startKeyedPoolThread threw in between (out of memory making a thread's state), the count stayed raised, and no failed worker creation would drop a task for want of a worker again for that app. The call now lowers it on the way out. Also corrects compute_async's comment, which still said its caller returns immediately: while the pool has no worker yet, it waits for the worker creations under way, as app.h says.
transfix
marked this pull request as ready for review
October 27, 2026 23:32
The required clang-format (changed lines) check runs only on PRs against master, so it first ran when this PR was retargeted from #834's branch. Formatting only.
Brings in #842 (the scheduler track), squash-merged as 72e4c60. The only conflict is docs/STATE_EXEC_BENCH.md, where both tracks edited the same paragraphs; the resolution keeps both tracks' edits. It is the one made when the three tracks were merged together and tested (perf/all), with perf/eval's edits taken out: perf/eval isn't on master yet. Every other file's change against master is the same as before the merge.
Owner
Author
Final A/B results (all three tracks)This is the A/B the description said would be posted here. It ran on 2026-10-27 against a7b966f, with Release builds of the state_exec benchmark on the same Windows machine as before.
Some absolute times for all three tracks together (phase 1, median wall time):
The combined build regresses nowhere:
Notes on single tracks:
|
transfix
added a commit
that referenced
this pull request
Oct 28, 2026
…er steps AsyncCalls.StepCostSetsTheDefaultRate has failed on optimized builds since #843 (072ab18). It requires kDefaultAsyncStepsPerCpuMs to stay within a factor of four of what a scheduler step costs. #843 made steps 2.5 to 4 times cheaper, and the default stayed at P3's 2000: - package-macos / libcvc-release-grpc (run 40616573869): 8,253 to 10,711 steps per CPU ms; failed 3/3, 2000 against lowest / 4 = 2063 to 2369. - package-windows / libcvc-release and -release-grpc: 8,387 to 9,340; failed once, then passed on a retry. - Locally (MSVC 14.44 Release, a loaded 22-thread box): 4,962 to 9,566. The default is now 5000, about the slowest of these. That is within a factor of four of every measurement, with room both ways. An async call's CPU time is now charged 2.5 times the steps it was, which is what that CPU buys in DSL steps since #843. Ariadne's default 5000-step action cap is now 1 ms of a kernel's CPU, not 2.5 ms. The async-calls tests whose bounds assumed 2000 (AS-18/26, AS-21 and AS-27, and the Python AS-21) now state them in terms of kDefaultAsyncStepsPerCpuMs. The docs give the new default and its measurements.
transfix
added a commit
that referenced
this pull request
Oct 28, 2026
The project version and the cvcpkg recipe family move to 3.7.2. Every recipe is at cvc_revision 1 already, so none restarts. 3.7.2 carries the dynamic plants on the terrain and in a Jolt world, and the four-wheel plant (#869): --plant dynamic and dynamic4w drive the ground, collide with the buildings and each other, and book the collisions. It also carries dyn_4w's port-Hamiltonian form (#850), dyn_bike's wheel-frame front slip (#852), the books goldens for GRL-SNAM's twins (#848, #849), pycvc's drive telemetry (#857) and keep-alives (#864), the macOS SDK's openssl (#846), and the state_exec scheduler and evaluator work (#842, #843, #844, #861, #863).
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.
Based on feat/state-exec-bench (#834). This PR touches the background task pool (
cvc::app),async_host/async_call, and the compute pool (cvc::thread_pool), plus their tests and docs. It does not change the evaluators or the schedulers.What changed
Background pool (
app::startThreadPooled/ newapp::submitPooled)wait=false,submitPooled) run on at mostgetThreadPoolSize()persistent workers. The queue is FIFO within a priority. A task has no thread key and nothreads()entry, and it is destroyed on its worker before it counts as done, so a finished task keeps nothing alive.std::condition_variable_any. Workers are signalled and created after the pool mutex is released, with no extra lock round trip.wait=true) keep their contract: each gets its own thread under its key, and the entry stays after the task ends. When the pool has room for the task and for everything already queued, it starts on the caller and is inthreads()beforestartThreadPooledreturns, soif (hasThread(k)) threads(k)->join();works.tryStartWorkerunlocked_threadPoolMutexby hand aroundthreads(key, ...). Its interruption points threw in a worker that another worker had just interrupted, and the caller'sscoped_lockthen unlocked the mutex a second time. On Windows that leavesboost::mutexlocked with no owner. The pool now gives anonymous tasks no keys, releases its mutex only through RAII, and runs its bookkeeping with interruption disabled.wait_for_threads()and~appinterrupt workers only while holding the pool mutex, with a generation count. A new worker waits at a gate until its creator has registered it in the worker list those interrupts go to. Any task a worker has taken, its first task included, is therefore interrupted however recently it was taken. Before this, a worker could take a task before it was registered, and the interrupt missed that task. A worker that the stop leaves unregistered ends without taking a task. Its creator interrupts it and joins it with a 5 s bound (this was an untimed join).~appdrops the queued tasks, destroying them unrun before it joins the workers. A task submitted after that point is dropped too, andsubmitPooledreturns false. A dropped task is reported, not silent. An async call whose kernel was dropped raisesRuntimeError(<name>: not run: the app's background pool has stopped, for a late submit and a queued drop alike) and leaves the host's in-flight count, so its process isn't left parked andasync_host::shutdown()doesn't hang.launch_pool_taskpostson_error's value. A newcompute_asyncoverload withon_errorreports a drop or a throw. The 4-argument form still calls neither callback for a dropped job and releases both.wait()is not a completion barrier: it interrupts running tasks and gives up after 5 s. The docs now say so.async_host
post().run_kernelsettles the call and posts its completion when the kernel ends, then frees the kernel on its own thread. Freeing captures no longer counts against the call's timeout.kernel_taskheld by value as thestd::function's target. It ends the call exactly once: either the kernel runs, or the executor destroys the task unrun. The executor does that when it refuses the task (a stopped pool, or a stopped lane, which raises<name>: lane '<lane>' is stoppedas before) and when the pool drops its queue at~app.launch_pool_task's andcompute_async's tasks are built the same way.shared_ptrcapture would have cost a second block per call under libstdc++, which keeps only a trivially copyable callable instd::function's buffer.computePool (
thread_pool::parallel_for)chunk_contextis unchanged.After merging master (#825, #827)
wait=falsejobs has nothing left to do under anonymous tasks, so it was dropped. Its four tests now assert the same guarantees on anonymous tasks:threads()doesn't grow, concurrent calls don't cancel each other, and a finished job's captures are released.compute_asynckeeps feat(ariadne): tf_editor, the ColorTable2 transfer-function widget, with contour tree/spectrum overlays #827's fallback: it throwsboost::thread_resource_errorwhen no worker can be started, so a threaded tf overlay task drops to cooperative mode. While the pool has no worker yet, a submission waits, at most 5 s, for the worker creations already under way before it decides.launch_pool_taskgo through a newapp::trySubmitPooled. When no worker can start, they fail at once instead of waiting forever:<fn>: not run: no background worker could be started. A task they queued that is later left with no worker running or being created is dropped with that message. So is acompute_asyncjob withon_error; one withouton_errorstays queued until a later submission starts a worker. A threaded tf overlay task whose chunk is left with no worker carries on cooperatively.startThreadPooled(wait=true)throwsboost::thread_resource_erroragain when its keyed task's thread can't be created, as the base did. A keyed task dropped on a deferred path is logged before its slot is freed.~appinterrupts everything before it joins anything. It sweepsthreads()again after joining the pool's workers: a thread a worker registered meanwhile was missed and, in a reproducer, crashed. It closes the pool before the async host's shutdown when the pool has no worker, so the shutdown can't hang. It holds interruption off until its last member is destroyed, so a pending interrupt can't throw inside a member destructor.cvc::app's layout changed (new members), so code built against the oldapp.hmust be rebuilt.Docs
submitPooled(F3). 3.6 describes dropped kernels and gives each cause its message:not run: the app's background pool has stoppedfor the pool,lane '<lane>' is stoppedfor a lane.A/B against the frozen baseline (a7b966f), pinned CPU 12, interleaved, on a loaded machine
--bg-oversubscribeDriver profile, async.pool_aging k=5000 bg: the worker wake is about 4% of samples (it was about 17% with
boost::condition_variable's per-wait semaphore).async_host::callis about 7% inclusive, down from about 19%.Not regressions:
Regression set: no point the track touches moved beyond noise, and the outliers do not reproduce.
These numbers come from a heavily loaded machine. Re-run eval.* on a quiet machine after the three tracks merge.
Tests
Every state_exec_*_test binary, ariadne_runtime_test, ariadne_host_test, app_test, async_lane_test and thread_pool_test pass. app_test has 116 tests, state_exec_async_calls_test has 46 and tf_overlay_tasks_test has 15. The pool-failure and teardown tests (
AppPoolSpawnFailure.*:AppPoolTeardown.*) passed 200 repeats, as did the no-worker async-call tests. All 13 pycvc pytest files pass. geometry_test SDFV2ParallelExecution (keyed pool join pattern) and the volren concurrent-render test pass.New tests:
AppTest.ThreadPoolFloodPastPoolSizeCompletes(1000 tasks on 4 workers; hung on the old code).AppPoolTeardown.AnInterruptRightAfterAWorkerStartsReachesItsTaskandAppPoolTeardown.AWorkerStartedAsThePoolStopsTakesNoTask. Both use the seam, and both failed with the gate disabled.AppPoolTeardown.ATaskSubmittedOnceThePoolHasStoppedIsDroppedAndReportedandAppPoolTeardown.ComputeAsyncReportsAThrowOrADroppedJobToOnError.AsyncCalls.ACallMadeOnceTheAppsPoolHasStoppedRaisesAndLeavesTheHost,AsyncCalls.ACallStillQueuedWhenTheAppsPoolStopsRaisesAndLeavesTheHostandAsyncCalls.APoolTaskTheAppDropsStillPostsOnErrorsValue. All three failed with the drop guards disabled.AsyncCalls.ACallToAStoppedLaneRaisesAndLeavesTheHost.Risks
threads(),threadKey()orthreadsChanged. I audited the whole tree (async_host, compute_async, async_task, cvcGL, state_object/ariadne, tests, bench) and nothing relies on that.cvc::appchanged. The public API is additive only. It addssubmitPooled, which returns bool (false only when the stopped pool drops the task), and acompute_async(n, fn, on_done, on_error, priority)overload. It also adds protected and member fields:PoolWorkerGateandpoolWorkerLoop(gate),_poolWorkerAdmitted, and a test seam_poolWorkerCreatedHook(astd::function, empty in the library, called between a new worker's start and its registration).enqueuePoolTasknow returns bool, andasync_hosthas a private nestedkernel_task. No subclass ofappexists outside the tests: app_test'sprobe_appuses the seam,stopThreadPooland_poolInterruptGen, and state_exec_async_calls_test'sstoppable_appusesstopThreadPool. pycvc does not wrap these members, and it builds and passes.