/*
 * Copyright (c) 2009-Present, Redis Ltd.
 * All rights reserved.
 *
 * Licensed under your choice of (a) the Redis Source Available License 2.0
 * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the
 * GNU Affero General Public License v3 (AGPLv3).
 */

#include "fmacros.h"
/* CRoaring's x64 (AVX2/AVX512) and NEON acceleration is disabled, for two
 * reasons. First, build correctness: CRoaring exposes target-specific inline
 * helpers from its public headers, so this translation unit's SIMD
 * configuration must match the one deps/Makefile uses to build libcroaring
 * (CROARING_CFLAGS defines the same two flags); mixing settings would compile
 * incompatible inline definitions on the two sides of the library boundary.
 * Second, portability: with the SIMD paths compiled out, the binary needs no
 * -march flags or CPU runtime dispatch, matching how Redis builds its own
 * bit-manipulation code. Revisit if benchmarks justify wiring CRoaring's
 * runtime dispatch into the Redis build. */
#ifndef ROARING_DISABLE_X64
#define ROARING_DISABLE_X64 1
#endif
#ifndef DISABLENEON
#define DISABLENEON 1
#endif
#include <roaring/containers/array.h>
#include <roaring/containers/bitset.h>
#include <roaring/containers/containers.h>
#include <roaring/containers/run.h>
#include <roaring/memory.h>
#include <roaring/roaring.h>
#include <roaring/roaring64.h>
#include <roaring/roaring_array.h>
/* Local Redis patch to CRoaring: exposes struct roaring64_bitmap_s and the
 * leaf encoding so memory accounting, fork-child dismissal and active defrag
 * can walk every allocation, like they do for the other core types. Must come
 * after containers.h (it needs container_t). */
#include <roaring/roaring64_internal.h>

#ifdef STRINGIFY
#undef STRINGIFY
#endif

#include "server.h"
#include "bitroar.h"
#include "lzf.h"
#include "rdb.h"

/* Reuse the established string BITOP vector kernels after bounded roaring
 * operands have been materialized. Their scalar tail remains local below. */
#ifdef HAVE_AVX2
unsigned long bitopCommandAVX(unsigned char **keys, unsigned char *res,
                              bitroarOp op, unsigned long numkeys,
                              unsigned long minlen);
#endif
#ifdef HAVE_AVX512
unsigned long bitopCommandAVX512(unsigned char **keys, unsigned char *res,
                                 bitroarOp op, unsigned long numkeys,
                                 unsigned long minlen);
#endif

/* Derived from the byte bound in bitroar.h; only this file needs the
 * bit-offset form. */
#define BITROAR_MAX_BITOFFSET (BITROAR_MAX_BYTES * 8 - 1)

/* Full allocation accounting is only needed for per-key/slot memory tracking
 * or MEMORY USAGE. New objects start unknown so default hot paths can defer
 * the O(containers) allocation walk until a caller actually needs it. */
#define BITROAR_ALLOC_SIZE_UNKNOWN SIZE_MAX

/* Bitmap objects use Roaring internally. Client-visible command limits are
 * enforced by command handlers; the internal bound protects arithmetic
 * invariants. */
typedef struct bitroar {
    uint64_t byte_len;
    size_t alloc_size;          /* Total memory, or BITROAR_ALLOC_SIZE_UNKNOWN. */
    roaring64_bitmap_t *roaring;
} bitroar;

static size_t bitroarRoaringAllocSize(const roaring64_bitmap_t *r);
static size_t bitroarRangeAllocSize(const roaring64_bitmap_t *r,
                                    uint64_t start, uint64_t end);
static void bitroarRefreshAllocSize(bitroar *bitmap);
static void bitroarRefreshRangeAllocSize(bitroar *bitmap, uint64_t start,
                                         uint64_t end, size_t old_size);
static void bitroarArtKeyFromHigh48(uint64_t high48, art_key_chunk_t key[ART_KEY_BYTES]);

static bitroar *bitroarGet(const robj *o) {
    serverAssert(o->type == OBJ_BITMAP);
    serverAssert(o->encoding == OBJ_ENCODING_BITMAP_ROARING);
    return o->ptr;
}

static void bitroarAdjustAllocSize(size_t *alloc_size, size_t old_size, size_t new_size) {
    if (*alloc_size == BITROAR_ALLOC_SIZE_UNKNOWN) return;

    if (new_size >= old_size) {
        serverAssert(SIZE_MAX - *alloc_size >= new_size - old_size);
        *alloc_size += new_size - old_size;
    } else {
        serverAssert(*alloc_size >= old_size - new_size);
        *alloc_size -= old_size - new_size;
    }
}

static void bitroarAppendContainer(roaring64_bitmap_t *roaring, uint64_t high48,
                                   container_t *container, uint8_t typecode)
{
    if (roaring->first_free == roaring->capacity) {
        uint64_t new_capacity;

        if (roaring->capacity == 0)
            new_capacity = 2;
        else if (roaring->capacity < 1024)
            new_capacity = roaring->capacity * 2;
        else
            new_capacity = roaring->capacity + roaring->capacity / 4;

        container_t **containers = roaring_realloc(
            roaring->containers, new_capacity * sizeof(*containers));
        serverAssert(containers != NULL);
        memset(containers + roaring->capacity, 0,
               (new_capacity - roaring->capacity) * sizeof(*containers));
        roaring->containers = containers;
        roaring->capacity = new_capacity;
    }

    uint64_t index = roaring->first_free++;
    roaring->containers[index] = container;

    art_key_chunk_t key[ART_KEY_BYTES];
    bitroarArtKeyFromHigh48(high48, key);
    art_insert(&roaring->art, key, (art_val_t)((index << 8) | typecode));
}

static unsigned char bitroarReverseByte(unsigned char value) {
    value = (unsigned char)(((value & 0xf0) >> 4) | ((value & 0x0f) << 4));
    value = (unsigned char)(((value & 0xcc) >> 2) | ((value & 0x33) << 2));
    value = (unsigned char)(((value & 0xaa) >> 1) | ((value & 0x55) << 1));
    return value;
}

static int bitroarRawChunkFitsArray(const unsigned char *buf, size_t len, int *cardinality) {
    int count = 0;

    for (size_t i = 0; i < len; i++) {
        count += __builtin_popcount(buf[i]);
        if (count > DEFAULT_MAX_SIZE) return 0;
    }
    *cardinality = count;
    return 1;
}

static void bitroarAppendRawArrayContainer(roaring64_bitmap_t *roaring, const unsigned char *buf,
                                           size_t len, int cardinality, uint64_t high48)
{
    array_container_t *array = array_container_create_given_capacity(cardinality);
    serverAssert(array != NULL);
    array->cardinality = cardinality;

    int32_t out = 0;
    for (size_t byte = 0; byte < len; byte++) {
        unsigned char value = buf[byte];
        for (int bit = 0; bit < 8; bit++) {
            if (value & (0x80 >> bit))
                array->array[out++] = (uint16_t)(byte * 8 + bit);
        }
    }
    serverAssert(out == cardinality);

    bitroarAppendContainer(roaring, high48, (container_t *)array, ARRAY_CONTAINER_TYPE);
}

static void bitroarAppendRawBitsetContainer(roaring64_bitmap_t *roaring,
                                            const unsigned char *buf,
                                            size_t len, uint64_t high48)
{
    bitset_container_t *bitset = bitset_container_create();
    serverAssert(bitset != NULL);

    int cardinality = 0;
    size_t byte = 0;
    for (int word = 0; word < BITSET_CONTAINER_SIZE_IN_WORDS; word++) {
        uint64_t bits = 0;

        for (int lane = 0; lane < 8 && byte < len; lane++, byte++) {
            unsigned char value = buf[byte];
            cardinality += __builtin_popcount(value);
            bits |= (uint64_t)bitroarReverseByte(value) << (lane * 8);
        }
        bitset->words[word] = bits;
    }
    bitset->cardinality = cardinality;

    bitroarAppendContainer(roaring, high48, (container_t *)bitset, BITSET_CONTAINER_TYPE);
}

/* Build a Roaring bitmap from raw bitmap string bytes by constructing one
 * container per 2^16-bit chunk. This conversion runs on every
 * bitmap-default-roaring write that converts a string and on every string
 * BITOP source, so dense chunks must avoid per-bit roaring64_bitmap_add calls.
 * The optimize pass is only worth paying for bitmaps that are kept
 * (run_optimize/shrink_to_fit walk every container); BITOP operand temporaries
 * are freed within the command, so their callers pass optimize=0. */
static roaring64_bitmap_t *bitroarFromRaw(const unsigned char *buf, size_t len, int optimize) {
    roaring64_bitmap_t *roaring = roaring64_bitmap_create();

    const size_t container_bytes = BITSET_CONTAINER_SIZE_IN_WORDS * sizeof(uint64_t);
    for (size_t offset = 0; offset < len; offset += container_bytes) {
        size_t chunk_len = len - offset;
        if (chunk_len > container_bytes)
            chunk_len = container_bytes;

        uint64_t high48 = offset / container_bytes;
        int cardinality;
        if (bitroarRawChunkFitsArray(buf + offset, chunk_len, &cardinality)) {
            if (cardinality == 0) continue;
            bitroarAppendRawArrayContainer(roaring, buf + offset,
                                           chunk_len, cardinality, high48);
        } else {
            bitroarAppendRawBitsetContainer(roaring, buf + offset, chunk_len, high48);
        }
    }

    if (optimize) {
        roaring64_bitmap_run_optimize(roaring);
        roaring64_bitmap_shrink_to_fit(roaring);
    }
    return roaring;
}

static int bitroarNormalizeAlignment(size_t *alignment) {
    size_t normalized;

    if (*alignment < sizeof(void *)) {
        *alignment = sizeof(void *);
        return C_OK;
    }
    if ((*alignment & (*alignment - 1)) == 0) return C_OK;

    normalized = sizeof(void *);
    while (normalized < *alignment) {
        if (normalized > SIZE_MAX / 2) return C_ERR;
        normalized <<= 1;
    }
    *alignment = normalized;
    return C_OK;
}

