public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH manager v2 7/9] api: metrics export: stream sorted metrics via incremental k-way merge
Date: Tue,  1 Dec 2026 11:19:02 +0100	[thread overview]
Message-ID: <20261201101913.1885484-8-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261201101913.1885484-1-t.lamprecht@proxmox.com>

Even with non-blocking peer fan-out, decoding all remote metrics into
Perl hashes before sorting and gzip-compressing consumes ~950 B per
metric (~973 MiB VmHWM at 1 million metrics) and still stalls the
pveproxy worker during JSON encoding and compression.

Add PVE::PullMetricExport::Reader (an incremental gzip+JSON scanner
using 256 KiB compressed input slices and 64 KiB Compress::Raw::Zlib
inflate chunks for remote peers, or direct buffer scanning for plain
local_json), a binary min-heap, cooperative 256 KiB slice scheduling,
and build_kway_merge_stream() to PVE::PullMetricExport, and wire
PVE::PullMetricExport::export() to return an AsyncStreamResponse when
PVE::APIServer::AnyEvent::async_stream_supported() is true. The HTTP
server owns the outer json/extjs API2 envelope while PullMetricExport
emits the inner {"data":[...]} payload.

Remote peer bodies stay gzip-compressed while fetching and are merged
in global timestamp order without allocating per-metric Perl hashes.
For flat printable-ASCII objects, Reader validates the object and
extracts its signed 64-bit integer timestamp without building a Perl
hash. For escapes, UTF-8, or nested values, it locates the object end,
decodes the object, checks its signed 64-bit integer timestamp
(rejecting strings, integral floats like 1.0/1e2, and overflows), and
rejects duplicate top-level timestamp keys. Both paths enforce the
4 MiB per-object size limit. By default, a peer that fails to open or
yield its first metric is skipped with a warning. With fail-on-error=1,
a first-read error produces API status 502 before streaming starts and a
peer or fan-out timeout produces 504; a subsequent reader error or
decreasing per-peer timestamp aborts the response instead of closing
with HTTP 200. Slices are scheduled via AnyEvent->idle paired with a
clock-synced 10 ms fallback timer.

Measured on a single pveproxy worker in a mock harness (25 ms per-peer
latency, RSA-2048 TLS with SHA-256 pinning, gzip, 16-peer per-export
cap, 34 FDs; scenarios are nodes x guests, hist10 = 10 history
generations per node, TTFB = time to first byte, Buffered = async
fan-out decoding all remote metrics into Perl hashes before JSON
encoding and gzip, Max /ping HOL = maximum concurrent /ping head-of-line
latency on the same worker):

Scenario            | Mode          |  Total |  TTFB |    VmHWM | Max /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest       | Sync LWP      | 1034ms |    -  | 106 MiB  |       1024 ms
(25,475 metrics)    | K-way stream  |  196ms | 114ms |  84 MiB  |        5.0 ms
25x100 hist10       | Sync LWP      | 2302ms |    -  | 338 MiB  |       2354 ms
(254,750 metrics)   | K-way stream  |  871ms | 123ms |  99 MiB  |        9.4 ms
100x100 latest      | Sync LWP      | 4195ms |    -  | 180 MiB  |       4178 ms
(101,900 metrics)   | K-way stream  |  687ms | 399ms |  91 MiB  |        7.3 ms
100x1000            | Buffered      |  5.1 s |    -  | 973 MiB  |         -
(1,001,900 metrics) | K-way stream  | 3296ms | 397ms | 103 MiB  |        9.5 ms

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---

Changes in v2:
- Account queued peer payloads and active heap readers against the
  worker-wide retained-byte admission threshold, releasing bytes
  incrementally as each peer reader exhausts or on stream cleanup, and
  drop local_json from %opts once handed to the starter.
- Validate original signed 64-bit JSON integer timestamp tokens
  (inclusive INT64_MIN to INT64_MAX, rejecting strings, integral floats
  like 1.0/1e2, overflows, and literal/escaped duplicate keys; fast-path
  <=18-char integer tokens on the flat path) and the 4 MiB per-object
  size limit identically across flat Reader, fallback Reader, and
  buffered decode_peer_metrics().
- Retain incremental fallback object-scanner state across 64 KiB inflate
  refills so multi-chunk objects scan in linear time, and document
  Reader's PVE-specific envelope scope.
- Abort k-way merge on decreasing per-peer timestamps and propagate
  pre-start fail-on-error=1 failures as API status 504/502 (halting
  synchronous initial dispatch on strict failure).
- Refresh benchmark numbers against the v2 implementation.

 PVE/Makefile                   |   2 +-
 PVE/PullMetricExport.pm        | 400 ++++++++++++++++++++++++++++++---
 PVE/PullMetricExport/Makefile  |  15 ++
 PVE/PullMetricExport/Reader.pm | 396 ++++++++++++++++++++++++++++++++
 4 files changed, 783 insertions(+), 30 deletions(-)
 create mode 100644 PVE/PullMetricExport/Makefile
 create mode 100644 PVE/PullMetricExport/Reader.pm

