Skip to content

Support parallel worker shutdown with simple_one_for_one - #223

Closed
vkatsuba wants to merge 1 commit into
inaka:mainfrom
vkatsuba:issue-172
Closed

vkatsuba wants to merge 1 commit into
inaka:mainfrom
vkatsuba:issue-172

Conversation

@vkatsuba

Copy link
Copy Markdown
Contributor

Summary

Related issue: inaka/worker_pool#172.

Problem and resulting behavior

Workers supervised with the existing static strategies shut down sequentially. When several workers need time to clean up, each worker waits for the previous worker to finish before beginning its own cleanup, increasing the time needed to stop the pool.

This PR adds working support for explicitly selecting simple_one_for_one as the worker supervision strategy. OTP then shuts down those workers in parallel, allowing their cleanup callbacks to overlap. The supervisor still waits for shutdown to complete, subject to worker and ancestor shutdown deadlines; the public stop operation does not become fire-and-forget.

The pool retains its configured size. Using a dynamic OTP child template internally does not introduce a public API for resizing the pool.

Implementation

Worker specifications

wpool_process_sup:init/1 now selects between two forms of child specification:

  • For simple_one_for_one, it returns a single worker template whose start arguments are supplied when each worker is started.
  • For existing strategies, it returns the individual named worker specifications used previously.

The template and individual specifications retain restart => permanent, the configured worker_shutdown, and the callback module metadata. Worker names and callback initialization arguments remain unchanged.

Both supported supervisor flag formats are accepted:

strategy => {simple_one_for_one, 5, 60}
strategy => #{
    strategy => simple_one_for_one,
    intensity => 5,
    period => 60
}

Startup, recovery, and failed initialization

For the new strategy, wpool_process_sup:start_link/3 starts the supervisor and then starts the configured number of workers through supervisor:start_child/2. It returns success only after all initial workers have started.

Initialization runs through the supervisor start function, so it also runs when the worker supervisor is restarted by its parent. Initialization is not limited to the public pool creation call.

If a worker fails to start, the partially initialized supervisor is unlinked from the caller and stopped along with its already started workers before an error identifying the failed worker is returned.

Workers remain permanent. Normal worker exits continue to trigger replacement, and abnormal exits are handled by OTP's permanent-child restart policy.

Existing behavior and compatibility

The feature is opt-in through the existing strategy option. No new public functions or options are required.

The final change preserves:

  • The original application root and supervision tree.
  • The original wpool_sup implementation, including its child template and restart settings.
  • Existing pool placement and termination through wpool_sup.
  • The default worker supervision strategy and existing option defaults.
  • Worker names, initialization arguments, and permanent restart policy.
  • Sequential worker shutdown for the existing static strategies.
  • Parallel shutdown of supervised pools when the application stops.
  • The existing outer shutdown timeout of 2000 ms for start_sup_pool/2.

There is no additional application supervisor or separate group for pools using the new strategy. Changes to executable production code are confined to wpool_process_sup; wpool.erl only gains documentation.

Compatibility was checked against the existing test suites and additional regression tests. Worker specifications were also compared directly with the original implementation for 19 existing configurations: defaults and all three static strategies in tuple/map forms with different worker shutdown settings. Those specifications matched.

These checks establish the tested behavior on OTP 28.5; they are not a claim that every possible external integration or OTP version has been verified.

Shutdown deadlines and usage

Pools managed by wpool_sup

{ok, _} = wpool:start_sup_pool(my_pool, #{
    workers => 10,
    worker => {my_worker, []},
    strategy => {simple_one_for_one, 5, 60},
    pool_sup_shutdown => infinity,
    worker_shutdown => 1000
}),
ok = wpool:stop_sup_pool(my_pool).

pool_sup_shutdown => infinity allows the worker supervisor to wait for its children. It does not remove the existing 2000 ms deadline imposed on the pool by wpool_sup. This outer deadline applies to the new strategy as well as the existing strategies.

Each worker's worker_shutdown timeout is subject to the deadlines of its ancestors. Parallel cleanup does not guarantee that a worker can finish after an ancestor has exhausted its shutdown allowance.

Cleanup requiring more than 2000 ms

