From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 62E1A1FF0B7 for ; Mon, 30 Nov 2026 02:02:42 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 730C8217F2; Mon, 30 Nov 2026 02:01:59 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH apiclient 05/09] add bounded AnyEvent request pool with backpressure and timeout Date: Mon, 30 Nov 2026 01:58:09 +0100 Message-ID: <20261130010113.2166775-6-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com> References: <20261130010113.2166775-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: 1796000480904 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.853 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: QQA2CA4LZKE74FJNTHRKMAR5O253TLMR X-Message-ID-Hash: QQA2CA4LZKE74FJNTHRKMAR5O253TLMR 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 --- src/Makefile | 3 +- src/PVE/APIClient/AnyEvent/Pool.pm | 272 ++++++++++++ src/test/anyevent_pool.t | 690 +++++++++++++++++++++++++++++ 3 files changed, 964 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..518b998 --- /dev/null +++ b/src/PVE/APIClient/AnyEvent/Pool.pm @@ -0,0 +1,272 @@ +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; + +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; +} + +my sub cleanup_state($state) { + my @cancels = grep { ref($_) eq 'CODE' } values %{ $state->{active} }; + # 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 on_start_error)}; + + for my $cancel (@cancels) { + invoke_callback($cancel); + } +} + +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}); + + AnyEvent->now_update(); + my $elapsed = AnyEvent->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}); + + AnyEvent->now_update(); + $state->{timeout_started_at} = AnyEvent->time; + $state->{timeout_watcher} = AE::timer( + $state->{remaining_timeout}, + 0, + sub { + 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}); + + AnyEvent->now_update(); + my $elapsed = AnyEvent->time - $state->{timeout_started_at}; + $elapsed = 0 if $elapsed < 0; + return $elapsed >= $state->{remaining_timeout} ? 1 : 0; +} + +my sub check_can_dispatch($state) { + my $can_dispatch = $state->{can_dispatch}; + return 1 if !$can_dispatch; + + my $ok = eval { $can_dispatch->() }; + 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_can_dispatch($state); + 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}; + + resume_timeout($state); + if (timeout_expired($state)) { + $timed_out = 1; + last; + } + + my $item = shift @{ $state->{queue} }; + my $id = $item->{id}; + my $item_done = 0; + + $state->{active}->{$id} = undef; + + my $finish_item = sub { + return if $item_done; + $item_done = 1; + return if $state->{done}; + + delete $state->{active}->{$id}; + $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}; + } + 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 && ref($cancel) eq 'CODE') { + invoke_callback($cancel); + } + } elsif (!$item_done) { + $state->{active}->{$id} = 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 using `can_dispatch` must invoke `$pool->{dispatch}->()` when backpressure starts or +# clears: `overall_timeout` suspends while queued items are held back by `can_dispatch` (once the +# queue is empty, active items stay subject to the deadline), and a backpressured pool with no +# active items stays paused until `dispatch()` is called. A throwing `can_dispatch` warns and stops +# dispatch without pausing `overall_timeout` (without a timeout, queued items stay paused until a +# later `dispatch()` succeeds or `cancel()` runs). 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, $on_start_error) = + @opts{ 'items', 'start_item', 'on_done', 'can_dispatch', 'on_start_error' }; + 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($on_start_error) && ref($on_start_error) ne 'CODE') { + croak "on_start_error must be a CODE ref"; + } + + my $max_concurrent = $opts{max_concurrent} // 16; + if (ref($max_concurrent) || $max_concurrent !~ /^[0-9]+$/ || $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]+)$/ + || $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, + on_start_error => $on_start_error, + max_concurrent => $max_concurrent, + }; + + 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..30657f7 --- /dev/null +++ b/src/test/anyevent_pool.t @@ -0,0 +1,690 @@ +#!/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'); +}; + +done_testing(); -- 2.47.3