diff --git a/PVE/Makefile b/PVE/Makefile
index 81a42f8d0..b4b1be303 100644
--- a/PVE/Makefile
+++ b/PVE/Makefile
@@ -1,6 +1,6 @@
 include ../defines.mk
 
-SUBDIRS=API2 Status CLI Service Ceph Jobs
+SUBDIRS=API2 Status CLI Service Ceph Jobs PullMetricExport
 
 PERLSOURCE = 			\
 	API2.pm			\
diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm
index 867909977..272d9bb1a 100644
--- a/PVE/PullMetricExport.pm
+++ b/PVE/PullMetricExport.pm
@@ -1,14 +1,16 @@
 package PVE::PullMetricExport;
 
-# Asynchronous cluster-wide pull-metric fan-out for GET /cluster/metrics/export.
-# export() fetches remote nodes concurrently (capped via PVE::APIClient::AnyEvent::Pool),
-# returning a deferred PVE::APIServer::AnyEvent::AsyncResponse inside pveproxy or blocking on an
-# AnyEvent CondVar for CLI/pvesh callers.
+# Asynchronous cluster-wide pull-metric fan-out and streaming export for GET
+# /cluster/metrics/export. export() selects between two paths:
+# - Incremental k-way merge stream (default when AsyncStream is supported): keeps remote peer
+#   responses gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then
+#   merges local and remote streams in global timestamp order in cooperative 256 KiB slices.
+# - Buffered async_response (non-stream HTTP formats) or AnyEvent CondVar (CLI/pvesh callers).
 
 use v5.36;
 
 use AnyEvent;
-use B;
+use JSON qw(decode_json encode_json);
 
 use PVE::APIClient::AnyEvent;
 use PVE::APIClient::AnyEvent::Pool;
@@ -16,11 +18,18 @@ use PVE::APIServer::AnyEvent;
 use PVE::Exception;
 use PVE::SafeSyslog ();
 
+use PVE::PullMetricExport::Reader;
+
 our $MAX_WORKER_CONCURRENT_PEERS = 32;
 # Dispatch admission threshold on completed retained wire bodies across overlapping exports (not a
 # hard worker RSS bound: in-flight responses are charged on completion, buffered mode retains
 # decoded hashes, and the oldest all-peers export may exceed it to avoid self-deadlock).
 our $MAX_WORKER_RETAINED_BYTES = 128 * 1024 * 1024;
+our $STREAM_SLICE_BYTES = 262144;
+our $SLICE_FALLBACK_INTERVAL = 0.01;
+
+my $STREAM_PREFIX = '{"data":[';
+my $STREAM_SUFFIX = ']}';
 
 my $WORKER_RETAINED_BYTES = 0;
 my @WORKER_ALL_PEERS_HOLDERS;
@@ -280,34 +289,24 @@ my sub start_metric_fanout(%opts) {
     );
 }
 