/* CRoaring only uses its aligned allocator for bitset container words (see
 * BITROAR_BITSET_WORDS_ALIGNMENT). bitroarAlignedAllocBase() maps the pointer
 * it returns back to the zmalloc allocation that holds it. */
#if defined(USE_JEMALLOC)
/* jemalloc honors the alignment itself, so the words get an exact-size
 * allocation: 8 KiB of words stay in the 8 KiB size class instead of spilling
 * into the next one, and the pointer is its own zmalloc allocation. */
static void *bitroarAlignedMalloc(size_t alignment, size_t size) {
    if (bitroarNormalizeAlignment(&alignment) != C_OK) return NULL;
    /* Unlike malloc(), mallocx() leaves a zero size undefined. */
    return zmalloc_with_flags(size ? size : 1, MALLOCX_ALIGN(alignment));
}

static void *bitroarAlignedAllocBase(void *ptr) {
    return ptr;
}
#else
/* Other allocators have no aligned zmalloc variant, so over-allocate and keep
 * a pointer to the zmalloc base just below the aligned address. */
static void *bitroarAlignedMalloc(size_t alignment, size_t size) {
    void *base;
    uintptr_t raw, aligned;
    size_t extra;

    if (bitroarNormalizeAlignment(&alignment) != C_OK) return NULL;
    if (alignment - 1 > SIZE_MAX - sizeof(void *)) return NULL;
    extra = alignment - 1 + sizeof(void *);
    if (size > SIZE_MAX - extra) return NULL;

    base = zmalloc(size + extra);
    raw = (uintptr_t)base + sizeof(void *);
    aligned = (raw + alignment - 1) & ~((uintptr_t)alignment - 1);
    ((void **)aligned)[-1] = base;
    return (void *)aligned;
}

static void *bitroarAlignedAllocBase(void *ptr) {
    if (ptr == NULL) return NULL;
    return ((void **)ptr)[-1];
}
#endif

static void bitroarAlignedFree(void *ptr) {
    if (ptr == NULL) return;
    void *base = bitroarAlignedAllocBase(ptr);
    zfree(base);
}

static size_t bitroarMallocSize(const void *ptr) {
    return ptr == NULL ? 0 : zmalloc_usable_size((void *)ptr);
}

static size_t bitroarAlignedMallocSize(void *ptr) {
    void *base = bitroarAlignedAllocBase(ptr);
    return base == NULL ? 0 : zmalloc_usable_size(base);
}

void bitroarInit(void) {
    roaring_memory_t memory_hook = {
        .malloc = zmalloc,
        .realloc = zrealloc,
        .calloc = zcalloc_num,
        .free = zfree,
        .aligned_malloc = bitroarAlignedMalloc,
        .aligned_free = bitroarAlignedFree,
    };

    roaring_init_memory_hook(memory_hook);
}

robj *bitroarCreate(void) {
    bitroar *bitmap = zmalloc(sizeof(*bitmap));
    bitmap->byte_len = 0;
    bitmap->roaring = roaring64_bitmap_create();
    bitmap->alloc_size = BITROAR_ALLOC_SIZE_UNKNOWN;

    robj *o = createObject(OBJ_BITMAP, bitmap);
    o->encoding = OBJ_ENCODING_BITMAP_ROARING;
    return o;
}

robj *bitroarCreateFromString(const unsigned char *buf, size_t len) {
#if SIZE_MAX > BITROAR_MAX_BYTES_RAW
    if ((uint64_t)len > BITROAR_MAX_BYTES) return NULL;
#endif

    bitroar *bitmap = zmalloc(sizeof(*bitmap));
    bitmap->byte_len = len;
    bitmap->roaring = bitroarFromRaw(buf, len, 1);
    bitmap->alloc_size = BITROAR_ALLOC_SIZE_UNKNOWN;

    robj *o = createObject(OBJ_BITMAP, bitmap);
    o->encoding = OBJ_ENCODING_BITMAP_ROARING;
    return o;
}

/* Rebuild a bitmap from the RoaringFormatSpec 64-bit portable format. The
 * serialized containers do not encode Redis' logical byte length because
 * trailing zero bytes contain no set bits, so the RDB payload stores it
 * separately. The portable format is little-endian on every architecture. */
robj *bitroarCreateFromPortable(const unsigned char *buf, size_t len, uint64_t byte_len) {
    roaring64_bitmap_t *roaring;

    if (byte_len > BITROAR_MAX_BYTES) return NULL;
#if SIZE_MAX < UINT64_MAX
    if (byte_len > (uint64_t)SIZE_MAX) return NULL;
#endif
    if (roaring64_bitmap_portable_deserialize_size((const char *)buf, len) != len)
        return NULL;

    roaring = roaring64_bitmap_portable_deserialize_safe((const char *)buf, len);
    if (roaring == NULL) return NULL;

    const char *reason = NULL;
    if (!roaring64_bitmap_internal_validate(roaring, &reason) ||
        (!roaring64_bitmap_is_empty(roaring) &&
         (roaring64_bitmap_maximum(roaring) >> 3) >= byte_len))
    {
        roaring64_bitmap_free(roaring);
        return NULL;
    }

    /* Serialized containers keep the types they had when saved, and SETBIT or
     * BITFIELD writes never compact them. Optimize here so RDB load, full sync
     * and RESTORE turn dense runs kept as BITSET containers into RUN
     * containers, then trim the spare slots that inserting the containers one
     * at a time left in the container index. Both walks visit each container
     * once, the same order of work as the deserialization above. */
    roaring64_bitmap_run_optimize(roaring);
    roaring64_bitmap_shrink_to_fit(roaring);

    bitroar *bitmap = zmalloc(sizeof(*bitmap));
    bitmap->byte_len = byte_len;
    bitmap->roaring = roaring;
    bitmap->alloc_size = BITROAR_ALLOC_SIZE_UNKNOWN;

    robj *o = createObject(OBJ_BITMAP, bitmap);
    o->encoding = OBJ_ENCODING_BITMAP_ROARING;
    return o;
}

robj *bitroarDup(const robj *o) {
    bitroar *src = bitroarGet(o);
    bitroar *dst = zmalloc(sizeof(*dst));
    dst->byte_len = src->byte_len;
    dst->roaring = roaring64_bitmap_copy(src->roaring);
    dst->alloc_size = BITROAR_ALLOC_SIZE_UNKNOWN;

    robj *copy = createObject(OBJ_BITMAP, dst);
    copy->encoding = OBJ_ENCODING_BITMAP_ROARING;
    return copy;
}

void bitroarFree(robj *o) {
    bitroar *bitmap = bitroarGet(o);
    roaring64_bitmap_free(bitmap->roaring);
    zfree(bitmap);
}

uint64_t bitroarLen(const robj *o) {
    return bitroarGet(o)->byte_len;
}

/* --- ART walk helpers ---
 *
 * CRoaring's 64-bit bitmap keeps one container per 2^16-bit chunk, indexed by
 * the chunk's high 48 bits in an ART. ART nodes are index-based (no parent or
 * child pointers), the leaf value encodes a typecode plus an index into one
 * flat container pointer array, and copy-on-write does not exist for 64-bit
 * bitmaps, so shared containers can never appear.
 *
 * art_t.nodes[] is indexed by node typecode 1..5 (leaf, node4, node16,
 * node48, node256); slot 0 belongs to the null typecode and is deliberately
 * left uninitialized by art_init_cleared(), so walks must never touch it. */
#define BITROAR_ART_MIN_NODE_TYPE 1
#define BITROAR_ART_MAX_NODE_TYPE 5
/* Keep Roaring BITOP latency competitive for small steady-state results without
 * letting skipped run compression create unbounded memory growth. */
#define BITROAR_BITOP_FAST_RESULT_MAX_BYTES (1024 * 1024)

static void bitroarArtKeyFromHigh48(uint64_t high48, art_key_chunk_t key[ART_KEY_BYTES]) {
    for (int i = 0; i < ART_KEY_BYTES; i++)
        key[i] = (art_key_chunk_t)(high48 >> (8 * (ART_KEY_BYTES - 1 - i)));
}

static uint64_t bitroarArtKeyToHigh48(const art_key_chunk_t key[ART_KEY_BYTES]) {
    uint64_t v = 0;
    for (int i = 0; i < ART_KEY_BYTES; i++) v = (v << 8) | key[i];
    return v;
}

static int bitroarIsFrozen(const roaring64_bitmap_t *r) {
    return r->flags & ROARING_FLAG_FROZEN;
}

static size_t bitroarContainerAllocSize(const roaring64_bitmap_t *r,
                                        const container_t *container,
                                        uint8_t typecode)
{
    if (container == NULL) return 0;
    serverAssert(typecode != SHARED_CONTAINER_TYPE);

    size_t size = bitroarMallocSize(container);
    if (bitroarIsFrozen(r)) return size;

    switch (typecode) {
    case ARRAY_CONTAINER_TYPE: {
        const array_container_t *array = const_CAST_array(container);
        return size + bitroarMallocSize(array->array);
    }
    case BITSET_CONTAINER_TYPE: {
        const bitset_container_t *bitset = const_CAST_bitset(container);
        return size + bitroarAlignedMallocSize(bitset->words);
    }
    case RUN_CONTAINER_TYPE: {
        const run_container_t *run = const_CAST_run(container);
        return size + bitroarMallocSize(run->runs);
    }
    default:
        serverPanic("Unknown Roaring bitmap container type");
    }
}

static size_t bitroarRoaringAllocSize(const roaring64_bitmap_t *r) {
    size_t size = bitroarMallocSize(r);

    if (!bitroarIsFrozen(r)) {
        for (int i = BITROAR_ART_MIN_NODE_TYPE; i <= BITROAR_ART_MAX_NODE_TYPE; i++)
            size += bitroarMallocSize(r->art.nodes[i]);
    }
    size += bitroarMallocSize(r->containers);

    art_iterator_t it = art_init_iterator((art_t *)&r->art, true);
    while (it.value != NULL) {
        roaring64_leaf_t leaf = (roaring64_leaf_t)*it.value;
        size += bitroarContainerAllocSize(
            r, r->containers[roaring64_leaf_index(leaf)],
            roaring64_leaf_typecode(leaf));
        art_iterator_next(&it);
    }
    return size;
}

