Data-DDSketch-Shared

 view release on metacpan or  search on metacpan

lib/Data/DDSketch/Shared.pm  view on Meta::CPAN

=head1 DESCRIPTION

A B<DDSketch> in shared memory: it estimates any B<quantile> of a stream of
numbers to within a configured B<relative accuracy> C<alpha> (default 1%), in a
fixed amount of memory, no matter how many values are added. Unlike a fixed
histogram, the guarantee is B<relative>: the returned value for any quantile is
within a factor C<alpha> of the true value, whether that quantile is a
microsecond or an hour -- which is what you want for latencies and other
long-tailed, wide-dynamic-range data.

Each value C<v> falls into a logarithmic bucket keyed by
C<ceil(log_gamma(|v|))>, with C<gamma = (1 + alpha) / (1 - alpha)>; every value
in a bucket is within C<alpha> of the bucket's representative value. Positive and
negative magnitudes use separate bucket stores and exact zeros a dedicated
counter, so the full real line is covered. The sketch also tracks the exact
count, minimum, and maximum, plus a running sum, giving mean and true extremes
for free.

Because the buckets live in a shared mapping, B<several processes feed one
sketch>: any process that opens the same backing file, inherits the anonymous
mapping across C<fork>, or reopens a passed memfd contributes to and reads the
same distribution. A write-preferring futex rwlock with dead-process recovery
guards mutation. B<Linux-only>. Requires 64-bit Perl.

Memory is bounded at C<num_buckets> counters per sign (default 2048): the buckets
form a fixed window centred on value 1, and values whose magnitude falls outside
the window collapse into the nearest extreme bucket. With the defaults the window
spans roughly C<1.3e-9> to C<7.6e8>, so ordinary data never reaches the edges;
raise C<num_buckets> for a wider exact range. Two sketches created with the same
C<alpha> and C<num_buckets> can be merged.

=head1 METHODS

=head2 Constructors

    my $dd = Data::DDSketch::Shared->new($path, $alpha, $num_buckets, $mode);
    my $dd = Data::DDSketch::Shared->new(undef, 0.01);            # anonymous, 2048 buckets
    my $dd = Data::DDSketch::Shared->new_memfd($name, $alpha, $num_buckets);
    my $dd = Data::DDSketch::Shared->new_from_fd($fd);
    my $ro = Data::DDSketch::Shared->new_readonly($path);         # frozen file, read-only

C<$alpha> is the relative accuracy (default 0.01 = 1%; between 1e-6 and 0.5).
C<$num_buckets> is the number of counters per sign (default 2048; between 8
and 2^24) and sets both the memory use (C<2 * num_buckets * 8> bytes plus a
fixed header) and the exact value range. C<new> and C<new_memfd> croak on an
out-of-range C<$alpha> or C<$num_buckets>. When reopening an existing file or
memfd the stored geometry wins and the caller's arguments do not resize it --
but they are still range-checked, so an out-of-range value croaks. An optional
file B<mode> may be passed as the last argument to C<new> (e.g. C<0660>) for
cross-user sharing; it defaults to C<0600> (owner-only). C<new_readonly> opens
a B<frozen> file read-only for lock-free querying (see L</"FROZEN (READ-ONLY)
MODE">).

=head2 Feeding values

    my $n = $dd->add($value);        # add one value; returns the new total count
    $dd->insert($value);             # alias for add
    $dd->add_many(\@values);         # add a batch under a single write lock
    $dd->clear;                      # empty the sketch

C<add> adds one finite number (croaks on C<NaN> or infinity) and returns the
running total count. C<add_many> adds an array reference of numbers under one
write lock, validating them all first. Negative values and zero are supported.

=head2 Querying

    my $v   = $dd->quantile($q);     # value at quantile $q in 0 .. 1 (undef if empty)
    my $med = $dd->median;           # quantile(0.5)
    $dd->min; $dd->max;              # exact smallest / largest value (undef if empty)
    $dd->mean;                       # running mean (undef if empty)
    $dd->sum; $dd->count;            # running sum and exact number of values
    $dd->zero_count;                 # how many exact-zero values were added

C<quantile> returns the estimated value at quantile C<$q> (e.g. C<0.99> for the
99th percentile), guaranteed within relative error C<alpha> of the true value; it
returns C<undef> for an empty sketch and croaks if C<$q> is outside C<[0, 1]>.
C<min>, C<max>, and C<count> are B<exact> (tracked separately from the
buckets; a writer crash can turn C<min> and C<max> into estimates, see
L</"CRASH SAFETY">);
C<sum> and C<mean> are double-precision running values subject to
floating-point rounding.

=head2 Merging and introspection

    $dd->merge($other);              # fold another sketch's values in (same alpha + num_buckets)
    $dd->alpha; $dd->gamma; $dd->num_buckets;
    $dd->stats;   # { alpha, gamma, num_buckets, count, zero_count, sum, min, max, mean, ops, mmap_size, frozen, readonly }

C<merge> requires C<$other> to have the same C<alpha> and C<num_buckets> and
croaks otherwise; afterwards this sketch represents the combined distribution.

=head2 Lifecycle

    $dd->path; $dd->memfd; $dd->sync; $dd->unlink;

C<sync> flushes the mapping to its backing store (a no-op for anonymous and
memfd sketches); C<unlink> removes the backing file (also callable as C<<
Class->unlink($path) >>) and croaks if the removal fails -- except when the
file is already gone, which is what you asked for; it is likewise a no-op when
there is no backing file (anonymous or memfd); C<path> returns the backing
path (C<undef> for anonymous, memfd, or fd-reopened sketches) and C<memfd> the
backing descriptor.

=head1 ACCURACY

For any quantile, the returned value C<e> and the true value C<v> satisfy
C<|e - v| <= alpha * |v|> -- a relative guarantee that holds across the whole
range, so the 99.9th percentile of a heavy tail is as accurate (in relative
terms) as the median. This is the property a fixed-bucket histogram lacks. The
count, minimum, and maximum are exact; the sum and mean are double-precision
running values subject to floating-point rounding. The only approximation is
the per-quantile value, and only for magnitudes inside the representable window;
magnitudes outside it collapse into the extreme bucket and lose accuracy.

=head1 SHARING ACROSS PROCESSES

The sketch lives in a shared mapping, shared the same three ways as the rest
of the family: a B<backing file>, an B<anonymous mapping inherited across
C<fork>>, or a B<memfd> passed to an unrelated process and reopened with C<<
new_from_fd($fd) >>. The descriptor you pass is duplicated
(C<F_DUPFD_CLOEXEC>), so it stays yours to close and closing it does not



( run in 1.921 second using v1.01-cache-2.11-cpan-60884a8df76 )