Data-DDSketch-Shared
view release on metacpan or search on metacpan
memset(base, 0, (size_t)L.neg);
double gamma = (1.0 + alpha) / (1.0 - alpha);
hdr->version = DD_VERSION;
hdr->num_buckets = num_buckets;
hdr->bias = num_buckets / 2;
hdr->gamma = gamma;
hdr->inv_ln_gamma = 1.0 / log(gamma);
hdr->alpha = alpha;
hdr->total_count = 0;
hdr->zero_count = 0;
hdr->sum = 0.0;
hdr->min_value = INFINITY;
hdr->max_value = -INFINITY;
hdr->neg_off = L.neg;
hdr->pos_off = L.pos;
hdr->total_size = total;
hdr->reader_slots_off = L.reader_slots;
/* Publish magic LAST, as a release store: it is the commit point, so a
creator killed before it leaves magic==0 and never a file mistaken for
a valid one. A kill during the field stores leaves one to remove by
hand. */
__atomic_store_n(&hdr->magic, DD_MAGIC, __ATOMIC_RELEASE);
__atomic_thread_fence(__ATOMIC_SEQ_CST);
}
static inline uint64_t *dd_neg(DdHandle *h) { return (uint64_t *)((char *)h->base + h->neg_off); }
static inline uint64_t *dd_pos(DdHandle *h) { return (uint64_t *)((char *)h->base + h->pos_off); }
/* Layer B trusted bound: the number of bucket counters guaranteed to lie within
* the real mapping for the store at `off`. Derived from the process-local
* mmap_size (fixed at attach, not peer-writable) and the SAME cached offset the
* accessors use, so a corrupt hdr->num_buckets can never drive a store access
* outside the mapping. Equals num_buckets for a valid sketch. */
static inline uint64_t dd_store_max(DdHandle *h, uint64_t off) {
if (off >= h->mmap_size) return 0;
return (h->mmap_size - off) / sizeof(uint64_t);
}
static inline DdHandle *dd_setup(void *base, size_t map_size,
const char *path, int backing_fd) {
DdHeader *hdr = (DdHeader *)base;
DdHandle *h = (DdHandle *)calloc(1, sizeof(DdHandle));
if (!h) {
munmap(base, map_size);
if (backing_fd >= 0) close(backing_fd);
return NULL;
}
h->hdr = hdr;
h->base = base;
h->reader_slots = (DdReaderSlot *)((uint8_t *)base + sizeof(DdHeader)); /* trusted layout, not the peer-writable header offset */
h->occ = (uint64_t *)((uint8_t *)base + dd_layout_for(0).occ); /* trusted layout offset (occ offset is num_buckets-independent) */
/* single validated read of each geometry field; cached so the bound and the
pointers/arithmetic it feeds stay consistent even under later peer corruption */
h->neg_off = hdr->neg_off;
h->pos_off = hdr->pos_off;
h->num_buckets = hdr->num_buckets;
h->bias = hdr->bias;
/* Derive gamma / inv_ln_gamma from the validated alpha rather than trusting
the stored copies: validate_header bounds alpha to [DD_MIN_ALPHA,
DD_MAX_ALPHA], so these are always finite and in range, whereas a corrupt
stored inv_ln_gamma (NaN/wild) would make the key computation's double->
int64 cast undefined behaviour. */
h->gamma = (1.0 + hdr->alpha) / (1.0 - hdr->alpha);
h->inv_ln_gamma = 1.0 / log(h->gamma);
h->mmap_size = map_size;
/* Layer B: if the mapping cannot hold `num_buckets` in each store, clamp the
cached count to what actually fits (pos is the last, tightest region). */
{
uint64_t nfit = dd_store_max(h, h->neg_off);
uint64_t pfit = dd_store_max(h, h->pos_off);
uint64_t fit = nfit < pfit ? nfit : pfit;
if ((uint64_t)h->num_buckets > fit) h->num_buckets = (uint32_t)fit;
}
h->path = path ? strdup(path) : NULL;
if (path && !h->path) {
munmap(base, map_size);
if (backing_fd >= 0) close(backing_fd);
free(h);
return NULL;
}
h->backing_fd = backing_fd;
h->my_slot_idx = UINT32_MAX;
return h;
}
/* Validate a mapped header (shared by dd_create reopen and dd_open_fd). */
static inline int dd_validate_header(const DdHeader *hdr, uint64_t file_size) {
if (hdr->magic != DD_MAGIC) return 0;
if (hdr->version != DD_VERSION) return 0;
if (hdr->num_buckets < DD_MIN_BUCKETS || hdr->num_buckets > DD_MAX_BUCKETS) return 0;
if (hdr->bias != hdr->num_buckets / 2) return 0;
if (!(hdr->alpha >= DD_MIN_ALPHA && hdr->alpha <= DD_MAX_ALPHA)) return 0; /* same bounds as create; rejects NaN */
if (!(hdr->gamma > 1.0)) return 0;
if (hdr->total_size != file_size) return 0;
if (hdr->total_size != dd_total_size(hdr->num_buckets)) return 0;
DdLayout L = dd_layout_for(hdr->num_buckets);
if (hdr->reader_slots_off != L.reader_slots) return 0;
if (hdr->neg_off != L.neg) return 0;
if (hdr->pos_off != L.pos) return 0;
return 1;
}
/* validate the requested relative accuracy + bucket count */
static int dd_validate_args(double alpha, uint64_t num_buckets, char *errbuf) {
if (errbuf) errbuf[0] = '\0';
if (!(alpha >= DD_MIN_ALPHA && alpha <= DD_MAX_ALPHA))
{ DD_ERR("alpha (relative accuracy) must be between 1e-6 and 0.5"); return 0; }
if (num_buckets < DD_MIN_BUCKETS || num_buckets > DD_MAX_BUCKETS)
{ DD_ERR("num_buckets must be between 8 and 2^24"); return 0; }
return 1;
}
/* Securely obtain a fd for a path-backed segment: create it exclusively
* (O_CREAT|O_EXCL|O_NOFOLLOW at `mode`, default 0600 = owner-only), or, if it
* already exists, attach to it (O_RDWR|O_NOFOLLOW, no O_CREAT). O_EXCL blocks a
* pre-seeded or hard-linked file and O_NOFOLLOW a symlink swap, so a local
* attacker can no longer redirect or poison the backing store through the path.
* Cross-user sharing is opt-in via a wider `mode` (e.g. 0660); the caller still
* validates the file's contents via dd_validate_header. */
static int dd_secure_open(const char *path, mode_t mode, char *errbuf) {
for (int attempt = 0; attempt < 100; attempt++) {
int fd = open(path, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC, mode);
if (fd >= 0) { (void)fchmod(fd, mode); return fd; } /* exact mode: umask narrowed the O_EXCL create */
if (errno != EEXIST) { DD_ERR("create %s: %s", path, strerror(errno)); return -1; }
fd = open(path, O_RDWR|O_NOFOLLOW|O_CLOEXEC);
if (fd >= 0) return fd;
if (errno == ENOENT) continue; /* creator unlinked between our two opens; retry */
DD_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */
return -1;
}
DD_ERR("open %s: create/attach kept racing", path);
return -1;
}
/* True iff the whole file is zero -- what an abandoned mid-init
creator leaves. Lets recovery re-init only a provably-empty file, never
one that merely starts with a zero word. Cold path, so a byte scan is
fine. Read, not mapped: a read fault on a tmpfs hole allocates the page. */
static int dd_file_is_zero(int fd, uint64_t size) {
char buf[16384];
for (uint64_t off = 0; off < size; ) {
ssize_t n = pread(fd, buf, size - off < sizeof buf ? (size_t)(size - off) : sizeof buf, (off_t)off);
if (n <= 0) return 0;
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0;
off += (uint64_t)n;
}
return 1;
}
/* Opt-in (DATA_DDSKETCH_SHARED_SPARSE=0): reserving commits memory this module otherwise fills lazily. */
static int dd_reserve(int fd, uint64_t size) {
const char *sp = getenv("DATA_DDSKETCH_SHARED_SPARSE");
if (pread(fd, &magic, sizeof magic, offsetof(DdHeader, magic)) != (ssize_t)sizeof magic || magic != DD_MAGIC) {
DD_ERR("%s: invalid DDSketch file", path); close(fd); return NULL;
}
size_t ms = (size_t)st.st_size;
void *base = mmap(NULL, ms, PROT_READ, MAP_SHARED, fd, 0);
close(fd); /* the mapping keeps the file; a read-only view needs no fd (no msync/ftruncate) */
if (base == MAP_FAILED) { DD_ERR("mmap %s: %s", path, strerror(errno)); return NULL; }
if (!dd_validate_header((DdHeader *)base, (uint64_t)st.st_size)) {
DD_ERR("%s: invalid DDSketch file", path); munmap(base, ms); return NULL;
}
if (!__atomic_load_n(&((DdHeader *)base)->sealed, __ATOMIC_ACQUIRE)) {
DD_ERR("%s is not frozen: call ->freeze on the producer before opening read-only", path);
munmap(base, ms); return NULL;
}
DdHandle *h = dd_setup(base, ms, path, -1); /* munmaps on OOM */
if (!h) { DD_ERR("out of memory"); return NULL; }
h->readonly = 1;
return h;
}
/* Seal a sketch: make it permanently immutable so it can be shipped and opened
* read-only. Takes the write lock so no add/merge/clear is in flight, publishes
* the seal, then flushes it (file/memfd-backed). Afterwards every mutator
* croaks and a read-write reopen is refused. */
static int dd_freeze(DdHandle *h) {
dd_rwlock_wrlock(h);
__atomic_store_n(&h->hdr->sealed, 1, __ATOMIC_RELEASE);
dd_rwlock_wrunlock(h);
if (h->path || h->backing_fd >= 0) return dd_msync(h); /* durability for file/memfd-backed */
return 0; /* anonymous: the seal lives in shared memory (visible to forks); nothing to flush */
}
/* ================================================================
* DDSketch operations (callers hold the lock)
*
* A value v != 0 maps to a logarithmic bucket key = ceil(log_gamma(|v|)); each
* bucket [gamma^(k-1), gamma^k) collects a count, so a bucket's representative
* value is within relative error alpha of every value it holds. Positive and
* negative magnitudes use separate stores; exact zeros use a dedicated counter.
* The bucket key is mapped to a fixed centred window slot = key + bias (bias =
* num_buckets/2); keys past either end collapse into the extreme bucket, which
* bounds memory while keeping every sketch of the same (alpha, num_buckets)
* layout mergeable by a plain element-wise sum.
* ================================================================ */
/* representative value of positive bucket key k: 2*gamma^k/(gamma+1), the value
* whose relative distance to every point in the bucket is at most alpha */
static inline double dd_value_of_key(DdHandle *h, int64_t key) {
return 2.0 * pow(h->gamma, (double)key) / (h->gamma + 1.0);
}
/* map a bucket key to a store slot in the fixed centred window, collapsing keys
* past either end into the extreme bucket. */
static inline uint64_t dd_slot_of_key(DdHandle *h, int64_t key) {
int64_t s = key + (int64_t)h->bias;
if (s < 0) return 0;
if ((uint64_t)s >= (uint64_t)h->num_buckets) return h->num_buckets ? h->num_buckets - 1 : 0;
return (uint64_t)s;
}
/* insert one finite value (caller holds the write lock; caller has rejected NaN/Inf) */
static void dd_insert_locked(DdHandle *h, double v, uint64_t count) {
DdHeader *hdr = h->hdr;
if (v == 0.0) {
hdr->zero_count += count;
} else if (h->num_buckets != 0) { /* Layer B: unusable mapping */
double mag = v > 0 ? v : -v;
int64_t key = (int64_t)ceil(log(mag) * h->inv_ln_gamma);
uint64_t slot = dd_slot_of_key(h, key);
uint64_t *store = (v > 0) ? dd_pos(h) : dd_neg(h);
store[slot] += count;
}
/* Quantiles walk the buckets up to total_count: a writer killed before it must add nothing. */
__atomic_signal_fence(__ATOMIC_SEQ_CST);
hdr->total_count += count;
hdr->sum += v * (double)count;
if (v < hdr->min_value) hdr->min_value = v;
if (v > hdr->max_value) hdr->max_value = v;
}
/* value at 0-based rank `rank` (typically q*(count-1)), walking buckets from
* most-negative to most-positive; *found set to 1 when a bucket is returned.
* (caller holds a lock) */
static double dd_value_at_rank(DdHandle *h, double rank, int *found) {
uint64_t nb = h->num_buckets;
uint64_t cum = 0;
*found = 1;
/* negative store: larger key = more negative value, so walk high slot -> low */
uint64_t *neg = dd_neg(h);
for (uint64_t i = nb; i-- > 0; ) {
cum += neg[i];
if ((double)cum > rank) {
int64_t key = (int64_t)i - (int64_t)h->bias;
return -dd_value_of_key(h, key);
}
}
/* exact zeros */
cum += h->hdr->zero_count;
if ((double)cum > rank) return 0.0;
/* positive store: low slot -> high */
uint64_t *pos = dd_pos(h);
for (uint64_t i = 0; i < nb; i++) {
cum += pos[i];
if ((double)cum > rank) {
int64_t key = (int64_t)i - (int64_t)h->bias;
return dd_value_of_key(h, key);
}
}
*found = 0; /* rank beyond total (empty) */
return 0.0;
}
/* merge another sketch's stores into this one (caller guarantees equal geometry).
* src_neg/src_pos are snapshots of length src_nb. */
static void dd_merge_locked(DdHandle *dst, const uint64_t *src_neg, const uint64_t *src_pos,
uint64_t src_nb, uint64_t src_total, uint64_t src_zero,
double src_sum, double src_min, double src_max) {
uint64_t nb = dst->num_buckets;
if (nb > src_nb) nb = src_nb; /* Layer B: clamp to both buffers */
uint64_t *neg = dd_neg(dst), *pos = dd_pos(dst);
for (uint64_t i = 0; i < nb; i++) { neg[i] += src_neg[i]; pos[i] += src_pos[i]; }
( run in 0.787 second using v1.01-cache-2.11-cpan-60884a8df76 )