static size_t bitroarTopLevelAllocSize(const roaring64_bitmap_t *r) {
    size_t size = bitroarMallocSize(r);

    if (!bitroarIsFrozen(r)) {
        for (int i = BITROAR_ART_MIN_NODE_TYPE; i <= BITROAR_ART_MAX_NODE_TYPE; i++)
            size += bitroarMallocSize(r->art.nodes[i]);
    }
    size += bitroarMallocSize(r->containers);
    return size;
}

/* Mutating one bit or range can only change the top-level CRoaring arrays and
 * the containers whose high 48 bits fall inside that range. Keep hot
 * accounting updates proportional to the mutation instead of walking every
 * bitmap container. */
static size_t bitroarRangeAllocSize(const roaring64_bitmap_t *r,
                                    uint64_t start, uint64_t end)
{
    size_t size = bitroarTopLevelAllocSize(r);

    if (start >= end) return size;

    uint64_t last_high48 = (end - 1) >> 16;
    art_key_chunk_t key[ART_KEY_BYTES];
    bitroarArtKeyFromHigh48(start >> 16, key);
    art_iterator_t it = art_lower_bound((art_t *)&r->art, key);
    while (it.value != NULL) {
        uint64_t high48 = bitroarArtKeyToHigh48(it.key);
        if (high48 > last_high48) break;

        roaring64_leaf_t leaf = (roaring64_leaf_t)*it.value;
        size += bitroarContainerAllocSize(
            r, r->containers[roaring64_leaf_index(leaf)],
            roaring64_leaf_typecode(leaf));
        art_iterator_next(&it);
    }
    return size;
}

/* Whole-object refreshes walk all containers and are therefore performed only
 * when allocation data is requested. Servers with memory tracking enabled ask
 * for it while inserting an object; otherwise the first MEMORY USAGE does. */
static void bitroarRefreshAllocSize(bitroar *bitmap) {
    bitmap->alloc_size = bitroarMallocSize(bitmap) + bitroarRoaringAllocSize(bitmap->roaring);
}

static void bitroarRefreshRangeAllocSize(bitroar *bitmap, uint64_t start,
                                         uint64_t end, size_t old_size)
{
    size_t new_size = bitroarRangeAllocSize(bitmap->roaring, start, end);
    bitroarAdjustAllocSize(&bitmap->alloc_size, old_size, new_size);
}

size_t bitroarAllocSize(const robj *o) {
    bitroar *bitmap = bitroarGet(o);

    if (bitmap->alloc_size == BITROAR_ALLOC_SIZE_UNKNOWN)
        bitroarRefreshAllocSize(bitmap);
    return bitmap->alloc_size;
}

size_t bitroarContainerCountUpTo(const robj *o, size_t limit) {
    bitroar *bitmap = bitroarGet(o);
    size_t count = 0;

    art_iterator_t it = art_init_iterator((art_t *)&bitmap->roaring->art, true);
    while (it.value != NULL && count < limit) {
        count++;
        art_iterator_next(&it);
    }
    return count;
}

size_t bitroarContainerCount(const robj *o) {
    return bitroarContainerCountUpTo(o, SIZE_MAX);
}

static void bitroarDismissContainer(container_t *container, uint8_t type) {
    if (container == NULL) return;

    switch (type) {
    case ARRAY_CONTAINER_TYPE: {
        array_container_t *array = CAST_array(container);
        dismissMemory(array->array, (size_t)array->capacity * sizeof(*array->array));
        dismissMemory(array, sizeof(*array));
        break;
    }
    case BITSET_CONTAINER_TYPE: {
        bitset_container_t *bitset = CAST_bitset(container);
        dismissMemory(bitroarAlignedAllocBase(bitset->words), 0);
        dismissMemory(bitset, sizeof(*bitset));
        break;
    }
    case RUN_CONTAINER_TYPE: {
        run_container_t *run = CAST_run(container);
        dismissMemory(run->runs, (size_t)run->capacity * sizeof(*run->runs));
        dismissMemory(run, sizeof(*run));
        break;
    }
    default:
        serverPanic("Unknown Roaring bitmap container type");
    }
}

void bitroarDismiss(robj *o, size_t size_hint) {
    bitroar *bitmap = bitroarGet(o);
    roaring64_bitmap_t *r = bitmap->roaring;
    size_t count = bitroarContainerCount(o);

    /* Iterate the containers only when the average container payload is
     * likely to span whole pages, like the other complex types (see
     * dismissObject()). */
    if (count > 0 && size_hint / count >= server.page_size) {
        art_iterator_t it = art_init_iterator((art_t *)&r->art, true);
        while (it.value != NULL) {
            roaring64_leaf_t leaf = (roaring64_leaf_t)*it.value;
            bitroarDismissContainer(
                r->containers[roaring64_leaf_index(leaf)],
                roaring64_leaf_typecode(leaf));
            art_iterator_next(&it);
        }
    }

    for (int i = BITROAR_ART_MIN_NODE_TYPE; i <= BITROAR_ART_MAX_NODE_TYPE; i++) {
        if (r->art.nodes[i] != NULL) dismissMemory(r->art.nodes[i], 0);
    }
    dismissMemory(r->containers, 0);
    dismissMemory(r, sizeof(*r));
    dismissMemory(bitmap, sizeof(*bitmap));
}

/* --- Active defrag support ---
 *
 * Every allocation CRoaring makes for a bitmap goes through the zmalloc-backed
 * memory hook installed in bitroarInit(), so active defrag can relocate
 * each one with activeDefragAlloc(). The walk mirrors bitroarDismiss():
 * the wrapper struct, the Roaring bitmap struct, the per-type ART node arrays
 * (which hold indices, not pointers, so relocating them needs no fixups), the
 * flat container pointer array, and every container with its payload buffer.
 * Relocating a container only requires updating its slot in the container
 * pointer array; the ART leaf stores an index that does not change. */

/* CRoaring requests this alignment for bitset container word buffers in the
 * portable build Redis uses (see align_size in CRoaring's
 * bitset_container_create(); the SIMD-gated 64-byte case is compiled out by
 * ROARING_DISABLE_X64). With jemalloc the words are an exact-size block in the
 * 8 KiB size class, whose regions are at least 4 KiB aligned, so relocating
 * it within that class keeps the alignment. Otherwise bitroarAlignedMalloc()
 * over-allocates by alignment - 1 + sizeof(void *), so re-deriving an aligned
 * offset inside a relocated block always fits. */
#define BITROAR_BITSET_WORDS_ALIGNMENT 32

static void *bitroarActiveDefragAlloc(bitroar *bitmap, void *ptr) {
    size_t old_size = zmalloc_usable_size(ptr);
    void *newptr = activeDefragAlloc(ptr);
    if (newptr != NULL)
        bitroarAdjustAllocSize(&bitmap->alloc_size, old_size,
                               zmalloc_usable_size(newptr));
    return newptr;
}

static bitroar *bitroarActiveDefragSelf(bitroar *bitmap) {
    size_t old_size = zmalloc_usable_size(bitmap);
    bitroar *newbitmap = activeDefragAlloc(bitmap);
    if (newbitmap != NULL)
        bitroarAdjustAllocSize(&newbitmap->alloc_size, old_size,
                               zmalloc_usable_size(newbitmap));
    return newbitmap;
}

#if defined(USE_JEMALLOC)
/* With 4 or 8 KiB pages each 8 KiB slab holds a single region, so the defrag
 * hint never moves these words; larger pages or forced defrag can. */
static void bitroarDefragBitsetWords(bitroar *bitmap, bitset_container_t *bitset) {
    uint64_t *words;

    if (bitset->words == NULL) return;
    words = bitroarActiveDefragAlloc(bitmap, bitset->words);
    if (words == NULL) return;

    /* activeDefragAlloc() drops the alignment flag but keeps the usable size,
     * and with it the size class, so the words must still be aligned. */
    serverAssert(((uintptr_t)words & (BITROAR_BITSET_WORDS_ALIGNMENT - 1)) == 0);
    bitset->words = words;
}
#else
static void bitroarDefragBitsetWords(bitroar *bitmap, bitset_container_t *bitset) {
    void *base, *newbase;
    uintptr_t aligned;
    size_t old_off, new_off;

    if (bitset->words == NULL) return;
    base = bitroarAlignedAllocBase(bitset->words);
    /* activeDefragAlloc() may free base. Capture every relationship to the old
     * allocation before calling it. */
    old_off = (size_t)((char *)bitset->words - (char *)base);
    newbase = bitroarActiveDefragAlloc(bitmap, base);
    if (newbase == NULL) return;

    /* The relocation copied the block verbatim, so the words still sit at
     * their old offset; re-derive the aligned offset for the new base address
     * and slide the words when the two differ. */
    aligned = ((uintptr_t)newbase + sizeof(void *) +
               (BITROAR_BITSET_WORDS_ALIGNMENT - 1)) &
              ~((uintptr_t)BITROAR_BITSET_WORDS_ALIGNMENT - 1);
    new_off = (size_t)(aligned - (uintptr_t)newbase);
    if (new_off != old_off)
        memmove((char *)newbase + new_off, (char *)newbase + old_off,
                sizeof(uint64_t) * BITSET_CONTAINER_SIZE_IN_WORDS);
    ((void **)aligned)[-1] = newbase;
    bitset->words = (uint64_t *)aligned;
}
#endif

/* Defrag one container; returns the moved container pointer, or NULL if the
 * container struct itself did not move (its payload may still have moved). */
static container_t *bitroarDefragContainer(container_t *container,
                                           bitroar *bitmap, uint8_t type) {
    void *new_container;

    if (container == NULL) return NULL;

    switch (type) {
    case ARRAY_CONTAINER_TYPE: {
        array_container_t *array = CAST_array(container);
        uint16_t *values;
        if ((new_container = bitroarActiveDefragAlloc(bitmap, array)) != NULL)
            array = (array_container_t *)new_container;
        if (array->array != NULL &&
            (values = bitroarActiveDefragAlloc(bitmap, array->array)) != NULL)
            array->array = values;
        return (container_t *)new_container;
    }
    case BITSET_CONTAINER_TYPE: {
        bitset_container_t *bitset = CAST_bitset(container);
        if ((new_container = bitroarActiveDefragAlloc(bitmap, bitset)) != NULL)
            bitset = (bitset_container_t *)new_container;
        bitroarDefragBitsetWords(bitmap, bitset);
        return (container_t *)new_container;
    }
    case RUN_CONTAINER_TYPE: {
        run_container_t *run = CAST_run(container);
        rle16_t *runs;
        if ((new_container = bitroarActiveDefragAlloc(bitmap, run)) != NULL)
            run = (run_container_t *)new_container;
        if (run->runs != NULL &&
            (runs = bitroarActiveDefragAlloc(bitmap, run->runs)) != NULL)
            run->runs = runs;
        return (container_t *)new_container;
    }
    default:
        serverPanic("Unknown Roaring bitmap container type");
    }
}

/* Relocate the wrapper struct, roaring struct, ART node arrays and container
 * pointer array, and refresh o->ptr. Container payloads are handled
 * separately so the walk can be split into incremental steps. */
static roaring64_bitmap_t *bitroarDefragTopLevel(robj *o) {
    bitroar *bitmap = bitroarGet(o), *newbitmap;
    roaring64_bitmap_t *r, *newroaring;

    if ((newbitmap = bitroarActiveDefragSelf(bitmap)) != NULL)
        o->ptr = bitmap = newbitmap;
    if ((newroaring = bitroarActiveDefragAlloc(bitmap, bitmap->roaring)) != NULL)
        bitmap->roaring = newroaring;
    r = bitmap->roaring;

    for (int i = BITROAR_ART_MIN_NODE_TYPE; i <= BITROAR_ART_MAX_NODE_TYPE; i++) {
        void *moved;
        if (r->art.nodes[i] != NULL &&
            (moved = bitroarActiveDefragAlloc(bitmap, r->art.nodes[i])) != NULL)
            r->art.nodes[i] = moved;
    }
    if (r->containers != NULL) {
        container_t **moved = bitroarActiveDefragAlloc(bitmap, r->containers);
        if (moved != NULL) r->containers = moved;
    }
    return r;
}

static void bitroarDefragLeafContainer(roaring64_bitmap_t *r, bitroar *bitmap,
                                       roaring64_leaf_t leaf)
{
    uint64_t index = roaring64_leaf_index(leaf);
    container_t *moved = bitroarDefragContainer(
        r->containers[index], bitmap, roaring64_leaf_typecode(leaf));
    if (moved != NULL) r->containers[index] = moved;
    server.stat_active_defrag_scanned++;
}

void bitroarDefrag(robj *o) {
    bitroar *bitmap;
    roaring64_bitmap_t *r = bitroarDefragTopLevel(o);
    bitmap = bitroarGet(o);

    art_iterator_t it = art_init_iterator(&r->art, true);
    while (it.value != NULL) {
        bitroarDefragLeafContainer(r, bitmap, (roaring64_leaf_t)*it.value);
        art_iterator_next(&it);
    }
}

/* Incremental defrag step for bitmaps queued with defragLater(): 'cursor' is
 * one plus the high 48 bits of the last container processed (so it is never 0
 * mid-walk; 0 also relocates the top-level allocations). The key-space cursor
 * survives concurrent writes: containers added or removed between steps only
 * make the walk skip or revisit a few containers, which is harmless for
 * defrag. The cursor also fits where unsigned long is 32 bits: size_t is 32
 * bits there too, and bitroarCanRepresentBit() and the loaders keep
 * byte_len <= SIZE_MAX, so every set bit is below 2^35 and every high48 key
 * below 2^19. Returns the new cursor, 0 when done. */
unsigned long bitroarDefragIncremental(robj *o, unsigned long cursor) {
    bitroar *bitmap;
    roaring64_bitmap_t *r;
    art_iterator_t it;
    long iterations = 0;

    if (cursor == 0) {
        r = bitroarDefragTopLevel(o);
        bitmap = bitroarGet(o);
        it = art_init_iterator(&r->art, true);
    } else {
        art_key_chunk_t key[ART_KEY_BYTES];
        bitmap = bitroarGet(o);
        r = bitmap->roaring;
        bitroarArtKeyFromHigh48((uint64_t)cursor, key);
        it = art_lower_bound(&r->art, key);
    }

    while (it.value != NULL) {
        bitroarDefragLeafContainer(r, bitmap, (roaring64_leaf_t)*it.value);
        uint64_t high48 = bitroarArtKeyToHigh48(it.key);
        art_iterator_next(&it);
        if (++iterations >= 128 && it.value != NULL)
            return (unsigned long)(high48 + 1);
    }
    return 0;
}

uint64_t bitroarCardinality(const robj *o) {
    bitroar *bitmap = bitroarGet(o);
    return roaring64_bitmap_get_cardinality(bitmap->roaring);
}

uint64_t bitroarRangeCardinality(const robj *o, uint64_t start, uint64_t end) {
    bitroar *bitmap = bitroarGet(o);
    uint64_t bit_len = bitmap->byte_len * 8;

    if (start >= end || start >= bit_len) return 0;
    if (end > bit_len) end = bit_len;
    return roaring64_bitmap_range_cardinality(bitmap->roaring, start, end);
}

void bitroarVisitSetBitRanges(const robj *o,
                              bitroarRangeCallback *callback,
                              void *privdata)
{
    bitroar *bitmap = bitroarGet(o);
    roaring64_iterator_t *it = roaring64_iterator_create(bitmap->roaring);
    roaring64_range_closed_t ranges[128];
    size_t count;

    do {
        count = roaring64_iterator_read_ranges(
            it, ranges, sizeof(ranges) / sizeof(ranges[0]));
        for (size_t i = 0; i < count; i++)
            callback(ranges[i].min, ranges[i].max + 1, privdata);
    } while (count == sizeof(ranges) / sizeof(ranges[0]));

    roaring64_iterator_free(it);
}

/* Visit the set bits in the half-open bit interval [start, end), in ascending
 * offset order. The iterator seeks directly to 'start' and uses a fixed
 * buffer instead of allocating an array proportional to the result size. */
static void bitroarVisitSetBits(bitroar *bitmap, uint64_t start, uint64_t end,
                                bitroarValuesCallback *callback, void *privdata)
{
    roaring64_iterator_t *it = roaring64_iterator_create(bitmap->roaring);
    if (!roaring64_iterator_move_equalorlarger(it, start)) {
        roaring64_iterator_free(it);
        return;
    }

    uint64_t values[256];
    const uint64_t requested = sizeof(values) / sizeof(values[0]);
    while (1) {
        uint64_t read = roaring64_iterator_read(it, values, requested);
        /* Drop the values at or beyond 'end' from the last batch. */
        uint64_t inrange = read;
        while (inrange != 0 && values[inrange - 1] >= end) inrange--;
        if (inrange == 0 || !callback(values, (size_t)inrange, privdata)) break;
        if (inrange < requested) break;
    }

    roaring64_iterator_free(it);
}

/* Pass the offsets in [start, end) to 'callback' in batches of up to 256.
 * Return 0 once the callback asks to stop. */
static int bitroarVisitInterval(uint64_t start, uint64_t end,
                                bitroarValuesCallback *callback, void *privdata)
{
    uint64_t values[256];
    const size_t requested = sizeof(values) / sizeof(values[0]);
    while (start < end) {
        size_t count = 0;
        while (count < requested && start < end) values[count++] = start++;
        if (!callback(values, count, privdata)) return 0;
    }
    return 1;
}

/* Visit the clear bits in the half-open bit interval [start, end), in
 * ascending offset order. They are the gaps between the runs of set bits, so
 * reading whole runs skips long runs of set bits at once. */
static void bitroarVisitClearBits(bitroar *bitmap, uint64_t start, uint64_t end,
                                  bitroarValuesCallback *callback, void *privdata)
{
    roaring64_iterator_t *it = roaring64_iterator_create(bitmap->roaring);
    roaring64_range_closed_t ranges[128];
    const size_t requested = sizeof(ranges) / sizeof(ranges[0]);
    uint64_t next = start; /* The lowest offset not visited yet. */
    size_t count;

    roaring64_iterator_move_equalorlarger(it, start);
    do {
        count = roaring64_iterator_read_ranges(it, ranges, requested);
        for (size_t i = 0; i < count; i++) {
            uint64_t gap_end = ranges[i].min < end ? ranges[i].min : end;
            if (!bitroarVisitInterval(next, gap_end, callback, privdata) ||
                ranges[i].max >= end - 1)
            {
                roaring64_iterator_free(it);
                return;
            }
            next = ranges[i].max + 1;
        }
    } while (count == requested);
    roaring64_iterator_free(it);

    bitroarVisitInterval(next, end, callback, privdata);
}

/* Visit the bits set to 'bit' (0 or 1) in the half-open bit interval
 * [start, end), in ascending offset order, passing their offsets to 'callback'
 * in batches until it returns 0. */
void bitroarVisitBits(const robj *o, int bit, uint64_t start, uint64_t end,
                      bitroarValuesCallback *callback, void *privdata)
{
    if (start >= end) return;

    bitroar *bitmap = bitroarGet(o);
    if (bit)
        bitroarVisitSetBits(bitmap, start, end, callback, privdata);
    else
        bitroarVisitClearBits(bitmap, start, end, callback, privdata);
}

static long long bitroarFirstSetBit(bitroar *bitmap, uint64_t start, uint64_t end) {
    roaring64_bitmap_t *r = bitmap->roaring;

    if (start >= end) return -1;

    art_key_chunk_t key[ART_KEY_BYTES];
    bitroarArtKeyFromHigh48(start >> 16, key);
    art_iterator_t it = art_lower_bound(&r->art, key);

    while (it.value != NULL) {
        uint64_t high48 = bitroarArtKeyToHigh48(it.key);
        uint64_t container_base = high48 << 16;
        uint16_t low16;

        if (container_base >= end) break;

        roaring64_leaf_t leaf = (roaring64_leaf_t)*it.value;
        uint8_t typecode = roaring64_leaf_typecode(leaf);
        container_t *container = r->containers[roaring64_leaf_index(leaf)];

        if (high48 == (start >> 16)) {
            roaring_container_iterator_t container_it = {0};
            if (container_iterator_lower_bound(container, typecode,
                                               &container_it, &low16,
                                               (uint16_t)(start & 0xffff))) {
                uint64_t value = container_base + low16;
                if (value < end) return (long long)value;
            }
        } else {
            uint64_t value = container_base + container_minimum(container, typecode);
            if (value < end) return (long long)value;
        }

        art_iterator_next(&it);
    }
    return -1;
}

/* First clear bit in [from, 1<<16) within one container, or -1 if every bit
 * from 'from' to the end of the container is set. */
static int32_t bitroarContainerFirstClearBit(const container_t *container,
                                             uint8_t type, uint32_t from)
{
    switch (type) {
    case ARRAY_CONTAINER_TYPE: {
        const array_container_t *array = const_CAST_array(container);
        int32_t lo = 0, hi = array->cardinality;
        while (lo < hi) {
            int32_t mid = (lo + hi) / 2;
            if (array->array[mid] < from) lo = mid + 1;
            else hi = mid;
        }
        uint32_t expected = from;
        for (int32_t i = lo; i < array->cardinality; i++) {
            if (array->array[i] != expected) return (int32_t)expected;
            expected++;
        }
        return expected < (1 << 16) ? (int32_t)expected : -1;
    }
    case BITSET_CONTAINER_TYPE: {
        const bitset_container_t *bitset = const_CAST_bitset(container);
        uint32_t word_idx = from >> 6;
        uint64_t word = ~bitset->words[word_idx] & (UINT64_MAX << (from & 63));
        while (1) {
            if (word) return (int32_t)(word_idx * 64 + __builtin_ctzll(word));
            if (++word_idx >= BITSET_CONTAINER_SIZE_IN_WORDS) return -1;
            word = ~bitset->words[word_idx];
        }
    }
    case RUN_CONTAINER_TYPE: {
        const run_container_t *run = const_CAST_run(container);
        uint32_t pos = from;
        for (int32_t i = 0; i < run->n_runs; i++) {
            uint32_t rstart = run->runs[i].value;
            uint32_t rend = rstart + run->runs[i].length;
            if (pos < rstart) return (int32_t)pos;
            if (pos <= rend) pos = rend + 1;
        }
        return pos < (1 << 16) ? (int32_t)pos : -1;
    }
    default:
        serverPanic("Unknown Roaring bitmap container type");
    }
}

/* Walk containers in key order looking for the first clear bit: a gap before
 * the next container is all zeroes, and within a container each type can find
 * its first absent bit directly. This stays proportional to the containers
 * spanned by set bits, never to the number of set bits, so dense runs spanning
 * billions of bits do not degrade BITPOS. */
static long long bitroarFirstClearBit(bitroar *bitmap,
                                      uint64_t start, uint64_t end,
                                      int end_given)
{
    roaring64_bitmap_t *r = bitmap->roaring;
    uint64_t pos = start;

    if (start >= end) return -1;

    art_key_chunk_t key[ART_KEY_BYTES];
    bitroarArtKeyFromHigh48(pos >> 16, key);
    art_iterator_t it = art_lower_bound(&r->art, key);

    while (pos < end) {
        if (it.value == NULL) return (long long)pos;

        uint64_t container_base = bitroarArtKeyToHigh48(it.key) << 16;
        if (container_base > pos) return (long long)pos;

        roaring64_leaf_t leaf = (roaring64_leaf_t)*it.value;
        int32_t clear = bitroarContainerFirstClearBit(
            r->containers[roaring64_leaf_index(leaf)],
            roaring64_leaf_typecode(leaf),
            (uint32_t)(pos - container_base));
        if (clear >= 0) {
            uint64_t clear_pos = container_base + (uint64_t)clear;
            if (clear_pos < end) return (long long)clear_pos;
            break;
        }

        pos = container_base + (1 << 16);
        art_iterator_next(&it);
    }

    /* Every bit in [start, end) is set. When the caller gave no explicit end
     * the range is implicitly followed by an imaginary trailing zero. */
    return end_given ? -1 : (long long)end;
}

long long bitroarBitpos(const robj *o, int bit, uint64_t start,
                        uint64_t end, int end_given)
{
    bitroar *bitmap = bitroarGet(o);
    uint64_t bit_len = bitmap->byte_len * 8;

    if (start >= end || start >= bit_len) return -1;
    if (end > bit_len) end = bit_len;

    return bit ? bitroarFirstSetBit(bitmap, start, end) :
                 bitroarFirstClearBit(bitmap, start, end, end_given);
}

/* Whether 'bitoffset' lies inside the logical range a bitmap may hold. Writes
 * from master and AOF clients skip the proto-max-bulk-len offset check, so
 * this is the only bound they meet. Where size_t is narrower than 64 bits it
 * also keeps byte_len (the byte index plus one) within SIZE_MAX: the RDB
 * loader and bitroarCreateFromPortable() reject larger lengths, so the same
 * build could not load such a bitmap back. */
int bitroarCanRepresentBit(uint64_t bitoffset) {
    if (bitoffset > BITROAR_MAX_BITOFFSET) return 0;
#if SIZE_MAX < UINT64_MAX
    if ((bitoffset >> 3) >= (uint64_t)SIZE_MAX) return 0;
#endif
    return 1;
}

int bitroarGetBit(const robj *o, uint64_t bitoffset) {
    bitroar *bitmap = bitroarGet(o);

    if (!bitroarCanRepresentBit(bitoffset)) return 0;
    if ((bitoffset >> 3) >= bitmap->byte_len) return 0;
    return roaring64_bitmap_contains(bitmap->roaring, bitoffset);
}

int bitroarSetBit(robj *o, uint64_t bitoffset, int on) {
    bitroar *bitmap = bitroarGet(o);
    uint64_t byte = bitoffset >> 3;
    size_t old_size = 0;
    int track_alloc_size = bitmap->alloc_size != BITROAR_ALLOC_SIZE_UNKNOWN;

    if (!bitroarCanRepresentBit(bitoffset))
        return C_ERR;

    if (byte + 1 > bitmap->byte_len)
        bitmap->byte_len = byte + 1;

    if (track_alloc_size)
        old_size = bitroarRangeAllocSize(bitmap->roaring, bitoffset, bitoffset + 1);
    if (on)
        roaring64_bitmap_add(bitmap->roaring, bitoffset);
    else
        roaring64_bitmap_remove(bitmap->roaring, bitoffset);
    if (track_alloc_size)
        bitroarRefreshRangeAllocSize(bitmap, bitoffset, bitoffset + 1, old_size);

    return C_OK;
}

uint64_t bitroarGetUnsignedBitfield(const robj *o, uint64_t offset, uint64_t bits) {
    bitroar *bitmap = bitroarGet(o);
    uint64_t bit_len = bitmap->byte_len * 8;
    uint64_t last_bit;
    uint64_t value = 0;
    uint64_t cached_high48 = UINT64_MAX;
    const container_t *container = NULL;
    uint8_t typecode = 0;

    if (bits == 0) return 0;
    if (!bitroarCanRepresentBit(offset) || offset >= bit_len) return 0;
    if (offset <= UINT64_MAX - (bits - 1)) {
        last_bit = offset + bits - 1;
        if (last_bit < bit_len && (offset >> 16) == (last_bit >> 16)) {
            uint64_t high48 = offset >> 16;
            art_key_chunk_t key[ART_KEY_BYTES];
            bitroarArtKeyFromHigh48(high48, key);
            roaring64_leaf_t *leaf = (roaring64_leaf_t *)art_find(&bitmap->roaring->art, key);

            if (leaf == NULL) return 0;

            typecode = roaring64_leaf_typecode(*leaf);
            container = bitmap->roaring->containers[roaring64_leaf_index(*leaf)];
            if (container_contains_range(container, (uint16_t)offset,
                                         (uint32_t)(uint16_t)last_bit + 1, typecode))
            {
                return bits == 64 ? UINT64_MAX : ((UINT64_C(1) << bits) - 1);
            }
            cached_high48 = high48;
        }
    }

    for (uint64_t j = 0; j < bits; j++) {
        if (offset > UINT64_MAX - j) {
            value <<= bits - j;
            break;
        }

        uint64_t bitoffset = offset + j;
        if (!bitroarCanRepresentBit(bitoffset) || bitoffset >= bit_len) {
            value <<= bits - j;
            break;
        }

        uint64_t high48 = bitoffset >> 16;
        if (high48 != cached_high48) {
            art_key_chunk_t key[ART_KEY_BYTES];
            bitroarArtKeyFromHigh48(high48, key);
            roaring64_leaf_t *leaf = (roaring64_leaf_t *)art_find(&bitmap->roaring->art, key);
            if (leaf != NULL) {
                typecode = roaring64_leaf_typecode(*leaf);
                container = bitmap->roaring->containers[roaring64_leaf_index(*leaf)];
            } else {
                container = NULL;
                typecode = 0;
            }
            cached_high48 = high48;
        }

        uint64_t bitval = container != NULL &&
            container_contains(container, (uint16_t)bitoffset, typecode);
        value = (value << 1) | bitval;
    }

    return value;
}