-my sub validate_integer_timestamp($val) {
-    return undef if !defined($val) || ref($val);
-    my $flags = B::svref_2object(\$val)->FLAGS;
-    return undef if ($flags & (B::SVf_POK | B::SVf_NOK | B::SVf_IVisUV)) || !($flags & B::SVf_IOK);
-    return $val + 0;
-}
-
 my sub decode_peer_metrics($body_ref, $is_gzip = 0) {
-    my $decoded = PVE::APIClient::AnyEvent::decode_json_body($body_ref, $is_gzip);
-    if (
-        ref($decoded) ne 'HASH'
-        || ref($decoded->{data}) ne 'HASH'
-        || ref($decoded->{data}->{data}) ne 'ARRAY'
-    ) {
-        die "unexpected response format\n";
-    }
-
-    my $items = $decoded->{data}->{data};
-    for my $item (@$items) {
-        if (ref($item) ne 'HASH') {
-            die "unexpected metric entry format\n";
+    # Validate through Reader so buffered and streaming exports enforce identical wire timestamp
+    # range, duplicate-key rejection, and per-object size limits.
+    my $reader = PVE::PullMetricExport::Reader->open(body => $$body_ref, gzip => $is_gzip);
+    my @items;
+    eval {
+        while (defined(my $obj = $reader->next())) {
+            my $entry = decode_json($obj);
+            $entry->{timestamp} = $reader->ts();
+            push @items, $entry;
         }
-        my $ts = validate_integer_timestamp($item->{timestamp});
-        die "unexpected metric entry format\n" if !defined($ts);
-        $item->{timestamp} = $ts;
+    };
+    if (my $err = $@) {
+        $reader->close();
+        die $err;
     }
 
-    return $items;
+    return \@items;
 }
 
 sub build_buffered_fanout(%opts) {
@@ -399,9 +398,352 @@ sub build_buffered_fanout(%opts) {
     };
 }
 
+my sub open_peer_reader($name, $body, $is_gzip, $fail_on_error = 0) {
+    my $reader;
+    my $first_obj = eval {
+        $reader = PVE::PullMetricExport::Reader->open(
+            body => $body,
+            gzip => $is_gzip,
+        );
+        undef $body;
+        return $reader->next();
+    };
+    if (my $err = $@) {
+        log_peer_error($name, $err);
+        $reader->close() if $reader;
+        if ($fail_on_error) {
+            die PVE::Exception->new("could not fetch metrics from $name: $err", code => 502);
+        }
+        return undef;
+    }
+
+    return undef if !defined($first_obj);
+    return {
+        name => $name,
+        reader => $reader,
+        obj => $first_obj,
+        ts => $reader->ts(),
+    };
+}
+
+my sub heap_push($heap, $entry) {
+    push @$heap, $entry;
+    my $idx = $#$heap;
+    while ($idx > 0) {
+        my $parent = int(($idx - 1) / 2);
+        last if $heap->[$parent]->{ts} <= $heap->[$idx]->{ts};
+        @{$heap}[$parent, $idx] = @{$heap}[$idx, $parent];
+        $idx = $parent;
+    }
+}
+
+my sub heap_sift_down($heap, $idx) {
+    my $size = scalar(@$heap);
+    while (1) {
+        my $left = 2 * $idx + 1;
+        last if $left >= $size;
+        my $right = $left + 1;
+        my $smallest =
+            ($right < $size && $heap->[$right]->{ts} < $heap->[$left]->{ts}) ? $right : $left;
+        last if $heap->[$idx]->{ts} <= $heap->[$smallest]->{ts};
+        @{$heap}[$idx, $smallest] = @{$heap}[$smallest, $idx];
+        $idx = $smallest;
+    }
+}
+
+# Return the second-smallest timestamp in the min-heap so kway_merge_step can drain consecutive
+# metrics from the top node without sifting down until its timestamp exceeds the next node.
+my sub heap_second_min_ts($heap) {
+    return undef if @$heap <= 1;
+    if (@$heap > 2 && $heap->[2]->{ts} < $heap->[1]->{ts}) {
+        return $heap->[2]->{ts};
+    }
+    return $heap->[1]->{ts};
+}
+
+my sub clear_slice_watchers($state) {
+    delete @{$state}{qw(slice_idle slice_timer)};
+}
+
+my sub cleanup_stream($state) {
+    clear_slice_watchers($state);
+    if (my $fanout = delete $state->{fanout}) {
+        $fanout->{cancel}->();
+    }
+    release_all_peer_bytes($state);
+    delete $state->{local_json};
+    @{ $state->{peer_payloads} } = () if $state->{peer_payloads};
+    @{ $state->{ready_peers} } = () if $state->{ready_peers};
+    if (my $heap = $state->{heap}) {
+        $_->{reader}->close() for @$heap;
+        @$heap = ();
+    }
+    if (my $active = delete $state->{active_reader}) {
+        $active->{reader}->close();
+    }
+    delete $state->{stream};
+}
+
+my sub abort_stream($state, $err = undef) {
+    return if $state->{done};
+    $state->{done} = 1;
+    my $stream = $state->{stream};
+    cleanup_stream($state);
+    $stream->abort($err) if $stream && !$stream->is_closed();
+}
+
+my sub schedule_slice($state, $cb) {
+    clear_slice_watchers($state);
+
+    my $run = sub {
+        clear_slice_watchers($state);
+        eval { $cb->(); };
+        abort_stream($state, $@) if $@;
+    };
+
+    # AnyEvent::Loop skips select() when timers are already due, while idle alone can starve under
+    # continuous competing I/O. Sync the loop clock before arming the fallback timer so its
+    # deadline stays strictly in the future and ready I/O runs first.
+    AnyEvent->now_update();
+    $state->{slice_idle} = AnyEvent->idle(cb => $run);
+    $state->{slice_timer} = AnyEvent->timer(after => $SLICE_FALLBACK_INTERVAL, cb => $run);
+}
+
+my sub finish_stream($state, $out) {
+    my $stream = $state->{stream};
+    $out .= $STREAM_SUFFIX;
+    $state->{done} = 1;
+    cleanup_stream($state);
+    return if !$stream || $stream->is_closed();
+    eval {
+        $stream->write($out);
+        $stream->finish();
+    };
+    if (my $err = $@) {
+        $stream->abort($err) if !$stream->is_closed();
+    }
+}
+
+my sub after_stream_write($state, $ok, $step_cb, $notify_pool = undef) {
+    my $stream = $state->{stream};
+    return if $state->{done} || !$stream || $stream->is_closed();
+
+    if (!$ok || $stream->is_backpressured()) {
+        clear_slice_watchers($state);
+        $state->{waiting_drain} = 1;
+        # Poke pool dispatch right as backpressure begins so the pool re-evaluates can_dispatch()
+        # and pauses its overall_timeout budget while waiting for on_drain.
+        $notify_pool->() if $notify_pool;
+        $stream->on_drain(sub {
+            $state->{waiting_drain} = 0;
+            return if $state->{done} || $stream->is_closed();
+            eval {
+                $notify_pool->() if $notify_pool;
+                $step_cb->();
+            };
+            abort_stream($state, $@) if $@;
+        });
+    } else {
+        $notify_pool->() if $notify_pool;
+        schedule_slice($state, $step_cb);
+    }
+}
+
+my sub kway_merge_step($state) {
+    my $self = __SUB__;
+    clear_slice_watchers($state);
+    my $stream = $state->{stream};
+    return if $state->{done} || !$stream || $stream->is_closed();
+
+    my $out = '';
+    if (!$state->{started_stream}) {
+        $state->{started_stream} = 1;
+        return if !$stream->start();
+        $out = $STREAM_PREFIX;
+    }
+
+    my $heap = $state->{heap};
+    while (@$heap && length($out) < $STREAM_SLICE_BYTES) {
+        my $top = $heap->[0];
+        my $reader = $top->{reader};
+        my $next_min_ts = heap_second_min_ts($heap);
+        my $exhausted = 0;
+
+        eval {
+            while (length($out) < $STREAM_SLICE_BYTES) {
+                $out .= ',' if !$state->{first_item};
+                $state->{first_item} = 0;
+                $out .= $top->{obj};
+
+                my $prev_ts = $top->{ts};
+                my $obj = $reader->next();
+                if (!defined($obj)) {
+                    $exhausted = 1;
+                    last;
+                }
+                my $next_ts = $reader->ts();
+                die "non-monotonic peer timestamps ($next_ts < $prev_ts)\n"
+                    if $next_ts < $prev_ts;
+                $top->{obj} = $obj;
+                $top->{ts} = $next_ts;
+
+                if (defined($next_min_ts) && $top->{ts} > $next_min_ts) {
+                    heap_sift_down($heap, 0);
+                    last;
+                }
+            }
+        };
+        if (my $err = $@) {
+            log_peer_error($top->{name}, $err);
+            $reader->close();
+            abort_stream($state, "could not stream metrics from $top->{name}: $err");
+            return;
+        }
+
+        if ($exhausted) {
+            release_peer_bytes($state, delete $top->{retained_bytes});
+            my $last = pop @$heap;
+            if (@$heap) {
+                $heap->[0] = $last;
+                heap_sift_down($heap, 0);
+            }
+        }
+    }
+
+    if (!@$heap) {
+        finish_stream($state, $out);
+        return;
+    }
+
+    my $ok = $stream->write($out);
+    after_stream_write($state, $ok, sub { $self->($state) });
+}
+
+sub build_kway_merge_stream(%opts) {
+    my $local_json = delete $opts{local_json};
+    my $fail_on_error = $opts{fail_on_error} ? 1 : 0;
+
+    return sub {
+        my ($stream) = @_;
+
+        my $state = {
+            stream => $stream,
+            done => 0,
+            needs_all_peers => 1,
+            retained_bytes => 0,
+            local_json => $local_json,
+            peer_payloads => [],
+            heap => [],
+            started_stream => 0,
+            first_item => 1,
+        };
+        undef $local_json;
+
+        my $fanout = start_metric_fanout(
+            %opts,
+            is_done => sub { return $state->{done}; },
+            byte_state => $state,
+            on_peer => sub {
+                my ($name, $body_ref, $is_gzip) = @_;
+                return if $state->{done};
+                my $bytes = length($$body_ref // '');
+                retain_peer_bytes($state, $bytes);
+                push @{ $state->{peer_payloads} },
+                    {
+                        name => $name,
+                        body => $$body_ref,
+                        gzip => $is_gzip,
+                        retained_bytes => $bytes,
+                    };
+            },
+            on_peer_error => $fail_on_error
+            ? sub {
+                my ($name, $err, $code) = @_;
+                abort_stream(
+                    $state,
+                    PVE::Exception->new(
+                        "could not fetch metrics from $name: $err",
+                        code => $code,
+                    ),
+                );
+            }
+            : undef,
+            on_done => sub($timed_out, $timeout) {
+                return if $state->{done} || $stream->is_closed();
+                delete $state->{fanout};
+
+                if ($timed_out) {
+                    abort_stream(
+                        $state,
+                        PVE::Exception->new(
+                            "cluster metric fan-out timed out after ${timeout}s\n",
+                            code => 504,
+                        ),
+                    );
+                    return;
+                }
+
+                eval {
+                    if (defined(my $local = delete $state->{local_json})) {
+                        if (my $entry = open_peer_reader('local', $local, 0, $fail_on_error)) {
+                            heap_push($state->{heap}, $entry);
+                        }
+                    }
+
+                    my $payloads = $state->{peer_payloads};
+                    while (my $peer = shift @$payloads) {
+                        my $bytes = $peer->{retained_bytes};
+                        my $entry = open_peer_reader(
+                            $peer->{name},
+                            $peer->{body},
+                            $peer->{gzip},
+                            $fail_on_error,
+                        );
+                        undef $peer;
+                        if ($entry) {
+                            $entry->{retained_bytes} = $bytes;
+                            heap_push($state->{heap}, $entry);
+                        } else {
+                            release_peer_bytes($state, $bytes);
+                        }
+                    }
+
+                    kway_merge_step($state);
+                };
+                abort_stream($state, $@) if $@;
+            },
+        );
+        if ($state->{done}) {
+            $fanout->{cancel}->();
+        } else {
+            $state->{fanout} = $fanout;
+        }
+
+        return sub {
+            return if $state->{done};
+            $state->{done} = 1;
+            cleanup_stream($state);
+        };
+    };
+}
+
 sub export(%opts) {
     my $metrics = $opts{metrics} // [];
 
+    if (PVE::APIServer::AnyEvent::async_stream_supported()) {
+        my $local_json;
+        if (@$metrics) {
+            # Encode local metrics into the same wire envelope as remote peers so the streaming
+            # reader and k-way merge heap drain local and remote sources uniformly.
+            @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+            $local_json = encode_json({ data => { data => $metrics } });
+            @$metrics = ();
+        }
+        return PVE::APIServer::AnyEvent::async_stream_response(
+            build_kway_merge_stream(%opts, local_json => $local_json),
+        );
+    }
+
     my $finalize = sub {
         # In-place sort avoids allocating a second copy of large metric arrays.
         @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
diff --git a/PVE/PullMetricExport/Makefile b/PVE/PullMetricExport/Makefile
new file mode 100644
index 000000000..5098a6e52
--- /dev/null
+++ b/PVE/PullMetricExport/Makefile
@@ -0,0 +1,15 @@
+include ../../defines.mk
+
+PERLSOURCE = 			\
+	Reader.pm
+
+all:
+
+.PHONY: clean
+clean:
+	rm -rf *~
+
+.PHONY: install
+install: $(PERLSOURCE)
+	install -d $(PERLLIBDIR)/PVE/PullMetricExport
+	install -m 0644 $(PERLSOURCE) $(PERLLIBDIR)/PVE/PullMetricExport
diff --git a/PVE/PullMetricExport/Reader.pm b/PVE/PullMetricExport/Reader.pm
new file mode 100644
index 000000000..d4ee00c4f
--- /dev/null
+++ b/PVE/PullMetricExport/Reader.pm
@@ -0,0 +1,396 @@
+package PVE::PullMetricExport::Reader;
+
+# Incremental gzip+JSON metric array reader for remote peer responses and local_json.
+# Intentionally specialized by design for PVE's local-only endpoint exact envelope
+# ({"data":{"data":[...]}}); additional envelope members are not supported.
+# Scans in bounded 256 KiB compressed input slices and 64 KiB inflate chunks (or scans plain
+# local_json directly), validating flat printable-ASCII RFC 8259 objects without allocating
+# per-metric Perl hashes (falling back to quote/brace scanning + decode_json for escapes, UTF-8,
+# or nesting, rejecting duplicate timestamp keys and non-i64 timestamps).
+# Contract: open(body => $str, gzip => $bool) validates the opening envelope; next() returns each
+# raw JSON object string (enforcing unique signed 64-bit integer timestamp and max object size,
+# updating obj()/ts()) or undef on clean EOF; dies on corrupt, malformed, oversized, truncated, or
+# trailing data (callers call close() on error).
+
+use v5.36;
+
+use B;
+use Compress::Raw::Zlib qw(WANT_GZIP Z_OK Z_STREAM_END Z_BUF_ERROR);
+use JSON qw(decode_json);
+
+our $GZIP_INPUT_CHUNK_BYTES = 262144;
+our $MAX_METRIC_OBJECT_BYTES = 4 * 1024 * 1024;
+my $INT64_MIN = -9223372036854775807 - 1;
+
+# Validate a raw JSON wire token as an unquoted signed 64-bit JSON integer in
+# [-9223372036854775808, 9223372036854775807] (rejecting strings, integral floats like 1.0/1e2,
+# booleans, nulls, and out-of-range values) and return its Perl signed IV, or undef if invalid.
+sub parse_signed_int64_token($tok) {
+    return undef if !defined($tok) || $tok !~ /\A-?(?:0|[1-9][0-9]*)\z/;
+    return $INT64_MIN if $tok eq '-9223372036854775808';
+    my $num = $tok + 0;
+    my $flags = B::svref_2object(\$num)->FLAGS;
+    return undef if ($flags & (B::SVf_NOK | B::SVf_IVisUV)) || !($flags & B::SVf_IOK);
+    return $num;
+}
+
+# Extract the raw wire token of the unique top-level key decoding to "timestamp" in a validated
+# JSON object string, dying on duplicate top-level timestamp keys (including escaped forms).
+my sub extract_unique_timestamp_token($obj) {
+    my $count = 0;
+    my $ts_tok;
+    my $depth = 0;
+    my $expect_key = 0;
+    my $expect_ts_val = 0;
+    pos($obj) = 0;
+
+    while ($obj =~ /\G[ \t\r\n]*(\{|\}|\[|\]|:|,|"(?:[^"\\]++|\\.)*+"|[^ \t\r\n\{\}\[\]:,"]+)/gc) {
+        my $tok = $1;
+        if ($expect_ts_val) {
+            next if $tok eq ':';
+            $expect_ts_val = 0;
+            $ts_tok = $tok if !defined($ts_tok);
+        }
+        if ($tok eq '{' || $tok eq '[') {
+            $depth++;
+            $expect_key = 1 if $depth == 1 && $tok eq '{';
+        } elsif ($tok eq '}' || $tok eq ']') {
+            $depth--;
+        } elsif ($depth == 1 && $tok eq ',') {
+            $expect_key = 1;
+        } elsif ($depth == 1 && $expect_key && substr($tok, 0, 1) eq '"') {
+            $expect_key = 0;
+            if ($tok eq '"timestamp"') {
+                $count++;
+                $expect_ts_val = 1;
+            } elsif (index($tok, '\\') >= 0) {
+                my $key = decode_json("[$tok]")->[0];
+                if ($key eq 'timestamp') {
+                    $count++;
+                    $expect_ts_val = 1;
+                }
+            }
+        }
+    }
+
+    die "duplicate timestamp key\n" if $count > 1;
+    return $count == 1 ? $ts_tok : undef;
+}
+
+# Exact RFC 8259 flat JSON object grammar restricted to printable ASCII strings without escapes.
+# Composed as strings before compiling once to avoid nested (?^:...) regex scopes in the hot loop.
+my $JSON_WS = '[ \t\r\n]*';
+my $JSON_ASCII_STR = '"[\x20\x21\x23-\x5b\x5d-\x7e]*"';
+my $JSON_NUM = '-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?';
+my $JSON_PRIM = "(?:$JSON_ASCII_STR|$JSON_NUM|true|false|null)";
+my $JSON_FLAT_PAIR = "$JSON_ASCII_STR$JSON_WS:$JSON_WS$JSON_PRIM";
+my $JSON_NON_TS_PAIR = "(?!\"timestamp\"$JSON_WS:)$JSON_FLAT_PAIR";
+my $FLAT_JSON_OBJ_RE =
+    qr/\G(\{$JSON_WS(?:$JSON_NON_TS_PAIR$JSON_WS,$JSON_WS)*+"timestamp"$JSON_WS:$JSON_WS(-?(?:0|[1-9][0-9]*))(?:$JSON_WS,$JSON_WS$JSON_NON_TS_PAIR)*+$JSON_WS\})/;
+my $ENVELOPE_OPEN_RE =
+    qr/\G$JSON_WS\{$JSON_WS"data"$JSON_WS:$JSON_WS\{$JSON_WS"data"$JSON_WS:$JSON_WS\[/;
+my $ENVELOPE_CLOSE_RE = qr/\G$JSON_WS\}$JSON_WS\}$JSON_WS\z/;
+
+# Incrementally scan a JSON object starting at $start, resuming from $scan across refills so
+# multi-chunk objects take linear work. $scan->{offset} is relative to $start (invariant across
+# refill() buffer compaction). Returns the index right after the matching '}', or undef if
+# incomplete (updating $scan in place).
+my sub find_json_object_end($buf_ref, $start, $scan, $max_bytes = $MAX_METRIC_OBJECT_BYTES) {
+    my $len = length($$buf_ref);
+    my $limit = $start + $max_bytes;
+    my $depth = $scan->{depth};
+    my $in_string = $scan->{in_string};
+    my $cur = $start + $scan->{offset};
+
+    if ($scan->{escaped}) {
+        return undef if $cur >= $len;
+        $cur += 1;
+        $scan->{escaped} = 0;
+        if ($cur > $limit) {
+            die "metric object exceeds maximum size\n";
+        }
+    }
+
+    pos($$buf_ref) = $cur;
+
+    while ($$buf_ref =~ /(["{}\\])/gc) {
+        my $after = pos($$buf_ref);
+        if ($after > $limit) {
+            die "metric object exceeds maximum size\n";
+        }
+        my $tok = $1;
+        if ($in_string) {
+            if ($tok eq '\\') {
+                if ($after >= $len) {
+                    $scan->{depth} = $depth;
+                    $scan->{in_string} = 1;
+                    $scan->{escaped} = 1;
+                    $scan->{offset} = $after - $start;
+                    return undef;
+                }
+                pos($$buf_ref) = $after + 1;
+                if ($after + 1 > $limit) {
+                    die "metric object exceeds maximum size\n";
+                }
+            } elsif ($tok eq '"') {
+                $in_string = 0;
+            }
+        } elsif ($tok eq '"') {
+            $in_string = 1;
+        } elsif ($tok eq '{') {
+            $depth++;
+        } elsif ($tok eq '}') {
+            $depth--;
+            if ($depth == 0) {
+                die "metric object exceeds maximum size\n" if $after - $start > $max_bytes;
+                return $after;
+            }
+        }
+    }
+
+    $scan->{depth} = $depth;
+    $scan->{in_string} = $in_string;
+    $scan->{escaped} = 0;
+    $scan->{offset} = $len - $start;
+    return undef;
+}
+
+my sub refill($self) {
+    return 0 if $self->{eof};
+
+    # Compact the already-parsed prefix before inflating the next 64 KiB chunk so buffer memory
+    # stays bounded across multi-megabyte peer payloads.
+    if ($self->{pos} > 0) {
+        substr($self->{buf}, 0, $self->{pos}, '');
+        $self->{pos} = 0;
+    }
+
+    while (1) {
+        if (!length($self->{in_chunk}) && defined($self->{input})) {
+            $self->{in_chunk} = substr($self->{input}, $self->{input_pos}, $GZIP_INPUT_CHUNK_BYTES);
+            $self->{input_pos} += length($self->{in_chunk});
+            undef $self->{input} if $self->{input_pos} >= length($self->{input});
+        }
+
+        my $prev_in = length($self->{in_chunk});
+        my $chunk = '';
+        my $status = $self->{inflater}->inflate($self->{in_chunk}, $chunk);
+        if ($status == Z_STREAM_END) {
+            if (length($self->{in_chunk}) || defined($self->{input})) {
+                die "unexpected trailing data after gzip stream\n";
+            }
+            $self->{eof} = 1;
+            undef $self->{input};
+            undef $self->{in_chunk};
+            undef $self->{inflater};
+            $self->{buf} .= $chunk;
+            return length($chunk) > 0 ? 1 : 0;
+        } elsif ($status == Z_BUF_ERROR) {
+            if (length($chunk) > 0) {
+                $self->{buf} .= $chunk;
+                return 1;
+            }
+            next if defined($self->{input});
+            die "truncated gzip stream\n";
+        } elsif ($status != Z_OK) {
+            die "failed to gunzip stream (zlib status $status)\n";
+        }
+
+        if (length($chunk) > 0) {
+            $self->{buf} .= $chunk;
+            return 1;
+        }
+        next if defined($self->{input}) || length($self->{in_chunk}) < $prev_in;
+        die "truncated gzip stream\n";
+    }
+}
+
+sub open($class, %opts) {
+    my $is_gzip = $opts{gzip} ? 1 : 0;
+
+    my $inflater;
+    if ($is_gzip) {
+        my $status;
+        ($inflater, $status) = Compress::Raw::Zlib::Inflate->new(
+            -WindowBits => WANT_GZIP,
+            -Bufsize => 65536,
+            -LimitOutput => 1,
+        );
+        die "failed to initialize gzip inflater (status $status)\n" if $status != Z_OK;
+    }
+
+    # Plain payloads (such as local_json) are scanned directly in buf without chunk copying.
+    my $self = bless {
+        ts => 0,
+        obj => undef,
+        buf => $is_gzip ? '' : ($opts{body} // ''),
+        pos => 0,
+        input => $is_gzip ? $opts{body} : undef,
+        input_pos => 0,
+        in_chunk => '',
+        inflater => $inflater,
+        eof => $is_gzip ? 0 : 1,
+        closed => 0,
+        need_comma => 0,
+    }, $class;
+    delete $opts{body};
+
+    eval {
+        my $matched = 0;
+        while (1) {
+            pos($self->{buf}) = 0;
+            if ($self->{buf} =~ m/$ENVELOPE_OPEN_RE/gc) {
+                $self->{pos} = pos($self->{buf});
+                $matched = 1;
+                last;
+            }
+            last if length($self->{buf}) >= 4096;
+            last if !refill($self);
+        }
+        die "unexpected response format\n" if !$matched;
+    };
+    if (my $err = $@) {
+        $self->close();
+        die $err;
+    }
+
+    return $self;
+}
+
+sub next($self) {
+    return undef if $self->{closed};
+
+    while (1) {
+        # Compact PVE metric JSON uses ',{' between objects; skipping whitespace regexes on this
+        # common separator and matching flat ASCII objects avoids per-metric hash allocations,
+        # while escapes, UTF-8, nested values, or syntax errors fall back to decode_json.
+        my $pos = $self->{pos};
+        if (!defined($self->{scan_state})) {
+            if ($self->{need_comma} == 1 && substr($self->{buf}, $pos, 2) eq ',{') {
+                $pos++;
+                $self->{pos} = $pos;
+                $self->{need_comma} = 2;
+            } else {
+                pos($self->{buf}) = $pos;
+                $self->{buf} =~ /\G[ \t\r\n]*/gc;
+                $pos = pos($self->{buf});
+
+                if ($pos >= length($self->{buf})) {
+                    $self->{pos} = $pos;
+                    next if refill($self);
+                    die "truncated metrics array\n";
+                }
+
+                my $ch = substr($self->{buf}, $pos, 1);
+                if ($ch eq ']') {
+                    die "unexpected token in metrics array\n" if $self->{need_comma} == 2;
+                    $self->{pos} = $pos + 1;
+                    while (!$self->{eof}) {
+                        die "unexpected trailing data\n"
+                            if length($self->{buf}) - $self->{pos} > 4096;
+                        last if !refill($self);
+                    }
+                    die "unexpected trailing data\n" if length($self->{buf}) - $self->{pos} > 4096;
+                    pos($self->{buf}) = $self->{pos};
+                    if ($self->{buf} !~ m/$ENVELOPE_CLOSE_RE/gc) {
+                        die "unexpected trailing data\n";
+                    }
+                    $self->close();
+                    return undef;
+                }
+
+                if ($self->{need_comma} == 1) {
+                    die "unexpected token in metrics array\n" if $ch ne ',';
+                    $self->{need_comma} = 2;
+                    pos($self->{buf}) = $pos + 1;
+                    $self->{buf} =~ /\G[ \t\r\n]*/gc;
+                    $pos = pos($self->{buf});
+                    if ($pos >= length($self->{buf})) {
+                        $self->{pos} = $pos;
+                        next if refill($self);
+                        die "truncated metrics array\n";
+                    }
+                    $ch = substr($self->{buf}, $pos, 1);
+                }
+
+                die "unexpected token in metrics array\n" if $ch ne '{';
+                $self->{pos} = $pos;
+            }
+        }
+
+        # Fast path: flat printable-ASCII RFC 8259 object with a unique integer timestamp,
+        # validated and captured in a single non-backtracking pass without Perl hash allocation.
+        # Skip once an incomplete object has already entered the incremental fallback scanner.
+        if (!defined($self->{scan_state})) {
+            pos($self->{buf}) = $pos;
+            if ($self->{buf} =~ m/$FLAT_JSON_OBJ_RE/gc) {
+                my $end = pos($self->{buf});
+                if ($end - $pos > $MAX_METRIC_OBJECT_BYTES) {
+                    die "metric object exceeds maximum size\n";
+                }
+                my ($obj, $ts_tok) = ($1, $2);
+                # Any <=18-char integer token (|x| < 10^18) fits in signed int64 without invoking
+                # B::svref_2object; only 19+ char tokens near INT64 bounds need full range checking.
+                my $num =
+                    length($ts_tok) <= 18
+                    ? ($ts_tok + 0)
+                    : parse_signed_int64_token($ts_tok);
+                die "missing integer timestamp\n" if !defined($num);
+                $self->{ts} = $num;
+                $self->{pos} = $end;
+                $self->{need_comma} = 1;
+                $self->{obj} = $obj;
+                return $obj;
+            }
+            $self->{scan_state} = {
+                offset => 0,
+                depth => 0,
+                in_string => 0,
+                escaped => 0,
+            };
+        }
+
+        # Fallback: incremental bounded object scan + strict decode_json for escapes, UTF-8,
+        # nesting, or syntax errors (validating the original wire timestamp token and rejecting
+        # duplicates).
+        my $end = find_json_object_end(
+            \$self->{buf}, $pos, $self->{scan_state}, $MAX_METRIC_OBJECT_BYTES,
+        );
+        if (defined($end)) {
+            undef $self->{scan_state};
+            my $obj = substr($self->{buf}, $pos, $end - $pos);
+            my $decoded = decode_json($obj);
+            die "unexpected metric object\n" if ref($decoded) ne 'HASH';
+            my $ts_tok = extract_unique_timestamp_token($obj);
+            my $ts = parse_signed_int64_token($ts_tok);
+            die "missing integer timestamp\n" if !defined($ts);
+            $self->{ts} = $ts;
+            $self->{pos} = $end;
+            $self->{need_comma} = 1;
+            $self->{obj} = $obj;
+            return $obj;
+        }
+
+        if (length($self->{buf}) - $self->{pos} > $MAX_METRIC_OBJECT_BYTES) {
+            die "metric object exceeds maximum size\n";
+        }
+        next if refill($self);
+        die "truncated metric object\n";
+    }
+}
+
+sub obj($self) {
+    return $self->{obj};
+}
+
+sub ts($self) {
+    return $self->{ts};
+}
+
+sub close($self) {
+    return if !$self || $self->{closed};
+    $self->{closed} = 1;
+    delete @{$self}{qw(input in_chunk inflater buf obj scan_state)};
+}
+
+1;
-- 
2.47.3





  parent reply	other threads:[~2026-12-01 10:21 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 1/9] response: support deferred async API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 2/9] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 3/9] response: support incremental streaming API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH apiclient v2 4/9] add non-blocking AnyEvent API client Thomas Lamprecht
2026-12-01 10:19 ` [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 6/9] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
2026-12-01 10:19 ` Thomas Lamprecht [this message]
2026-12-01 10:19 ` [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 9/9] test: add pull metric export test suite Thomas Lamprecht

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261201101913.1885484-8-t.lamprecht@proxmox.com \
    --to=t.lamprecht@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal