Data-Reservoir-Shared
view release on metacpan or search on metacpan
lib/Data/Reservoir/Shared.pm view on Meta::CPAN
=head2 Weighted sampling (A-Res)
A reservoir created with C<new_weighted> keeps a B<weighted> random sample: each
item carries a positive weight and is retained with probability proportional to
its weight rather than uniformly. This is the B<Efraimidis-Spirakis A-Res>
algorithm -- each observed item is assigned a key C<log(u) / weight> (with C<u>
uniform in C<(0,1]>) and the C<k> items with the largest keys are kept, tracked
in a shared min-heap so a heavier arrival can evict the current lightest member.
With a single slot the probability of keeping item C<i> is exactly
C<< w_i / sum(w) >>. Feed weighted items with C<< $rsv->add($item, $weight) >> (the
weight must be a finite number greater than zero); everything else -- C<sample>,
C<count>, C<get>, C<clear>, and cross-process sharing -- works identically. A
weighted reservoir stores an extra C<k * 16> bytes for the heap and records its
mode in the header, so a reopened segment stays weighted. Weighted files from
earlier releases must be recreated for the logarithmic key format.
=head1 METHODS
=head2 Constructors
my $rsv = Data::Reservoir::Shared->new($path, $k, $item_size);
my $rsv = Data::Reservoir::Shared->new(undef, $k); # anonymous, item_size 256
my $rsv = Data::Reservoir::Shared->new_memfd($name, $k, $item_size);
my $rsv = Data::Reservoir::Shared->new_from_fd($fd);
# weighted (A-Res) reservoir -- same arguments, weighted sampling
my $rsv = Data::Reservoir::Shared->new_weighted($path, $k, $item_size);
my $rsv = Data::Reservoir::Shared->new_weighted_memfd($name, $k, $item_size);
C<$k> is the reservoir size (the number of items to retain, at least 1).
C<$item_size> is the maximum bytes stored per item (default 256; items are
truncated to it). C<new> and C<new_memfd> croak on a size below 1 or an
out-of-range C<$item_size>. 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).
The constructors create a new segment sparse: pages are allocated as they are
first written, and once the filesystem is full, a write to a page not yet
allocated dies with SIGBUS. Set C<DATA_RESERVOIR_SHARED_SPARSE=0> to reserve
the whole segment at creation, so a full filesystem or unsupported reservation
makes them croak instead;
on tmpfs and memfd that commits the segment's memory at once, and a memory
cgroup too small for it gets an OOM kill rather than a croak.
=head2 Sampling
my $kept = $rsv->add($item); # uniform: 1 if now stored, 0 if discarded
my $kept = $rsv->add($item, $weight); # weighted reservoir: weight must be > 0
my $n = $rsv->add_many(\@items); # uniform: array ref of items
my $n = $rsv->add_many([[$item,$w], ...]); # weighted: [item, weight] pairs
my @items = $rsv->sample; # current sample (a list, up to k items)
my $it = $rsv->get($i); # the i-th retained item (0-based), or undef
$rsv->clear; # empty the reservoir (seen resets to 0)
C<add> feeds one item and returns B<1 if it is now stored> in the reservoir or
B<0 if it was discarded>. On a B<weighted> reservoir C<add> takes a second
argument, the item's weight (a finite number greater than zero -- a missing,
zero, negative, infinite, or NaN weight croaks). C<add_many> feeds an array
reference under a single write lock, returning how many of the batch were
stored (an item that replaces an earlier sample counts as stored; use C<count>
for the number currently retained); for a weighted reservoir each element must
be an C<< [$item, $weight] >> pair. C<sample> returns the retained items as a
list (order is not meaningful); C<get> returns a single retained item by
index. C<clear> empties the reservoir and resets the seen counter.
=head2 Introspection and RNG
$rsv->count; # number of items currently held: min(seen, k)
$rsv->seen; # total items observed
$rsv->capacity; # k
$rsv->item_size; # max bytes per item
$rsv->is_weighted; # true for a weighted (A-Res) reservoir
$rsv->seed($n); # set the RNG state (for reproducible sampling in tests)
$rsv->stats; # { size, item_size, count, seen, ops, mmap_size, weighted }
C<seed> sets the shared RNG state to a fixed value, making subsequent sampling
deterministic -- useful for reproducible tests. By default the RNG is seeded from
process and clock entropy at creation, so different runs draw different samples.
=head2 Lifecycle
$rsv->path; $rsv->memfd; $rsv->sync; $rsv->unlink;
C<sync> flushes the mapping to its backing store (a no-op for anonymous and memfd
reservoirs); C<unlink> removes the backing file (also callable as
C<< Class->unlink($path) >>); C<path> returns the backing path (C<undef> for
anonymous, memfd, or fd-reopened reservoirs) and C<memfd> the backing descriptor.
=head1 SHARING ACROSS PROCESSES
The reservoir 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
disturb the handle. Every process's C<add> feeds the one shared reservoir, and
the shared RNG keeps the sampling probabilities consistent across producers.
=head1 SECURITY
Backing files are created with mode C<0600> (owner-only) by default; pass an
explicit octal mode (e.g. C<0660>) as the last argument to C<new> for cross-user
sharing. The file is opened with C<O_NOFOLLOW> and C<O_EXCL>, and the header is
validated on attach. Any process granted write access is trusted not to corrupt
the mapping.
=head1 CRASH SAFETY
Mutation is guarded by a futex-based write-preferring rwlock with PID-encoded
ownership and dead-owner recovery. The process that recovers the lock finishes
a heap reordering the dead writer left part-way, from a record kept in the
header, so the sample stays ordered and holds each item once. A kill while an
C<add> is copying an item over a replaced one can leave that slot holding the
new item's length over the old item's bytes.
B<Limitation>: PID reuse is not detected (very unlikely in practice).
Reader-slot exhaustion (slotless readers): dead-process recovery attributes a
crashed lock holder's contribution through its reader-slot. The slot table holds
( run in 1.352 second using v1.01-cache-2.11-cpan-60884a8df76 )