Use the existing wpool:child_spec/2 API to place the pool under a caller-owned supervisor. That child specification already uses an outer shutdown timeout of infinity:

%% In the owning supervisor's init/1:
PoolSpec = wpool:child_spec(my_pool, #{
    workers => 10,
    worker => {my_worker, []},
    strategy => {simple_one_for_one, 5, 60},
    pool_sup_shutdown => infinity,
    worker_shutdown => 5000
}),
{ok, {{one_for_one, 5, 60}, [PoolSpec]}}.

All supervisors above this subtree must also allow sufficient shutdown time. Worker callbacks must trap exits to run cleanup in terminate/2. Parallel shutdown does not define an ordering between worker cleanup callbacks, so it should be selected only when those callbacks can run concurrently.

Tests

A new wpool_shutdown_SUITE adds 15 Common Test cases covering:

  • Parallel worker shutdown, using a barrier that prevents any worker from finishing until all workers have entered terminate/2.
  • Forced termination when worker_shutdown expires.
  • Replacement after a normal worker exit and restoration after a worker supervisor restart.
  • Cleanup when startup fails after some workers have already started.
  • Map-form supervisor flags and single-worker pools.
  • Preservation of the outer 2000 ms timeout across default, static, and new strategies.
  • Parallel pool shutdown during application termination for existing and new worker strategies.
  • Existing application termination behavior when its root supervisor exits.
  • Sequential worker shutdown for the default strategy.
  • Full pool replacement and subsequent request handling for existing and new strategies.
  • Standalone pool startup, request handling, and shutdown.
  • Cleanup lasting longer than two seconds through child_spec/2 under a caller-owned supervisor.
  • Preservation of the original supervisor template and direct pool placement.

The barrier assertions check overlapping cleanup directly instead of inferring parallel execution solely from elapsed time. The longer cleanup case separately verifies that the existing child_spec/2 path permits shutdown beyond the start_sup_pool/2 deadline.

Validation

Local validation used OTP 28.5:

Check Result
Full Common Test run 71 tests passed
New shutdown suite 15 tests passed
Total code coverage 92.15%, above the configured 90% minimum
wpool_process_sup coverage 97%
Formatting check Passed
Lint Passed
Hank Passed with its existing ignored warnings
Xref Passed
Dialyzer Five existing warnings in existing test files; no warnings in the new suite or changed implementation

Dialyzer does not exit successfully: the remaining warnings concern cthr:pal/2, unmatched return values, and the existing complete_coverage/1 specification/contract checks. These warnings are reported rather than suppressed by this PR.

OTP 29 validation remains for CI; it has not been run locally.

Documentation

The README now explains how to enable parallel worker shutdown, the unchanged outer 2000 ms deadline, and the existing child_spec/2 path for longer cleanup. The pool_sup_shutdown type documentation in wpool.erl describes the same behavior and limitations.

Add support for simple_one_for_one as the worker supervision strategy,
allowing workers to execute their shutdown cleanup in parallel.

Use a single child specification for this strategy and explicitly start
the configured number of named workers before returning from start_link.
Keep workers permanent so they are restarted after both normal and
abnormal exits.

Run worker initialization through the supervisor start function so the
configured pool size is restored when the worker supervisor restarts.
If a worker fails to start, stop the partially initialized supervisor
and its workers before returning an error.

Support both tuple and map forms of supervisor flags.

Preserve existing application supervision and shutdown behavior:
- Keep the original application root and wpool_sup implementation.
- Preserve the default worker supervision strategy and shutdown options.
- Retain the 2000 ms outer shutdown timeout for start_sup_pool/2.
- Preserve parallel shutdown of supervised pools and sequential worker
  shutdown for existing worker supervision strategies.
- Keep the public API and worker naming unchanged.

Document the new strategy, cleanup requirements, and inherited shutdown
deadlines. Include an example using child_spec/2 under a user supervisor
for cleanup that needs more than the start_sup_pool/2 outer timeout.

Add 15 Common Test cases covering:
- Parallel worker shutdown and forced termination on timeout.
- Normal worker exits, worker supervisor restarts, and pool restarts.
- Cleanup after partially failed startup.
- Tuple and map strategy configuration.
- Single-worker and standalone pools.
- Existing supervision tree and outer shutdown timeout.
- Parallel pool shutdown during application termination.
- Existing sequential worker shutdown and supervisor failure behavior.
- Cleanup lasting over two seconds through child_spec/2.

