Repository navigation
fix(volume): run HDF5 work on the caller's app and stop swallowing interrupts - #825
Merged
Merged
Conversation
…terrupts volume_io_test segfaulted intermittently when the whole binary ran as one process, in a test after CvcRawRoundTrip. It took two lifetime bugs: - hdf5_io kept the app that registered it and worked through that app instead of the one each call passes. Every cvc::app registers another hdf5_io into the process-wide handler map, and the first one registered serves every later call. So once the process's first app was destroyed, every HDF5 call ran through freed memory, and writeVolumeFile started its build_hierarchy thread on that dead app, where the writing app's ~app never saw it. hdf5_io now keeps no app; the maxdim default its constructor set moves to register_hdf5_io. - thread_info, thread_feedback and hdf5_utils::library_lock call app methods that are interruption points inside catch-alls. An interrupt that arrived there was thrown and swallowed, and boost clears the request when it throws, so the thread kept running. ~app gave up joining the hierarchy thread after 5 s and freed the app under it. They now hold interruption off (disable_interruption) while they keep their books, so the request stays pending for the thread's next interruption point. New tests, each failing without its fix: - Hdf5VolumeTest.HierarchyThreadRunsOnTheCallersApp - Hdf5VolumeTest.LibraryLockKeepsAnInterruptPending - AppTest.ThreadBookkeepingKeepsAnInterruptPending hdf5_volume_test's comment on its shared app described the first bug as the reason for sharing; it now says the sharing is no longer needed.
…sphere Master fails LbieMesherTest.AdapterKeepsLbiesHexahedronCorners on every platform: mean scaled Jacobian 0.49893 < 0.5. #802 added the test and #808 merged 13 minutes later from a branch that never had it, so neither PR's CI ran the two together. The mesh is fine; the threshold was set on the wrong mesh. The test's sphere (17^3 samples over [-1,1]^3, voxels 0.125 across) meshes as 27 hexahedra, a 3x3x3 block with 64 vertices, before and after #808. Measured: - #802's LBIE: the block was a cube inside the sphere. Its 56 outer vertices were 0.31-0.50 from the centre (radius 0.5), every hexahedron ~1.0, mean 0.9996. - #808's LBIE: the 56 outer vertices are on the sphere (0.491-0.513). The edge and corner hexahedra become wedges: mean 0.499, worst 0.218, none inverted. - The pre-#802 twisted adapter on today's mesh: every hexahedron inside out, mean -0.78. So the check that matters is that no hexahedron is inverted. The test now requires every hexahedron to be right-handed (it allowed a tenth to be inverted) and a mean above 0.4 instead of 0.5. The twisted layout still fails both by far.
transfix
enabled auto-merge (squash)
October 27, 2026 00:22
transfix
added a commit
that referenced
this pull request
Oct 27, 2026
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.
transfix
added a commit
that referenced
this pull request
Oct 27, 2026
…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.
transfix
added a commit
that referenced
this pull request
Oct 28, 2026
…ncurrent compute fan-outs (#843) * state_exec_bench: a benchmark suite for the evaluators, the schedulers 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. * state_exec_bench: an in-process sampling profiler (--sample, Windows 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. * thread_pool: run concurrent fan-outs side by side, wake only enlisted 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. * app: persistent background-pool workers; fix the stall and hang past 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. * async_host: less per-call work; kernels on the pool's persistent workers 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. * app: don't start a pool worker per task in a burst 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). * app: start pool workers outside the pool mutex 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. * async_host: a call leaves the host's cancel list when its kernel ends 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). * docs: the background pool, async host and compute pool pathologies after 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. * app: a keyed task with room registers before it returns; a burst gets 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. * async_host: settle a call before freeing its kernel; build the progress 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. * docs: wait() is not a barrier; fan-outs share a pool's workers; keyed 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. * docs: the async-track bench numbers from the final A/B - 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. * app: a new pool worker takes no task before it is registered - 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). * app, async_host: a task the stopped pool drops reports it - 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. * docs: dropped pool tasks report it; a new worker's first task is interruptible - 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. * app, async_host, async_task: a pool task's drop guard is its own callable - 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. * docs: a dropped kernel's message names its cause; drop guards hold their 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++. * app_test: master's compute_async reap tests assert their guarantees on 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. * app: keep #827's overlay fallback, interrupt before joining in ~app, 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. * docs: pool comments the merged background pool made stale - 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. * app: ~app sweeps threads() again after joining the pool's workers 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. * app: compute_async's hand-back waits for the worker creations under way 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). * app, async_host, async_task: fail an async call at once when no worker 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. * app: startThreadPooled(wait=true) throws when its task's thread can't 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. * app: ~app holds interruption off until its last member is destroyed 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. * docs: closeThreadPool in the pool comments; when wait() throws an interrupt 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. * app_test: bound the creation-reliance test's waits by the clock 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. * app: log a keyed task's drop before freeing its slot 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. * app, async_host, async_task: drop a trySubmitPooled task left with no 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. * docs: when a pool submission waits, ~app's shutdown order, no-worker 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. * app: keep a compute_async job without on_error queued when no worker 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. * tf: carry an overlay task on cooperatively when its chunk is left with 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. * app: a trySubmitPooled call that starts a queued keyed task decides about 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. * app_test: cover the drop a failed creation leaves to a waiting trySubmitPooled 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. * docs: when and where the pool drops a task left with no worker 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. * app: a deciding pool submission that throws leaves no hand-back check 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. * style: clang-format 18 on the lines this branch changes 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.
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.
Summary
volume_io_testsegfaulted intermittently when the whole binary ran as one process, in a test afterVolumeIOTest.CvcRawRoundTrip. CI runs each case in its own process, so it never showed there. The crash needed two lifetime bugs; this fixes both.1.
hdf5_ioworked through the app that registered ithdf5_iokept thecvc::app&it was constructed with and used it, not thectxeach method is passed.cvc::app()runsregisterDefaultHandlers(), which appends a newhdf5_ioto the process-widevolume_file_io::handlerMap().writeVolumeFilealso started itsbuild_hierarchythread on that dead app, so the writing app's~appnever saw the thread to join it.hdf5_volume_test.cppalready described this and worked around it with one leaked app for the whole binary.volume_io_testmakes a new app per test, so it hit the bug.Fix:
hdf5_iokeeps no app and uses each call'sctx. Its constructor used to set thevolmagick.hdf5_io.maxdimdefault; that moves toregister_hdf5_io, so every app still gets it. Most of the diff inhdf5_io.cppis the mechanical_ctx→ctxrename.2. Interrupts were swallowed, so
~appcouldn't stop the hierarchy threadapp::thread_info,app::thread_feedbackandhdf5_utils::library_lockcall app methods that are interruption points, insidecatch (...). Every HDF5 call takes alibrary_lock, and every read and write constructs athread_info.~appgave up joining it after 5 s (try_join_for) and freed the app under it.Fix #1 alone didn't close this. The new
HierarchyThreadRunsOnTheCallersApptest caught it: the thread kept computing through the 5 s join.Fix: those constructors and destructors hold interruption off (
boost::this_thread::disable_interruption) while they keep their books, so the request stays pending until the thread's next interruption point. The catch-alls stay for other exceptions.Tests
Each new test fails without its fix, every time:
Hdf5VolumeTest.HierarchyThreadRunsOnTheCallersApp: a write from an app other than the first one registered must start the hierarchy thread on that app, and its results must land there. Its~appmust join hierarchy work that is still running.own->hasThread(...)is false.joinable()check fails.AppTest.ThreadBookkeepingKeepsAnInterruptPending: interrupt a thread before it constructsthread_feedback/thread_info; its next interruption point must still throw. Without fix Move more trans-vr code to trans-cvc #2 it failed 50 of 50 repeats.Hdf5VolumeTest.LibraryLockKeepsAnInterruptPending: the same check forlibrary_lock. Failed 50 of 50 without fix Move more trans-vr code to trans-cvc #2.hdf5_volume_test's comment on its shared app gave bug #1 as the reason for sharing it. The comment now says the sharing is no longer needed for safety. The shared app itself is unchanged.Verification (Windows, MSVC 14.44 Release, cvcpkg prefix)
volume_io_test, one process per run:UnknownExtensionThrows, afterCvcRawRoundTrip;app_test(87),hdf5_volume_test(24),volume_io_extra_test(54).LbieMesherTest.AdapterKeepsLbiesHexahedronCorners: mean scaled Jacobian 0.49893, limit 0.5.Not changed (possible follow-ups)
cvc::appappends another copy of every volume and geometry handler to the global maps, so a read that fails tries every copy. In the unfixed log, one failed read insideCvcRawRoundTriptried 14hdf5_iocopies, each opening the file. That no longer affects lifetimes (the handlers are stateless now), but it costs time and gives huge error strings. Registering once, or dropping duplicates byid(), would fix it.CvcRawRoundTriptakes ~11–13 s with or without the fix, even run alone with one handler, and one hierarchy level takes ~9 s. Everyhdf5_utilscall reopens the file. This predates this PR; I haven't profiled it.~appstill waits at most 5 s per thread, then lets the thread go on running unjoined. With interrupts no longer lost, the hierarchy thread stops at its next interruption point, well inside that limit.