int bitroarSetUnsignedBitfield(robj *o, uint64_t offset, uint64_t bits, uint64_t value) {
    bitroar *bitmap = bitroarGet(o);
    uint64_t positions_to_add[64];
    uint64_t positions_to_remove[64];
    size_t add_count = 0, remove_count = 0;
    size_t old_size = 0;
    int track_alloc_size = bitmap->alloc_size != BITROAR_ALLOC_SIZE_UNKNOWN;

    if (bits == 0) return C_OK;
    if (offset > UINT64_MAX - (bits - 1)) return C_ERR;

    uint64_t last_bit = offset + bits - 1;
    if (!bitroarCanRepresentBit(last_bit)) return C_ERR;

    uint64_t byte = last_bit >> 3;
    if (byte + 1 > bitmap->byte_len)
        bitmap->byte_len = byte + 1;

    for (uint64_t j = 0; j < bits; j++) {
        uint64_t bitoffset = offset + j;
        int bitval = (value & ((uint64_t)1 << (bits - 1 - j))) != 0;
        if (bitval)
            positions_to_add[add_count++] = bitoffset;
        else
            positions_to_remove[remove_count++] = bitoffset;
    }

    if (track_alloc_size)
        old_size = bitroarRangeAllocSize(bitmap->roaring, offset,
                                         last_bit + 1);
    if (add_count)
        roaring64_bitmap_add_many(bitmap->roaring, add_count,
                                  positions_to_add);
    if (remove_count) {
        /* remove_many can keep same-container state after a removal deletes
         * that container; BITFIELD clears may include already-clear bits after
         * the last set bit. */
        for (size_t j = 0; j < remove_count; j++)
            roaring64_bitmap_remove(bitmap->roaring, positions_to_remove[j]);
    }
    if (track_alloc_size)
        bitroarRefreshRangeAllocSize(bitmap, offset, last_bit + 1, old_size);

    return C_OK;
}

static void bitroarMaterializeRawRange(unsigned char *raw, size_t chunk_len,
                                      uint32_t start, uint32_t end)
{
    uint32_t bit = start;

    while (bit <= end) {
        size_t byte = bit >> 3;
        if (byte >= chunk_len) break;

        if ((bit & 7) == 0 && bit + 7 <= end) {
            size_t fill = ((size_t)end - bit + 1) >> 3;
            size_t remaining = chunk_len - byte;
            if (fill > remaining) fill = remaining;
            memset(raw + byte, 0xff, fill);
            bit += (uint32_t)(fill * 8);
        } else {
            raw[byte] |= 1 << (7 - (bit & 7));
            bit++;
        }
    }
}

static void bitroarMaterializeContainer(unsigned char *raw, size_t byte_len, uint64_t high48,
                                        const container_t *container, uint8_t typecode)
{
    const size_t container_bytes = BITSET_CONTAINER_SIZE_IN_WORDS * sizeof(uint64_t);
    uint64_t byte_base = high48 * container_bytes;
    if (byte_base >= byte_len) return;

    size_t chunk_len = byte_len - (size_t)byte_base;
    if (chunk_len > container_bytes) chunk_len = container_bytes;
    unsigned char *chunk = raw + (size_t)byte_base;

    container = container_unwrap_shared(container, &typecode);
    switch (typecode) {
    case BITSET_CONTAINER_TYPE: {
        const bitset_container_t *bitset = const_CAST_bitset(container);
        size_t byte = 0;
        for (int word = 0;
             word < BITSET_CONTAINER_SIZE_IN_WORDS && byte < chunk_len;
             word++)
        {
            uint64_t bits = bitset->words[word];
            for (int lane = 0; lane < 8 && byte < chunk_len; lane++, byte++)
                chunk[byte] = bitroarReverseByte((bits >> (lane * 8)) & 0xff);
        }
        break;
    }
    case ARRAY_CONTAINER_TYPE: {
        const array_container_t *array = const_CAST_array(container);
        for (int32_t i = 0; i < array->cardinality; i++) {
            uint16_t offset = array->array[i];
            size_t byte = offset >> 3;
            if (byte >= chunk_len) break;
            chunk[byte] |= 1 << (7 - (offset & 7));
        }
        break;
    }
    case RUN_CONTAINER_TYPE: {
        const run_container_t *run = const_CAST_run(container);
        for (int32_t i = 0; i < run->n_runs; i++) {
            uint32_t start = run->runs[i].value;
            uint32_t end = start + run->runs[i].length;
            bitroarMaterializeRawRange(chunk, chunk_len, start, end);
        }
        break;
    }
    default:
        serverPanic("Unknown Roaring bitmap container type");
    }
}

static sds bitroarMaterializeRoaring(const roaring64_bitmap_t *roaring,
                                     size_t byte_len, int try_alloc)
{
    sds raw = try_alloc ? sdstrynewlen(NULL, byte_len) : sdsnewlen(NULL, byte_len);
    if (raw == NULL) return NULL;

    art_iterator_t it = art_init_iterator((art_t *)&roaring->art, true);
    while (it.value != NULL) {
        roaring64_leaf_t leaf = (roaring64_leaf_t)*it.value;
        bitroarMaterializeContainer(
            (unsigned char *)raw, byte_len, bitroarArtKeyToHigh48(it.key),
            roaring->containers[roaring64_leaf_index(leaf)],
            roaring64_leaf_typecode(leaf));
        art_iterator_next(&it);
    }
    return raw;
}

static sds bitroarMaterializeRaw(const robj *o, int proto_limited, int try_alloc) {
    bitroar *bitmap = bitroarGet(o);
    if (proto_limited &&
        bitmap->byte_len > (uint64_t)server.proto_max_bulk_len) return NULL;
    if (bitmap->byte_len > (uint64_t)SIZE_MAX) return NULL;
    return bitroarMaterializeRoaring(bitmap->roaring, (size_t)bitmap->byte_len, try_alloc);
}

/* Flatten the bitmap for DEBUG BITMAP-RAW. This is deliberately not a general
 * production serialization API: it returns NULL when the logical length
 * exceeds proto-max-bulk-len. */
sds bitroarMaterializeForDebug(const robj *o) {
    return bitroarMaterializeRaw(o, 1, 0);
}

/* Serialize the internal containers in the RoaringFormatSpec 64-bit portable
 * format. Its size is proportional to resident bitmap data rather than the
 * logical byte length, so sparse bitmaps with high offsets remain cheap to
 * persist. */
sds bitroarSerializePortable(const robj *o) {
    bitroar *bitmap = bitroarGet(o);
    size_t len = roaring64_bitmap_portable_size_in_bytes(bitmap->roaring);
    sds payload = sdsnewlen(SDS_NOINIT, len);
    size_t written = roaring64_bitmap_portable_serialize(bitmap->roaring, payload);
    serverAssert(written == len);
    return payload;
}

/* Roaring-space BITOP reads its sources one at a time. Native bitmaps are
 * borrowed from the keyspace, while a string source is converted into a
 * temporary Roaring bitmap only when it is read, and at most one such
 * conversion is alive at a time. Converting every string up front would make
 * the command's peak memory grow with the number of source arguments rather
 * than with the size of the data, since the same key may be listed any number
 * of times and maxmemory is only checked before the command runs. Reading the
 * same string object again (a repeated key) reuses the live conversion. */
typedef struct bitroarOpSources {
    robj **objects;
    size_t numkeys;
    const robj *converted_obj;      /* String source 'converted' was built from. */
    roaring64_bitmap_t *converted;  /* Live string conversion, or NULL. */
} bitroarOpSources;

typedef struct bitroarRawOpSource {
    const unsigned char *raw;
    sds owned;
    size_t len;
} bitroarRawOpSource;

/* Dense mixed operands are cheaper to flatten and combine as machine words
 * than to convert every string source into a temporary Roaring bitmap. This is
 * the only non-debug raw materialization path. Keep it deliberately narrow:
 * Roaring-only and sparse workloads retain Roaring algebra, while the 1 MiB
 * result and aggregate-input caps bound all temporary raw buffers. */
static int bitroarUseMixedRawOp(robj **objects, size_t numkeys, uint64_t maxlen) {
    int has_string = 0;
    int has_roaring = 0;

    if (maxlen > BITROAR_BITOP_FAST_RESULT_MAX_BYTES) return 0;

    for (size_t i = 0; i < numkeys; i++) {
        robj *o = objects[i];
        if (o == NULL) continue;

        if (o->type == OBJ_BITMAP) {
            has_roaring = 1;
        } else {
            serverAssert(o->type == OBJ_STRING);
            has_string = 1;
        }
    }

    if (!has_string || !has_roaring) return 0;

    /* Cardinality is a full container walk, so only pay it after the cheap
     * type scan proves this is a genuinely mixed operation. Keep the sum of
     * all retained roaring buffers within the same cap as an individual result;
     * otherwise many small operands could make the temporary memory unbounded.
     * At least one set bit per logical byte is a conservative signal that
     * flattening is preferable to sparse container algebra. */
    uint64_t materialized_bytes = 0;
    for (size_t i = 0; i < numkeys; i++) {
        robj *o = objects[i];
        if (o == NULL || o->type != OBJ_BITMAP) continue;

        uint64_t logical_len = bitroarLen(o);
        if (logical_len > BITROAR_BITOP_FAST_RESULT_MAX_BYTES - materialized_bytes)
            return 0;
        materialized_bytes += logical_len;
        if (bitroarCardinality(o) < logical_len) return 0;
    }

    return 1;
}

static uint64_t bitroarRawOpLoadWord(const bitroarRawOpSource *source, size_t offset) {
    uint64_t word = 0;
    if (offset >= source->len) return 0;

    size_t copy = source->len - offset;
    if (copy > sizeof(word)) copy = sizeof(word);
    memcpy(&word, source->raw + offset, copy);
    return word;
}