Validation on OTP 28.5:
- All 71 Common Test cases pass.
- Total coverage is 92%.
- Formatting, lint, hank, and xref checks pass.
- Worker specifications match the original implementation for 19
  existing configurations.
- Dialyzer reports five existing test warnings.

Refs inaka#172
@vkatsuba

Copy link
Copy Markdown
Contributor Author

Hey Mr. @elbrujohalcon! Please, review PR when you will have a time for it.

@codecov

codecov Bot commented Nov 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.42857% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 92.15%. Comparing base (eace4a7) to head (80c3f7e).
⚠️ Report is 66 commits behind head on main.

Files with missing lines Patch % Lines
src/wpool_process_sup.erl 96.42% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #223      +/-   ##
==========================================
- Coverage   92.57%   92.15%   -0.43%     
==========================================
  Files          10       10              
  Lines         458      548      +90     
==========================================
+ Hits          424      505      +81     
- Misses         34       43       +9     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@elbrujohalcon

Copy link
Copy Markdown
Member

Thanks for the contribution, @vkatsuba but given…

  • the length of the change, …
  • the fact that noboy ever used simple_one_for_one as a strategy for worker pool supervisors in almost 7 years, and…
  • the fact that this library is used in really heavy duty software (like MongooseIM, for example), which makes me very paranoid about large changes here, in general…

I think I prefer to go the exact opposite direction here, as I stated on the ticket: #172 (comment)

If, to be able to support simple_one_for_one supervisor strategy, we need such a large change… it would be better to just not support simple_one_for_one strategy, add that to the docs and move along… 🤷🏻

@vkatsuba

Copy link
Copy Markdown
Contributor Author

@elbrujohalcon I understand the concern about changing a library...

I’d like to clarify the scope of the final implementation: most of the PR consists of documentation and regression tests. Executable production changes are confined to wpool_process_sup; the application supervision tree and wpool_sup remain unchanged.

Existing behavior is preserved

The existing strategies retain their worker specifications, defaults, restart policy, naming, and shutdown timeouts. The new behavior is explicitly enabled by selecting simple_one_for_one.

I also compared the generated worker specifications against the original implementation for 19 existing configurations, and they matched.

Validation

Validation on OTP 28.5 includes:

  • All 71 tests passing, including 15 new shutdown and compatibility tests.
  • Tests for parallel cleanup, shutdown timeouts, partial startup failure, worker and supervisor restarts, and preservation of existing shutdown behavior.
  • 92% overall coverage and 97% coverage of wpool_process_sup.
  • Passing formatting, lint, hank, and xref checks.

This does not eliminate every possible production risk, but the implementation deliberately preserves existing behavior and limits the functional change to the opt-in strategy.

Would you be open to reconsidering it on that narrower basis? If the project prefers to explicitly exclude simple_one_for_one regardless of implementation size, I respect that decision.

@elbrujohalcon

Copy link
Copy Markdown
Member

I still think we don't need to introduce new code that we will later need to maintain just for a use case that was proven, at the very least, unpopular in all the years this library was around.
So, no. Let's exclude simple_one_for_one.

@vkatsuba

Copy link
Copy Markdown
Contributor Author

I still think we don't need to introduce new code that we will later need to maintain just for a use case that was proven, at the very least, unpopular in all the years this library was around. So, no. Let's exclude simple_one_for_one.

@elbrujohalcon clear, make sense. In this case I recommend close issue #172 with the commend. Also, please take a look at other opened issues and close issues which are not needed to implement - to avoid double work as in the current case.

@elbrujohalcon

Copy link
Copy Markdown
Member

I would not close the ticket since we still need to add documentation stating that we don't support simple_one_for_one.
To avoid double work in a well-maintained library such as this, whenever you see a ticket that you want to work on just write comment, like "Is this still needed? What's the plan to deal with this?" and you'll get a response from me or @NelsonVides in no more than 24 hours.
I'll still follow your advice and do backlog trimming… but it won't be right now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants