From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 757041FF09F for ; Tue, 01 Dec 2026 11:21:38 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 92018217D5; Tue, 01 Dec 2026 11:20:33 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout Date: Tue, 1 Dec 2026 11:19:00 +0100 Message-ID: <20261201101913.1885484-6-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201101913.1885484-1-t.lamprecht@proxmox.com> References: <20261201101913.1885484-1-t.lamprecht@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796120358999 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.852 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) KAM_MAILER 2 Automated Mailer Tag Left in Email RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: AT5MEBIB2MJKXYWDGH7QWT4UJ7ADEZXB X-Message-ID-Hash: AT5MEBIB2MJKXYWDGH7QWT4UJ7ADEZXB X-MailFrom: t.lamprecht@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Fanning out asynchronous API calls across many cluster nodes needs a concurrency cap, shared timeout budget, and clean cancellation without reimplementing slot tracking in each caller. Add PVE::APIClient::AnyEvent::Pool to drive bounded-concurrency batches iteratively without deep recursion on synchronous completions. The pool supports optional backpressure gating via can_dispatch() that pauses the overall_timeout budget while downstream consumers are busy, isolates synchronous start_item() and can_dispatch() exceptions, cancels active operations on timeout or manual cancel, and releases references cleanly to avoid cycles. Signed-off-by: Thomas Lamprecht --- Changes in v2: - Add create_limiter() shared capacity limiter (with exception-isolated dynamic cap evaluation, FIFO waiter wakeup with re-entrant wake deferral so newly queued waiters cannot strand, and cancel/timeout permit release) and an optional can_admit capacity gate so busy-worker waits count toward overall_timeout while downstream backpressure via can_dispatch pauses it. - Measure elapsed timeout budget with CLOCK_MONOTONIC, sync AE::now before arming the timeout watcher, and rearm if the watcher fires before the monotonic budget expires. - Document deadline/wakeup semantics and expand pool unit tests. src/Makefile | 3 +- src/PVE/APIClient/AnyEvent/Pool.pm | 444 +++++++++++++ src/test/anyevent_pool.t | 995 +++++++++++++++++++++++++++++ 3 files changed, 1441 insertions(+), 1 deletion(-) create mode 100644 src/PVE/APIClient/AnyEvent/Pool.pm create mode 100644 src/test/anyevent_pool.t diff --git a/src/Makefile b/src/Makefile index d6327c6..178380c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -6,9 +6,10 @@ DOCDIR=$(DESTDIR)/usr/share/doc/$(PACKAGE) all: -install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm PVE/APIClient/AnyEvent.pm examples/*.pl +install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm PVE/APIClient/AnyEvent.pm PVE/APIClient/AnyEvent/Pool.pm examples/*.pl install -D -m 0644 PVE/APIClient/LWP.pm $(PERL5DIR)/PVE/APIClient/LWP.pm install -m 0644 PVE/APIClient/AnyEvent.pm $(PERL5DIR)/PVE/APIClient/AnyEvent.pm + install -D -m 0644 PVE/APIClient/AnyEvent/Pool.pm $(PERL5DIR)/PVE/APIClient/AnyEvent/Pool.pm install -m 0644 PVE/APIClient/Exception.pm $(PERL5DIR)/PVE/APIClient/Exception.pm install -d -m 755 $(DOCDIR)/examples install -m 0755 examples/example1.pl $(DOCDIR)/examples diff --git a/src/PVE/APIClient/AnyEvent/Pool.pm b/src/PVE/APIClient/AnyEvent/Pool.pm new file mode 100644 index 0000000..c4d5903 --- /dev/null +++ b/src/PVE/APIClient/AnyEvent/Pool.pm @@ -0,0 +1,444 @@ +package PVE::APIClient::AnyEvent::Pool; + +# Bounded-concurrency async request pool for multi-target fan-out inside an AnyEvent event loop. +# Drives queued operations iteratively up to a concurrency cap with optional backpressure gating, +# shared timeout accounting, exception isolation, and idempotent cancellation. See start() below +# for the full callback and backpressure contract. + +use v5.36; + +use AnyEvent; +use Carp; +use Net::SSLeay; +use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC); + +my sub mono_time() { + return clock_gettime(CLOCK_MONOTONIC); +} + +my sub invoke_callback($cb, @args) { + eval { $cb->(@args); }; + my $err = $@; + # Clear OpenSSL errors left by TLS teardowns or user callbacks (see PVE::APIServer::AnyEvent). + Net::SSLeay::ERR_clear_error(); + warn $err if $err; +} + +# Create a shared capacity limiter usable across multiple Pool::start() instances. +# $limit may be a positive integer or a CODE ref evaluated dynamically to return the current cap. +sub create_limiter($limit) { + if (ref($limit) eq 'CODE') { + # Dynamic cap evaluated on each acquire/wake. + } elsif (!ref($limit) && defined($limit) && $limit =~ /^[0-9]+\z/ && $limit >= 1) { + $limit = int($limit); + } else { + croak "limit must be a positive integer or CODE ref"; + } + + return bless { + limit => $limit, + active => 0, + waiters => [], + waking => 0, + wake_scheduled => 0, + }, 'PVE::APIClient::AnyEvent::Pool::Limiter'; +} + +my sub limiter_cap($limiter) { + my $raw; + if (ref($limiter->{limit}) eq 'CODE') { + $raw = eval { $limiter->{limit}->() }; + my $err = $@; + Net::SSLeay::ERR_clear_error(); + if ($err) { + warn $err; + return undef; + } + } else { + $raw = $limiter->{limit}; + } + my $cap = int($raw // 1); + return $cap < 1 ? 1 : $cap; +} + +my sub wake_limiter_waiters($limiter) { + if ($limiter->{waking}) { + $limiter->{wake_pending} = 1; + return; + } + my $self = __SUB__; + $limiter->{waking} = 1; + eval { + my $remaining = scalar(@{ $limiter->{waiters} }); + while ($remaining-- > 0 && @{ $limiter->{waiters} }) { + my $cap = limiter_cap($limiter); + last if !defined($cap) || $limiter->{active} >= $cap; + my $waiter = shift @{ $limiter->{waiters} }; + $waiter->{queued} = 0; + next if $waiter->{done}; + my $dispatch = $waiter->{dispatch}; + $dispatch->() if $dispatch; + } + }; + my $err = $@; + $limiter->{waking} = 0; + if (delete $limiter->{wake_pending} && !$limiter->{wake_scheduled} && @{ $limiter->{waiters} }) + { + $limiter->{wake_scheduled} = 1; + AE::postpone(sub { + $limiter->{wake_scheduled} = 0; + $self->($limiter); + }); + } + warn $err if $err; +} + +my sub schedule_wake_limiter_waiters($limiter) { + return if $limiter->{wake_scheduled} || !@{ $limiter->{waiters} }; + $limiter->{wake_scheduled} = 1; + AE::postpone(sub { + $limiter->{wake_scheduled} = 0; + wake_limiter_waiters($limiter); + }); +} + +my sub cleanup_state($state) { + my @entries = values %{ $state->{active} }; + my $limiter = $state->{limiter}; + if (my $waiter = $state->{limiter_waiter}) { + $waiter->{done} = 1; + delete $waiter->{dispatch}; + if ($waiter->{queued} && $limiter && !$limiter->{waking}) { + $waiter->{queued} = 0; + @{ $limiter->{waiters} } = grep { $_ != $waiter } @{ $limiter->{waiters} }; + } + } + + # Clear in place so no lingering reference holds onto active guards or queued items. + %{ $state->{active} } = (); + @{ $state->{queue} } = (); + undef $state->{timeout_watcher}; + undef $state->{timeout_started_at}; + delete @{$state}{qw(start_item on_done can_dispatch can_admit on_start_error limiter limiter_waiter)}; + + for my $entry (@entries) { + if (ref($entry) eq 'HASH') { + invoke_callback($entry->{cancel}) if ref($entry->{cancel}) eq 'CODE'; + $entry->{release}->(1) if ref($entry->{release}) eq 'CODE'; + } + } +} + +my sub complete_pool($state, $timed_out = 0) { + return if $state->{done}; + $state->{done} = 1; + + my @pending_ids; + if ($timed_out) { + my @ids = (keys %{ $state->{active} }, map { $_->{id} } @{ $state->{queue} }); + @pending_ids = sort @ids; + } + + my $on_done = $state->{on_done}; + cleanup_state($state); + + invoke_callback($on_done, $timed_out ? 1 : 0, \@pending_ids) if $on_done; +} + +my sub pause_timeout($state) { + return if !defined($state->{remaining_timeout}) || !defined($state->{timeout_started_at}); + + my $elapsed = mono_time() - $state->{timeout_started_at}; + $elapsed = 0 if $elapsed < 0; + + $state->{remaining_timeout} -= $elapsed; + $state->{remaining_timeout} = 0 if $state->{remaining_timeout} < 0; + undef $state->{timeout_started_at}; + undef $state->{timeout_watcher}; +} + +my sub resume_timeout($state) { + return if $state->{done}; + return if !defined($state->{remaining_timeout}) || defined($state->{timeout_started_at}); + + my $self = __SUB__; + $state->{timeout_started_at} = mono_time(); + AnyEvent->now_update(); + $state->{timeout_watcher} = AE::timer( + $state->{remaining_timeout}, + 0, + sub { + return if $state->{done} || !defined($state->{timeout_started_at}); + my $elapsed = mono_time() - $state->{timeout_started_at}; + $elapsed = 0 if $elapsed < 0; + if ($elapsed < $state->{remaining_timeout}) { + $state->{remaining_timeout} -= $elapsed; + undef $state->{timeout_started_at}; + undef $state->{timeout_watcher}; + $self->($state); + return; + } + complete_pool($state, 1); + }, + ); +} + +my sub timeout_expired($state) { + return 0 if !defined($state->{remaining_timeout}); + return $state->{remaining_timeout} <= 0 ? 1 : 0 if !defined($state->{timeout_started_at}); + + my $elapsed = mono_time() - $state->{timeout_started_at}; + $elapsed = 0 if $elapsed < 0; + return $elapsed >= $state->{remaining_timeout} ? 1 : 0; +} + +my sub check_gate($cb) { + return 1 if !$cb; + + my $ok = eval { $cb->() }; + my $err = $@; + Net::SSLeay::ERR_clear_error(); + if ($err) { + warn $err; + return undef; + } + return $ok ? 1 : 0; +} + +my sub dispatch_pool($state) { + return if $state->{done} || $state->{dispatching}; + $state->{dispatching} = 1; + my $self = __SUB__; + + my $backpressured = 0; + my $timed_out = 0; + while (!$state->{done} && @{ $state->{queue} }) { + my $ok = check_gate($state->{can_dispatch}); + last if $state->{done}; + if (!defined($ok)) { + # Stop dispatching on callback error without suspending overall_timeout. + last; + } + if (!$ok) { + $backpressured = 1; + last; + } + + last if scalar(keys %{ $state->{active} }) >= $state->{max_concurrent}; + + my $admit = check_gate($state->{can_admit}); + last if $state->{done}; + if (!defined($admit) || !$admit) { + # Capacity gate: keep item queued without pausing overall_timeout. + last; + } + + my $limiter = $state->{limiter}; + if ($limiter) { + my $cap = limiter_cap($limiter); + if (!defined($cap) || $limiter->{active} >= $cap) { + my $waiter = $state->{limiter_waiter}; + if ($waiter && !$waiter->{queued} && !$waiter->{done}) { + $waiter->{queued} = 1; + push @{ $limiter->{waiters} }, $waiter; + } + last; + } + } + + resume_timeout($state); + if (timeout_expired($state)) { + $timed_out = 1; + last; + } + + my $item = shift @{ $state->{queue} }; + my $id = $item->{id}; + my $item_done = 0; + + my $slot_released = 0; + my $release_slot; + if ($limiter) { + $limiter->{active}++; + $release_slot = sub { + my ($defer_wake) = @_; + return if $slot_released; + $slot_released = 1; + $limiter->{active}-- if $limiter->{active} > 0; + if ($defer_wake) { + schedule_wake_limiter_waiters($limiter); + } else { + wake_limiter_waiters($limiter); + } + }; + } + + my $active_entry = { cancel => undef, release => $release_slot }; + $state->{active}->{$id} = $active_entry; + + my $finish_item = sub { + return if $item_done; + $item_done = 1; + if ($state->{done}) { + $release_slot->(0) if $release_slot; + return; + } + + delete $state->{active}->{$id}; + $release_slot->(0) if $release_slot; + $self->($state); + }; + + my $start_item = $state->{start_item}; + my $cancel = eval { $start_item->($item, $finish_item) }; + my $err = $@; + Net::SSLeay::ERR_clear_error(); + + if ($err) { + if (!$item_done) { + $item_done = 1; + delete $state->{active}->{$id} if !$state->{done}; + $release_slot->(0) if $release_slot; + } + if (my $on_start_error = $state->{on_start_error}) { + invoke_callback($on_start_error, $id, $err); + } else { + warn $err; + } + } elsif ($state->{done}) { + # Pool was cancelled or timed out synchronously while starting this item. + if (!$item_done) { + invoke_callback($cancel) if ref($cancel) eq 'CODE'; + $release_slot->(1) if $release_slot; + } + } elsif (!$item_done) { + $active_entry->{cancel} = ref($cancel) eq 'CODE' ? $cancel : undef; + } + + if (!$state->{done} && timeout_expired($state)) { + $timed_out = 1; + last; + } + } + + $state->{dispatching} = 0; + + if (!$state->{done}) { + if ($timed_out || timeout_expired($state)) { + complete_pool($state, 1); + } elsif (!@{ $state->{queue} } && !%{ $state->{active} }) { + complete_pool($state, 0); + } elsif ($backpressured) { + pause_timeout($state); + } else { + resume_timeout($state); + } + } +} + +# Run a bounded-concurrency pool of async operations (each item needs a unique scalar `id`). +# Callers may share a worker-wide capacity cap across pools via `limiter => create_limiter($n)` +# (releasing a permit wakes queued waiters in FIFO order; increasing a dynamic limit does not wake +# waiters automatically, so call `$pool->{dispatch}->()` to use new capacity immediately), or +# supply `can_dispatch` (backpressure gate) / `can_admit` (custom capacity gate) and invoke +# `$pool->{dispatch}->()` when eligibility changes. Waiting for a worker slot (`limiter` or +# `can_admit`) counts toward `overall_timeout`. While work remains queued, a false `can_dispatch` +# pauses `overall_timeout` even if all slots are occupied; once the queue is empty, the deadline +# continues to apply to active requests. A backpressured pool with no active items stays paused +# until `dispatch()` is called. A throwing `can_dispatch` or `can_admit` warns and stops dispatch +# without pausing `overall_timeout`. Synchronous `start_item` errors are isolated via +# `on_start_error`, and `on_done->($timed_out, $pending_ids)` runs once on completion or timeout +# (never after `cancel()`, and may fire synchronously inside `start()` for empty or synchronous +# item lists). +sub start(%opts) { + my ($items, $start_item, $on_done, $can_dispatch, $can_admit, $on_start_error, $limiter) = + @opts{ + 'items', 'start_item', 'on_done', 'can_dispatch', 'can_admit', 'on_start_error', + 'limiter', + }; + croak "items must be an ARRAY ref" if ref($items) ne 'ARRAY'; + + croak "start_item must be a CODE ref" if ref($start_item) ne 'CODE'; + croak "on_done must be a CODE ref" if ref($on_done) ne 'CODE'; + if (defined($can_dispatch) && ref($can_dispatch) ne 'CODE') { + croak "can_dispatch must be a CODE ref"; + } + if (defined($can_admit) && ref($can_admit) ne 'CODE') { + croak "can_admit must be a CODE ref"; + } + if (defined($on_start_error) && ref($on_start_error) ne 'CODE') { + croak "on_start_error must be a CODE ref"; + } + if (defined($limiter) && ref($limiter) ne 'PVE::APIClient::AnyEvent::Pool::Limiter') { + croak "limiter must be a PVE::APIClient::AnyEvent::Pool::Limiter"; + } + + my $max_concurrent = $opts{max_concurrent} // 16; + if (ref($max_concurrent) || $max_concurrent !~ /^[0-9]+\z/ || $max_concurrent < 1) { + croak "max_concurrent must be a positive integer"; + } + + my $overall_timeout = $opts{overall_timeout}; + if (defined($overall_timeout)) { + if ( + ref($overall_timeout) + || $overall_timeout !~ /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/ + || $overall_timeout <= 0 + ) { + croak "overall_timeout must be a positive number"; + } + } + + my %seen_ids; + for my $item (@$items) { + croak "each item must be a HASH ref" if ref($item) ne 'HASH'; + my $id = $item->{id}; + if (!defined($id) || ref($id) || $id eq '') { + croak "each item must have a non-empty scalar id"; + } + croak "duplicate item id '$id'" if $seen_ids{$id}++; + } + + my $state = { + done => 0, + dispatching => 0, + active => {}, + queue => [@$items], + remaining_timeout => $overall_timeout, + timeout_started_at => undef, + timeout_watcher => undef, + start_item => $start_item, + on_done => $on_done, + can_dispatch => $can_dispatch, + can_admit => $can_admit, + on_start_error => $on_start_error, + max_concurrent => $max_concurrent, + limiter => $limiter, + limiter_waiter => undef, + }; + + if ($limiter) { + $state->{limiter_waiter} = { + done => 0, + queued => 0, + dispatch => sub { dispatch_pool($state); }, + }; + } + + my $pool = { + dispatch => sub { + dispatch_pool($state); + }, + cancel => sub { + return if $state->{done}; + $state->{done} = 1; + cleanup_state($state); + }, + }; + + dispatch_pool($state); + + return $pool; +} + +1; diff --git a/src/test/anyevent_pool.t b/src/test/anyevent_pool.t new file mode 100644 index 0000000..1dc4b9f --- /dev/null +++ b/src/test/anyevent_pool.t @@ -0,0 +1,995 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use AnyEvent; +use Scalar::Util qw(weaken); +use Test::More; + +use PVE::APIClient::AnyEvent::Pool; + +my sub run_with_timeout { + my ($cb, $timeout) = @_; + $timeout //= 5; + my $cv = AE::cv; + my $t = AE::timer($timeout, 0, sub { $cv->croak("test timed out after ${timeout}s") }); + $cb->($cv); + return $cv->recv(); +} + +subtest 'upfront argument and item id validation' => sub { + for my $case ( + [ + 'non-array items', + { items => 'bad', start_item => sub { }, on_done => sub { } }, + qr/items must be an ARRAY ref/, + ], + [ + 'non-hash item', + { items => ['bad'], start_item => sub { }, on_done => sub { } }, + qr/each item must be a HASH ref/, + ], + [ + 'missing id', + { items => [{}], start_item => sub { }, on_done => sub { } }, + qr/non-empty scalar id/, + ], + [ + 'empty id', + { items => [{ id => '' }], start_item => sub { }, on_done => sub { } }, + qr/non-empty scalar id/, + ], + [ + 'duplicate id', + { + items => [{ id => 'n1' }, { id => 'n2' }, { id => 'n1' }], + start_item => sub { }, + on_done => sub { }, + }, + qr/duplicate item id 'n1'/, + ], + [ + 'invalid max_concurrent', + { + items => [{ id => 'n1' }], + max_concurrent => 0, + start_item => sub { }, + on_done => sub { }, + }, + qr/max_concurrent/, + ], + [ + 'invalid overall_timeout', + { + items => [{ id => 'n1' }], + overall_timeout => -1, + start_item => sub { }, + on_done => sub { }, + }, + qr/overall_timeout/, + ], + [ + 'invalid can_dispatch', + { + items => [{ id => 'n1' }], + can_dispatch => 'nope', + start_item => sub { }, + on_done => sub { }, + }, + qr/can_dispatch/, + ], + [ + 'invalid on_start_error', + { + items => [{ id => 'n1' }], + on_start_error => [], + start_item => sub { }, + on_done => sub { }, + }, + qr/on_start_error/, + ], + ) { + my ($name, $opts, $re) = @$case; + eval { PVE::APIClient::AnyEvent::Pool::start(%$opts) }; + like($@, $re, "validation rejects $name"); + } + + my @done_args; + PVE::APIClient::AnyEvent::Pool::start( + items => [], + start_item => sub { fail('start_item should not run for empty pool') }, + on_done => sub { @done_args = @_ }, + ); + is_deeply(\@done_args, [0, []], 'empty items completes immediately with (0, [])'); +}; + +subtest 'concurrency cap enforcement' => sub { + my @items = map { { id => "item-$_" } } (1 .. 10); + my $active = 0; + my $max_seen = 0; + my $finished = 0; + my @timers; + + my $res = run_with_timeout(sub { + my ($cv) = @_; + PVE::APIClient::AnyEvent::Pool::start( + items => \@items, + max_concurrent => 3, + start_item => sub { + my ($item, $finish_item) = @_; + $active++; + $max_seen = $active if $active > $max_seen; + my $t; + $t = AE::timer( + 0.01, + 0, + sub { + undef $t; + $active--; + $finished++; + $finish_item->(); + }, + ); + push @timers, \$t; + return sub { undef $t }; + }, + on_done => sub { + $cv->send([@_]); + }, + ); + }); + + is($max_seen, 3, 'concurrency capped at max_concurrent => 3'); + is($finished, 10, 'all 10 items completed'); + is_deeply($res, [0, []], 'on_done received (0, [])'); +}; + +subtest 'iterative safety on 200 synchronous completions' => sub { + my @warnings; + local $SIG{__WARN__} = sub { push @warnings, @_ }; + + my @items = map { { id => "sync-$_" } } (1 .. 200); + my @seen; + my $done_count = 0; + + PVE::APIClient::AnyEvent::Pool::start( + items => \@items, + max_concurrent => 4, + start_item => sub { + my ($item, $finish_item) = @_; + push @seen, $item->{id}; + $finish_item->(); + $finish_item->(); # idempotent second call + return undef; + }, + on_done => sub { + my ($timed_out, $pending) = @_; + $done_count++; + is($timed_out, 0, 'synchronous pool did not time out'); + is_deeply($pending, [], 'synchronous pool has no pending ids'); + }, + ); + + is(scalar(@seen), 200, 'all 200 synchronous items processed'); + is($done_count, 1, 'on_done fired exactly once'); + is_deeply(\@warnings, [], 'no deep recursion or other warnings emitted'); +}; + +subtest 'synchronous start_item exception isolation' => sub { + my @items = map { { id => "err-$_" } } (1 .. 5); + my %start_errors; + my @completed; + my $done_calls = 0; + + PVE::APIClient::AnyEvent::Pool::start( + items => \@items, + max_concurrent => 2, + start_item => sub { + my ($item, $finish_item) = @_; + die "boom $item->{id}\n" if $item->{id} eq 'err-2' || $item->{id} eq 'err-4'; + push @completed, $item->{id}; + $finish_item->(); + return undef; + }, + on_start_error => sub { + my ($id, $err) = @_; + $start_errors{$id} = $err; + }, + on_done => sub { + $done_calls++; + is_deeply(\@_, [0, []], 'pool still completes after isolated start_item errors'); + }, + ); + + is_deeply(\@completed, [qw(err-1 err-3 err-5)], 'non-failing items ran to completion'); + like($start_errors{'err-2'}, qr/boom err-2/, 'err-2 passed to on_start_error'); + like($start_errors{'err-4'}, qr/boom err-4/, 'err-4 passed to on_start_error'); + is($done_calls, 1, 'on_done fired once'); +}; + +subtest 'backpressure pauses overall_timeout budget' => sub { + # Case A: paused longer than overall_timeout, then unblocks and completes. + my $allow_dispatch = 1; + my $pool; + my $timed_out_during_pause = 0; + my $pause_timer; + + my $res_a = run_with_timeout(sub { + my ($cv) = @_; + $pool = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'a' }, { id => 'b' }], + max_concurrent => 1, + overall_timeout => 0.15, + can_dispatch => sub { return $allow_dispatch }, + start_item => sub { + my ($item, $finish_item) = @_; + my $t; + $t = AE::timer( + 0.02, + 0, + sub { + undef $t; + if ($item->{id} eq 'a') { + # Trigger backpressure before finishing item a so item b pauses. + $allow_dispatch = 0; + $pause_timer = AE::timer( + 0.25, + 0, + sub { + undef $pause_timer; + $allow_dispatch = 1; + $pool->{dispatch}->(); + }, + ); + } + $finish_item->(); + }, + ); + return sub { undef $t }; + }, + on_done => sub { + my ($timed_out, $pending) = @_; + $timed_out_during_pause = 1 if $timed_out; + $cv->send([$timed_out, $pending]); + }, + ); + }); + + is($timed_out_during_pause, 0, 'pool did not time out while paused by backpressure'); + is_deeply($res_a, [0, []], 'pool finished cleanly after backpressure cleared'); + + # Case B: starts paused longer than overall_timeout, then resumes and expires on remaining budget. + my $allow_b = 0; + my $b_started = 0; + my $b_cancelled = 0; + my $pool_b; + my $resume_t; + + my $res_b = run_with_timeout(sub { + my ($cv) = @_; + $pool_b = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'z' }, { id => 'm' }], + max_concurrent => 1, + overall_timeout => 0.10, + can_dispatch => sub { return $allow_b }, + start_item => sub { + my ($item, $finish_item) = @_; + $b_started++; + return sub { $b_cancelled++ }; + }, + on_done => sub { + $cv->send([@_]); + }, + ); + + $resume_t = AE::timer( + 0.20, + 0, + sub { + undef $resume_t; + is($b_started, 0, 'no items dispatched during initial backpressure pause'); + $allow_b = 1; + $pool_b->{dispatch}->(); + }, + ); + }); + + is($b_started, 1, 'first item dispatched once backpressure cleared'); + is($b_cancelled, 1, 'active item cancelled when remaining budget expired'); + is_deeply($res_b, [1, ['m', 'z']], 'timeout reported sorted active + queued pending ids'); + + # Case C: backpressure entered while active == max_concurrent pauses overall_timeout. + my $allow_c = 1; + my $pool_c; + my ($bp_enter_t, $bp_clear_t); + + my $res_c = run_with_timeout(sub { + my ($cv) = @_; + $pool_c = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'a' }, { id => 'b' }], + max_concurrent => 1, + overall_timeout => 0.08, + can_dispatch => sub { return $allow_c }, + start_item => sub { + my ($item, $finish_item) = @_; + my $delay = $item->{id} eq 'a' ? 0.12 : 0.01; + my $t; + $t = AE::timer( + $delay, + 0, + sub { + undef $t; + $finish_item->(); + }, + ); + return sub { undef $t }; + }, + on_done => sub { + $cv->send([@_]); + }, + ); + + $bp_enter_t = AE::timer( + 0.01, + 0, + sub { + undef $bp_enter_t; + $allow_c = 0; + $pool_c->{dispatch}->(); + }, + ); + $bp_clear_t = AE::timer( + 0.15, + 0, + sub { + undef $bp_clear_t; + $allow_c = 1; + $pool_c->{dispatch}->(); + }, + ); + }); + + is_deeply( + $res_c, + [0, []], + 'backpressure entered while active == max_concurrent pauses deadline', + ); + + # Case D: throwing can_dispatch warns and does NOT pause overall_timeout. + my @warnings; + local $SIG{__WARN__} = sub { push @warnings, @_ }; + my $res_d = run_with_timeout(sub { + my ($cv) = @_; + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'd1' }, { id => 'd2' }], + max_concurrent => 1, + overall_timeout => 0.08, + can_dispatch => sub { die "can_dispatch boom\n" }, + start_item => sub { fail('start_item must not run when can_dispatch throws') }, + on_done => sub { $cv->send([@_]) }, + ); + }); + is_deeply( + $res_d, + [1, ['d1', 'd2']], + 'throwing can_dispatch does not pause overall_timeout', + ); + ok( + scalar(grep { /can_dispatch boom/ } @warnings) >= 1, + 'throwing can_dispatch emits warning', + ); + + # Case E: can_dispatch synchronously finishing an active item while active == max_concurrent + # immediately dispatches the queued item without stalling. + my $first_finish; + my $trigger_finish = 0; + my @started_e; + my $pool_e; + my $res_e; + $pool_e = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'first' }, { id => 'second' }], + max_concurrent => 1, + overall_timeout => 2, + can_dispatch => sub { + if ($trigger_finish && $first_finish) { + $trigger_finish = 0; + my $fin = $first_finish; + undef $first_finish; + $fin->(); + } + return 1; + }, + start_item => sub { + my ($item, $finish_item) = @_; + push @started_e, $item->{id}; + if ($item->{id} eq 'first') { + $first_finish = $finish_item; + return sub { }; + } + $finish_item->(); + return undef; + }, + on_done => sub { $res_e = [@_] }, + ); + is_deeply(\@started_e, ['first'], 'only first item started before dispatch trigger'); + $trigger_finish = 1; + $pool_e->{dispatch}->(); + is_deeply( + \@started_e, + ['first', 'second'], + 'queued item dispatched immediately after can_dispatch finished active item', + ); + is_deeply($res_e, [0, []], 'pool completed without stalling after reentrant finish'); +}; + +subtest 'timeout returns sorted active and queued pending ids and cancels active ops' => sub { + my @items = map { { id => $_ } } qw(n5 n1 n4 n2 n3); + my %cancelled; + my @late_finishers; + my $done_calls = 0; + + my $res = run_with_timeout(sub { + my ($cv) = @_; + PVE::APIClient::AnyEvent::Pool::start( + items => \@items, + max_concurrent => 2, + overall_timeout => 0.08, + start_item => sub { + my ($item, $finish_item) = @_; + if ($item->{id} eq 'n5') { + $finish_item->(); + return undef; + } + push @late_finishers, $finish_item; + return sub { $cancelled{ $item->{id} }++ }; + }, + on_done => sub { + $done_calls++; + $cv->send([@_]); + }, + ); + }); + + is_deeply($res, [1, [qw(n1 n2 n3 n4)]], 'timeout returns exact sorted active + queued ids'); + is_deeply(\%cancelled, { n1 => 1, n4 => 1 }, 'active ops cancelled on timeout'); + + $_->() for @late_finishers; + is($done_calls, 1, 'late finish_item calls after timeout do not re-fire on_done'); +}; + +subtest 'synchronous start_item exceeding overall_timeout enforces deadline' => sub { + # Multi-item: first synchronous start_item exceeds overall_timeout; queued items do not start. + my @started_multi; + my $done_multi; + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 's1' }, { id => 's2' }, { id => 's3' }], + max_concurrent => 2, + overall_timeout => 0.03, + start_item => sub { + my ($item, $finish_item) = @_; + push @started_multi, $item->{id}; + select(undef, undef, undef, 0.06); + $finish_item->(); + return undef; + }, + on_done => sub { + $done_multi = [@_]; + }, + ); + is_deeply( + \@started_multi, + ['s1'], + 'remaining queued items are not started after synchronous timeout expiry', + ); + is_deeply( + $done_multi, + [1, ['s2', 's3']], + 'multi-item synchronous timeout reports timed_out=1 and remaining queued ids', + ); + + # Single-item: synchronous start_item finishes after exceeding overall_timeout. + my @started_single; + my $done_single; + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'only' }], + max_concurrent => 1, + overall_timeout => 0.03, + start_item => sub { + my ($item, $finish_item) = @_; + push @started_single, $item->{id}; + select(undef, undef, undef, 0.06); + $finish_item->(); + return undef; + }, + on_done => sub { + $done_single = [@_]; + }, + ); + is_deeply(\@started_single, ['only'], 'single synchronous item started'); + is_deeply( + $done_single, + [1, []], + 'single-item synchronous timeout reports timed_out=1 with empty pending list', + ); +}; + +subtest 'manual cancellation and synchronous cancel inside start_item' => sub { + my %cancelled; + my $done_calls = 0; + my @late_finishers; + + my $pool = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'x1' }, { id => 'x2' }, { id => 'x3' }], + max_concurrent => 2, + overall_timeout => 5, + start_item => sub { + my ($item, $finish_item) = @_; + push @late_finishers, $finish_item; + return sub { $cancelled{ $item->{id} }++ }; + }, + on_done => sub { $done_calls++ }, + ); + + $pool->{cancel}->(); + $pool->{cancel}->(); # idempotent + $pool->{dispatch}->(); + $_->() for @late_finishers; + + is_deeply(\%cancelled, { x1 => 1, x2 => 1 }, 'active items cancelled exactly once'); + is($done_calls, 0, 'on_done never fires after cancel'); + + # Synchronous cancel during start_item cancels the returned cancel coderef too. + my $sync_returned_cancelled = 0; + my $sync_pool; + my $s1_finish; + $sync_pool = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 's1' }, { id => 's2' }], + max_concurrent => 1, + start_item => sub { + my ($item, $finish_item) = @_; + if ($item->{id} eq 's1') { + $s1_finish = $finish_item; + return sub { }; + } + $sync_pool->{cancel}->(); + return sub { $sync_returned_cancelled++ }; + }, + on_done => sub { fail('on_done must not fire after sync cancel') }, + ); + $s1_finish->(); + is( + $sync_returned_cancelled, + 1, + 'cancel returned after sync pool cancel is invoked immediately', + ); +}; + +subtest 'weakened-ref destruction across completion, timeout, and cancel' => sub { + # 1. Normal completion + my ($w_pool, $w_cb_token, $w_item); + { + my $cb_token = { done_path => 1 }; + my $item = { id => 'c1', payload => { x => 1 } }; + $w_cb_token = $cb_token; + $w_item = $item; + weaken($w_cb_token); + weaken($w_item); + + my $pool = PVE::APIClient::AnyEvent::Pool::start( + items => [$item], + start_item => sub { + my (undef, $finish_item) = @_; + my $keep = $cb_token; + $finish_item->(); + return sub { my $k = $cb_token }; + }, + on_done => sub { my $keep = $cb_token }, + ); + undef $cb_token; + undef $item; + + # Callbacks and items must already be released even while $pool handle is still held. + is($w_cb_token, undef, 'completion frees user callbacks while pool handle is held'); + is($w_item, undef, 'completion frees queued item while pool handle is held'); + + $w_pool = $pool; + weaken($w_pool); + } + is($w_pool, undef, 'completed pool handle freed cleanly'); + + # 2. Timeout path + my ($wt_pool, $wt_cb_token, $wt_cancel_token, $wt_item); + { + my $cb_token = { timeout_path => 1 }; + my $cancel_token = { cancel_guard => 1 }; + my $item = { id => 't1' }; + $wt_cb_token = $cb_token; + $wt_cancel_token = $cancel_token; + $wt_item = $item; + weaken($wt_cb_token); + weaken($wt_cancel_token); + weaken($wt_item); + + my $pool; + run_with_timeout(sub { + my ($cv) = @_; + $pool = PVE::APIClient::AnyEvent::Pool::start( + items => [$item], + overall_timeout => 0.03, + start_item => sub { + my $keep = $cb_token; + my $ct = $cancel_token; + return sub { my $c = $ct }; + }, + on_done => sub { + my $keep = $cb_token; + $cv->send(1); + }, + ); + }); + undef $cb_token; + undef $cancel_token; + undef $item; + + is($wt_cb_token, undef, 'timeout frees user callbacks while pool handle is held'); + is( + $wt_cancel_token, + undef, + 'timeout frees active cancel closures while pool handle is held', + ); + is($wt_item, undef, 'timeout frees item while pool handle is held'); + + $wt_pool = $pool; + weaken($wt_pool); + } + is($wt_pool, undef, 'timed-out pool handle freed cleanly'); + + # 3. Cancel path + my ($wc_pool, $wc_cb_token, $wc_cancel_token, $wc_item); + { + my $cb_token = { cancel_path => 1 }; + my $cancel_token = { cancel_guard => 1 }; + my $item = { id => 'k1' }; + $wc_cb_token = $cb_token; + $wc_cancel_token = $cancel_token; + $wc_item = $item; + weaken($wc_cb_token); + weaken($wc_cancel_token); + weaken($wc_item); + + my $pool = PVE::APIClient::AnyEvent::Pool::start( + items => [$item], + overall_timeout => 5, + start_item => sub { + my $keep = $cb_token; + my $ct = $cancel_token; + return sub { my $c = $ct }; + }, + on_done => sub { my $keep = $cb_token }, + ); + $pool->{cancel}->(); + undef $cb_token; + undef $cancel_token; + undef $item; + + is($wc_cb_token, undef, 'cancel frees user callbacks while pool handle is held'); + is( + $wc_cancel_token, + undef, + 'cancel frees active cancel closures while pool handle is held', + ); + is($wc_item, undef, 'cancel frees item while pool handle is held'); + + $wc_pool = $pool; + weaken($wc_pool); + } + is($wc_pool, undef, 'cancelled pool handle freed cleanly'); +}; + +subtest 'can_admit capacity gate vs can_dispatch backpressure timeout accounting' => sub { + # 1. can_admit => 0 keeps items queued WITHOUT pausing overall_timeout. + my $cv1 = AE::cv; + my $started1 = 0; + my $pool1 = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'a' }, { id => 'b' }], + overall_timeout => 0.08, + can_admit => sub { return 0 }, + start_item => sub { + $started1++; + return sub { }; + }, + on_done => sub { + my ($timed_out, $pending) = @_; + $cv1->send([$timed_out, $pending]); + }, + ); + my $res1 = $cv1->recv; + is($started1, 0, 'can_admit => 0 prevented starting items'); + is($res1->[0], 1, 'can_admit => 0 does NOT pause overall_timeout (timed out)'); + is_deeply($res1->[1], ['a', 'b'], 'all unadmitted items reported as pending on timeout'); + + # 2. When can_dispatch => 0 holds the last item back, overall_timeout pauses past deadline + # even if can_admit flips true while backpressured. + my $cv2 = AE::cv; + my $admit = 0; + my $allow_dispatch = 1; + my $started2 = 0; + my $pool2; + $pool2 = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'only' }], + overall_timeout => 0.1, + can_dispatch => sub { return $allow_dispatch }, + can_admit => sub { return $admit }, + start_item => sub { + my ($item, $finish) = @_; + $started2++; + $finish->(); + return undef; + }, + on_done => sub { + my ($timed_out, $pending) = @_; + $cv2->send([$timed_out, $pending]); + }, + ); + # Enter backpressure before timeout expires, then free capacity (admit = 1) while still + # backpressured, wait past the 0.1s deadline, then clear backpressure. + my $t1 = AE::timer( + 0.02, + 0, + sub { + $allow_dispatch = 0; + $pool2->{dispatch}->(); + }, + ); + my $t2 = AE::timer( + 0.05, + 0, + sub { + $admit = 1; + $pool2->{dispatch}->(); + }, + ); + my $t3 = AE::timer( + 0.22, + 0, + sub { + is( + $started2, + 0, + 'item stayed queued while backpressured even after can_admit became true', + ); + $allow_dispatch = 1; + $pool2->{dispatch}->(); + }, + ); + my $res2 = $cv2->recv; + is($started2, 1, 'item started once backpressure cleared'); + is($res2->[0], 0, 'backpressure paused overall_timeout past deadline'); + is_deeply($res2->[1], [], 'no pending items on clean completion'); +}; + +subtest 'shared capacity limiter across multiple pools' => sub { + my $cap = 3; + my $limiter = PVE::APIClient::AnyEvent::Pool::create_limiter(sub { return $cap; }); + + my $in_flight = 0; + my $peak = 0; + my %pending; + my @done_pools; + my $cv = AE::cv; + + my $make_pool = sub { + my ($prefix, $count) = @_; + my @items = map { { id => "$prefix-$_" } } (1 .. $count); + return PVE::APIClient::AnyEvent::Pool::start( + items => \@items, + max_concurrent => 2, + limiter => $limiter, + start_item => sub { + my ($item, $finish) = @_; + $in_flight++; + $peak = $in_flight if $in_flight > $peak; + $pending{ $item->{id} } = $finish; + return sub { + if (delete $pending{ $item->{id} }) { + $in_flight--; + } + }; + }, + on_done => sub { + my ($timed_out) = @_; + push @done_pools, [$prefix, $timed_out]; + $cv->send if @done_pools == 2; + }, + ); + }; + + # Pool A takes 2 slots, pool B takes 1 (and queues 1), pool C queues all 2. + my $pA = $make_pool->('A', 2); + my $pB = $make_pool->('B', 2); + my $pC = $make_pool->('C', 2); + + is($in_flight, 3, 'shared limiter caps total active items across pools at 3'); + is($limiter->{active}, 3, 'limiter active count matches in-flight items'); + + # Cancel pool B: its active slot frees and wakes pool C cleanly without leaking waiters. + $pB->{cancel}->(); + my $t_drive; + $t_drive = AE::timer( + 0.02, + 0.01, + sub { + my @keys = sort keys %pending; + if (@keys) { + my $k = shift @keys; + my $fin = delete $pending{$k}; + $in_flight--; + $fin->(); + } else { + undef $t_drive; + } + }, + ); + my $guard = AE::timer(2, 0, sub { $cv->croak('shared limiter test timed out'); }); + $cv->recv; + + is($peak, 3, 'peak concurrency never exceeded shared limiter cap'); + is($limiter->{active}, 0, 'limiter active count returned to 0 after completion and cancel'); + is(scalar(@{ $limiter->{waiters} }), 0, 'no stale waiters left in limiter queue'); + is_deeply( + [sort map { $_->[0] } @done_pools], + ['A', 'C'], + 'surviving pools A and C both completed after B was cancelled', + ); + + # Pool waiting on a saturated limiter still times out against overall_timeout. + my $full_lim = PVE::APIClient::AnyEvent::Pool::create_limiter(1); + my $holder_fin; + my $holder = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'hold' }], + limiter => $full_lim, + start_item => sub { + my (undef, $finish) = @_; + $holder_fin = $finish; + return undef; + }, + on_done => sub { }, + ); + my $cv_to = AE::cv; + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'blocked' }], + limiter => $full_lim, + overall_timeout => 0.05, + start_item => sub { fail('should not start while limiter is full'); }, + on_done => sub { $cv_to->send([@_]); }, + ); + my $to_res = $cv_to->recv; + is($to_res->[0], 1, 'pool waiting on full shared limiter timed out'); + is_deeply($to_res->[1], ['blocked'], 'timed-out limiter waiter reported pending item'); + $holder_fin->(); + is($full_lim->{active}, 0, 'limiter active count returned to 0 after holder finished'); + + # A throwing dynamic limiter callback warns without leaving the pool stuck in dispatching=1. + my $throw_once = 1; + my $flaky_lim = PVE::APIClient::AnyEvent::Pool::create_limiter(sub { + die "transient cap error\n" if $throw_once; + return 1; + }); + my @warnings; + my $flaky_started = 0; + my $cv_flaky = AE::cv; + my $flaky_pool; + { + local $SIG{__WARN__} = sub { push @warnings, $_[0]; }; + $flaky_pool = PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'retry-me' }], + limiter => $flaky_lim, + start_item => sub { + my (undef, $finish) = @_; + $flaky_started++; + $finish->(); + return undef; + }, + on_done => sub { $cv_flaky->send($_[0]); }, + ); + } + is($flaky_started, 0, 'throwing dynamic limiter held item without crashing'); + like(join('', @warnings), qr/transient cap error/, 'throwing dynamic limiter logged warning'); + $throw_once = 0; + $flaky_pool->{dispatch}->(); + is($cv_flaky->recv(), 0, 'pool dispatched and completed cleanly once dynamic limiter recovered'); + is($flaky_started, 1, 'queued item ran after dynamic limiter recovered'); +}; + +subtest 'resume_timeout respects monotonic budget despite stale loop clock' => sub { + require Time::HiRes; + # Make AE::now lag behind monotonic time by sleeping inside a callback without now_update(). + AnyEvent->now_update(); + Time::HiRes::usleep(120_000); + + my $timed_out; + my $item_timer; + my $res = run_with_timeout( + sub { + my ($cv) = @_; + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'n1' }], + overall_timeout => 0.15, + start_item => sub { + my (undef, $finish) = @_; + AnyEvent->now_update(); + $item_timer = AE::timer(0.05, 0, sub { + undef $item_timer; + $finish->(); + }); + return sub { undef $item_timer; }; + }, + on_done => sub { + ($timed_out) = @_; + $cv->send($timed_out); + }, + ); + }, + 2, + ); + is($res, 0, 'pool did not time out early when started with stale AE::now'); +}; + +subtest 're-entrant limiter slot release inside wake_limiter_waiters does not strand waiters' => sub { + my $lim = PVE::APIClient::AnyEvent::Pool::create_limiter(1); + my $a_finish; + my ($b_started, $c_started, $c_done) = (0, 0, 0); + + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'a1' }], + limiter => $lim, + start_item => sub { + my (undef, $finish) = @_; + $a_finish = $finish; + return undef; + }, + on_done => sub { }, + ); + + my $cv_c = AE::cv; + # Pool B waits on the cap-1 limiter; when woken, its start_item queues Pool C while holding + # the slot and then completes synchronously (re-entering wake_limiter_waiters). + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'b1' }], + limiter => $lim, + start_item => sub { + my (undef, $finish) = @_; + $b_started++; + PVE::APIClient::AnyEvent::Pool::start( + items => [{ id => 'c1' }], + limiter => $lim, + start_item => sub { + my (undef, $c_finish) = @_; + $c_started++; + $c_finish->(); + return undef; + }, + on_done => sub { + $c_done = 1; + $cv_c->send(1); + }, + ); + $finish->(); + return undef; + }, + on_done => sub { }, + ); + + $a_finish->(); + + my $guard = AE::timer(2, 0, sub { $cv_c->croak('re-entrant limiter waiter C stranded'); }); + is($cv_c->recv(), 1, 'newly queued pool C woke after re-entrant synchronous release'); + is($b_started, 1, 'pool B ran once'); + is($c_started, 1, 'pool C ran once'); + is($c_done, 1, 'pool C completed'); + is($lim->{active}, 0, 'limiter active count returned to 0'); + is(scalar(@{ $lim->{waiters} }), 0, 'no waiters left stranded in limiter'); +}; + +done_testing(); -- 2.47.3