static uint64_t bitroarRawOpWord(bitroarOp op,
                                 bitroarRawOpSource *sources,
                                 size_t numkeys, size_t offset)
{
    uint64_t output = bitroarRawOpLoadWord(&sources[0], offset);

    switch (op) {
    case BITOP_AND:
        for (size_t i = 1; i < numkeys; i++)
            output &= bitroarRawOpLoadWord(&sources[i], offset);
        break;
    case BITOP_OR:
        for (size_t i = 1; i < numkeys; i++)
            output |= bitroarRawOpLoadWord(&sources[i], offset);
        break;
    case BITOP_XOR:
        for (size_t i = 1; i < numkeys; i++)
            output ^= bitroarRawOpLoadWord(&sources[i], offset);
        break;
    case BITOP_NOT:
        output = ~output;
        break;
    case BITOP_DIFF:
    case BITOP_DIFF1:
    case BITOP_ANDOR: {
        uint64_t disjunction = 0;
        for (size_t i = 1; i < numkeys; i++)
            disjunction |= bitroarRawOpLoadWord(&sources[i], offset);
        if (op == BITOP_DIFF)
            output &= ~disjunction;
        else if (op == BITOP_DIFF1)
            output = ~output & disjunction;
        else
            output &= disjunction;
        break;
    }
    case BITOP_ONE: {
        uint64_t common = 0;
        for (size_t i = 1; i < numkeys; i++) {
            uint64_t word = bitroarRawOpLoadWord(&sources[i], offset);
            common |= output & word;
            output ^= word;
            output &= ~common;
        }
        break;
    }
    default:
        serverPanic("Unknown Roaring bitmap BITOP");
    }

    return output;
}

static roaring64_bitmap_t *bitroarApplyMixedRawOp(bitroarOp op, robj **objects,
                                                  size_t numkeys, size_t maxlen,
                                                  int try_alloc)
{
    bitroarRawOpSource *sources = zcalloc(sizeof(*sources) * numkeys);
    unsigned char **raw_sources = zmalloc(sizeof(*raw_sources) * numkeys);
    size_t minlen = maxlen;

    for (size_t i = 0; i < numkeys; i++) {
        robj *o = objects[i];
        if (o == NULL) {
            raw_sources[i] = NULL;
            minlen = 0;
            continue;
        }

        if (o->type == OBJ_BITMAP) {
            sources[i].len = (size_t)bitroarLen(o);
            /* The mixed-path cap, rather than proto-max-bulk-len, bounds this
             * internal temporary so lowering the protocol limit cannot change
             * whether an otherwise valid Roaring BITOP succeeds. */
            sources[i].owned = bitroarMaterializeRaw(o, 0, try_alloc);
            if (sources[i].owned == NULL) {
                for (size_t j = 0; j < i; j++) sdsfree(sources[j].owned);
                zfree(raw_sources);
                zfree(sources);
                return NULL;
            }
            sources[i].raw = (unsigned char *)sources[i].owned;
        } else {
            serverAssert(o->type == OBJ_STRING);
            sources[i].len = sdslen(o->ptr);
            sources[i].raw = (unsigned char *)o->ptr;
        }
        raw_sources[i] = (unsigned char *)sources[i].raw;
        if (sources[i].len < minlen) minlen = sources[i].len;
    }

    sds raw_result = try_alloc ? sdstrynewlen(SDS_NOINIT, maxlen) :
                                 sdsnewlen(SDS_NOINIT, maxlen);
    if (raw_result == NULL) {
        for (size_t i = 0; i < numkeys; i++) sdsfree(sources[i].owned);
        zfree(raw_sources);
        zfree(sources);
        return NULL;
    }
    size_t offset = 0;
    int used_vector = 0;
#ifdef HAVE_AVX512
    if (__builtin_cpu_supports("avx512f") && minlen >= 10000 && numkeys >= 8) {
        offset = bitopCommandAVX512(raw_sources,
                                    (unsigned char *)raw_result, op,
                                    (unsigned long)numkeys,
                                    (unsigned long)minlen);
        used_vector = 1;
    }
#endif
#ifdef HAVE_AVX2
    if (!used_vector && __builtin_cpu_supports("avx2")) {
        offset = bitopCommandAVX(raw_sources, (unsigned char *)raw_result, op,
                                (unsigned long)numkeys,
                                (unsigned long)minlen);
    }
#else
    UNUSED(used_vector);
#endif
    for (; offset + sizeof(uint64_t) <= maxlen; offset += sizeof(uint64_t)) {
        uint64_t output = bitroarRawOpWord(op, sources, numkeys, offset);
        memcpy(raw_result + offset, &output, sizeof(output));
    }
    if (offset < maxlen) {
        uint64_t output = bitroarRawOpWord(op, sources, numkeys, offset);
        memcpy(raw_result + offset, &output, maxlen - offset);
    }

    roaring64_bitmap_t *result = bitroarFromRaw((unsigned char *)raw_result, maxlen, 0);
    sdsfree(raw_result);
    for (size_t i = 0; i < numkeys; i++) sdsfree(sources[i].owned);
    zfree(raw_sources);
    zfree(sources);
    return result;
}

static int bitroarHasRunContainers(const roaring64_bitmap_t *roaring) {
    art_iterator_t it = art_init_iterator((art_t *)&roaring->art, true);
    while (it.value != NULL) {
        roaring64_leaf_t leaf = (roaring64_leaf_t)*it.value;
        uint8_t typecode = roaring64_leaf_typecode(leaf);
        serverAssert(typecode != SHARED_CONTAINER_TYPE);
        if (typecode == RUN_CONTAINER_TYPE) return 1;
        art_iterator_next(&it);
    }
    return 0;
}

static int bitroarOpSourcesBorrowedWithoutRuns(const bitroarOpSources *sources) {
    for (size_t i = 0; i < sources->numkeys; i++) {
        robj *o = sources->objects[i];
        if (o == NULL) continue;
        if (o->type != OBJ_BITMAP) return 0;
        if (bitroarHasRunContainers(bitroarGet(o)->roaring)) return 0;
    }
    return 1;
}

static void bitroarInitOpSources(bitroarOpSources *sources, robj **objects, size_t numkeys) {
    sources->objects = objects;
    sources->numkeys = numkeys;
    sources->converted_obj = NULL;
    sources->converted = NULL;
}

static void bitroarReleaseOpSources(bitroarOpSources *sources) {
    if (sources->converted != NULL)
        roaring64_bitmap_free(sources->converted);
    sources->converted_obj = NULL;
    sources->converted = NULL;
}

/* Return source 'i' for reading, or NULL for a missing key. Reading a string
 * source other than the one currently converted frees that conversion before
 * building the new one, so the result is only valid until the next call. */
static const roaring64_bitmap_t *bitroarGetOpSource(bitroarOpSources *sources, size_t i) {
    robj *o = sources->objects[i];

    if (o == NULL) return NULL;
    if (o->type == OBJ_BITMAP) return bitroarGet(o)->roaring;

    serverAssert(o->type == OBJ_STRING);
    if (sources->converted_obj != o) {
        bitroarReleaseOpSources(sources);
        sources->converted = bitroarFromRaw((unsigned char *)o->ptr, sdslen(o->ptr), 0);
        sources->converted_obj = o;
    }
    return sources->converted;
}

/* Return a new Roaring bitmap holding source 'i', used to seed an accumulator.
 * String sources are converted directly into it rather than into a temporary
 * that would then have to be copied. */
static roaring64_bitmap_t *bitroarCopyOpSource(bitroarOpSources *sources, size_t i) {
    robj *o = sources->objects[i];
    roaring64_bitmap_t *copy;

    if (o == NULL) {
        copy = roaring64_bitmap_create();
    } else if (o->type == OBJ_BITMAP) {
        copy = roaring64_bitmap_copy(bitroarGet(o)->roaring);
    } else {
        serverAssert(o->type == OBJ_STRING);
        copy = bitroarFromRaw((unsigned char *)o->ptr, sdslen(o->ptr), 0);
    }
    serverAssert(copy != NULL);
    return copy;
}

/* Return the missing-chunk allocation budget for BITOP NOT. Any value clients
 * can create under the current proto-max-bulk-len must stay complementable,
 * as its string form is, so the fixed floor is raised to the chunks such a
 * value can span. BITFIELD checks only a field's first bit against the limit,
 * so a 64-bit field can extend the logical length up to 8 bytes past it.
 * Longer values (restored, loaded or created under a larger limit) remain
 * bounded. */
uint64_t bitroarBitopNotMissingChunkLimit(void) {
    uint64_t reachable_len = (uint64_t)server.proto_max_bulk_len + 8;
    uint64_t reachable_chunks = ((reachable_len - 1) >> 13) + 1;
    return max(reachable_chunks, BITROAR_BITOP_NOT_MAX_MISSING_CHUNKS);
}

/* Return whether complementing this borrowed Roaring source stays within the
 * given missing-chunk allocation budget. Every nonempty ART leaf accounts for
 * one logical chunk that NOT does not have to create from nothing. Stop once
 * enough leaves have been seen, so rejecting a huge sparse value is
 * proportional to its resident containers rather than its logical length. */
int bitroarBitopNotWithinMissingChunkLimit(const robj *o, uint64_t max_missing) {
    bitroar *bitmap = bitroarGet(o);
    if (bitmap->byte_len == 0) return 1;

    uint64_t logical_chunks = ((bitmap->byte_len - 1) >> 13) + 1;
    if (logical_chunks <= max_missing) return 1;

    uint64_t required_present = logical_chunks - max_missing;
    uint64_t present = 0;
    art_iterator_t it = art_init_iterator(&bitmap->roaring->art, true);
    while (it.value != NULL && present < required_present) {
        present++;
        art_iterator_next(&it);
    }
    return present == required_present;
}

static uint32_t bitroarNotChunkEnd(uint64_t high48, uint64_t last_high48,
                                   uint64_t bit_len)
{
    if (high48 != last_high48) return 1U << 16;
    return (uint32_t)(bit_len - (high48 << 16));
}

/* CRoaring negates an ARRAY container by first expanding it to an 8 KiB
 * BITSET. A compact source with one ARRAY container per logical chunk would
 * retain all of those bitsets until the final run-optimization pass. Build a
 * borrowed source's complement one chunk at a time instead, using a temporary
 * RUN only when the complement's run representation is smaller than the
 * direct ARRAY or BITSET result. */
static void bitroarAppendNotChunk(roaring64_bitmap_t *result,
                                  const roaring64_bitmap_t *source,
                                  const roaring64_leaf_t *leaf,
                                  uint64_t high48, uint32_t chunk_end)
{
    container_t *complement;
    uint8_t complement_type;

    if (leaf == NULL) {
        complement = container_range_of_ones(0, chunk_end, &complement_type);
    } else {
        uint8_t source_type = roaring64_leaf_typecode(*leaf);
        const container_t *source_container =
            source->containers[roaring64_leaf_index(*leaf)];
        source_container = container_unwrap_shared(source_container, &source_type);

        if (source_type == ARRAY_CONTAINER_TYPE) {
            const array_container_t *source_array = const_CAST_array(source_container);
            serverAssert(source_array->cardinality > 0);
            serverAssert(source_array->array[source_array->cardinality - 1] < chunk_end);

            int32_t complement_cardinality = (int32_t)chunk_end - source_array->cardinality;
            int32_t complement_runs = array_container_number_of_runs(source_array) + 1;
            if (source_array->array[0] == 0) complement_runs--;
            if (source_array->array[source_array->cardinality - 1] ==
                chunk_end - 1)
                complement_runs--;
            serverAssert(complement_cardinality >= 0);
            serverAssert(complement_runs >= 0);

            int32_t direct_size = complement_cardinality <= DEFAULT_MAX_SIZE ?
                array_container_serialized_size_in_bytes(complement_cardinality) :
                    bitset_container_serialized_size_in_bytes();
            int32_t run_size = run_container_serialized_size_in_bytes(complement_runs);

            if (run_size < direct_size) {
                run_container_t *source_run = run_container_from_array(source_array);
                serverAssert(source_run != NULL);
                complement_type = (uint8_t)run_container_negation_range(
                    source_run, 0, chunk_end, &complement);
                run_container_free(source_run);
            } else {
                complement = container_not_range(source_container, source_type,
                                                 0, chunk_end,
                                                 &complement_type);
            }
        } else {
            complement = container_not_range(source_container, source_type,
                                             0, chunk_end, &complement_type);
        }
    }

    serverAssert(complement != NULL);
    if (container_nonzero_cardinality(complement, complement_type)) {
        bitroarAppendContainer(result, high48, complement, complement_type);
    } else {
        container_free(complement, complement_type);
    }
}

static roaring64_bitmap_t *bitroarNotOpSource(const roaring64_bitmap_t *source,
                                              uint64_t bit_len)
{
    roaring64_bitmap_t *result = roaring64_bitmap_create();
    serverAssert(result != NULL);
    if (bit_len == 0) return result;

    serverAssert(source != NULL);
    uint64_t last_high48 = (bit_len - 1) >> 16;
    uint64_t next_high48 = 0;
    art_iterator_t it = art_init_iterator((art_t *)&source->art, true);

    while (it.value != NULL) {
        uint64_t source_high48 = bitroarArtKeyToHigh48(it.key);
        if (source_high48 > last_high48) break;
        serverAssert(source_high48 >= next_high48);

        while (next_high48 < source_high48) {
            bitroarAppendNotChunk(result, source, NULL, next_high48,
                bitroarNotChunkEnd(next_high48, last_high48, bit_len));
            next_high48++;
        }

        bitroarAppendNotChunk(result, source,
            (const roaring64_leaf_t *)it.value, source_high48,
            bitroarNotChunkEnd(source_high48, last_high48, bit_len));
        next_high48 = source_high48 + 1;
        art_iterator_next(&it);
    }

    while (next_high48 <= last_high48) {
        bitroarAppendNotChunk(result, source, NULL, next_high48,
            bitroarNotChunkEnd(next_high48, last_high48, bit_len));
        next_high48++;
    }
    return result;
}

static roaring64_bitmap_t *bitroarUnionOpSources(bitroarOpSources *sources, size_t start) {
    roaring64_bitmap_t *result = roaring64_bitmap_create();
    serverAssert(result != NULL);

    for (size_t i = start; i < sources->numkeys; i++) {
        const roaring64_bitmap_t *source = bitroarGetOpSource(sources, i);
        if (source != NULL)
            roaring64_bitmap_or_inplace(result, source);
    }
    return result;
}

static roaring64_bitmap_t *bitroarExactlyOneOpSources(bitroarOpSources *sources) {
    roaring64_bitmap_t *result = bitroarCopyOpSource(sources, 0);
    roaring64_bitmap_t *multiple = roaring64_bitmap_create();
    serverAssert(multiple != NULL);

    for (size_t i = 1; i < sources->numkeys; i++) {
        const roaring64_bitmap_t *source = bitroarGetOpSource(sources, i);
        roaring64_bitmap_t *both;

        if (source == NULL) continue;

        both = roaring64_bitmap_and(result, source);
        serverAssert(both != NULL);
        roaring64_bitmap_or_inplace(multiple, both);
        roaring64_bitmap_free(both);

        roaring64_bitmap_xor_inplace(result, source);
        roaring64_bitmap_andnot_inplace(result, multiple);
    }

    roaring64_bitmap_free(multiple);
    return result;
}

/* Compute a BITOP over string and Roaring bitmap sources and return the result
 * as a new Roaring bitmap object whose logical length is 'maxlen', matching the
 * string semantics where the destination length equals the longest source.
 * Sparse, large and Roaring-only operations stay entirely in Roaring space;
 * bounded dense mixed operands use the raw-word path above. With 'try_alloc'
 * set, failing to allocate that path's raw temporaries returns NULL instead
 * of aborting; otherwise this never returns NULL. */
robj *bitroarApplyOp(bitroarOp op, robj **objects, size_t numkeys, uint64_t maxlen,
                     int try_alloc)
{
    bitroarOpSources sources;
    const roaring64_bitmap_t *source;
    roaring64_bitmap_t *result = NULL;
    int optimize_result = 1;
    int shrink_result = 1;

    serverAssert(numkeys > 0);
    /* Constructors and RDB loading reject longer logical lengths before an
     * object can reach a command path. */
    serverAssert(maxlen <= BITROAR_MAX_BYTES);

    if (bitroarUseMixedRawOp(objects, numkeys, maxlen)) {
        result = bitroarApplyMixedRawOp(op, objects, numkeys, (size_t)maxlen, try_alloc);
        if (result == NULL) return NULL;
        optimize_result = 0;
        shrink_result = 0;
        goto bitop_result;
    }

    bitroarInitOpSources(&sources, objects, numkeys);

    switch (op) {
    case BITOP_AND: {
        int skip_optimize = maxlen <= BITROAR_BITOP_FAST_RESULT_MAX_BYTES &&
            bitroarOpSourcesBorrowedWithoutRuns(&sources);
        result = bitroarCopyOpSource(&sources, 0);
        for (size_t i = 1; i < numkeys; i++) {
            source = bitroarGetOpSource(&sources, i);
            if (source != NULL)
                roaring64_bitmap_and_inplace(result, source);
            else
                roaring64_bitmap_clear(result);
        }
        if (skip_optimize) {
            optimize_result = 0;
            shrink_result = 0;
        }
        break;
    }
    case BITOP_OR:
        result = bitroarCopyOpSource(&sources, 0);
        for (size_t i = 1; i < numkeys; i++) {
            source = bitroarGetOpSource(&sources, i);
            if (source != NULL)
                roaring64_bitmap_or_inplace(result, source);
        }
        break;
    case BITOP_XOR:
        result = bitroarCopyOpSource(&sources, 0);
        for (size_t i = 1; i < numkeys; i++) {
            source = bitroarGetOpSource(&sources, i);
            if (source != NULL)
                roaring64_bitmap_xor_inplace(result, source);
        }
        break;
    case BITOP_NOT:
        if (objects[0] != NULL && objects[0]->type == OBJ_STRING) {
            /* String sources already occupy memory proportional to maxlen.
             * Convert them straight into the result and complement it in
             * place so dense strings do not require a second full set of
             * containers. */
            result = bitroarCopyOpSource(&sources, 0);
            roaring64_bitmap_flip_inplace(result, 0, maxlen * 8);
        } else {
            result = bitroarNotOpSource(bitroarGetOpSource(&sources, 0), maxlen * 8);
        }
        break;
    case BITOP_DIFF:
        result = bitroarCopyOpSource(&sources, 0);
        for (size_t i = 1; i < numkeys; i++) {
            source = bitroarGetOpSource(&sources, i);
            if (source != NULL)
                roaring64_bitmap_andnot_inplace(result, source);
        }
        break;
    case BITOP_DIFF1:
        result = bitroarUnionOpSources(&sources, 1);
        source = bitroarGetOpSource(&sources, 0);
        if (source != NULL)
            roaring64_bitmap_andnot_inplace(result, source);
        break;
    case BITOP_ANDOR:
        result = bitroarUnionOpSources(&sources, 1);
        source = bitroarGetOpSource(&sources, 0);
        if (source != NULL)
            roaring64_bitmap_and_inplace(result, source);
        else
            roaring64_bitmap_clear(result);
        break;
    case BITOP_ONE:
        result = bitroarExactlyOneOpSources(&sources);
        break;
    default:
        serverPanic("Unknown Roaring bitmap BITOP");
    }

    bitroarReleaseOpSources(&sources);

bitop_result:
    /* Large or potentially run-friendly results still pay the conversion and
     * compaction cost before being stored; small roaring steady-state results
     * skip both full-result CRoaring walks above. */
    if (optimize_result) roaring64_bitmap_run_optimize(result);
    if (shrink_result) roaring64_bitmap_shrink_to_fit(result);

    bitroar *bitmap = zmalloc(sizeof(*bitmap));
    bitmap->byte_len = maxlen;
    bitmap->roaring = result;
    bitmap->alloc_size = BITROAR_ALLOC_SIZE_UNKNOWN;

    robj *o = createObject(OBJ_BITMAP, bitmap);
    o->encoding = OBJ_ENCODING_BITMAP_ROARING;
    return o;
}
