#include <dirent.h>
#include <errno.h>
#include <stdbool.h>
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <poll.h>
#include <stddef.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#if defined(__APPLE__)
#include <sys/event.h>
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#include <CommonCrypto/CommonCryptoError.h>
#include <CommonCrypto/CommonKeyDerivation.h>
#if defined(YAZA_WITH_TLS)
#include <CoreFoundation/CoreFoundation.h>
#include <Security/SecCertificate.h>
#include <Security/SecImportExport.h>
#include <Security/SecureTransport.h>
#include <Security/SecPolicy.h>
#include <Security/SecTrust.h>
#endif
#elif defined(__linux__)
#include <sys/epoll.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/crypto.h>
#if defined(YAZA_WITH_TLS)
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#endif
#else
#error "YAZA cryptographic providers are not configured for this target"
#endif
#if defined(YAZA_WITH_ARGON2)
#include <argon2.h>
#endif
#ifdef YAZA_WITH_POSTGRES
#include <libpq-fe.h>
#endif

extern int yaza_argc;
extern char **yaza_argv;
int yaza_argc;
char **yaza_argv;

typedef struct yaza_memory_arena {
    struct yaza_memory_header *allocations;
    size_t live_bytes;
    size_t peak_bytes;
    size_t allocation_limit;
    uint64_t allocation_count;
} yaza_memory_arena;

typedef struct yaza_memory_header {
    max_align_t alignment;
    uint64_t magic;
    size_t size;
    yaza_memory_arena *arena;
    struct yaza_memory_header *previous;
    struct yaza_memory_header *next;
} yaza_memory_header;

#define YAZA_MEMORY_MAGIC UINT64_C(0x59415a414d454d31)
#define YAZA_PROGRAM_MEMORY_LIMIT (512U * 1024U * 1024U)
#define YAZA_REQUEST_MEMORY_LIMIT (64U * 1024U * 1024U)

/* Per-thread allocation context. Worker execution must never overwrite another request's arena. */
static _Thread_local yaza_memory_arena *yaza_current_memory_arena = NULL;
static yaza_memory_arena yaza_program_memory_arena;
static bool yaza_program_memory_initialized = false;
static pthread_mutex_t yaza_program_memory_mutex = PTHREAD_MUTEX_INITIALIZER;

static void yaza_program_memory_lock(void) {
    if (pthread_mutex_lock(&yaza_program_memory_mutex) != 0) abort();
}

static void yaza_program_memory_unlock(void) {
    if (pthread_mutex_unlock(&yaza_program_memory_mutex) != 0) abort();
}

static void yaza_memory_arena_reset(yaza_memory_arena *arena);
static void yaza_net_shutdown(void);
static void yaza_fs_roots_shutdown(void);
static void yaza_pg_pool_shutdown(int64_t timeout_ms);
static void yaza_ttl_cache_shutdown(void);
static int64_t yaza_monotonic_milliseconds(void);
static void yaza_exec_search_path(const char *command, char *const arguments[], char *const environment[]);

static void *yaza_system_malloc(size_t size) { return malloc(size); }
static void *yaza_system_calloc(size_t count, size_t size) { return calloc(count, size); }
static void *yaza_system_realloc(void *pointer, size_t size) { return realloc(pointer, size); }
static void yaza_system_free(void *pointer) { free(pointer); }

static void yaza_memory_arena_init(yaza_memory_arena *arena, size_t allocation_limit) {
    memset(arena, 0, sizeof(*arena));
    arena->allocation_limit = allocation_limit;
}

static yaza_memory_arena *yaza_memory_arena_enter(yaza_memory_arena *arena) {
    yaza_memory_arena *previous = yaza_current_memory_arena;
    yaza_current_memory_arena = arena;
    return previous;
}

static void yaza_memory_arena_leave(yaza_memory_arena *arena, yaza_memory_arena *previous) {
    yaza_memory_arena_reset(arena);
    yaza_memory_arena_enter(previous);
}

static void yaza_memory_arena_reset(yaza_memory_arena *arena) {
    bool shared = arena == &yaza_program_memory_arena;
    if (shared) yaza_program_memory_lock();
    yaza_memory_header *header = arena->allocations;
    while (header != NULL) {
        yaza_memory_header *next = header->next;
        header->magic = 0;
        yaza_system_free(header);
        header = next;
    }
    arena->allocations = NULL;
    arena->live_bytes = 0;
    arena->allocation_count = 0;
    if (shared) yaza_program_memory_unlock();
}

static size_t yaza_program_memory_live_bytes(void) {
    yaza_program_memory_lock();
    size_t live_bytes = yaza_program_memory_arena.live_bytes;
    yaza_program_memory_unlock();
    return live_bytes;
}

static void yaza_memory_shutdown(void) {
    if (!yaza_program_memory_initialized) return;
    yaza_pg_pool_shutdown(5000);
    yaza_net_shutdown();
    yaza_fs_roots_shutdown();
    yaza_ttl_cache_shutdown();
    yaza_memory_arena_reset(&yaza_program_memory_arena);
    yaza_program_memory_initialized = false;
    yaza_current_memory_arena = NULL;
}

static void *yaza_memory_malloc(size_t size) {
    if (size == 0) size = 1;
    if (size > SIZE_MAX - sizeof(yaza_memory_header)) return NULL;
    size_t allocation_size = sizeof(yaza_memory_header) + size;
    yaza_memory_arena *arena = yaza_current_memory_arena;
    bool shared = arena == &yaza_program_memory_arena;
    if (shared) yaza_program_memory_lock();
    if (arena != NULL && (allocation_size > arena->allocation_limit ||
                          arena->live_bytes > arena->allocation_limit - allocation_size)) {
        if (shared) yaza_program_memory_unlock();
        return NULL;
    }
    yaza_memory_header *header = (yaza_memory_header *)yaza_system_malloc(allocation_size);
    if (header == NULL) {
        if (shared) yaza_program_memory_unlock();
        return NULL;
    }
    header->magic = YAZA_MEMORY_MAGIC;
    header->size = size;
    header->arena = arena;
    header->previous = NULL;
    header->next = NULL;
    if (arena != NULL) {
        header->next = arena->allocations;
        if (header->next != NULL) header->next->previous = header;
        arena->allocations = header;
        arena->live_bytes += allocation_size;
        if (arena->peak_bytes < arena->live_bytes) arena->peak_bytes = arena->live_bytes;
        if (arena->allocation_count < UINT64_MAX) arena->allocation_count++;
    }
    if (shared) yaza_program_memory_unlock();
    return header + 1;
}

static void *yaza_memory_calloc(size_t count, size_t size) {
    if (size != 0 && count > SIZE_MAX / size) return NULL;
    size_t total = count * size;
    void *pointer = yaza_memory_malloc(total);
    if (pointer != NULL) memset(pointer, 0, total);
    return pointer;
}

static void yaza_memory_free(void *pointer) {
    if (pointer == NULL) return;
    yaza_memory_header *header = ((yaza_memory_header *)pointer) - 1;
    if (header->magic != YAZA_MEMORY_MAGIC) {
        fprintf(stderr, "yaza: attempted to release a pointer outside the YAZA allocator\n");
        abort();
    }
    yaza_memory_arena *arena = header->arena;
    bool shared = arena == &yaza_program_memory_arena;
    if (shared) yaza_program_memory_lock();
    if (arena != NULL) {
        if (header->previous != NULL) header->previous->next = header->next;
        else arena->allocations = header->next;
        if (header->next != NULL) header->next->previous = header->previous;
        size_t allocation_size = sizeof(*header) + header->size;
        if (arena->live_bytes >= allocation_size) arena->live_bytes -= allocation_size;
        if (arena->allocation_count > 0) arena->allocation_count--;
    }
    header->magic = 0;
    yaza_system_free(header);
    if (shared) yaza_program_memory_unlock();
}

static void *yaza_memory_realloc(void *pointer, size_t size) {
    if (pointer == NULL) return yaza_memory_malloc(size);
    if (size == 0) {
        yaza_memory_free(pointer);
        return NULL;
    }
    if (size > SIZE_MAX - sizeof(yaza_memory_header)) return NULL;
    yaza_memory_header *header = ((yaza_memory_header *)pointer) - 1;
    if (header->magic != YAZA_MEMORY_MAGIC) {
        fprintf(stderr, "yaza: attempted to resize a pointer outside the YAZA allocator\n");
        abort();
    }
    yaza_memory_arena *arena = header->arena;
    bool shared = arena == &yaza_program_memory_arena;
    if (shared) yaza_program_memory_lock();
    size_t old_size = header->size;
    size_t old_allocation_size = sizeof(*header) + old_size;
    size_t new_allocation_size = sizeof(*header) + size;
    if (arena != NULL && new_allocation_size > old_allocation_size) {
        size_t growth = new_allocation_size - old_allocation_size;
        if (growth > arena->allocation_limit || arena->live_bytes > arena->allocation_limit - growth) {
            if (shared) yaza_program_memory_unlock();
            return NULL;
        }
    }
    yaza_memory_header *previous = header->previous;
    yaza_memory_header *next = header->next;
    yaza_memory_header *resized = (yaza_memory_header *)yaza_system_realloc(header, sizeof(*header) + size);
    if (resized == NULL) {
        if (shared) yaza_program_memory_unlock();
        return NULL;
    }
    resized->size = size;
    resized->previous = previous;
    resized->next = next;
    if (arena != NULL) {
        if (previous != NULL) previous->next = resized;
        else arena->allocations = resized;
        if (next != NULL) next->previous = resized;
        if (new_allocation_size >= old_allocation_size)
            arena->live_bytes += new_allocation_size - old_allocation_size;
        else
            arena->live_bytes -= old_allocation_size - new_allocation_size;
        if (arena->peak_bytes < arena->live_bytes) arena->peak_bytes = arena->live_bytes;
    }
    if (shared) yaza_program_memory_unlock();
    return resized + 1;
}

static bool yaza_memory_transfer(void *pointer, yaza_memory_arena *destination) {
    if (pointer == NULL || destination == NULL) return false;
    yaza_memory_header *header = ((yaza_memory_header *)pointer) - 1;
    if (header->magic != YAZA_MEMORY_MAGIC) return false;
    yaza_memory_arena *source = header->arena;
    if (source == destination) return true;
    bool shared = source == &yaza_program_memory_arena || destination == &yaza_program_memory_arena;
    if (shared) yaza_program_memory_lock();
    size_t allocation_size = sizeof(*header) + header->size;
    if (allocation_size > destination->allocation_limit ||
        destination->live_bytes > destination->allocation_limit - allocation_size) {
        if (shared) yaza_program_memory_unlock();
        return false;
    }
    if (source != NULL) {
        if (header->previous != NULL) header->previous->next = header->next;
        else source->allocations = header->next;
        if (header->next != NULL) header->next->previous = header->previous;
        if (source->live_bytes >= allocation_size) source->live_bytes -= allocation_size;
        if (source->allocation_count > 0) source->allocation_count--;
    }
    header->arena = destination;
    header->previous = NULL;
    header->next = destination->allocations;
    if (header->next != NULL) header->next->previous = header;
    destination->allocations = header;
    destination->live_bytes += allocation_size;
    if (destination->peak_bytes < destination->live_bytes) destination->peak_bytes = destination->live_bytes;
    if (destination->allocation_count < UINT64_MAX) destination->allocation_count++;
    if (shared) yaza_program_memory_unlock();
    return true;
}

#define malloc(size) yaza_memory_malloc(size)
#define calloc(count, size) yaza_memory_calloc((count), (size))
#define realloc(pointer, size) yaza_memory_realloc((pointer), (size))
#define free(pointer) yaza_memory_free(pointer)

/* Bounded deterministic scheduler core; readiness wakes C-core tasks through the native bridge. */
#define YAZA_SCHEDULER_MAX_TASKS 256U
#define YAZA_SCHEDULER_MAX_TIMERS 256U
#define YAZA_SCHEDULER_SLOT_BITS 9U
#define YAZA_SCHEDULER_SLOT_MASK ((UINT64_C(1) << YAZA_SCHEDULER_SLOT_BITS) - 1)
#define YAZA_TASK_MEMORY_LIMIT (64U * 1024U)

typedef enum {
    YAZA_TASK_INVALID = 0,
    YAZA_TASK_READY,
    YAZA_TASK_RUNNING,
    YAZA_TASK_WAITING,
    YAZA_TASK_COMPLETED,
    YAZA_TASK_FAILED,
    YAZA_TASK_CANCELLED
} yaza_task_state;

typedef enum {
    YAZA_TASK_STEP_YIELD = 0,
    YAZA_TASK_STEP_WAIT,
    YAZA_TASK_STEP_COMPLETE,
    YAZA_TASK_STEP_FAIL,
    YAZA_TASK_STEP_CANCEL
} yaza_task_step_result;

struct yaza_scheduler;
struct yaza_scheduler_task;
typedef yaza_task_step_result (*yaza_scheduler_step_fn)(struct yaza_scheduler *,
                                                        struct yaza_scheduler_task *, void *);

typedef struct yaza_scheduler_task {
    bool occupied, queued, accepting_children, completion_requested, join_requested, cancel_requested;
    uint64_t id, parent_id, deadline_ns, timer_generation;
    size_t timer_index;
    uint32_t child_count, child_failures;
    yaza_task_state state, completion_state;
    yaza_scheduler_step_fn step;
    void *context;
    yaza_memory_arena memory;
} yaza_scheduler_task;

typedef struct {
    uint64_t task_id, deadline_ns, generation;
    size_t task_slot;
} yaza_scheduler_timer;

typedef struct yaza_scheduler {
    yaza_scheduler_task tasks[YAZA_SCHEDULER_MAX_TASKS];
    uint64_t slot_generations[YAZA_SCHEDULER_MAX_TASKS];
    size_t free_slots[YAZA_SCHEDULER_MAX_TASKS], free_count;
    size_t ready_queue[YAZA_SCHEDULER_MAX_TASKS], ready_head, ready_count;
    yaza_scheduler_timer timers[YAZA_SCHEDULER_MAX_TIMERS];
    size_t timer_count;
    uint64_t current_task_id, tasks_created, tasks_completed;
} yaza_scheduler;

static yaza_scheduler_task *yaza_scheduler_find(yaza_scheduler *scheduler, uint64_t id, size_t *slot) {
    if (scheduler == NULL || id == 0) return NULL;
    uint64_t encoded_slot = id & YAZA_SCHEDULER_SLOT_MASK;
    if (encoded_slot == 0 || encoded_slot > YAZA_SCHEDULER_MAX_TASKS) return NULL;
    size_t index = (size_t)(encoded_slot - 1);
    yaza_scheduler_task *task = &scheduler->tasks[index];
    if (!task->occupied || task->id != id) return NULL;
    if (slot != NULL) *slot = index;
    return task;
}

static bool yaza_scheduler_terminal(yaza_task_state state) {
    return state == YAZA_TASK_COMPLETED || state == YAZA_TASK_FAILED || state == YAZA_TASK_CANCELLED;
}

static bool yaza_scheduler_enqueue(yaza_scheduler *scheduler, size_t slot) {
    if (scheduler == NULL || slot >= YAZA_SCHEDULER_MAX_TASKS) return false;
    yaza_scheduler_task *task = &scheduler->tasks[slot];
    if (!task->occupied || task->queued || task->state != YAZA_TASK_READY ||
        scheduler->ready_count == YAZA_SCHEDULER_MAX_TASKS) return false;
    size_t tail = (scheduler->ready_head + scheduler->ready_count) % YAZA_SCHEDULER_MAX_TASKS;
    scheduler->ready_queue[tail] = slot;
    scheduler->ready_count++;
    task->queued = true;
    return true;
}

static bool yaza_scheduler_timer_less(yaza_scheduler_timer a, yaza_scheduler_timer b) {
    return a.deadline_ns < b.deadline_ns || (a.deadline_ns == b.deadline_ns && a.task_id < b.task_id);
}

static void yaza_scheduler_timer_set_index(yaza_scheduler *scheduler,
                                           yaza_scheduler_timer timer, size_t index) {
    if (timer.task_slot >= YAZA_SCHEDULER_MAX_TASKS) return;
    yaza_scheduler_task *task = &scheduler->tasks[timer.task_slot];
    if (task->occupied && task->id == timer.task_id) task->timer_index = index;
}

static void yaza_scheduler_timer_swap(yaza_scheduler *scheduler, size_t a, size_t b) {
    yaza_scheduler_timer temporary = scheduler->timers[a];
    scheduler->timers[a] = scheduler->timers[b];
    scheduler->timers[b] = temporary;
    yaza_scheduler_timer_set_index(scheduler, scheduler->timers[a], a);
    yaza_scheduler_timer_set_index(scheduler, scheduler->timers[b], b);
}

static void yaza_scheduler_timer_up(yaza_scheduler *scheduler, size_t i) {
    while (i > 0) {
        size_t parent = (i - 1) / 2;
        if (!yaza_scheduler_timer_less(scheduler->timers[i], scheduler->timers[parent])) break;
        yaza_scheduler_timer_swap(scheduler, i, parent);
        i = parent;
    }
}

static void yaza_scheduler_timer_down(yaza_scheduler *scheduler, size_t i) {
    for (;;) {
        size_t left = i * 2 + 1, right = left + 1, smallest = i;
        if (left < scheduler->timer_count && yaza_scheduler_timer_less(scheduler->timers[left], scheduler->timers[smallest])) smallest = left;
        if (right < scheduler->timer_count && yaza_scheduler_timer_less(scheduler->timers[right], scheduler->timers[smallest])) smallest = right;
        if (smallest == i) break;
        yaza_scheduler_timer_swap(scheduler, i, smallest);
        i = smallest;
    }
}

static yaza_scheduler_timer yaza_scheduler_timer_remove(yaza_scheduler *scheduler, size_t i) {
    yaza_scheduler_timer removed = scheduler->timers[i];
    scheduler->timer_count--;
    yaza_scheduler_timer_set_index(scheduler, removed, SIZE_MAX);
    if (i != scheduler->timer_count) {
        scheduler->timers[i] = scheduler->timers[scheduler->timer_count];
        yaza_scheduler_timer_set_index(scheduler, scheduler->timers[i], i);
        if (i > 0 && yaza_scheduler_timer_less(scheduler->timers[i], scheduler->timers[(i - 1) / 2]))
            yaza_scheduler_timer_up(scheduler, i);
        else yaza_scheduler_timer_down(scheduler, i);
    }
    return removed;
}

static void yaza_scheduler_timer_remove_task(yaza_scheduler *scheduler, uint64_t id) {
    yaza_scheduler_task *task = yaza_scheduler_find(scheduler, id, NULL);
    if (task == NULL || task->timer_index >= scheduler->timer_count) return;
    size_t index = task->timer_index;
    if (scheduler->timers[index].task_id == id)
        (void)yaza_scheduler_timer_remove(scheduler, index);
}

static bool yaza_scheduler_timer_add(yaza_scheduler *scheduler, yaza_scheduler_timer timer) {
    if (scheduler->timer_count == YAZA_SCHEDULER_MAX_TIMERS) return false;
    yaza_scheduler_task *task = yaza_scheduler_find(scheduler, timer.task_id, NULL);
    if (task == NULL || task->timer_index != SIZE_MAX) return false;
    size_t i = scheduler->timer_count++;
    scheduler->timers[i] = timer;
    yaza_scheduler_timer_set_index(scheduler, scheduler->timers[i], i);
    yaza_scheduler_timer_up(scheduler, i);
    return true;
}

static void yaza_scheduler_init(yaza_scheduler *scheduler) {
    if (scheduler == NULL) return;
    memset(scheduler, 0, sizeof(*scheduler));
    for (size_t i = 0; i < YAZA_SCHEDULER_MAX_TASKS; i++) scheduler->slot_generations[i] = 1;
    for (size_t i = YAZA_SCHEDULER_MAX_TASKS; i > 0; i--)
        scheduler->free_slots[scheduler->free_count++] = i - 1;
}

static uint64_t yaza_scheduler_spawn(yaza_scheduler *scheduler, uint64_t parent_id,
                                     yaza_scheduler_step_fn step, void *context) {
    if (scheduler == NULL || step == NULL || scheduler->free_count == 0 ||
        (parent_id == 0 && scheduler->current_task_id != 0) ||
        (parent_id != 0 && scheduler->current_task_id != parent_id)) return 0;
    yaza_scheduler_task *parent = parent_id == 0 ? NULL : yaza_scheduler_find(scheduler, parent_id, NULL);
    if (parent_id != 0 && (parent == NULL || parent->state != YAZA_TASK_RUNNING ||
                           !parent->accepting_children || parent->cancel_requested ||
                           parent->child_count == UINT32_MAX)) return 0;
    size_t slot = scheduler->free_slots[--scheduler->free_count];
    uint64_t generation = scheduler->slot_generations[slot];
    if (generation == 0 || generation > (UINT64_MAX >> YAZA_SCHEDULER_SLOT_BITS)) return 0;
    yaza_scheduler_task *task = &scheduler->tasks[slot];
    memset(task, 0, sizeof(*task));
    task->occupied = true; task->accepting_children = true;
    task->id = (generation << YAZA_SCHEDULER_SLOT_BITS) | (uint64_t)(slot + 1);
    task->timer_index = SIZE_MAX;
    yaza_memory_arena_init(&task->memory, YAZA_TASK_MEMORY_LIMIT);
    task->parent_id = parent_id; task->state = YAZA_TASK_READY; task->step = step; task->context = context;
    if (!yaza_scheduler_enqueue(scheduler, slot)) {
        memset(task, 0, sizeof(*task));
        scheduler->free_slots[scheduler->free_count++] = slot;
        return 0;
    }
    if (parent != NULL) parent->child_count++;
    if (scheduler->tasks_created < UINT64_MAX) scheduler->tasks_created++;
    return task->id;
}

static yaza_task_state yaza_scheduler_state(const yaza_scheduler *scheduler, uint64_t id) {
    yaza_scheduler_task *task = yaza_scheduler_find((yaza_scheduler *)scheduler, id, NULL);
    return task == NULL ? YAZA_TASK_INVALID : task->state;
}

static bool yaza_scheduler_cancel_requested(const yaza_scheduler_task *task) {
    return task != NULL && task->cancel_requested;
}

static uint32_t yaza_scheduler_child_failures(const yaza_scheduler *scheduler, uint64_t id) {
    yaza_scheduler_task *task = yaza_scheduler_find((yaza_scheduler *)scheduler, id, NULL);
    return task == NULL ? 0 : task->child_failures;
}

static bool yaza_scheduler_join_children(yaza_scheduler *scheduler, uint64_t id) {
    yaza_scheduler_task *task = yaza_scheduler_find(scheduler, id, NULL);
    if (task == NULL || scheduler->current_task_id != id || task->state != YAZA_TASK_RUNNING) return false;
    if (task->child_count == 0) { task->join_requested = false; return true; }
    task->join_requested = true;
    return false;
}

static bool yaza_scheduler_sleep_until(yaza_scheduler *scheduler, uint64_t id, uint64_t deadline_ns) {
    size_t slot = 0;
    yaza_scheduler_task *task = yaza_scheduler_find(scheduler, id, &slot);
    if (task == NULL || scheduler->current_task_id != id || task->state != YAZA_TASK_RUNNING ||
        deadline_ns == 0 || task->deadline_ns != 0 || task->timer_generation == UINT64_MAX) return false;
    yaza_scheduler_timer timer = {id, deadline_ns, task->timer_generation + 1, slot};
    if (!yaza_scheduler_timer_add(scheduler, timer)) return false;
    task->timer_generation++;
    task->deadline_ns = deadline_ns;
    return true;
}

static bool yaza_scheduler_wake(yaza_scheduler *scheduler, uint64_t id) {
    size_t slot = 0;
    yaza_scheduler_task *task = yaza_scheduler_find(scheduler, id, &slot);
    if (task == NULL || task->state != YAZA_TASK_WAITING || task->completion_requested) return false;
    yaza_scheduler_timer_remove_task(scheduler, id);
    task->deadline_ns = 0; task->state = YAZA_TASK_READY;
    return yaza_scheduler_enqueue(scheduler, slot);
}

static bool yaza_scheduler_descends_from(yaza_scheduler *scheduler,
                                         const yaza_scheduler_task *task, uint64_t ancestor_id) {
    uint64_t parent_id = task->parent_id;
    for (size_t depth = 0; parent_id != 0 && depth < YAZA_SCHEDULER_MAX_TASKS; depth++) {
        if (parent_id == ancestor_id) return true;
        yaza_scheduler_task *parent = yaza_scheduler_find(scheduler, parent_id, NULL);
        if (parent == NULL) return false;
        parent_id = parent->parent_id;
    }
    return false;
}

static bool yaza_scheduler_cancel(yaza_scheduler *scheduler, uint64_t id) {
    yaza_scheduler_task *target = yaza_scheduler_find(scheduler, id, NULL);
    if (target == NULL || yaza_scheduler_terminal(target->state)) return false;
    for (size_t i = 0; i < YAZA_SCHEDULER_MAX_TASKS; i++) {
        yaza_scheduler_task *task = &scheduler->tasks[i];
        if (!task->occupied || yaza_scheduler_terminal(task->state) ||
            (task->id != id && !yaza_scheduler_descends_from(scheduler, task, id))) continue;
        task->cancel_requested = true;
        if (task->deadline_ns != 0) { yaza_scheduler_timer_remove_task(scheduler, task->id); task->deadline_ns = 0; }
        if (task->state == YAZA_TASK_WAITING && !task->completion_requested) {
            task->state = YAZA_TASK_READY;
            if (!yaza_scheduler_enqueue(scheduler, i)) return false;
        }
    }
    return true;
}

static void yaza_scheduler_cancel_siblings(yaza_scheduler *scheduler,
                                           const yaza_scheduler_task *failed_task) {
    if (scheduler == NULL || failed_task == NULL || failed_task->parent_id == 0) return;
    uint64_t parent_id = failed_task->parent_id;
    for (size_t i = 0; i < YAZA_SCHEDULER_MAX_TASKS; i++) {
        yaza_scheduler_task *sibling = &scheduler->tasks[i];
        if (!sibling->occupied || sibling->id == failed_task->id ||
            sibling->parent_id != parent_id || yaza_scheduler_terminal(sibling->state)) continue;
        (void)yaza_scheduler_cancel(scheduler, sibling->id);
    }
}

static void yaza_scheduler_finish(yaza_scheduler *scheduler, yaza_scheduler_task *task,
                                  yaza_task_state terminal_state) {
    task->state = terminal_state; task->completion_requested = false;
    task->accepting_children = false; task->deadline_ns = 0; task->join_requested = false;
    yaza_scheduler_timer_remove_task(scheduler, task->id);
    if (scheduler->tasks_completed < UINT64_MAX) scheduler->tasks_completed++;
}

static void yaza_scheduler_propagate(yaza_scheduler *scheduler, yaza_scheduler_task *finished) {
    while (finished != NULL && finished->parent_id != 0) {
        yaza_scheduler_task *parent = yaza_scheduler_find(scheduler, finished->parent_id, NULL);
        if (parent == NULL) return;
        if (parent->child_count > 0) parent->child_count--;
        if (finished->state == YAZA_TASK_FAILED && parent->child_failures < UINT32_MAX) parent->child_failures++;
        if (parent->child_count != 0) return;
        if (parent->completion_requested) {
            yaza_task_state state = parent->completion_state;
            if (parent->cancel_requested && state != YAZA_TASK_FAILED) state = YAZA_TASK_CANCELLED;
            else if (state == YAZA_TASK_COMPLETED && parent->child_failures != 0) state = YAZA_TASK_FAILED;
            yaza_scheduler_finish(scheduler, parent, state);
            finished = parent;
        } else if (parent->join_requested && parent->state == YAZA_TASK_WAITING) {
            size_t slot = 0;
            parent->join_requested = false; parent->state = YAZA_TASK_READY;
            (void)yaza_scheduler_find(scheduler, parent->id, &slot);
            (void)yaza_scheduler_enqueue(scheduler, slot);
            return;
        } else return;
    }
}

static bool yaza_scheduler_advance_time(yaza_scheduler *scheduler, uint64_t now_ns) {
    if (scheduler == NULL) return false;
    while (scheduler->timer_count > 0 && scheduler->timers[0].deadline_ns <= now_ns) {
        yaza_scheduler_timer timer = yaza_scheduler_timer_remove(scheduler, 0);
        size_t slot = 0;
        yaza_scheduler_task *task = yaza_scheduler_find(scheduler, timer.task_id, &slot);
        if (task == NULL || task->state != YAZA_TASK_WAITING || task->deadline_ns != timer.deadline_ns ||
            task->timer_generation != timer.generation) continue;
        task->deadline_ns = 0; task->state = YAZA_TASK_READY;
        if (!yaza_scheduler_enqueue(scheduler, slot)) return false;
    }
    return true;
}

static size_t yaza_scheduler_run(yaza_scheduler *scheduler, uint64_t now_ns, size_t step_budget) {
    if (scheduler == NULL || !yaza_scheduler_advance_time(scheduler, now_ns)) return 0;
    size_t steps = 0;
    while (steps < step_budget && scheduler->ready_count > 0) {
        size_t slot = scheduler->ready_queue[scheduler->ready_head];
        scheduler->ready_head = (scheduler->ready_head + 1) % YAZA_SCHEDULER_MAX_TASKS;
        scheduler->ready_count--;
        yaza_scheduler_task *task = &scheduler->tasks[slot];
        task->queued = false;
        if (!task->occupied || task->state != YAZA_TASK_READY) continue;
        bool cancellation_was_requested = task->cancel_requested;
        task->state = YAZA_TASK_RUNNING; scheduler->current_task_id = task->id;
        yaza_memory_arena *previous_arena = yaza_memory_arena_enter(&task->memory);
        yaza_task_step_result result = task->step(scheduler, task, task->context);
        yaza_memory_arena_enter(previous_arena);
        scheduler->current_task_id = 0; steps++;
        if (result == YAZA_TASK_STEP_YIELD) {
            task->state = YAZA_TASK_READY; (void)yaza_scheduler_enqueue(scheduler, slot);
        } else if (result == YAZA_TASK_STEP_WAIT) {
            task->state = YAZA_TASK_WAITING;
            if (!cancellation_was_requested && task->cancel_requested) {
                task->state = YAZA_TASK_READY;
                (void)yaza_scheduler_enqueue(scheduler, slot);
            }
        } else {
            task->completion_requested = true; task->accepting_children = false;
            task->completion_state = result == YAZA_TASK_STEP_FAIL ? YAZA_TASK_FAILED :
                (result == YAZA_TASK_STEP_CANCEL || task->cancel_requested) ? YAZA_TASK_CANCELLED : YAZA_TASK_COMPLETED;
            if (task->completion_state == YAZA_TASK_CANCELLED || task->completion_state == YAZA_TASK_FAILED)
                (void)yaza_scheduler_cancel(scheduler, task->id);
            if (task->completion_state == YAZA_TASK_FAILED)
                yaza_scheduler_cancel_siblings(scheduler, task);
            if (task->child_count != 0) task->state = YAZA_TASK_WAITING;
            else {
                yaza_task_state state = task->completion_state;
                if (state == YAZA_TASK_COMPLETED && task->child_failures != 0) state = YAZA_TASK_FAILED;
                yaza_scheduler_finish(scheduler, task, state);
                yaza_scheduler_propagate(scheduler, task);
            }
        }
        if (!yaza_scheduler_advance_time(scheduler, now_ns)) break;
    }
    return steps;
}

static bool yaza_scheduler_reap(yaza_scheduler *scheduler, uint64_t id) {
    size_t slot = 0;
    yaza_scheduler_task *task = yaza_scheduler_find(scheduler, id, &slot);
    if (task == NULL || !yaza_scheduler_terminal(task->state)) return false;
    for (size_t i = 0; i < YAZA_SCHEDULER_MAX_TASKS; i++)
        if (scheduler->tasks[i].occupied && scheduler->tasks[i].parent_id == id &&
            !yaza_scheduler_terminal(scheduler->tasks[i].state)) return false;
    yaza_memory_arena_reset(&task->memory);
    memset(task, 0, sizeof(*task));
    if (scheduler->slot_generations[slot] < (UINT64_MAX >> YAZA_SCHEDULER_SLOT_BITS)) {
        scheduler->slot_generations[slot]++;
        scheduler->free_slots[scheduler->free_count++] = slot;
    } else {
        scheduler->slot_generations[slot] = 0;
    }
    return true;
}

/* Bounded blocking-work pool. Workers publish owned results through a pipe wakeup;
 * completion callbacks are invoked only by the thread that calls collect(). */
#define YAZA_WORK_POOL_MAX_THREADS 32U
#define YAZA_WORK_POOL_MAX_JOBS 256U

typedef int (*yaza_work_run_fn)(void *context, const atomic_bool *cancelled,
                                int64_t deadline_ms, void **result_out);
typedef void (*yaza_work_complete_fn)(void *context, int status, void *result);

typedef struct {
    yaza_work_run_fn run;
    yaza_work_complete_fn complete;
    void *context;
    atomic_bool *cancelled;
    int64_t deadline_ms;
    int status;
    void *result;
} yaza_work_item;

typedef struct {
    pthread_mutex_t mutex;
    pthread_cond_t has_work;
    pthread_t threads[YAZA_WORK_POOL_MAX_THREADS];
    yaza_work_item queued[YAZA_WORK_POOL_MAX_JOBS];
    yaza_work_item completed[YAZA_WORK_POOL_MAX_JOBS];
    size_t thread_count;
    size_t capacity;
    size_t queue_head, queue_count;
    size_t completion_head, completion_count;
    size_t active_count;
    size_t exited_threads;
    size_t in_flight;
    uint64_t submitted_total;
    uint64_t rejected_total;
    uint64_t completed_total;
    uint64_t failed_total;
    uint64_t cancelled_total;
    uint64_t timed_out_total;
    int wake_read_fd, wake_write_fd;
    int wake_error;
    bool initialized, accepting, stopping, joined;
} yaza_work_pool;

typedef struct {
    size_t threads;
    size_t capacity;
    size_t queued;
    size_t active;
    size_t completing;
    size_t in_flight;
    uint64_t submitted_total;
    uint64_t rejected_total;
    uint64_t completed_total;
    uint64_t failed_total;
    uint64_t cancelled_total;
    uint64_t timed_out_total;
} yaza_work_pool_stats;

static void *yaza_work_pool_worker(void *opaque) {
    yaza_work_pool *pool = (yaza_work_pool *)opaque;
    for (;;) {
        if (pthread_mutex_lock(&pool->mutex) != 0) return NULL;
        while (pool->queue_count == 0 && !pool->stopping) {
            int wait_status = pthread_cond_wait(&pool->has_work, &pool->mutex);
            if (wait_status != 0) {
                pool->wake_error = wait_status;
                pool->stopping = true;
                pool->accepting = false;
                break;
            }
        }
        if (pool->queue_count == 0 && pool->stopping) {
            if (pool->exited_threads < pool->thread_count) pool->exited_threads++;
            (void)pthread_cond_broadcast(&pool->has_work);
            pthread_mutex_unlock(&pool->mutex);
            return NULL;
        }
        yaza_work_item item = pool->queued[pool->queue_head];
        memset(&pool->queued[pool->queue_head], 0, sizeof(pool->queued[pool->queue_head]));
        pool->queue_head = (pool->queue_head + 1) % pool->capacity;
        pool->queue_count--;
        pool->active_count++;
        pthread_mutex_unlock(&pool->mutex);

        item.status = 0;
        item.result = NULL;
        if (item.deadline_ms > 0) {
            int64_t now_ms = yaza_monotonic_milliseconds();
            if (now_ms < 0) item.status = EIO;
            else if (now_ms >= item.deadline_ms) item.status = ETIMEDOUT;
        }
        if (item.status == 0 && item.cancelled != NULL &&
            atomic_load_explicit(item.cancelled, memory_order_acquire)) item.status = ECANCELED;
        if (item.status == 0)
            item.status = item.run(item.context, item.cancelled, item.deadline_ms, &item.result);

        if (pthread_mutex_lock(&pool->mutex) != 0) return NULL;
        if (pool->completion_count >= pool->capacity) {
            pool->wake_error = EOVERFLOW;
            pool->stopping = true;
            pool->accepting = false;
            pthread_mutex_unlock(&pool->mutex);
            return NULL;
        }
        size_t tail = (pool->completion_head + pool->completion_count) % pool->capacity;
        pool->completed[tail] = item;
        pool->completion_count++;
        if (pool->active_count > 0) pool->active_count--;
        if (pool->completed_total < UINT64_MAX) pool->completed_total++;
        if (item.status != 0 && pool->failed_total < UINT64_MAX) pool->failed_total++;
        if (item.status == ECANCELED && pool->cancelled_total < UINT64_MAX)
            pool->cancelled_total++;
        if (item.status == ETIMEDOUT && pool->timed_out_total < UINT64_MAX)
            pool->timed_out_total++;
        const unsigned char wake_byte = 1;
        ssize_t wake_status;
        do {
            wake_status = write(pool->wake_write_fd, &wake_byte, sizeof(wake_byte));
        } while (wake_status < 0 && errno == EINTR);
        if (wake_status < 0 && errno != EAGAIN && errno != EWOULDBLOCK)
            pool->wake_error = errno;
        int completion_broadcast_status = pthread_cond_broadcast(&pool->has_work);
        if (completion_broadcast_status != 0) pool->wake_error = completion_broadcast_status;
        pthread_mutex_unlock(&pool->mutex);
    }
}

static bool yaza_work_pool_open(yaza_work_pool *pool, size_t thread_count, size_t capacity) {
    if (pool == NULL || thread_count == 0 || thread_count > YAZA_WORK_POOL_MAX_THREADS ||
        capacity == 0 || capacity > YAZA_WORK_POOL_MAX_JOBS) return false;
    memset(pool, 0, sizeof(*pool));
    pool->wake_read_fd = -1;
    pool->wake_write_fd = -1;
    int descriptors[2];
    if (pipe(descriptors) != 0) return false;
    for (size_t index = 0; index < 2; index++) {
        int flags = fcntl(descriptors[index], F_GETFL, 0);
        int descriptor_flags = fcntl(descriptors[index], F_GETFD, 0);
        if (flags < 0 || descriptor_flags < 0 ||
            fcntl(descriptors[index], F_SETFL, flags | O_NONBLOCK) < 0 ||
            fcntl(descriptors[index], F_SETFD, descriptor_flags | FD_CLOEXEC) < 0) {
            close(descriptors[0]);
            close(descriptors[1]);
            return false;
        }
    }
    pool->wake_read_fd = descriptors[0];
    pool->wake_write_fd = descriptors[1];
    if (pthread_mutex_init(&pool->mutex, NULL) != 0) goto open_failed_pipe;
    if (pthread_cond_init(&pool->has_work, NULL) != 0) {
        pthread_mutex_destroy(&pool->mutex);
        goto open_failed_pipe;
    }
    pool->capacity = capacity;
    pool->accepting = true;
    pool->initialized = true;
    for (size_t index = 0; index < thread_count; index++) {
        if (pthread_create(&pool->threads[index], NULL, yaza_work_pool_worker, pool) != 0) {
            pthread_mutex_lock(&pool->mutex);
            pool->accepting = false;
            pool->stopping = true;
            pthread_cond_broadcast(&pool->has_work);
            pthread_mutex_unlock(&pool->mutex);
            for (size_t started = 0; started < pool->thread_count; started++)
                pthread_join(pool->threads[started], NULL);
            pthread_cond_destroy(&pool->has_work);
            pthread_mutex_destroy(&pool->mutex);
            pool->initialized = false;
            goto open_failed_pipe;
        }
        pool->thread_count++;
    }
    return true;

open_failed_pipe:
    close(pool->wake_read_fd);
    close(pool->wake_write_fd);
    pool->wake_read_fd = -1;
    pool->wake_write_fd = -1;
    return false;
}

static bool yaza_work_pool_submit(yaza_work_pool *pool, yaza_work_run_fn run,
                                  yaza_work_complete_fn complete, void *context,
                                  atomic_bool *cancelled, int64_t deadline_ms) {
    if (pool == NULL || !pool->initialized || run == NULL || complete == NULL ||
        deadline_ms < 0) return false;
    if (pthread_mutex_lock(&pool->mutex) != 0) return false;
    if (!pool->accepting || pool->in_flight >= pool->capacity) {
        if (pool->rejected_total < UINT64_MAX) pool->rejected_total++;
        pthread_mutex_unlock(&pool->mutex);
        return false;
    }
    size_t tail = (pool->queue_head + pool->queue_count) % pool->capacity;
    pool->queued[tail] = (yaza_work_item){run, complete, context, cancelled, deadline_ms, 0, NULL};
    pool->queue_count++;
    pool->in_flight++;
    int signal_status = pthread_cond_signal(&pool->has_work);
    if (signal_status != 0) {
        pool->queue_count--;
        pool->in_flight--;
        memset(&pool->queued[tail], 0, sizeof(pool->queued[tail]));
        pool->wake_error = signal_status;
        if (pool->rejected_total < UINT64_MAX) pool->rejected_total++;
        pthread_mutex_unlock(&pool->mutex);
        return false;
    }
    if (pool->submitted_total < UINT64_MAX) pool->submitted_total++;
    pthread_mutex_unlock(&pool->mutex);
    return true;
}

static size_t yaza_work_pool_collect(yaza_work_pool *pool, size_t maximum) {
    if (pool == NULL || !pool->initialized || maximum == 0) return 0;
    unsigned char wake_bytes[128];
    for (;;) {
        ssize_t count = read(pool->wake_read_fd, wake_bytes, sizeof(wake_bytes));
        if (count > 0) continue;
        if (count < 0 && errno == EINTR) continue;
        break;
    }
    size_t collected = 0;
    while (collected < maximum) {
        if (pthread_mutex_lock(&pool->mutex) != 0) break;
        if (pool->completion_count == 0) {
            pthread_mutex_unlock(&pool->mutex);
            break;
        }
        yaza_work_item item = pool->completed[pool->completion_head];
        memset(&pool->completed[pool->completion_head], 0,
               sizeof(pool->completed[pool->completion_head]));
        pool->completion_head = (pool->completion_head + 1) % pool->capacity;
        pool->completion_count--;
        if (pool->in_flight > 0) pool->in_flight--;
        pthread_mutex_unlock(&pool->mutex);
        item.complete(item.context, item.status, item.result);
        collected++;
    }
    return collected;
}

static size_t yaza_work_pool_pending(yaza_work_pool *pool) {
    if (pool == NULL || !pool->initialized || pthread_mutex_lock(&pool->mutex) != 0) return 0;
    size_t pending = pool->in_flight;
    pthread_mutex_unlock(&pool->mutex);
    return pending;
}

static bool yaza_work_pool_get_stats(yaza_work_pool *pool, yaza_work_pool_stats *stats) {
    if (pool == NULL || stats == NULL || !pool->initialized ||
        pthread_mutex_lock(&pool->mutex) != 0) return false;
    *stats = (yaza_work_pool_stats){
        pool->thread_count, pool->capacity, pool->queue_count, pool->active_count,
        pool->completion_count, pool->in_flight, pool->submitted_total,
        pool->rejected_total, pool->completed_total, pool->failed_total,
        pool->cancelled_total, pool->timed_out_total
    };
    pthread_mutex_unlock(&pool->mutex);
    return true;
}

static int yaza_work_pool_wake_error(yaza_work_pool *pool) {
    if (pool == NULL || !pool->initialized || pthread_mutex_lock(&pool->mutex) != 0) return EINVAL;
    int error = pool->wake_error;
    pthread_mutex_unlock(&pool->mutex);
    return error;
}

static bool yaza_work_pool_stop(yaza_work_pool *pool) {
    if (pool == NULL || !pool->initialized) return false;
    if (pool->joined) return true;
    if (pthread_mutex_lock(&pool->mutex) != 0) return false;
    pool->accepting = false;
    pool->stopping = true;
    int broadcast_status = pthread_cond_broadcast(&pool->has_work);
    pthread_mutex_unlock(&pool->mutex);
    if (broadcast_status != 0) return false;
    bool joined = true;
    for (size_t index = 0; index < pool->thread_count; index++)
        if (pthread_join(pool->threads[index], NULL) != 0) joined = false;
    if (joined) pool->joined = true;
    return joined;
}

/* Bound server shutdown without detaching workers that still reference runtime state. */
static bool yaza_work_pool_stop_until(yaza_work_pool *pool, int64_t deadline_ms) {
    if (pool == NULL || !pool->initialized || deadline_ms <= 0) return false;
    if (pool->joined) return true;
    if (pthread_mutex_lock(&pool->mutex) != 0) return false;
    pool->accepting = false;
    pool->stopping = true;
    int broadcast_status = pthread_cond_broadcast(&pool->has_work);
    pthread_mutex_unlock(&pool->mutex);
    if (broadcast_status != 0) return false;

    for (;;) {
        if (pthread_mutex_lock(&pool->mutex) != 0) return false;
        bool all_exited = pool->exited_threads == pool->thread_count;
        pthread_mutex_unlock(&pool->mutex);
        if (all_exited) break;

        int64_t now_ms = yaza_monotonic_milliseconds();
        if (now_ms < 0 || now_ms >= deadline_ms) return false;
        struct timespec pause = {0, 1000000L};
        while (nanosleep(&pause, &pause) != 0 && errno == EINTR) {}
    }

    bool joined = true;
    for (size_t index = 0; index < pool->thread_count; index++)
        if (pthread_join(pool->threads[index], NULL) != 0) joined = false;
    if (joined) pool->joined = true;
    return joined;
}

static bool yaza_work_pool_close(yaza_work_pool *pool) {
    if (pool == NULL || !pool->initialized || !pool->joined ||
        yaza_work_pool_pending(pool) != 0) return false;
    pthread_cond_destroy(&pool->has_work);
    pthread_mutex_destroy(&pool->mutex);
    close(pool->wake_read_fd);
    close(pool->wake_write_fd);
    memset(pool, 0, sizeof(*pool));
    pool->wake_read_fd = -1;
    pool->wake_write_fd = -1;
    return true;
}

typedef struct {
    char **items;
    size_t length;
    size_t capacity;
} yaza_text_list;

/* Generic List[T] stores aligned, trivially copied YAZA values in the active
   arena. TextList remains the dedicated owning collection for Text values. */
typedef struct {
    unsigned char *items;
    size_t length;
    size_t capacity;
    size_t element_size;
    const char *element_type;
} yaza_typed_list;

typedef struct {
    unsigned char *data;
    size_t length;
} yaza_bytes;

typedef struct yaza_secret_text_buffer {
    size_t length;
    bool valid;
    unsigned char value[];
} yaza_secret_text_buffer;

typedef struct {
    yaza_secret_text_buffer *buffer;
} yaza_secret_text;

typedef struct yaza_variant {
    const char *type_name;
    const char *case_name;
    uint32_t case_index;
    void *payload;
    size_t payload_size;
} yaza_variant;

typedef enum {
    YAZA_OPTION_NONE = 0,
    YAZA_OPTION_TEXT = 1,
    YAZA_OPTION_NUMBER = 2,
    YAZA_OPTION_FLOAT64 = 3,
    YAZA_OPTION_BOOLEAN = 4,
    YAZA_OPTION_TEXT_LIST = 5,
    YAZA_OPTION_BYTES = 6,
    YAZA_OPTION_OPTION = 7,
    YAZA_OPTION_RESULT = 8,
    YAZA_OPTION_INT32 = 9,
    YAZA_OPTION_CUSTOM = 10,
    YAZA_OPTION_VARIANT = 11,
    YAZA_OPTION_SECRET_TEXT = 12
} yaza_option_kind;

typedef struct yaza_option yaza_option;
typedef struct yaza_result yaza_result;

struct yaza_option {
    bool is_some;
    yaza_option_kind kind;
    union {
        const char *text;
        int64_t number;
        int32_t int32;
        double float64;
        bool boolean;
        yaza_text_list *text_list;
        yaza_bytes bytes;
        yaza_secret_text secret_text;
        yaza_option *option;
        yaza_result *result;
        struct {
            void *data;
            size_t size;
            const char *type_name;
        } custom;
        yaza_variant *variant;
    } value;
};

struct yaza_result {
    bool is_ok;
    yaza_option payload;
};

static void *yaza_tagged_payload_copy(const void *source, size_t size) {
    void *copy = yaza_memory_malloc(size);
    if (copy == NULL) {
        fprintf(stderr, "yaza: memory limit exceeded while storing a tagged value\n");
        exit(1);
    }
    memcpy(copy, source, size);
    return copy;
}

static yaza_variant yaza_variant_make(const char *type_name, const char *case_name, uint32_t case_index, const void *payload, size_t payload_size) {
    yaza_variant result = {0};
    result.type_name = type_name;
    result.case_name = case_name;
    result.case_index = case_index;
    result.payload_size = payload_size;
    if (payload_size > 0) result.payload = yaza_tagged_payload_copy(payload, payload_size);
    return result;
}

static bool yaza_variant_is(yaza_variant value, const char *type_name, const char *case_name, uint32_t case_index) {
    return value.type_name != NULL && value.case_name != NULL && value.case_index == case_index &&
        strcmp(value.type_name, type_name) == 0 && strcmp(value.case_name, case_name) == 0;
}

static const void *yaza_variant_get_payload(yaza_variant value, const char *type_name, const char *case_name, uint32_t case_index, size_t expected_size) {
    if (!yaza_variant_is(value, type_name, case_name, case_index) || value.payload == NULL || value.payload_size != expected_size) {
        fprintf(stderr, "yaza: invalid payload for variant %s::%s\n", type_name, case_name);
        exit(1);
    }
    return value.payload;
}

static yaza_option yaza_option_none(void) {
    yaza_option result = {0};
    return result;
}

static yaza_option yaza_option_some_text(const char *value) {
    yaza_option result = {0};
    result.is_some = true; result.kind = YAZA_OPTION_TEXT; result.value.text = value;
    return result;
}

static yaza_option yaza_option_some_number(int64_t value) {
    yaza_option result = {0};
    result.is_some = true; result.kind = YAZA_OPTION_NUMBER; result.value.number = value;
    return result;
}

static yaza_option yaza_option_some_int32(int32_t value) {
    yaza_option result = {0};
    result.is_some = true; result.kind = YAZA_OPTION_INT32; result.value.int32 = value;
    return result;
}

static yaza_option yaza_option_some_float64(double value) {
    yaza_option result = {0};
    result.is_some = true; result.kind = YAZA_OPTION_FLOAT64; result.value.float64 = value;
    return result;
}

static yaza_option yaza_option_some_boolean(bool value) {
    yaza_option result = {0};
    result.is_some = true; result.kind = YAZA_OPTION_BOOLEAN; result.value.boolean = value;
    return result;
}

static yaza_option yaza_option_some_text_list(yaza_text_list *value) {
    yaza_option result = {0};
    result.is_some = true; result.kind = YAZA_OPTION_TEXT_LIST; result.value.text_list = value;
    return result;
}

static yaza_option yaza_option_some_bytes(yaza_bytes value) {
    yaza_option result = {0};
    result.is_some = true; result.kind = YAZA_OPTION_BYTES; result.value.bytes = value;
    return result;
}

static int64_t yaza_option_unwrap_error(const char *expected);

static yaza_option yaza_option_some_custom(const void *value, size_t size, const char *type_name) {
    yaza_option result = {0};
    result.is_some = true;
    result.kind = YAZA_OPTION_CUSTOM;
    result.value.custom.data = yaza_tagged_payload_copy(value, size);
    result.value.custom.size = size;
    result.value.custom.type_name = type_name;
    return result;
}

static const void *yaza_option_unwrap_custom(yaza_option value, size_t size, const char *type_name) {
    if (!value.is_some || value.kind != YAZA_OPTION_CUSTOM || value.value.custom.data == NULL ||
        value.value.custom.size != size || value.value.custom.type_name == NULL ||
        strcmp(value.value.custom.type_name, type_name) != 0)
        yaza_option_unwrap_error(type_name);
    return value.value.custom.data;
}

static yaza_option yaza_option_some_typed_list(yaza_typed_list *value, const char *type_name) {
    return yaza_option_some_custom(&value, sizeof(value), type_name);
}

static yaza_typed_list *yaza_option_unwrap_typed_list(yaza_option value, const char *type_name) {
    yaza_typed_list *result;
    memcpy(&result, yaza_option_unwrap_custom(value, sizeof(result), type_name), sizeof(result));
    return result;
}

static yaza_option yaza_option_some_variant(yaza_variant value) {
    yaza_option result = {0};
    yaza_variant *copy = (yaza_variant *)yaza_tagged_payload_copy(&value, sizeof(value));
    result.is_some = true;
    result.kind = YAZA_OPTION_VARIANT;
    result.value.variant = copy;
    return result;
}

static yaza_option yaza_option_some_option(yaza_option value) {
    yaza_option result = {0};
    yaza_option *copy = (yaza_option *)yaza_tagged_payload_copy(&value, sizeof(value));
    result.is_some = true; result.kind = YAZA_OPTION_OPTION; result.value.option = copy;
    return result;
}

static yaza_option yaza_option_some_result(yaza_result value) {
    yaza_option result = {0};
    yaza_result *copy = (yaza_result *)yaza_tagged_payload_copy(&value, sizeof(value));
    result.is_some = true; result.kind = YAZA_OPTION_RESULT; result.value.result = copy;
    return result;
}

static bool yaza_option_is_some(yaza_option value) {
    return value.is_some;
}

static int64_t yaza_option_unwrap_error(const char *expected) {
    fprintf(stderr, "yaza: attempted to unwrap none as %s\n", expected);
    exit(1);
    return 0;
}

static const char *yaza_option_unwrap_text(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_TEXT) yaza_option_unwrap_error("Text");
    return value.value.text;
}

static int64_t yaza_option_unwrap_number(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_NUMBER) yaza_option_unwrap_error("Number");
    return value.value.number;
}

static int32_t yaza_option_unwrap_int32(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_INT32) yaza_option_unwrap_error("Int32");
    return value.value.int32;
}

static double yaza_option_unwrap_float64(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_FLOAT64) yaza_option_unwrap_error("Float64");
    return value.value.float64;
}

static bool yaza_option_unwrap_boolean(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_BOOLEAN) yaza_option_unwrap_error("Boolean");
    return value.value.boolean;
}

static yaza_text_list *yaza_option_unwrap_text_list(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_TEXT_LIST) yaza_option_unwrap_error("TextList");
    return value.value.text_list;
}

static yaza_bytes yaza_option_unwrap_bytes(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_BYTES) yaza_option_unwrap_error("Bytes");
    return value.value.bytes;
}

static yaza_option yaza_option_unwrap_option(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_OPTION || value.value.option == NULL)
        yaza_option_unwrap_error("Option");
    return *value.value.option;
}

static yaza_result yaza_option_unwrap_result(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_RESULT || value.value.result == NULL)
        yaza_option_unwrap_error("Result");
    return *value.value.result;
}

static yaza_variant yaza_option_unwrap_variant(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_VARIANT || value.value.variant == NULL)
        yaza_option_unwrap_error("variant");
    return *value.value.variant;
}

static yaza_result yaza_result_ok(yaza_option payload) {
    yaza_result result = {0};
    result.is_ok = true; result.payload = payload;
    return result;
}

static yaza_result yaza_result_err(yaza_option payload) {
    yaza_result result = {0};
    result.is_ok = false; result.payload = payload;
    return result;
}

static bool yaza_result_is_ok(yaza_result value) {
    return value.is_ok;
}

static void yaza_result_wrong_variant(const char *requested) {
    fprintf(stderr, "yaza: attempted to read Result's %s payload from the other variant\n", requested);
    exit(1);
}

static const char *yaza_result_unwrap_text(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_text(value.payload);
}

static int64_t yaza_result_unwrap_number(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_number(value.payload);
}

static int32_t yaza_result_unwrap_int32(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_int32(value.payload);
}

static double yaza_result_unwrap_float64(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_float64(value.payload);
}

static bool yaza_result_unwrap_boolean(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_boolean(value.payload);
}

static yaza_text_list *yaza_result_unwrap_text_list(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_text_list(value.payload);
}

static yaza_bytes yaza_result_unwrap_bytes(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_bytes(value.payload);
}

static yaza_option yaza_result_unwrap_option(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_option(value.payload);
}

static yaza_result yaza_result_unwrap_result(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_result(value.payload);
}

static const char *yaza_result_unwrap_err_text(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_text(value.payload);
}

static int64_t yaza_result_unwrap_err_number(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_number(value.payload);
}

static int32_t yaza_result_unwrap_err_int32(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_int32(value.payload);
}

static double yaza_result_unwrap_err_float64(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_float64(value.payload);
}

static bool yaza_result_unwrap_err_boolean(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_boolean(value.payload);
}

static yaza_text_list *yaza_result_unwrap_err_text_list(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_text_list(value.payload);
}

static yaza_bytes yaza_result_unwrap_err_bytes(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_bytes(value.payload);
}

static yaza_option yaza_result_unwrap_err_option(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_option(value.payload);
}

static yaza_result yaza_result_unwrap_err_result(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_result(value.payload);
}

static yaza_variant yaza_result_unwrap_variant(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_variant(value.payload);
}

static yaza_variant yaza_result_unwrap_err_variant(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_variant(value.payload);
}

static yaza_typed_list *yaza_result_unwrap_typed_list(yaza_result value, const char *type_name) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_typed_list(value.payload, type_name);
}

static yaza_typed_list *yaza_result_unwrap_err_typed_list(yaza_result value, const char *type_name) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_typed_list(value.payload, type_name);
}

#define YAZA_MAX_BYTES (64U * 1024U * 1024U)

static yaza_option yaza_option_some_secret_text(yaza_secret_text value);

static char *yaza_copy_text(const char *text) {
    size_t length = strlen(text);
    char *copy = (char *)malloc(length + 1);
    if (copy == NULL) {
        fprintf(stderr, "yaza: out of memory\n");
        exit(1);
    }
    memcpy(copy, text, length + 1);
    return copy;
}

static yaza_text_list *yaza_text_list_new(void) {
    yaza_text_list *list = (yaza_text_list *)calloc(1, sizeof(yaza_text_list));
    if (list == NULL) {
        fprintf(stderr, "yaza: out of memory creating TextList\n");
        exit(1);
    }
    return list;
}

#define YAZA_TYPED_LIST_MAX_ITEMS UINT64_C(1048576)

static void yaza_typed_list_check(const yaza_typed_list *list, size_t element_size, const char *element_type) {
    if (list == NULL || element_size == 0 || list->element_size != element_size ||
        list->element_type == NULL || element_type == NULL || strcmp(list->element_type, element_type) != 0) {
        fprintf(stderr, "yaza: typed List element type mismatch\n");
        exit(1);
    }
}

static yaza_typed_list *yaza_typed_list_new(size_t element_size, const char *element_type) {
    if (element_size == 0 || element_size > YAZA_MAX_BYTES || element_type == NULL || element_type[0] == '\0') {
        fprintf(stderr, "yaza: invalid typed List element descriptor\n");
        exit(1);
    }
    yaza_typed_list *list = (yaza_typed_list *)yaza_memory_calloc(1, sizeof(*list));
    if (list == NULL) {
        fprintf(stderr, "yaza: out of memory creating typed List\n");
        exit(1);
    }
    list->element_size = element_size;
    list->element_type = element_type;
    return list;
}

static int64_t yaza_typed_list_count(const yaza_typed_list *list, size_t element_size, const char *element_type) {
    yaza_typed_list_check(list, element_size, element_type);
    return (int64_t)list->length;
}

static int64_t yaza_typed_list_push(yaza_typed_list *list, const void *item, size_t element_size, const char *element_type) {
    yaza_typed_list_check(list, element_size, element_type);
    if (item == NULL || list->length >= YAZA_TYPED_LIST_MAX_ITEMS) {
        fprintf(stderr, "yaza: typed List item or capacity is invalid\n");
        exit(1);
    }
    if (list->length == list->capacity) {
        size_t maximum_capacity = YAZA_MAX_BYTES / list->element_size;
        size_t capacity = list->capacity == 0 ? 8 : list->capacity;
        if (capacity > maximum_capacity / 2) capacity = maximum_capacity;
        else capacity *= 2;
        if (capacity <= list->length || capacity > SIZE_MAX / list->element_size) {
            fprintf(stderr, "yaza: typed List exceeds its memory bound\n");
            exit(1);
        }
        unsigned char *items = (unsigned char *)yaza_memory_realloc(list->items, capacity * list->element_size);
        if (items == NULL) {
            fprintf(stderr, "yaza: out of memory growing typed List\n");
            exit(1);
        }
        list->items = items;
        list->capacity = capacity;
    }
    memcpy(list->items + list->length * list->element_size, item, list->element_size);
    list->length++;
    return 0;
}

static int64_t yaza_typed_list_set(yaza_typed_list *list, int64_t index, const void *item, size_t element_size, const char *element_type) {
    yaza_typed_list_check(list, element_size, element_type);
    if (item == NULL || index < 0 || (uint64_t)index >= list->length) {
        fprintf(stderr, "yaza: typed List index is out of range\n");
        exit(1);
    }
    memcpy(list->items + (size_t)index * list->element_size, item, list->element_size);
    return 0;
}

static const void *yaza_typed_list_get(const yaza_typed_list *list, int64_t index, size_t element_size, const char *element_type) {
    yaza_typed_list_check(list, element_size, element_type);
    if (index < 0 || (uint64_t)index >= list->length) {
        fprintf(stderr, "yaza: typed List index is out of range\n");
        exit(1);
    }
    return list->items + (size_t)index * list->element_size;
}

/* Safe counterpart to list_get: an invalid index produces none instead of
   terminating the program. payload_kind is emitted by the type-aware compiler
   so the Option representation stays identical to ordinary some(value). */
static yaza_option yaza_typed_list_try_get_option(const yaza_typed_list *list, int64_t index,
                                                   size_t element_size, const char *element_type,
                                                   const char *payload_kind) {
    yaza_typed_list_check(list, element_size, element_type);
    if (index < 0 || (uint64_t)index >= list->length) return yaza_option_none();
    const void *item = list->items + (size_t)index * list->element_size;
    if (strcmp(payload_kind, "text") == 0) {
        const char *value = NULL; memcpy(&value, item, sizeof(value)); return yaza_option_some_text(value);
    }
    if (strcmp(payload_kind, "number") == 0) {
        int64_t value; memcpy(&value, item, sizeof(value)); return yaza_option_some_number(value);
    }
    if (strcmp(payload_kind, "int32") == 0) {
        int32_t value; memcpy(&value, item, sizeof(value)); return yaza_option_some_int32(value);
    }
    if (strcmp(payload_kind, "float64") == 0) {
        double value; memcpy(&value, item, sizeof(value)); return yaza_option_some_float64(value);
    }
    if (strcmp(payload_kind, "boolean") == 0) {
        bool value; memcpy(&value, item, sizeof(value)); return yaza_option_some_boolean(value);
    }
    if (strcmp(payload_kind, "text_list") == 0) {
        yaza_text_list *value = NULL; memcpy(&value, item, sizeof(value)); return yaza_option_some_text_list(value);
    }
    if (strcmp(payload_kind, "typed_list") == 0) {
        yaza_typed_list *value = NULL; memcpy(&value, item, sizeof(value)); return yaza_option_some_typed_list(value, element_type);
    }
    if (strcmp(payload_kind, "bytes") == 0) {
        yaza_bytes value; memcpy(&value, item, sizeof(value)); return yaza_option_some_bytes(value);
    }
    if (strcmp(payload_kind, "secret_text") == 0) {
        yaza_secret_text value; memcpy(&value, item, sizeof(value)); return yaza_option_some_secret_text(value);
    }
    if (strcmp(payload_kind, "option") == 0) {
        yaza_option value; memcpy(&value, item, sizeof(value)); return yaza_option_some_option(value);
    }
    if (strcmp(payload_kind, "result") == 0) {
        yaza_result value; memcpy(&value, item, sizeof(value)); return yaza_option_some_result(value);
    }
    if (strcmp(payload_kind, "variant") == 0) {
        yaza_variant value; memcpy(&value, item, sizeof(value)); return yaza_option_some_variant(value);
    }
    return yaza_option_some_custom(item, element_size, element_type);
}

static int64_t yaza_list_push_owned(yaza_text_list *list, char *text) {
    if (list == NULL) return 1;
    if (list->length == list->capacity) {
        size_t capacity = list->capacity == 0 ? 8 : list->capacity * 2;
        char **items = (char **)realloc(list->items, capacity * sizeof(char *));
        if (items == NULL) {
            fprintf(stderr, "yaza: out of memory growing TextList\n");
            exit(1);
        }
        list->items = items;
        list->capacity = capacity;
    }
    list->items[list->length++] = text;
    return 0;
}

static int64_t yaza_list_push(yaza_text_list *list, const char *text) {
    if (list == NULL) return 1;
    char *copy = yaza_copy_text(text);
    if (yaza_list_push_owned(list, copy) != 0) {
        free(copy);
        return 1;
    }
    return 0;
}

static int64_t yaza_list_set(yaza_text_list *list, int64_t index, const char *text) {
    if (list == NULL || index < 0 || (uint64_t)index >= list->length) {
        fprintf(stderr, "yaza: TextList index is out of range\n");
        exit(1);
    }
    char *replacement = yaza_copy_text(text);
    if (yaza_current_memory_arena == NULL) free(list->items[index]);
    list->items[index] = replacement;
    return 0;
}

static int64_t yaza_list_count(const yaza_text_list *list) {
    return list == NULL ? 0 : (int64_t)list->length;
}

static char *yaza_text_join(const yaza_text_list *list, const char *separator) {
    size_t separator_length = strlen(separator);
    size_t total = 1;
    size_t count = list == NULL ? 0 : list->length;
    for (size_t index = 0; index < count; index++) {
        size_t item_length = strlen(list->items[index]);
        if (item_length > SIZE_MAX - total) {
            fprintf(stderr, "yaza: joined Text is too large\n");
            exit(1);
        }
        total += item_length;
        if (index != 0) {
            if (separator_length > SIZE_MAX - total) {
                fprintf(stderr, "yaza: joined Text is too large\n");
                exit(1);
            }
            total += separator_length;
        }
    }
    char *joined = (char *)malloc(total);
    if (joined == NULL) {
        fprintf(stderr, "yaza: out of memory joining TextList\n");
        exit(1);
    }
    char *cursor = joined;
    for (size_t index = 0; index < count; index++) {
        if (index != 0) {
            memcpy(cursor, separator, separator_length);
            cursor += separator_length;
        }
        size_t item_length = strlen(list->items[index]);
        memcpy(cursor, list->items[index], item_length);
        cursor += item_length;
    }
    *cursor = '\0';
    return joined;
}

static char *yaza_list_get(const yaza_text_list *list, int64_t index) {
    if (list == NULL || index < 0 || (uint64_t)index >= list->length) {
        fprintf(stderr, "yaza: TextList index is out of range\n");
        exit(1);
    }
    return list->items[index];
}

static yaza_option yaza_list_try_get_option(const yaza_text_list *list, int64_t index) {
    if (list == NULL || index < 0 || (uint64_t)index >= list->length) return yaza_option_none();
    return yaza_option_some_text(list->items[index]);
}

static int64_t yaza_text_length(const char *text) {
    return (int64_t)strlen(text);
}

static int64_t yaza_number_error(const char *operation) {
    fprintf(stderr, "yaza: Number overflow or division error in %s\n", operation);
    exit(1);
    return 0;
}

static int64_t yaza_number_parse(const char *text) {
    errno = 0;
    char *end = NULL;
    long long value = strtoll(text, &end, 10);
    if (errno != 0 || end == text || *end != '\0') {
        fprintf(stderr, "yaza: invalid Number '%s'\n", text);
        exit(1);
    }
    return (int64_t)value;
}

static char *yaza_number_text(int64_t value) {
    char buffer[32];
    int written = snprintf(buffer, sizeof(buffer), "%lld", (long long)value);
    if (written < 0 || (size_t)written >= sizeof(buffer)) {
        return yaza_copy_text("0");
    }
    return yaza_copy_text(buffer);
}

static double yaza_float64_error(const char *operation) {
    fprintf(stderr, "yaza: invalid Float64 value or arithmetic error in %s\n", operation);
    exit(1);
    return 0.0;
}

static bool yaza_float64_text_valid(const char *text) {
    if (text == NULL || *text == '\0') return false;
    const unsigned char *cursor = (const unsigned char *)text;
    if (*cursor == '+' || *cursor == '-') cursor++;
    bool integer_digits = false;
    while (*cursor >= '0' && *cursor <= '9') {
        integer_digits = true;
        cursor++;
    }
    bool fraction_digits = false;
    if (*cursor == '.') {
        cursor++;
        while (*cursor >= '0' && *cursor <= '9') {
            fraction_digits = true;
            cursor++;
        }
        if (!fraction_digits) return false;
    }
    if (!integer_digits) return false;
    if (*cursor == 'e' || *cursor == 'E') {
        cursor++;
        if (*cursor == '+' || *cursor == '-') cursor++;
        bool exponent_digits = false;
        while (*cursor >= '0' && *cursor <= '9') {
            exponent_digits = true;
            cursor++;
        }
        if (!exponent_digits) return false;
    }
    return *cursor == '\0';
}

static double yaza_float64_parse(const char *text) {
    if (!yaza_float64_text_valid(text)) return yaza_float64_error("parsing");
    errno = 0;
    char *end = NULL;
    double value = strtod(text, &end);
    if (errno == ERANGE || end == text || *end != '\0' || !isfinite(value))
        return yaza_float64_error("parsing");
    return value;
}

static char *yaza_float64_text(double value) {
    if (!isfinite(value)) yaza_float64_error("formatting");
    char buffer[64];
    int written = snprintf(buffer, sizeof(buffer), "%.17g", value);
    if (written < 0 || (size_t)written >= sizeof(buffer)) yaza_float64_error("formatting");
    return yaza_copy_text(buffer);
}

static double yaza_float64_checked(double value, const char *operation) {
    if (!isfinite(value)) return yaza_float64_error(operation);
    return value;
}

static double yaza_float64_add(double left, double right) {
    return yaza_float64_checked(left + right, "addition");
}

static double yaza_float64_subtract(double left, double right) {
    return yaza_float64_checked(left - right, "subtraction");
}

static double yaza_float64_multiply(double left, double right) {
    return yaza_float64_checked(left * right, "multiplication");
}

static double yaza_float64_divide(double left, double right) {
    if (right == 0.0) return yaza_float64_error("division by zero");
    return yaza_float64_checked(left / right, "division");
}

static double yaza_float64_negate(double value) {
    return yaza_float64_checked(-value, "negation");
}

static double yaza_float64_from_number(int64_t value) {
    if (value < -INT64_C(9007199254740992) || value > INT64_C(9007199254740992))
        yaza_float64_error("Number to Float64 conversion would lose precision");
    return (double)value;
}

static int64_t yaza_number_from_float64(double value) {
    if (!isfinite(value) || value < -9223372036854775808.0 || value >= 9223372036854775808.0)
        return yaza_number_error("Float64 to Number conversion range");
    int64_t converted = (int64_t)value;
    if ((double)converted != value) return yaza_number_error("Float64 to Number conversion precision");
    return converted;
}

static int64_t yaza_add(int64_t left, int64_t right) {
    int64_t result;
    if (__builtin_add_overflow(left, right, &result)) return yaza_number_error("addition");
    return result;
}

static int64_t yaza_subtract(int64_t left, int64_t right) {
    int64_t result;
    if (__builtin_sub_overflow(left, right, &result)) return yaza_number_error("subtraction");
    return result;
}

static int64_t yaza_multiply(int64_t left, int64_t right) {
    int64_t result;
    if (__builtin_mul_overflow(left, right, &result)) return yaza_number_error("multiplication");
    return result;
}

static int64_t yaza_divide(int64_t left, int64_t right) {
    if (right == 0 || (left == INT64_MIN && right == -1)) {
        return yaza_number_error("division");
    }
    return left / right;
}

static int64_t yaza_modulo(int64_t left, int64_t right) {
    if (right == 0 || (left == INT64_MIN && right == -1)) {
        return yaza_number_error("remainder");
    }
    return left % right;
}

static int64_t yaza_negate(int64_t value) {
    if (value == INT64_MIN) return yaza_number_error("negation");
    return -value;
}

static int32_t yaza_int32_from_number(int64_t value) {
    if (value < INT32_MIN || value > INT32_MAX) {
        fprintf(stderr, "yaza: Number to Int32 conversion is out of range\n");
        exit(1);
    }
    return (int32_t)value;
}

static int64_t yaza_number_from_int32(int32_t value) {
    return (int64_t)value;
}

static const char *yaza_int32_text(int32_t value) {
    char buffer[16];
    int written = snprintf(buffer, sizeof(buffer), "%" PRId32, value);
    if (written < 0 || (size_t)written >= sizeof(buffer)) {
        fprintf(stderr, "yaza: Int32 formatting failed\n");
        exit(1);
    }
    return yaza_copy_text(buffer);
}

static int32_t yaza_int32_add(int32_t left, int32_t right) {
    int32_t result;
    if (__builtin_add_overflow(left, right, &result)) {
        fprintf(stderr, "yaza: Int32 overflow during addition\n");
        exit(1);
    }
    return result;
}

static int32_t yaza_int32_subtract(int32_t left, int32_t right) {
    int32_t result;
    if (__builtin_sub_overflow(left, right, &result)) {
        fprintf(stderr, "yaza: Int32 overflow during subtraction\n");
        exit(1);
    }
    return result;
}

static int32_t yaza_int32_multiply(int32_t left, int32_t right) {
    int32_t result;
    if (__builtin_mul_overflow(left, right, &result)) {
        fprintf(stderr, "yaza: Int32 overflow during multiplication\n");
        exit(1);
    }
    return result;
}

static int32_t yaza_int32_divide(int32_t left, int32_t right) {
    if (right == 0 || (left == INT32_MIN && right == -1)) {
        fprintf(stderr, "yaza: Int32 invalid division\n");
        exit(1);
    }
    return left / right;
}

static int32_t yaza_int32_modulo(int32_t left, int32_t right) {
    if (right == 0 || (left == INT32_MIN && right == -1)) {
        fprintf(stderr, "yaza: Int32 invalid remainder\n");
        exit(1);
    }
    return left % right;
}

static int32_t yaza_int32_negate(int32_t value) {
    if (value == INT32_MIN) {
        fprintf(stderr, "yaza: Int32 overflow during negation\n");
        exit(1);
    }
    return -value;
}

static int64_t yaza_text_byte(const char *text, int64_t index) {
    size_t length = strlen(text);
    if (index < 0 || (uint64_t)index >= length) {
        fprintf(stderr, "yaza: Text byte index is out of range\n");
        exit(1);
    }
    return (unsigned char)text[index];
}

static yaza_bytes yaza_bytes_copy(const unsigned char *source, size_t length) {
    yaza_bytes result = {NULL, length};
    if (length > YAZA_MAX_BYTES) {
        fprintf(stderr, "yaza: Bytes value exceeds the 64 MiB runtime limit\n");
        exit(1);
    }
    if (length == 0) return result;
    result.data = (unsigned char *)malloc(length);
    if (result.data == NULL) {
        fprintf(stderr, "yaza: out of memory creating Bytes value\n");
        exit(1);
    }
    memcpy(result.data, source, length);
    return result;
}

static yaza_bytes yaza_bytes_from_text(const char *text) {
    return yaza_bytes_copy((const unsigned char *)text, strlen(text));
}

static yaza_result yaza_bytes_from_text_bounded(const char *text, int64_t maximum_bytes) {
    if (maximum_bytes < 0 || (uint64_t)maximum_bytes > YAZA_MAX_BYTES)
        return yaza_result_err(yaza_option_some_text(yaza_copy_text("Text byte limit is outside the supported range")));
    size_t maximum = (size_t)maximum_bytes;
    size_t length = strnlen(text, maximum + 1);
    if (length > maximum)
        return yaza_result_err(yaza_option_some_text(yaza_copy_text("Text exceeds the configured byte limit")));
    return yaza_result_ok(yaza_option_some_bytes(yaza_bytes_copy((const unsigned char *)text, length)));
}

static yaza_bytes yaza_bytes_from_number(int64_t value) {
    if (value < 0 || value > 255) {
        fprintf(stderr, "yaza: bytes_from_number value must be between 0 and 255\n");
        exit(1);
    }
    const unsigned char byte = (unsigned char)value;
    return yaza_bytes_copy(&byte, 1);
}

static yaza_bytes yaza_secure_random_bytes(int64_t requested_length) {
    if (requested_length < 0 || (uint64_t)requested_length > YAZA_MAX_BYTES) {
        fprintf(stderr, "yaza: secure_random_bytes length must be between 0 and 64 MiB\n");
        exit(1);
    }
    size_t length = (size_t)requested_length;
    yaza_bytes result = {NULL, length};
    if (length == 0) return result;

    int random_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
    if (random_fd < 0) {
        fprintf(stderr, "yaza: operating-system random source is unavailable: %s\n", strerror(errno));
        exit(1);
    }
    result.data = (unsigned char *)malloc(length);
    if (result.data == NULL) {
        close(random_fd);
        fprintf(stderr, "yaza: out of memory requesting secure random bytes\n");
        exit(1);
    }

    size_t offset = 0;
    while (offset < length) {
        ssize_t received = read(random_fd, result.data + offset, length - offset);
        if (received > 0) {
            offset += (size_t)received;
        } else if (received < 0 && errno == EINTR) {
            continue;
        } else {
            int read_error = received == 0 ? EIO : errno;
            volatile unsigned char *wipe = result.data;
            for (size_t index = 0; index < length; index++) wipe[index] = 0;
            free(result.data);
            close(random_fd);
            fprintf(stderr, "yaza: operating-system random source failed: %s\n", strerror(read_error));
            exit(1);
        }
    }
    if (close(random_fd) != 0) {
        int close_error = errno;
        volatile unsigned char *wipe = result.data;
        for (size_t index = 0; index < length; index++) wipe[index] = 0;
        free(result.data);
        fprintf(stderr, "yaza: could not close operating-system random source: %s\n", strerror(close_error));
        exit(1);
    }
    return result;
}

static int64_t yaza_bytes_length(yaza_bytes value) {
    return (int64_t)value.length;
}

static int64_t yaza_bytes_get(yaza_bytes value, int64_t index) {
    if (index < 0 || (uint64_t)index >= value.length || value.data == NULL) {
        fprintf(stderr, "yaza: Bytes index is out of range\n");
        exit(1);
    }
    return (int64_t)value.data[index];
}

static yaza_bytes yaza_bytes_slice(yaza_bytes value, int64_t start, int64_t length) {
    if (start < 0 || length < 0 || (uint64_t)start > value.length ||
        (uint64_t)length > value.length - (size_t)start) {
        fprintf(stderr, "yaza: Bytes slice is out of range\n");
        exit(1);
    }
    if (length == 0) return (yaza_bytes){NULL, 0};
    return yaza_bytes_copy(value.data + start, (size_t)length);
}

static yaza_bytes yaza_bytes_concat(yaza_bytes left, yaza_bytes right) {
    if (right.length > YAZA_MAX_BYTES - left.length) {
        fprintf(stderr, "yaza: concatenated Bytes exceeds the 64 MiB runtime limit\n");
        exit(1);
    }
    size_t length = left.length + right.length;
    yaza_bytes result = {NULL, length};
    if (length == 0) return result;
    result.data = (unsigned char *)malloc(length);
    if (result.data == NULL) {
        fprintf(stderr, "yaza: out of memory concatenating Bytes values\n");
        exit(1);
    }
    if (left.length > 0) memcpy(result.data, left.data, left.length);
    if (right.length > 0) memcpy(result.data + left.length, right.data, right.length);
    return result;
}

static bool yaza_bytes_equal(yaza_bytes left, yaza_bytes right) {
    return left.length == right.length &&
        (left.length == 0 || memcmp(left.data, right.data, left.length) == 0);
}

static bool yaza_bytes_equal_constant_time(yaza_bytes left, yaza_bytes right) {
    if (left.length != right.length) return false;
    unsigned char difference = 0;
    for (size_t index = 0; index < left.length; index++)
        difference |= (unsigned char)(left.data[index] ^ right.data[index]);
    return difference == 0;
}

static void yaza_secure_wipe(void *data, size_t length) {
    volatile unsigned char *bytes = (volatile unsigned char *)data;
    for (size_t index = 0; index < length; index++) bytes[index] = 0;
}

/* Process-local bounded TTL cache. Entries use fixed storage so request-arena
   resets can never invalidate them and cache growth cannot exceed this table. */
#define YAZA_TTL_CACHE_MAX_ENTRIES 128U
#define YAZA_TTL_CACHE_MAX_KEY_BYTES 255U
#define YAZA_TTL_CACHE_MAX_VALUE_BYTES 4095U
#define YAZA_TTL_CACHE_MAX_TTL_MS INT64_C(604800000)

typedef struct {
    bool active;
    int64_t expires_at_ms;
    uint64_t last_used;
    char key[YAZA_TTL_CACHE_MAX_KEY_BYTES + 1U];
    char value[YAZA_TTL_CACHE_MAX_VALUE_BYTES + 1U];
} yaza_ttl_cache_entry;

static pthread_mutex_t yaza_ttl_cache_mutex = PTHREAD_MUTEX_INITIALIZER;
static yaza_ttl_cache_entry yaza_ttl_cache_entries[YAZA_TTL_CACHE_MAX_ENTRIES];
static uint64_t yaza_ttl_cache_usage_sequence = 0;

static void yaza_ttl_cache_entry_clear(yaza_ttl_cache_entry *entry) {
    if (entry == NULL) return;
    yaza_secure_wipe(entry->key, sizeof(entry->key));
    yaza_secure_wipe(entry->value, sizeof(entry->value));
    entry->active = false;
    entry->expires_at_ms = 0;
    entry->last_used = 0;
}

static uint64_t yaza_ttl_cache_next_usage_locked(void) {
    if (yaza_ttl_cache_usage_sequence == UINT64_MAX) {
        yaza_ttl_cache_usage_sequence = 0;
        for (size_t index = 0; index < YAZA_TTL_CACHE_MAX_ENTRIES; index++)
            yaza_ttl_cache_entries[index].last_used = 0;
    }
    return ++yaza_ttl_cache_usage_sequence;
}

static bool yaza_ttl_cache_key_length(const char *key, size_t *length) {
    if (key == NULL || length == NULL) return false;
    size_t measured = strnlen(key, YAZA_TTL_CACHE_MAX_KEY_BYTES + 1U);
    if (measured == 0 || measured > YAZA_TTL_CACHE_MAX_KEY_BYTES) return false;
    *length = measured;
    return true;
}

static yaza_option yaza_ttl_cache_get(const char *key) {
    size_t key_length = 0;
    if (!yaza_ttl_cache_key_length(key, &key_length)) return yaza_option_none();
    int64_t now_ms = yaza_monotonic_milliseconds();
    if (now_ms < 0 || pthread_mutex_lock(&yaza_ttl_cache_mutex) != 0)
        return yaza_option_none();

    char copied_value[YAZA_TTL_CACHE_MAX_VALUE_BYTES + 1U] = {0};
    bool found = false;
    for (size_t index = 0; index < YAZA_TTL_CACHE_MAX_ENTRIES; index++) {
        yaza_ttl_cache_entry *entry = &yaza_ttl_cache_entries[index];
        if (!entry->active) continue;
        if (entry->expires_at_ms <= now_ms) {
            yaza_ttl_cache_entry_clear(entry);
            continue;
        }
        if (strlen(entry->key) == key_length && memcmp(entry->key, key, key_length) == 0) {
            memcpy(copied_value, entry->value, strlen(entry->value) + 1U);
            entry->last_used = yaza_ttl_cache_next_usage_locked();
            found = true;
            break;
        }
    }
    pthread_mutex_unlock(&yaza_ttl_cache_mutex);
    if (!found) {
        yaza_secure_wipe(copied_value, sizeof(copied_value));
        return yaza_option_none();
    }
    char *owned_value = yaza_copy_text(copied_value);
    yaza_secure_wipe(copied_value, sizeof(copied_value));
    return yaza_option_some_text(owned_value);
}

static bool yaza_ttl_cache_set(const char *key, const char *value, int64_t ttl_ms) {
    size_t key_length = 0;
    if (!yaza_ttl_cache_key_length(key, &key_length) || value == NULL ||
        ttl_ms < 1 || ttl_ms > YAZA_TTL_CACHE_MAX_TTL_MS)
        return false;
    size_t value_length = strnlen(value, YAZA_TTL_CACHE_MAX_VALUE_BYTES + 1U);
    if (value_length > YAZA_TTL_CACHE_MAX_VALUE_BYTES) return false;
    int64_t now_ms = yaza_monotonic_milliseconds();
    if (now_ms < 0 || now_ms > INT64_MAX - ttl_ms ||
        pthread_mutex_lock(&yaza_ttl_cache_mutex) != 0)
        return false;

    size_t chosen = YAZA_TTL_CACHE_MAX_ENTRIES;
    size_t least_recent = 0;
    uint64_t least_recent_usage = UINT64_MAX;
    for (size_t index = 0; index < YAZA_TTL_CACHE_MAX_ENTRIES; index++) {
        yaza_ttl_cache_entry *entry = &yaza_ttl_cache_entries[index];
        if (entry->active && entry->expires_at_ms <= now_ms) yaza_ttl_cache_entry_clear(entry);
        if (entry->active && strlen(entry->key) == key_length &&
            memcmp(entry->key, key, key_length) == 0) {
            chosen = index;
            break;
        }
        if (!entry->active && chosen == YAZA_TTL_CACHE_MAX_ENTRIES) chosen = index;
        if (entry->active && entry->last_used < least_recent_usage) {
            least_recent = index;
            least_recent_usage = entry->last_used;
        }
    }
    if (chosen == YAZA_TTL_CACHE_MAX_ENTRIES) chosen = least_recent;
    yaza_ttl_cache_entry *entry = &yaza_ttl_cache_entries[chosen];
    yaza_ttl_cache_entry_clear(entry);
    memcpy(entry->key, key, key_length);
    entry->key[key_length] = '\0';
    memcpy(entry->value, value, value_length);
    entry->value[value_length] = '\0';
    entry->expires_at_ms = now_ms + ttl_ms;
    entry->last_used = yaza_ttl_cache_next_usage_locked();
    entry->active = true;
    pthread_mutex_unlock(&yaza_ttl_cache_mutex);
    return true;
}

static bool yaza_ttl_cache_remove(const char *key) {
    size_t key_length = 0;
    if (!yaza_ttl_cache_key_length(key, &key_length) ||
        pthread_mutex_lock(&yaza_ttl_cache_mutex) != 0)
        return false;
    bool removed = false;
    int64_t now_ms = yaza_monotonic_milliseconds();
    for (size_t index = 0; index < YAZA_TTL_CACHE_MAX_ENTRIES; index++) {
        yaza_ttl_cache_entry *entry = &yaza_ttl_cache_entries[index];
        if (!entry->active) continue;
        if (now_ms >= 0 && entry->expires_at_ms <= now_ms) {
            yaza_ttl_cache_entry_clear(entry);
            continue;
        }
        if (strlen(entry->key) == key_length && memcmp(entry->key, key, key_length) == 0) {
            yaza_ttl_cache_entry_clear(entry);
            removed = true;
            break;
        }
    }
    pthread_mutex_unlock(&yaza_ttl_cache_mutex);
    return removed;
}

static int64_t yaza_ttl_cache_clear(void) {
    if (pthread_mutex_lock(&yaza_ttl_cache_mutex) != 0) return -1;
    int64_t removed = 0;
    for (size_t index = 0; index < YAZA_TTL_CACHE_MAX_ENTRIES; index++) {
        if (yaza_ttl_cache_entries[index].active) removed++;
        yaza_ttl_cache_entry_clear(&yaza_ttl_cache_entries[index]);
    }
    pthread_mutex_unlock(&yaza_ttl_cache_mutex);
    return removed;
}

static void yaza_ttl_cache_shutdown(void) {
    (void)yaza_ttl_cache_clear();
}

#define YAZA_SECRET_TEXT_MAX_BYTES (64U * 1024U)

static yaza_option yaza_option_some_secret_text(yaza_secret_text value) {
    yaza_option result = {0};
    result.is_some = true;
    result.kind = YAZA_OPTION_SECRET_TEXT;
    result.value.secret_text = value;
    return result;
}

static yaza_secret_text yaza_option_unwrap_secret_text(yaza_option value) {
    if (!value.is_some || value.kind != YAZA_OPTION_SECRET_TEXT)
        yaza_option_unwrap_error("SecretText");
    return value.value.secret_text;
}

static yaza_secret_text yaza_result_unwrap_secret_text(yaza_result value) {
    if (!value.is_ok) yaza_result_wrong_variant("ok");
    return yaza_option_unwrap_secret_text(value.payload);
}

static yaza_secret_text yaza_result_unwrap_err_secret_text(yaza_result value) {
    if (value.is_ok) yaza_result_wrong_variant("err");
    return yaza_option_unwrap_secret_text(value.payload);
}

static yaza_option yaza_secret_text_from_text(const char *text) {
    if (text == NULL) return yaza_option_none();
    size_t length = strnlen(text, YAZA_SECRET_TEXT_MAX_BYTES + 1U);
    if (length == 0 || length > YAZA_SECRET_TEXT_MAX_BYTES ||
        length > SIZE_MAX - sizeof(yaza_secret_text_buffer) - 1U)
        return yaza_option_none();
    yaza_secret_text_buffer *buffer = (yaza_secret_text_buffer *)calloc(
        1, sizeof(yaza_secret_text_buffer) + length + 1U);
    if (buffer == NULL) return yaza_option_none();
    buffer->length = length;
    buffer->valid = true;
    memcpy(buffer->value, text, length);
    buffer->value[length] = '\0';
    return yaza_option_some_secret_text((yaza_secret_text){buffer});
}

static yaza_option yaza_secret_text_from_env(const char *name) {
    if (name == NULL || *name == '\0' || strchr(name, '=') != NULL) return yaza_option_none();
    const char *value = getenv(name);
    if (value == NULL) return yaza_option_none();
    return yaza_secret_text_from_text(value);
}

static bool yaza_secret_text_is_valid(yaza_secret_text value) {
    return value.buffer != NULL && value.buffer->valid;
}

static yaza_option yaza_secret_text_reveal(yaza_secret_text value) {
    if (!yaza_secret_text_is_valid(value)) return yaza_option_none();
    return yaza_option_some_text((const char *)value.buffer->value);
}

static const char *yaza_secret_text_redacted(yaza_secret_text value) {
    (void)value;
    return "<redacted>";
}

static bool yaza_secret_text_zeroize(yaza_secret_text value) {
    if (!yaza_secret_text_is_valid(value)) return false;
    yaza_secure_wipe(value.buffer->value, value.buffer->length + 1U);
    value.buffer->length = 0;
    value.buffer->valid = false;
    return true;
}

static int64_t yaza_bytes_zeroize(yaza_bytes value) {
    if (value.data != NULL && value.length != 0) yaza_secure_wipe(value.data, value.length);
    return 0;
}

static yaza_bytes yaza_crypto_sha256(yaza_bytes input) {
    unsigned char digest[32];
#if defined(__APPLE__)
    const void *input_data = input.length == 0 ? (const void *)"" : (const void *)input.data;
    if (CC_SHA256(input_data, (CC_LONG)input.length, digest) == NULL) {
        fprintf(stderr, "yaza: operating-system SHA-256 provider failed\n");
        exit(1);
    }
#else
    unsigned int digest_length = 0;
    if (EVP_Digest(input.length == 0 ? "" : input.data, input.length, digest, &digest_length, EVP_sha256(), NULL) != 1 || digest_length != sizeof(digest)) {
        fprintf(stderr, "yaza: operating-system SHA-256 provider failed\n");
        exit(1);
    }
#endif
    yaza_bytes result = yaza_bytes_copy(digest, sizeof(digest));
    yaza_secure_wipe(digest, sizeof(digest));
    return result;
}

static yaza_bytes yaza_crypto_hmac_sha256(yaza_bytes key, yaza_bytes message) {
    unsigned char digest[32];
#if defined(__APPLE__)
    const void *key_data = key.length == 0 ? (const void *)"" : (const void *)key.data;
    const void *message_data = message.length == 0 ? (const void *)"" : (const void *)message.data;
    CCHmac(kCCHmacAlgSHA256, key_data, key.length, message_data, message.length, digest);
#else
    unsigned int digest_length = 0;
    if (HMAC(EVP_sha256(), key.length == 0 ? "" : key.data, (int)key.length,
             message.length == 0 ? "" : message.data, message.length, digest, &digest_length) == NULL || digest_length != sizeof(digest)) {
        fprintf(stderr, "yaza: operating-system HMAC-SHA-256 provider failed\n");
        exit(1);
    }
#endif
    yaza_bytes result = yaza_bytes_copy(digest, sizeof(digest));
    yaza_secure_wipe(digest, sizeof(digest));
    return result;
}

static yaza_result yaza_crypto_error(const char *message) {
    return yaza_result_err(yaza_option_some_text(yaza_copy_text(message)));
}

static yaza_result yaza_crypto_pbkdf2_sha256(yaza_bytes password, yaza_bytes salt, int64_t iterations, int64_t key_length) {
    if (iterations < 1 || iterations > 1000000)
        return yaza_crypto_error("PBKDF2 iterations must be between 1 and 1000000");
    if (key_length < 1 || key_length > 64)
        return yaza_crypto_error("PBKDF2-SHA-256 output must be between 1 and 64 bytes");
    if (salt.length < 1 || salt.length > 1024)
        return yaza_crypto_error("PBKDF2 salt must be between 1 and 1024 bytes");
    unsigned char derived[64];
#if defined(__APPLE__)
    const int status = CCKeyDerivationPBKDF(kCCPBKDF2,
        password.length == 0 ? "" : (const char *)password.data, password.length,
        salt.data, salt.length, kCCPRFHmacAlgSHA256, (uint32_t)iterations,
        derived, (size_t)key_length);
    if (status != kCCSuccess) {
        yaza_secure_wipe(derived, sizeof(derived));
        return yaza_crypto_error("operating-system PBKDF2-SHA-256 provider failed");
    }
#else
    if (PKCS5_PBKDF2_HMAC(password.length == 0 ? "" : (const char *)password.data, (int)password.length,
            salt.data, (int)salt.length, (int)iterations, EVP_sha256(), (int)key_length, derived) != 1) {
        yaza_secure_wipe(derived, sizeof(derived));
        return yaza_crypto_error("operating-system PBKDF2-SHA-256 provider failed");
    }
#endif
    yaza_bytes output = yaza_bytes_copy(derived, (size_t)key_length);
    yaza_secure_wipe(derived, sizeof(derived));
    return yaza_result_ok(yaza_option_some_bytes(output));
}

#define YAZA_ARGON2ID_PASSWORD_MAX 1024U
#define YAZA_ARGON2ID_SALT_BYTES 16U
#define YAZA_ARGON2ID_HASH_BYTES 32U
#define YAZA_ARGON2ID_MEMORY_KIB 19456U
#define YAZA_ARGON2ID_ITERATIONS 2U
#define YAZA_ARGON2ID_PARALLELISM 1U

static bool yaza_argon2id_base64_field_valid(const char *value, size_t expected_length) {
    if (value == NULL || strlen(value) != expected_length) return false;
    for (const unsigned char *cursor = (const unsigned char *)value; *cursor != '\0'; cursor++) {
        if (!((*cursor >= 'A' && *cursor <= 'Z') || (*cursor >= 'a' && *cursor <= 'z') ||
              (*cursor >= '0' && *cursor <= '9') || *cursor == '+' || *cursor == '/')) return false;
    }
    return true;
}

static bool yaza_argon2id_encoded_parameters_are_bounded(const char *encoded) {
    static const char prefix[] = "$argon2id$v=19$m=19456,t=2,p=1$";
    if (encoded == NULL) return false;
    size_t encoded_length = strnlen(encoded, 161);
    if (encoded_length == 0 || encoded_length >= 161 ||
        encoded_length != sizeof(prefix) - 1 + 22 + 1 + 43 ||
        strncmp(encoded, prefix, sizeof(prefix) - 1) != 0) return false;
    const char *salt = encoded + sizeof(prefix) - 1;
    const char *separator = strchr(salt, '$');
    if (separator == NULL || (size_t)(separator - salt) != 22 || strchr(separator + 1, '$') != NULL) return false;
    char salt_copy[23];
    memcpy(salt_copy, salt, 22);
    salt_copy[22] = '\0';
    return yaza_argon2id_base64_field_valid(salt_copy, 22) &&
        yaza_argon2id_base64_field_valid(separator + 1, 43);
}

static yaza_result yaza_crypto_argon2id_hash(yaza_bytes password, yaza_bytes salt) {
    if (password.length > YAZA_ARGON2ID_PASSWORD_MAX)
        return yaza_crypto_error("Argon2id password exceeds the 1024-byte limit");
    if (salt.length != YAZA_ARGON2ID_SALT_BYTES || salt.data == NULL)
        return yaza_crypto_error("Argon2id password salt must contain exactly 16 bytes");
#if !defined(YAZA_WITH_ARGON2)
    return yaza_crypto_error("Argon2id provider is unavailable; install the YAZA Argon2 provider package");
#else
    char encoded[161] = {0};
    const int status = argon2id_hash_encoded(YAZA_ARGON2ID_ITERATIONS, YAZA_ARGON2ID_MEMORY_KIB,
        YAZA_ARGON2ID_PARALLELISM, password.length == 0 ? (const void *)"" : (const void *)password.data, password.length,
        salt.data, salt.length, YAZA_ARGON2ID_HASH_BYTES, encoded, sizeof(encoded));
    if (status != ARGON2_OK || !yaza_argon2id_encoded_parameters_are_bounded(encoded)) {
        yaza_secure_wipe(encoded, sizeof(encoded));
        return yaza_crypto_error("Argon2id provider failed to produce a valid password hash");
    }
    const char *copy = yaza_copy_text(encoded);
    yaza_secure_wipe(encoded, sizeof(encoded));
    if (copy == NULL) return yaza_crypto_error("Argon2id password hash allocation failed");
    return yaza_result_ok(yaza_option_some_text(copy));
#endif
}

static yaza_result yaza_crypto_argon2id_verify(yaza_bytes password, const char *encoded) {
    if (password.length > YAZA_ARGON2ID_PASSWORD_MAX)
        return yaza_crypto_error("Argon2id password exceeds the 1024-byte limit");
    if (!yaza_argon2id_encoded_parameters_are_bounded(encoded))
        return yaza_crypto_error("password hash format or parameters are unsupported");
#if !defined(YAZA_WITH_ARGON2)
    return yaza_crypto_error("Argon2id provider is unavailable; install the YAZA Argon2 provider package");
#else
    const int status = argon2id_verify(encoded,
        password.length == 0 ? (const void *)"" : (const void *)password.data, password.length);
    if (status == ARGON2_OK) return yaza_result_ok(yaza_option_some_boolean(true));
    if (status == ARGON2_VERIFY_MISMATCH) return yaza_result_ok(yaza_option_some_boolean(false));
    return yaza_crypto_error("Argon2id provider failed to verify the password hash");
#endif
}

static bool yaza_utf8_valid(const unsigned char *data, size_t length) {
    size_t index = 0;
    while (index < length) {
        unsigned char first = data[index++];
        if (first == 0) return false;
        if (first <= 0x7f) continue;
        if (first >= 0xc2 && first <= 0xdf) {
            if (index >= length || (data[index] & 0xc0) != 0x80) return false;
            index++;
            continue;
        }
        if (first >= 0xe0 && first <= 0xef) {
            if (index + 1 >= length) return false;
            unsigned char second = data[index], third = data[index + 1];
            if ((third & 0xc0) != 0x80 || (second & 0xc0) != 0x80) return false;
            if ((first == 0xe0 && second < 0xa0) || (first == 0xed && second >= 0xa0)) return false;
            index += 2;
            continue;
        }
        if (first >= 0xf0 && first <= 0xf4) {
            if (index + 2 >= length) return false;
            unsigned char second = data[index], third = data[index + 1], fourth = data[index + 2];
            if ((second & 0xc0) != 0x80 || (third & 0xc0) != 0x80 || (fourth & 0xc0) != 0x80) return false;
            if ((first == 0xf0 && second < 0x90) || (first == 0xf4 && second > 0x8f)) return false;
            index += 3;
            continue;
        }
        return false;
    }
    return true;
}

static char *yaza_bytes_to_text(yaza_bytes value) {
    if (!yaza_utf8_valid(value.data, value.length)) {
        fprintf(stderr, "yaza: Bytes value is not valid non-NUL UTF-8 Text\n");
        exit(1);
    }
    char *text = (char *)malloc(value.length + 1);
    if (text == NULL) {
        fprintf(stderr, "yaza: out of memory converting Bytes to Text\n");
        exit(1);
    }
    if (value.length > 0) memcpy(text, value.data, value.length);
    text[value.length] = '\0';
    return text;
}

static yaza_option yaza_bytes_to_text_checked(yaza_bytes value) {
    if (!yaza_utf8_valid(value.data, value.length)) return yaza_option_none();
    return yaza_option_some_text(yaza_bytes_to_text(value));
}

static char *yaza_text_slice(const char *text, int64_t start, int64_t length) {
    size_t text_length = strlen(text);
    if (start < 0 || length < 0 || (uint64_t)start > text_length ||
        (uint64_t)length > text_length - (size_t)start) {
        fprintf(stderr, "yaza: Text slice is out of range\n");
        exit(1);
    }
    char *slice = (char *)malloc((size_t)length + 1);
    if (slice == NULL) {
        size_t arena_live = yaza_current_memory_arena == NULL ? 0 : yaza_current_memory_arena->live_bytes;
        size_t arena_limit = yaza_current_memory_arena == NULL ? 0 : yaza_current_memory_arena->allocation_limit;
        fprintf(stderr, "yaza: out of memory creating Text slice (requested %zu bytes; arena %zu/%zu bytes)\n",
                (size_t)length + 1, arena_live, arena_limit);
        exit(1);
    }
    memcpy(slice, text + start, (size_t)length);
    slice[length] = '\0';
    return slice;
}

static int64_t yaza_text_find(const char *text, const char *needle) {
    const char *found = strstr(text, needle);
    return found == NULL ? -1 : (int64_t)(found - text);
}

static yaza_text_list *yaza_text_split(const char *text, const char *delimiter) {
    size_t delimiter_length = strlen(delimiter);
    if (delimiter_length == 0) {
        fprintf(stderr, "yaza: text_split delimiter cannot be empty\n");
        exit(1);
    }
    yaza_text_list *parts = yaza_text_list_new();
    const char *cursor = text;
    const char *found;
    while ((found = strstr(cursor, delimiter)) != NULL) {
        char *part = yaza_text_slice(cursor, 0, (int64_t)(found - cursor));
        if (yaza_list_push_owned(parts, part) != 0) {
            free(part);
            fprintf(stderr, "yaza: out of memory growing TextList\n");
            exit(1);
        }
        cursor = found + delimiter_length;
    }
    yaza_list_push(parts, cursor);
    return parts;
}

static yaza_text_list *yaza_text_lines(const char *text) {
    if (text[0] == '\0') return yaza_text_list_new();
    yaza_text_list *lines = yaza_text_split(text, "\n");
    size_t length = strlen(text);
    if (length > 0 && text[length - 1] == '\n' && lines->length > 0 &&
        lines->items[lines->length - 1][0] == '\0') {
        lines->length--;
    }
    return lines;
}

static char *yaza_text_trim(const char *text) {
    const char *start = text;
    while (*start != '\0' && isspace((unsigned char)*start)) start++;
    const char *end = text + strlen(text);
    while (end > start && isspace((unsigned char)end[-1])) end--;
    return yaza_text_slice(start, 0, (int64_t)(end - start));
}

static bool yaza_text_starts_with(const char *text, const char *prefix) {
    size_t prefix_length = strlen(prefix);
    return strncmp(text, prefix, prefix_length) == 0;
}

static bool yaza_text_ends_with(const char *text, const char *suffix) {
    size_t text_length = strlen(text);
    size_t suffix_length = strlen(suffix);
    return text_length >= suffix_length &&
        memcmp(text + text_length - suffix_length, suffix, suffix_length) == 0;
}

static int64_t yaza_text_compare(const char *left, const char *right) {
    return (int64_t)strcmp(left, right);
}

static atomic_uint_fast64_t yaza_text_concat_allocated_bytes = 0;
static atomic_uint_fast64_t yaza_text_concat_allocation_count = 0;

static char *yaza_text_concat(const char *left, const char *right) {
    size_t left_length = strlen(left);
    size_t right_length = strlen(right);
    if (right_length > SIZE_MAX - left_length - 1) {
        fprintf(stderr, "yaza: Text is too large\n");
        exit(1);
    }
    char *joined = (char *)malloc(left_length + right_length + 1);
    if (joined == NULL) {
        uint64_t allocated = atomic_load_explicit(&yaza_text_concat_allocated_bytes, memory_order_relaxed);
        uint64_t count = atomic_load_explicit(&yaza_text_concat_allocation_count, memory_order_relaxed);
        fprintf(stderr, "yaza: out of memory joining Text values (left=%zu bytes, right=%zu bytes, prior allocations=%" PRIu64 " bytes across %" PRIu64 " joins, arena=%zu bytes)\n",
                left_length, right_length, allocated, count,
                yaza_program_memory_initialized ? yaza_program_memory_live_bytes() : 0);
        exit(1);
    }
    atomic_fetch_add_explicit(&yaza_text_concat_allocated_bytes, (uint64_t)(left_length + right_length + 1), memory_order_relaxed);
    atomic_fetch_add_explicit(&yaza_text_concat_allocation_count, 1, memory_order_relaxed);
    memcpy(joined, left, left_length);
    memcpy(joined + left_length, right, right_length + 1);
    return joined;
}

static char *yaza_path_join(const char *left, const char *right) {
    size_t left_length = strlen(left);
    if (left_length == 0) return yaza_copy_text(right);
    if (right[0] == '/') return yaza_copy_text(right);
    if (left[left_length - 1] == '/') return yaza_text_concat(left, right);
    return yaza_text_concat(yaza_text_concat(left, "/"), right);
}

static bool yaza_file_exists(const char *path) {
    return access(path, F_OK) == 0;
}

static bool yaza_path_entry_exists(const char *path) {
    struct stat details;
    return lstat(path, &details) == 0;
}

static bool yaza_is_directory(const char *path) {
    struct stat details;
    return stat(path, &details) == 0 && S_ISDIR(details.st_mode);
}

static int64_t yaza_file_remove(const char *path) {
    if (unlink(path) == 0) return 0;
    fprintf(stderr, "yaza: cannot remove '%s': %s\n", path, strerror(errno));
    return 1;
}

static void yaza_json_write_string(FILE *stream, const char *value);

static char *yaza_diagnostic_file_uri(const char *path) {
    if (path == NULL || path[0] == '\0') return NULL;
    char absolute_path[PATH_MAX];
    if (path[0] == '/') {
        size_t path_length = strlen(path);
        if (path_length >= sizeof(absolute_path)) return NULL;
        memcpy(absolute_path, path, path_length + 1);
    } else {
        char working_directory[PATH_MAX];
        if (getcwd(working_directory, sizeof(working_directory)) == NULL) return NULL;
        int written = snprintf(absolute_path, sizeof(absolute_path), "%s/%s", working_directory, path);
        if (written < 0 || (size_t)written >= sizeof(absolute_path)) return NULL;
    }

    size_t path_length = strlen(absolute_path);
    if (path_length > (SIZE_MAX - 8) / 3) return NULL;
    char *uri = (char *)malloc(8 + path_length * 3);
    if (uri == NULL) return NULL;
    static const char hex[] = "0123456789ABCDEF";
    memcpy(uri, "file://", 7);
    size_t output = 7;
    for (size_t index = 0; index < path_length; index++) {
        unsigned char value = (unsigned char)absolute_path[index];
        bool unreserved = (value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z') ||
                          (value >= '0' && value <= '9') || value == '-' || value == '.' ||
                          value == '_' || value == '~' || value == '/';
        if (unreserved) {
            uri[output++] = (char)value;
        } else {
            uri[output++] = '%';
            uri[output++] = hex[value >> 4];
            uri[output++] = hex[value & 0x0f];
        }
    }
    uri[output] = '\0';
    return uri;
}

static int64_t yaza_exit(int64_t status) {
    exit((int)status);
    return status;
}

static int64_t yaza_fail(const char *message) {
    const char *source_path = getenv("YAZA_INTERNAL_SOURCE_FILE");
    const char *source_line = getenv("YAZA_INTERNAL_SOURCE_LINE");
    const char *source_start_column = getenv("YAZA_INTERNAL_SOURCE_START_COLUMN");
    const char *source_end_column = getenv("YAZA_INTERNAL_SOURCE_END_COLUMN");
    const char *diagnostic_format = getenv("YAZA_DIAGNOSTICS_FORMAT");
    if (diagnostic_format != NULL && strcmp(diagnostic_format, "json") == 0) {
        char *line_end = NULL;
        errno = 0;
        long line_number = source_line == NULL ? 0 : strtol(source_line, &line_end, 10);
        bool has_location = source_path != NULL && source_path[0] != '\0' &&
                            source_line != NULL && line_end != source_line && *line_end == '\0' &&
                            errno == 0 && line_number > 0 && line_number <= INT32_MAX;
        char *start_column_end = NULL;
        errno = 0;
        long start_column = source_start_column == NULL ? -1 : strtol(source_start_column, &start_column_end, 10);
        bool start_column_valid = source_start_column != NULL && start_column_end != source_start_column &&
                                  *start_column_end == '\0' && errno == 0 && start_column >= 0 && start_column <= INT32_MAX;
        char *end_column_end = NULL;
        errno = 0;
        long end_column = source_end_column == NULL ? -1 : strtol(source_end_column, &end_column_end, 10);
        bool end_column_valid = source_end_column != NULL && end_column_end != source_end_column &&
                                *end_column_end == '\0' && errno == 0 && end_column >= 0 && end_column <= INT32_MAX;
        bool has_statement_range = has_location && start_column_valid && end_column_valid && end_column > start_column;
        char *uri = yaza_diagnostic_file_uri(source_path);
        const char *code = has_location ? "YZA1000" : "YZA0001";
        fprintf(stdout, "{\"schema\":\"yaza.diagnostics\",\"schema_version\":1,\"diagnostics\":[{\"code\":");
        yaza_json_write_string(stdout, code);
        fprintf(stdout, ",\"severity\":\"error\",\"uri\":");
        if (uri == NULL) fputs("null", stdout);
        else yaza_json_write_string(stdout, uri);
        fprintf(stdout, ",\"range\":");
        if (has_location) {
            long zero_based_line = line_number - 1;
            if (has_statement_range) {
                fprintf(stdout, "{\"start\":{\"line\":%ld,\"character\":%ld},\"end\":{\"line\":%ld,\"character\":%ld},\"precision\":\"statement\"}",
                        zero_based_line, start_column, zero_based_line, end_column);
            } else {
                fprintf(stdout, "{\"start\":{\"line\":%ld,\"character\":0},\"end\":{\"line\":%ld,\"character\":1},\"precision\":\"line\"}",
                        zero_based_line, zero_based_line);
            }
        } else {
            fputs("null", stdout);
        }
        fprintf(stdout, ",\"message\":");
        yaza_json_write_string(stdout, message == NULL ? "compiler failure" : message);
        fputs(",\"related\":[],\"notes\":[]}],\"summary\":{\"error_count\":1,\"warning_count\":0}}\n", stdout);
        fflush(stdout);
        free(uri);
        exit(1);
    }
    if (source_path != NULL && *source_path != '\0' && source_line != NULL && *source_line != '\0' &&
        strcmp(source_line, "0") != 0)
        fprintf(stderr, "%s:%s: error: %s\n", source_path, source_line, message);
    else
        fprintf(stderr, "yaza: %s\n", message);
    exit(1);
    return 1;
}

static int64_t yaza_directory_create(const char *path) {
    if (mkdir(path, 0755) == 0) return 0;
    if (errno == EEXIST) {
        struct stat details;
        if (stat(path, &details) == 0 && S_ISDIR(details.st_mode)) return 0;
    }
    fprintf(stderr, "yaza: cannot create directory '%s': %s\n", path, strerror(errno));
    return 1;
}

static char *yaza_temp_directory(void) {
    char path[] = "/tmp/yaza-run.XXXXXX";
    char *created = mkdtemp(path);
    if (created == NULL) {
        fprintf(stderr, "yaza: cannot create temporary directory: %s\n", strerror(errno));
        exit(1);
    }
    return yaza_copy_text(created);
}

static int64_t yaza_directory_remove(const char *path) {
    if (rmdir(path) == 0) return 0;
    fprintf(stderr, "yaza: cannot remove directory '%s': %s\n", path, strerror(errno));
    return 1;
}

#define YAZA_REMOVE_TREE_MAX_DEPTH 64U
#define YAZA_REMOVE_TREE_MAX_ENTRIES 100000U

static int64_t yaza_remove_tree_contents(int directory_fd, size_t depth, size_t *entries,
                                         dev_t root_device, const char *root_path) {
    int scan_fd = dup(directory_fd);
    if (scan_fd < 0) {
        fprintf(stderr, "yaza: cannot scan temporary directory '%s': %s\n", root_path, strerror(errno));
        return 1;
    }
    DIR *directory = fdopendir(scan_fd);
    if (directory == NULL) {
        int saved_error = errno;
        close(scan_fd);
        fprintf(stderr, "yaza: cannot scan temporary directory '%s': %s\n", root_path, strerror(saved_error));
        return 1;
    }
    int64_t result = 0;
    for (;;) {
        errno = 0;
        struct dirent *entry = readdir(directory);
        if (entry == NULL) {
            if (errno != 0) {
                fprintf(stderr, "yaza: cannot finish scanning temporary directory '%s': %s\n", root_path, strerror(errno));
                result = 1;
            }
            break;
        }
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
        *entries += 1;
        if (*entries > YAZA_REMOVE_TREE_MAX_ENTRIES) {
            fprintf(stderr, "yaza: refusing to clean more than %u entries in temporary directory '%s'\n",
                    YAZA_REMOVE_TREE_MAX_ENTRIES, root_path);
            result = 1;
            break;
        }
        struct stat details;
        if (fstatat(directory_fd, entry->d_name, &details, AT_SYMLINK_NOFOLLOW) != 0) {
            if (errno == ENOENT) continue;
            fprintf(stderr, "yaza: cannot inspect temporary entry in '%s': %s\n", root_path, strerror(errno));
            result = 1;
            break;
        }
        if (S_ISDIR(details.st_mode)) {
            if (depth >= YAZA_REMOVE_TREE_MAX_DEPTH || details.st_dev != root_device) {
                fprintf(stderr, "yaza: refusing excessive depth or filesystem crossing while cleaning '%s'\n", root_path);
                result = 1;
                break;
            }
            int child_fd = openat(directory_fd, entry->d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
            if (child_fd < 0) {
                fprintf(stderr, "yaza: cannot open temporary subdirectory in '%s': %s\n", root_path, strerror(errno));
                result = 1;
                break;
            }
            struct stat opened_details;
            if (fstat(child_fd, &opened_details) != 0 || opened_details.st_dev != details.st_dev ||
                opened_details.st_ino != details.st_ino || !S_ISDIR(opened_details.st_mode)) {
                fprintf(stderr, "yaza: temporary subdirectory changed during cleanup of '%s'\n", root_path);
                close(child_fd);
                result = 1;
                break;
            }
            result = yaza_remove_tree_contents(child_fd, depth + 1, entries, root_device, root_path);
            if (close(child_fd) != 0 && result == 0) {
                fprintf(stderr, "yaza: cannot close temporary subdirectory in '%s': %s\n", root_path, strerror(errno));
                result = 1;
            }
            if (result != 0) break;
            if (unlinkat(directory_fd, entry->d_name, AT_REMOVEDIR) != 0) {
                fprintf(stderr, "yaza: cannot remove temporary subdirectory in '%s': %s\n", root_path, strerror(errno));
                result = 1;
                break;
            }
        } else if (unlinkat(directory_fd, entry->d_name, 0) != 0) {
            fprintf(stderr, "yaza: cannot remove temporary entry in '%s': %s\n", root_path, strerror(errno));
            result = 1;
            break;
        }
    }
    if (closedir(directory) != 0 && result == 0) {
        fprintf(stderr, "yaza: cannot close temporary directory scan for '%s': %s\n", root_path, strerror(errno));
        result = 1;
    }
    return result;
}

static bool yaza_is_managed_test_temp_path(const char *path) {
    static const char prefix[] = "/tmp/yaza-run.";
    if (path == NULL || strlen(path) != sizeof(prefix) - 1 + 6 ||
        memcmp(path, prefix, sizeof(prefix) - 1) != 0) return false;
    const char *suffix = path + sizeof(prefix) - 1;
    for (size_t index = 0; index < 6; index++) {
        unsigned char value = (unsigned char)suffix[index];
        if (!((value >= '0' && value <= '9') || (value >= 'A' && value <= 'Z') ||
              (value >= 'a' && value <= 'z'))) return false;
    }
    return true;
}

static int64_t yaza_test_temp_directory_remove(const char *path) {
    if (path == NULL || path[0] == '\0') {
        fprintf(stderr, "yaza: temporary directory path must not be empty\n");
        return 1;
    }
    if (!yaza_is_managed_test_temp_path(path)) {
        fprintf(stderr, "yaza: refusing to recursively remove a directory outside YAZA's private test-temp path\n");
        return 1;
    }
    struct stat path_details;
    if (lstat(path, &path_details) != 0 || !S_ISDIR(path_details.st_mode) ||
        path_details.st_uid != geteuid() || (path_details.st_mode & 0777) != 0700) {
        fprintf(stderr, "yaza: refusing to remove a non-private or unowned test temporary directory '%s'\n", path);
        return 1;
    }
    int directory_fd = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
    if (directory_fd < 0) {
        fprintf(stderr, "yaza: cannot open temporary directory '%s' without following links: %s\n", path, strerror(errno));
        return 1;
    }
    struct stat details;
    int stat_status = fstat(directory_fd, &details);
    if (stat_status != 0 || !S_ISDIR(details.st_mode) || details.st_dev != path_details.st_dev ||
        details.st_ino != path_details.st_ino || details.st_uid != geteuid() ||
        (details.st_mode & 0777) != 0700) {
        int saved_error = stat_status != 0 ? errno : EPERM;
        close(directory_fd);
        fprintf(stderr, "yaza: test temporary directory changed or is not private '%s': %s\n", path, strerror(saved_error));
        return 1;
    }
    size_t entries = 0;
    int64_t result = yaza_remove_tree_contents(directory_fd, 0, &entries, details.st_dev, path);
    if (close(directory_fd) != 0 && result == 0) {
        fprintf(stderr, "yaza: cannot close temporary directory '%s': %s\n", path, strerror(errno));
        result = 1;
    }
    if (result != 0) return result;
    if (rmdir(path) != 0) {
        fprintf(stderr, "yaza: cannot remove temporary directory '%s': %s\n", path, strerror(errno));
        return 1;
    }
    return 0;
}

static yaza_text_list *yaza_directory_list(const char *path) {
    DIR *directory = opendir(path);
    if (directory == NULL) {
        fprintf(stderr, "yaza: cannot list directory '%s': %s\n", path, strerror(errno));
        exit(1);
    }
    yaza_text_list *entries = yaza_text_list_new();
    struct dirent *entry;
    while ((entry = readdir(directory)) != NULL) {
        if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
            yaza_list_push(entries, entry->d_name);
        }
    }
    closedir(directory);
    return entries;
}

static char *yaza_arg(int index) {
    if (index == 0) return yaza_argv == NULL ? "" : yaza_argv[-1];
    if (index < 1 || index > yaza_argc) {
        fprintf(stderr, "yaza: argument %d was not provided\n", index);
        exit(2);
    }
    return yaza_argv[index - 1];
}

static char *yaza_file_read(const char *path) {
    FILE *file = fopen(path, "rb");
    if (file == NULL) {
        if (getenv("YAZA_DIAGNOSTICS_FORMAT") != NULL && strcmp(getenv("YAZA_DIAGNOSTICS_FORMAT"), "json") == 0)
            yaza_fail("cannot read source file");
        fprintf(stderr, "yaza: cannot open '%s': %s\n", path, strerror(errno));
        exit(1);
    }
    if (fseek(file, 0, SEEK_END) != 0) {
        if (getenv("YAZA_DIAGNOSTICS_FORMAT") != NULL && strcmp(getenv("YAZA_DIAGNOSTICS_FORMAT"), "json") == 0)
            yaza_fail("cannot read source file");
        fprintf(stderr, "yaza: cannot seek '%s': %s\n", path, strerror(errno));
        fclose(file);
        exit(1);
    }
    long size = ftell(file);
    if (size < 0 || fseek(file, 0, SEEK_SET) != 0) {
        if (getenv("YAZA_DIAGNOSTICS_FORMAT") != NULL && strcmp(getenv("YAZA_DIAGNOSTICS_FORMAT"), "json") == 0)
            yaza_fail("cannot read source file");
        fprintf(stderr, "yaza: cannot measure '%s': %s\n", path, strerror(errno));
        fclose(file);
        exit(1);
    }
    char *data = (char *)malloc((size_t)size + 1);
    if (data == NULL) {
        fprintf(stderr, "yaza: out of memory reading '%s'\n", path);
        fclose(file);
        exit(1);
    }
    size_t read_count = fread(data, 1, (size_t)size, file);
    if (read_count != (size_t)size && ferror(file)) {
        if (getenv("YAZA_DIAGNOSTICS_FORMAT") != NULL && strcmp(getenv("YAZA_DIAGNOSTICS_FORMAT"), "json") == 0)
            yaza_fail("cannot read source file");
        fprintf(stderr, "yaza: cannot read '%s': %s\n", path, strerror(errno));
        free(data);
        fclose(file);
        exit(1);
    }
    if (memchr(data, '\0', read_count) != NULL) {
        if (getenv("YAZA_DIAGNOSTICS_FORMAT") != NULL && strcmp(getenv("YAZA_DIAGNOSTICS_FORMAT"), "json") == 0)
            yaza_fail("YAZA source files cannot contain a zero byte");
        fprintf(stderr, "yaza: Text files cannot contain a zero byte yet: '%s'\n", path);
        free(data);
        fclose(file);
        exit(1);
    }
    data[read_count] = '\0';
    fclose(file);
    return data;
}

static yaza_bytes yaza_file_read_bytes(const char *path) {
    FILE *file = fopen(path, "rb");
    if (file == NULL) {
        fprintf(stderr, "yaza: cannot open '%s': %s\n", path, strerror(errno));
        exit(1);
    }
    if (fseek(file, 0, SEEK_END) != 0) {
        fprintf(stderr, "yaza: cannot seek '%s': %s\n", path, strerror(errno));
        fclose(file);
        exit(1);
    }
    long measured = ftell(file);
    if (measured < 0 || (uint64_t)measured > YAZA_MAX_BYTES || fseek(file, 0, SEEK_SET) != 0) {
        fprintf(stderr, "yaza: file '%s' exceeds the 64 MiB Bytes limit or cannot be measured\n", path);
        fclose(file);
        exit(1);
    }
    size_t capacity = (size_t)measured;
    unsigned char *data = capacity == 0 ? NULL : (unsigned char *)malloc(capacity);
    if (capacity > 0 && data == NULL) {
        fprintf(stderr, "yaza: out of memory reading Bytes from '%s'\n", path);
        fclose(file);
        exit(1);
    }
    size_t length = capacity == 0 ? 0 : fread(data, 1, capacity, file);
    if (ferror(file)) {
        fprintf(stderr, "yaza: cannot read Bytes from '%s': %s\n", path, strerror(errno));
        free(data);
        fclose(file);
        exit(1);
    }
    if (fclose(file) != 0) {
        fprintf(stderr, "yaza: cannot close '%s' after reading Bytes\n", path);
        free(data);
        exit(1);
    }
    if (length != capacity) {
        unsigned char *resized = length == 0 ? NULL : (unsigned char *)realloc(data, length);
        if (length > 0 && resized == NULL) {
            free(data);
            fprintf(stderr, "yaza: out of memory finalizing Bytes read\n");
            exit(1);
        }
        if (length == 0) free(data);
        data = resized;
    }
    return (yaza_bytes){data, length};
}

static yaza_bytes yaza_file_read_bytes_range(const char *path, int64_t offset, int64_t length) {
    if (offset < 0 || length < 0 || (uint64_t)length > YAZA_MAX_BYTES) {
        fprintf(stderr, "yaza: invalid Bytes file range\n");
        exit(1);
    }
    off_t file_offset = (off_t)offset;
    if ((int64_t)file_offset != offset) {
        fprintf(stderr, "yaza: Bytes file offset is not supported on this target\n");
        exit(1);
    }
    FILE *file = fopen(path, "rb");
    if (file == NULL) {
        fprintf(stderr, "yaza: cannot open '%s': %s\n", path, strerror(errno));
        exit(1);
    }
    if (fseeko(file, file_offset, SEEK_SET) != 0) {
        fprintf(stderr, "yaza: cannot seek to Bytes range in '%s': %s\n", path, strerror(errno));
        fclose(file);
        exit(1);
    }
    size_t capacity = (size_t)length;
    unsigned char *data = capacity == 0 ? NULL : (unsigned char *)malloc(capacity);
    if (capacity > 0 && data == NULL) {
        fprintf(stderr, "yaza: out of memory reading Bytes range\n");
        fclose(file);
        exit(1);
    }
    size_t read_length = capacity == 0 ? 0 : fread(data, 1, capacity, file);
    if (ferror(file)) {
        fprintf(stderr, "yaza: cannot read Bytes range from '%s': %s\n", path, strerror(errno));
        free(data);
        fclose(file);
        exit(1);
    }
    if (fclose(file) != 0) {
        fprintf(stderr, "yaza: cannot close '%s' after reading Bytes range\n", path);
        free(data);
        exit(1);
    }
    if (read_length < capacity) {
        if (read_length == 0) { free(data); data = NULL; }
        else {
            unsigned char *resized = (unsigned char *)realloc(data, read_length);
            if (resized != NULL) data = resized;
        }
    }
    return (yaza_bytes){data, read_length};
}

#define YAZA_FS_ROOT_CAPACITY 64
#define YAZA_FS_ROOT_SLOT_BITS 7
#define YAZA_FS_ROOT_SLOT_MASK ((UINT64_C(1) << YAZA_FS_ROOT_SLOT_BITS) - 1)
#define YAZA_FS_RELATIVE_PATH_LIMIT 4096
#define YAZA_FS_COMPONENT_LIMIT 128
#define YAZA_FS_DIRECTORY_ENTRY_LIMIT 4096
#define YAZA_FS_DIRECTORY_BYTES_LIMIT (512U * 1024U)

typedef struct {
    int descriptor;
    uint64_t generation;
    bool retired;
} yaza_fs_root_slot;

static yaza_fs_root_slot yaza_fs_roots[YAZA_FS_ROOT_CAPACITY];
static atomic_flag yaza_fs_roots_guard = ATOMIC_FLAG_INIT;
static bool yaza_fs_roots_initialized = false;
static atomic_uint_fast64_t yaza_fs_temp_sequence = 1;

static void yaza_fs_roots_lock(void) {
    while (atomic_flag_test_and_set_explicit(&yaza_fs_roots_guard, memory_order_acquire)) { }
}

static void yaza_fs_roots_unlock(void) {
    atomic_flag_clear_explicit(&yaza_fs_roots_guard, memory_order_release);
}

static void yaza_fs_roots_initialize_locked(void) {
    if (yaza_fs_roots_initialized) return;
    for (size_t index = 0; index < YAZA_FS_ROOT_CAPACITY; index++) {
        yaza_fs_roots[index].descriptor = -1;
        yaza_fs_roots[index].generation = 1;
        yaza_fs_roots[index].retired = false;
    }
    yaza_fs_roots_initialized = true;
}

static yaza_result yaza_fs_capability_error(const char *message) {
    return yaza_result_err(yaza_option_some_text(yaza_copy_text(message)));
}

static int64_t yaza_fs_root_handle(size_t slot, uint64_t generation) {
    return (int64_t)((generation << YAZA_FS_ROOT_SLOT_BITS) | (uint64_t)(slot + 1));
}

static bool yaza_fs_bounded_cstring_length(const char *value, size_t maximum, size_t *length) {
    if (value == NULL || length == NULL) return false;
    for (size_t index = 0; index <= maximum; index++) {
        if (value[index] == '\0') {
            *length = index;
            return true;
        }
    }
    return false;
}

static int yaza_fs_root_acquire(int64_t handle) {
    if (handle <= 0) return -1;
    uint64_t raw = (uint64_t)handle;
    uint64_t slot_value = raw & YAZA_FS_ROOT_SLOT_MASK;
    uint64_t generation = raw >> YAZA_FS_ROOT_SLOT_BITS;
    if (slot_value == 0 || slot_value > YAZA_FS_ROOT_CAPACITY || generation == 0) return -1;

    yaza_fs_roots_lock();
    yaza_fs_roots_initialize_locked();
    size_t slot = (size_t)(slot_value - 1);
    int duplicate = -1;
    if (!yaza_fs_roots[slot].retired && yaza_fs_roots[slot].descriptor >= 0 &&
        yaza_fs_roots[slot].generation == generation) {
        duplicate = dup(yaza_fs_roots[slot].descriptor);
        if (duplicate >= 0 && fcntl(duplicate, F_SETFD, FD_CLOEXEC) != 0) {
            close(duplicate);
            duplicate = -1;
        }
    }
    yaza_fs_roots_unlock();
    return duplicate;
}

static yaza_result yaza_fs_root_open(const char *path) {
    size_t path_length = 0;
    if (!yaza_fs_bounded_cstring_length(path, YAZA_FS_RELATIVE_PATH_LIMIT, &path_length) ||
        path_length == 0 || !yaza_utf8_valid((const unsigned char *)path, path_length))
        return yaza_fs_capability_error("filesystem root path is invalid or too long");

    int descriptor = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
    if (descriptor < 0) return yaza_fs_capability_error("filesystem root could not be opened as a directory");
    struct stat details;
    if (fstat(descriptor, &details) != 0 || !S_ISDIR(details.st_mode)) {
        close(descriptor);
        return yaza_fs_capability_error("filesystem root is not a directory");
    }

    yaza_fs_roots_lock();
    yaza_fs_roots_initialize_locked();
    size_t slot = YAZA_FS_ROOT_CAPACITY;
    for (size_t index = 0; index < YAZA_FS_ROOT_CAPACITY; index++) {
        if (!yaza_fs_roots[index].retired && yaza_fs_roots[index].descriptor < 0) {
            slot = index;
            break;
        }
    }
    if (slot == YAZA_FS_ROOT_CAPACITY) {
        yaza_fs_roots_unlock();
        close(descriptor);
        return yaza_fs_capability_error("filesystem root handle limit reached");
    }
    uint64_t generation = yaza_fs_roots[slot].generation;
    if (generation == 0 || generation > (uint64_t)(INT64_MAX >> YAZA_FS_ROOT_SLOT_BITS)) {
        yaza_fs_roots[slot].retired = true;
        yaza_fs_roots_unlock();
        close(descriptor);
        return yaza_fs_capability_error("filesystem root handle generation exhausted");
    }
    yaza_fs_roots[slot].descriptor = descriptor;
    int64_t handle = yaza_fs_root_handle(slot, generation);
    yaza_fs_roots_unlock();
    return yaza_result_ok(yaza_option_some_number(handle));
}

static yaza_result yaza_fs_root_close(int64_t handle) {
    if (handle <= 0) return yaza_fs_capability_error("filesystem root handle is invalid or closed");
    uint64_t raw = (uint64_t)handle;
    uint64_t slot_value = raw & YAZA_FS_ROOT_SLOT_MASK;
    uint64_t generation = raw >> YAZA_FS_ROOT_SLOT_BITS;
    if (slot_value == 0 || slot_value > YAZA_FS_ROOT_CAPACITY || generation == 0)
        return yaza_fs_capability_error("filesystem root handle is invalid or closed");

    yaza_fs_roots_lock();
    yaza_fs_roots_initialize_locked();
    size_t slot = (size_t)(slot_value - 1);
    if (yaza_fs_roots[slot].retired || yaza_fs_roots[slot].descriptor < 0 ||
        yaza_fs_roots[slot].generation != generation) {
        yaza_fs_roots_unlock();
        return yaza_fs_capability_error("filesystem root handle is invalid or closed");
    }
    int descriptor = yaza_fs_roots[slot].descriptor;
    yaza_fs_roots[slot].descriptor = -1;
    uint64_t maximum_generation = (uint64_t)(INT64_MAX >> YAZA_FS_ROOT_SLOT_BITS);
    if (yaza_fs_roots[slot].generation >= maximum_generation) {
        yaza_fs_roots[slot].retired = true;
    } else {
        yaza_fs_roots[slot].generation++;
    }
    yaza_fs_roots_unlock();
    if (close(descriptor) != 0) return yaza_fs_capability_error("filesystem root descriptor could not be closed");
    return yaza_result_ok(yaza_option_some_boolean(true));
}

static void yaza_fs_roots_shutdown(void) {
    yaza_fs_roots_lock();
    yaza_fs_roots_initialize_locked();
    for (size_t index = 0; index < YAZA_FS_ROOT_CAPACITY; index++) {
        int descriptor = yaza_fs_roots[index].descriptor;
        yaza_fs_roots[index].descriptor = -1;
        if (descriptor >= 0) close(descriptor);
        uint64_t maximum_generation = (uint64_t)(INT64_MAX >> YAZA_FS_ROOT_SLOT_BITS);
        if (yaza_fs_roots[index].generation >= maximum_generation) {
            yaza_fs_roots[index].retired = true;
        } else {
            yaza_fs_roots[index].generation++;
        }
    }
    yaza_fs_roots_unlock();
}

/* Consumes root_fd and returns an opened parent directory or -1. */
static int yaza_fs_open_parent(int root_fd, const char *relative_path,
                               char leaf[NAME_MAX + 1]) {
    if (root_fd < 0 || relative_path == NULL) {
        if (root_fd >= 0) close(root_fd);
        return -1;
    }
    size_t path_length = 0;
    if (!yaza_fs_bounded_cstring_length(relative_path, YAZA_FS_RELATIVE_PATH_LIMIT, &path_length) ||
        path_length == 0 ||
        relative_path[0] == '/' || relative_path[path_length - 1] == '/' ||
        !yaza_utf8_valid((const unsigned char *)relative_path, path_length)) {
        close(root_fd);
        return -1;
    }
    for (size_t index = 0; index < path_length; index++) {
        unsigned char byte = (unsigned char)relative_path[index];
        if (byte < 0x20 || byte == 0x7f || byte == '\\') {
            close(root_fd);
            return -1;
        }
    }

    char path_copy[YAZA_FS_RELATIVE_PATH_LIMIT + 1];
    memcpy(path_copy, relative_path, path_length + 1);
    size_t component_count = 0;
    size_t start = 0;
    int current = root_fd;
    for (;;) {
        size_t end = start;
        while (end < path_length && path_copy[end] != '/') end++;
        size_t component_length = end - start;
        component_count++;
        if (component_length == 0 || component_length > NAME_MAX || component_count > YAZA_FS_COMPONENT_LIMIT ||
            (component_length == 1 && path_copy[start] == '.') ||
            (component_length == 2 && path_copy[start] == '.' && path_copy[start + 1] == '.')) {
            close(current);
            return -1;
        }
        if (end == path_length) {
            memcpy(leaf, path_copy + start, component_length);
            leaf[component_length] = '\0';
            return current;
        }
        char component[NAME_MAX + 1];
        memcpy(component, path_copy + start, component_length);
        component[component_length] = '\0';
        int next = openat(current, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
        int saved_error = errno;
        close(current);
        if (next < 0) {
            errno = saved_error;
            return -1;
        }
        current = next;
        start = end + 1;
    }
}

static yaza_result yaza_fs_root_create_directory(int64_t handle, const char *relative_path) {
    int current = yaza_fs_root_acquire(handle);
    if (current < 0)
        return yaza_fs_capability_error("filesystem root handle is invalid or closed");

    size_t path_length = 0;
    if (!yaza_fs_bounded_cstring_length(relative_path, YAZA_FS_RELATIVE_PATH_LIMIT, &path_length) ||
        path_length == 0 || relative_path[0] == '/' || relative_path[path_length - 1] == '/' ||
        !yaza_utf8_valid((const unsigned char *)relative_path, path_length)) {
        close(current);
        return yaza_fs_capability_error("filesystem directory path is invalid or too long");
    }
    for (size_t index = 0; index < path_length; index++) {
        unsigned char byte = (unsigned char)relative_path[index];
        if (byte < 0x20 || byte == 0x7f || byte == '\\') {
            close(current);
            return yaza_fs_capability_error("filesystem directory path contains a forbidden byte");
        }
    }

    char path_copy[YAZA_FS_RELATIVE_PATH_LIMIT + 1];
    memcpy(path_copy, relative_path, path_length + 1);
    size_t component_count = 0;
    size_t start = 0;
    for (;;) {
        size_t end = start;
        while (end < path_length && path_copy[end] != '/') end++;
        size_t component_length = end - start;
        component_count++;
        if (component_length == 0 || component_length > NAME_MAX ||
            component_count > YAZA_FS_COMPONENT_LIMIT ||
            (component_length == 1 && path_copy[start] == '.') ||
            (component_length == 2 && path_copy[start] == '.' && path_copy[start + 1] == '.')) {
            close(current);
            return yaza_fs_capability_error("filesystem directory path has an invalid component");
        }
        if (end == path_length) break;
        start = end + 1;
    }

    start = 0;
    for (;;) {
        size_t end = start;
        while (end < path_length && path_copy[end] != '/') end++;
        size_t component_length = end - start;

        char component[NAME_MAX + 1];
        memcpy(component, path_copy + start, component_length);
        component[component_length] = '\0';
        if (mkdirat(current, component, S_IRWXU) != 0 && errno != EEXIST) {
            close(current);
            return yaza_fs_capability_error("filesystem directory could not be created within the root");
        }

        int next = openat(current, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
        if (next < 0) {
            close(current);
            return yaza_fs_capability_error("filesystem directory path is invalid or traverses a link");
        }
        struct stat details;
        if (fstat(next, &details) != 0 || !S_ISDIR(details.st_mode)) {
            close(next);
            close(current);
            return yaza_fs_capability_error("filesystem path component is not a directory");
        }
        if (close(current) != 0) {
            close(next);
            return yaza_fs_capability_error("filesystem directory traversal failed");
        }
        current = next;
        if (end == path_length) break;
        start = end + 1;
    }

    if (close(current) != 0)
        return yaza_fs_capability_error("filesystem directory descriptor could not be closed");
    return yaza_result_ok(yaza_option_some_boolean(true));
}

static int yaza_fs_root_open_directory(int64_t handle, const char *relative_path) {
    int root_fd = yaza_fs_root_acquire(handle);
    if (root_fd < 0) return -1;
    size_t path_length = 0;
    if (!yaza_fs_bounded_cstring_length(relative_path, YAZA_FS_RELATIVE_PATH_LIMIT, &path_length)) {
        close(root_fd);
        return -1;
    }
    if (path_length == 0) return root_fd;

    char leaf[NAME_MAX + 1];
    int parent_fd = yaza_fs_open_parent(root_fd, relative_path, leaf);
    if (parent_fd < 0) return -1;
    int directory_fd = openat(parent_fd, leaf, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
    close(parent_fd);
    if (directory_fd < 0) return -1;
    struct stat details;
    if (fstat(directory_fd, &details) != 0 || !S_ISDIR(details.st_mode)) {
        close(directory_fd);
        return -1;
    }
    return directory_fd;
}

static void yaza_fs_text_list_free(yaza_text_list *list) {
    if (list == NULL) return;
    for (size_t index = 0; index < list->length; index++) free(list->items[index]);
    free(list->items);
    free(list);
}

static bool yaza_fs_text_list_push_owned(yaza_text_list *list, char *text) {
    if (list == NULL || text == NULL || list->length >= YAZA_FS_DIRECTORY_ENTRY_LIMIT) return false;
    if (list->length == list->capacity) {
        size_t capacity = list->capacity == 0 ? 8 : list->capacity * 2;
        if (capacity > YAZA_FS_DIRECTORY_ENTRY_LIMIT) capacity = YAZA_FS_DIRECTORY_ENTRY_LIMIT;
        if (capacity <= list->length || capacity > SIZE_MAX / sizeof(*list->items)) return false;
        char **items = (char **)realloc(list->items, capacity * sizeof(*items));
        if (items == NULL) return false;
        list->items = items;
        list->capacity = capacity;
    }
    list->items[list->length++] = text;
    return true;
}

static bool yaza_fs_text_list_push_text(yaza_text_list *list, const char *text) {
    if (text == NULL) return false;
    size_t length = strlen(text);
    char *copy = (char *)malloc(length + 1);
    if (copy == NULL) return false;
    memcpy(copy, text, length + 1);
    if (!yaza_fs_text_list_push_owned(list, copy)) {
        free(copy);
        return false;
    }
    return true;
}

static bool yaza_fs_text_list_push_number(yaza_text_list *list, int64_t value) {
    char text[32];
    int length = snprintf(text, sizeof(text), "%" PRId64, value);
    if (length < 0 || (size_t)length >= sizeof(text)) return false;
    char *copy = (char *)malloc((size_t)length + 1);
    if (copy == NULL) return false;
    memcpy(copy, text, (size_t)length + 1);
    if (!yaza_fs_text_list_push_owned(list, copy)) {
        free(copy);
        return false;
    }
    return true;
}

static int yaza_fs_directory_name_compare(const void *left, const void *right) {
    const char *const *left_name = (const char *const *)left;
    const char *const *right_name = (const char *const *)right;
    return strcmp(*left_name, *right_name);
}

static yaza_result yaza_fs_root_list_directory(int64_t handle, const char *relative_path) {
    int directory_fd = yaza_fs_root_open_directory(handle, relative_path);
    if (directory_fd < 0)
        return yaza_fs_capability_error("filesystem directory path is invalid or traverses a link");
    DIR *directory = fdopendir(directory_fd);
    if (directory == NULL) {
        close(directory_fd);
        return yaza_fs_capability_error("filesystem directory could not be listed");
    }
    yaza_text_list *entries = (yaza_text_list *)calloc(1, sizeof(*entries));
    if (entries == NULL) {
        closedir(directory);
        return yaza_fs_capability_error("filesystem directory listing could not allocate its bounded result");
    }

    size_t total_name_bytes = 0;
    bool failed = false;
    for (;;) {
        errno = 0;
        struct dirent *entry = readdir(directory);
        if (entry == NULL) {
            if (errno != 0) failed = true;
            break;
        }
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;

        size_t name_length = 0;
        if (!yaza_fs_bounded_cstring_length(entry->d_name, NAME_MAX, &name_length) ||
            name_length == 0 || !yaza_utf8_valid((const unsigned char *)entry->d_name, name_length)) {
            failed = true;
            break;
        }
        for (size_t index = 0; index < name_length; index++) {
            unsigned char byte = (unsigned char)entry->d_name[index];
            if (byte < 0x20 || byte == 0x7f || byte == '\\') failed = true;
        }
        if (failed || entries->length >= YAZA_FS_DIRECTORY_ENTRY_LIMIT ||
            name_length > YAZA_FS_DIRECTORY_BYTES_LIMIT - total_name_bytes) {
            failed = true;
            break;
        }

        char *copy = (char *)malloc(name_length + 1);
        if (copy == NULL) {
            failed = true;
            break;
        }
        memcpy(copy, entry->d_name, name_length);
        copy[name_length] = '\0';
        if (!yaza_fs_text_list_push_owned(entries, copy)) {
            free(copy);
            failed = true;
            break;
        }
        total_name_bytes += name_length;
    }

    int close_status = closedir(directory);
    if (failed || close_status != 0) {
        yaza_fs_text_list_free(entries);
        return yaza_fs_capability_error("filesystem directory listing failed or exceeded its configured limit");
    }
    if (entries->length > 1)
        qsort(entries->items, entries->length, sizeof(entries->items[0]), yaza_fs_directory_name_compare);
    return yaza_result_ok(yaza_option_some_text_list(entries));
}

/* The public YAZA wrapper converts this fixed record into FsMetadata. Values
   are kind, size_bytes, permissions (mode & 0777), mtime seconds, mtime ns. */
static yaza_result yaza_fs_root_metadata(int64_t handle, const char *relative_path) {
    if (relative_path == NULL)
        return yaza_fs_capability_error("filesystem metadata path is invalid");
    int root_fd = yaza_fs_root_acquire(handle);
    if (root_fd < 0)
        return yaza_fs_capability_error("filesystem root handle is invalid or closed");

    size_t path_length = 0;
    if (!yaza_fs_bounded_cstring_length(relative_path, YAZA_FS_RELATIVE_PATH_LIMIT, &path_length)) {
        close(root_fd);
        return yaza_fs_capability_error("filesystem metadata path is invalid or too long");
    }

    struct stat details;
    int stat_status = -1;
    if (path_length == 0) {
        stat_status = fstat(root_fd, &details);
        int saved_error = errno;
        int close_status = close(root_fd);
        if (stat_status != 0 || close_status != 0) {
            errno = saved_error;
            return yaza_fs_capability_error("filesystem metadata could not be read");
        }
    } else {
        char leaf[NAME_MAX + 1];
        int parent_fd = yaza_fs_open_parent(root_fd, relative_path, leaf);
        if (parent_fd < 0)
            return yaza_fs_capability_error("filesystem metadata path is invalid or traverses a link");
        stat_status = fstatat(parent_fd, leaf, &details, AT_SYMLINK_NOFOLLOW);
        int saved_error = errno;
        int close_status = close(parent_fd);
        if (stat_status != 0 || close_status != 0) {
            errno = saved_error;
            return yaza_fs_capability_error("filesystem metadata could not be read");
        }
    }

    if ((!S_ISREG(details.st_mode) && !S_ISDIR(details.st_mode)) || details.st_size < 0 ||
        (uintmax_t)details.st_size > (uintmax_t)INT64_MAX)
        return yaza_fs_capability_error("filesystem metadata supports regular files and directories only");
#if defined(__APPLE__)
    int64_t modified_seconds = (int64_t)details.st_mtimespec.tv_sec;
    long modified_nanoseconds = details.st_mtimespec.tv_nsec;
#else
    int64_t modified_seconds = (int64_t)details.st_mtim.tv_sec;
    long modified_nanoseconds = details.st_mtim.tv_nsec;
#endif
    if (modified_nanoseconds < 0 || modified_nanoseconds >= 1000000000L)
        return yaza_fs_capability_error("filesystem modification timestamp is outside the supported range");

    yaza_text_list *fields = (yaza_text_list *)calloc(1, sizeof(*fields));
    if (fields == NULL)
        return yaza_fs_capability_error("filesystem metadata result could not be allocated");
    bool complete = yaza_fs_text_list_push_text(fields, S_ISREG(details.st_mode) ? "file" : "directory") &&
                    yaza_fs_text_list_push_number(fields, S_ISREG(details.st_mode) ? (int64_t)details.st_size : 0) &&
                    yaza_fs_text_list_push_number(fields, (int64_t)(details.st_mode & 0777)) &&
                    yaza_fs_text_list_push_number(fields, modified_seconds) &&
                    yaza_fs_text_list_push_number(fields, (int64_t)modified_nanoseconds);
    if (!complete) {
        yaza_fs_text_list_free(fields);
        return yaza_fs_capability_error("filesystem metadata result could not be allocated");
    }
    return yaza_result_ok(yaza_option_some_text_list(fields));
}

static yaza_result yaza_fs_root_read_bytes(int64_t handle, const char *relative_path,
                                           int64_t maximum_bytes) {
    if (maximum_bytes < 0 || (uint64_t)maximum_bytes > YAZA_MAX_BYTES)
        return yaza_fs_capability_error("filesystem read limit must be between 0 and 64 MiB");
    int root_fd = yaza_fs_root_acquire(handle);
    if (root_fd < 0) return yaza_fs_capability_error("filesystem root handle is invalid or closed");
    char leaf[NAME_MAX + 1];
    int parent_fd = yaza_fs_open_parent(root_fd, relative_path, leaf);
    if (parent_fd < 0) return yaza_fs_capability_error("filesystem path is invalid or cannot be resolved within the root");

    int descriptor = openat(parent_fd, leaf, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);
    int open_error = errno;
    close(parent_fd);
    if (descriptor < 0) {
        errno = open_error;
        return yaza_fs_capability_error("filesystem file could not be opened without following links");
    }
    struct stat details;
    if (fstat(descriptor, &details) != 0 || !S_ISREG(details.st_mode) || details.st_size < 0 ||
        (uint64_t)details.st_size > (uint64_t)maximum_bytes) {
        close(descriptor);
        return yaza_fs_capability_error("filesystem entry is not a regular file within the requested byte limit");
    }

    size_t capacity = (size_t)maximum_bytes;
    unsigned char *buffer = capacity == 0 ? NULL : (unsigned char *)malloc(capacity);
    if (capacity > 0 && buffer == NULL) {
        close(descriptor);
        return yaza_fs_capability_error("filesystem read could not allocate its bounded buffer");
    }
    size_t used = 0;
    bool failed = false;
    while (used < capacity) {
        ssize_t count = read(descriptor, buffer + used, capacity - used);
        if (count < 0 && errno == EINTR) continue;
        if (count < 0) failed = true;
        if (count <= 0) break;
        used += (size_t)count;
    }
    if (!failed && used == capacity) {
        unsigned char extra;
        ssize_t count;
        do { count = read(descriptor, &extra, 1); } while (count < 0 && errno == EINTR);
        if (count < 0) failed = true;
        else if (count > 0) failed = true;
    }
    int close_status = close(descriptor);
    if (failed || close_status != 0) {
        free(buffer);
        return yaza_fs_capability_error("filesystem read failed or exceeded its byte limit");
    }
    if (used == 0) {
        free(buffer);
        buffer = NULL;
    } else if (used < capacity) {
        unsigned char *resized = (unsigned char *)realloc(buffer, used);
        if (resized != NULL) buffer = resized;
    }
    return yaza_result_ok(yaza_option_some_bytes((yaza_bytes){buffer, used}));
}

static yaza_result yaza_fs_root_replace_bytes(int64_t handle, const char *relative_path,
                                              yaza_bytes data) {
    if (data.length > YAZA_MAX_BYTES || (data.length > 0 && data.data == NULL))
        return yaza_fs_capability_error("filesystem write exceeds the 64 MiB byte limit");
    int root_fd = yaza_fs_root_acquire(handle);
    if (root_fd < 0) return yaza_fs_capability_error("filesystem root handle is invalid or closed");
    char leaf[NAME_MAX + 1];
    int parent_fd = yaza_fs_open_parent(root_fd, relative_path, leaf);
    if (parent_fd < 0) return yaza_fs_capability_error("filesystem path is invalid or cannot be resolved within the root");

    char temporary[128];
    int descriptor = -1;
    bool temporary_created = false;
    for (unsigned int attempt = 0; attempt < 32; attempt++) {
        uint64_t sequence = atomic_fetch_add_explicit(&yaza_fs_temp_sequence, 1, memory_order_relaxed);
        int written = snprintf(temporary, sizeof(temporary), ".yaza-write-%" PRId64 "-%" PRIu64 "-%u",
                              (int64_t)getpid(), sequence, attempt);
        if (written < 0 || (size_t)written >= sizeof(temporary)) break;
        descriptor = openat(parent_fd, temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
                            S_IRUSR | S_IWUSR);
        if (descriptor >= 0) {
            temporary_created = true;
            break;
        }
        if (errno != EEXIST) break;
    }
    if (descriptor < 0) {
        close(parent_fd);
        return yaza_fs_capability_error("filesystem could not create a private replacement file");
    }

    size_t offset = 0;
    bool failed = false;
    while (offset < data.length) {
        ssize_t count = write(descriptor, data.data + offset, data.length - offset);
        if (count < 0 && errno == EINTR) continue;
        if (count <= 0) {
            failed = true;
            break;
        }
        offset += (size_t)count;
    }
    if (!failed && fsync(descriptor) != 0) failed = true;
    if (close(descriptor) != 0) failed = true;
    if (!failed && renameat(parent_fd, temporary, parent_fd, leaf) != 0) failed = true;
    if (failed && temporary_created) unlinkat(parent_fd, temporary, 0);
    close(parent_fd);
    if (failed) return yaza_fs_capability_error("filesystem atomic replacement failed");
    return yaza_result_ok(yaza_option_some_boolean(true));
}

static int64_t yaza_file_write(const char *path, const char *data) {
    FILE *file = fopen(path, "wb");
    if (file == NULL) {
        fprintf(stderr, "yaza: cannot write '%s': %s\n", path, strerror(errno));
        return 1;
    }
    size_t length = strlen(data);
    size_t written = fwrite(data, 1, length, file);
    int close_failed = fclose(file) != 0;
    int failed = written != length || close_failed;
    if (failed) {
        fprintf(stderr, "yaza: failed writing '%s'\n", path);
        return 1;
    }
    return 0;
}

static int64_t yaza_file_write_atomic(const char *path, const char *data) {
    if (path == NULL || path[0] == '\0' || data == NULL) {
        fprintf(stderr, "yaza: atomic write requires a non-empty path and Text value\n");
        return 1;
    }
    const char *slash = strrchr(path, '/');
    const char *suffix = ".yaza-atomic-XXXXXX";
    size_t directory_length = 0;
    if (slash != NULL) directory_length = slash == path ? 1 : (size_t)(slash - path);
    size_t suffix_length = strlen(suffix);
    if (directory_length > SIZE_MAX - suffix_length - 2) {
        fprintf(stderr, "yaza: atomic-write path is too large\n");
        return 1;
    }
    size_t template_length = directory_length + suffix_length + (directory_length == 0 ? 1 : 2);
    char *temporary_path = (char *)malloc(template_length);
    if (temporary_path == NULL) {
        fprintf(stderr, "yaza: out of memory preparing atomic write\n");
        return 1;
    }
    size_t cursor = 0;
    if (directory_length > 0) {
        memcpy(temporary_path, path, directory_length);
        cursor = directory_length;
        if (temporary_path[cursor - 1] != '/') temporary_path[cursor++] = '/';
    }
    memcpy(temporary_path + cursor, suffix, suffix_length + 1);

    struct stat existing;
    mode_t replacement_mode = 0600;
    if (lstat(path, &existing) == 0 && S_ISREG(existing.st_mode))
        replacement_mode = existing.st_mode & 0777;

    int descriptor = mkstemp(temporary_path);
    if (descriptor < 0) {
        fprintf(stderr, "yaza: cannot create atomic-write temporary file for '%s': %s\n", path, strerror(errno));
        free(temporary_path);
        return 1;
    }

    size_t length = strlen(data);
    size_t offset = 0;
    int failed = 0;
    while (offset < length) {
        ssize_t written = write(descriptor, data + offset, length - offset);
        if (written < 0 && errno == EINTR) continue;
        if (written <= 0) {
            failed = 1;
            break;
        }
        offset += (size_t)written;
    }
    if (!failed && fchmod(descriptor, replacement_mode) != 0) failed = 1;
    if (!failed && fsync(descriptor) != 0) failed = 1;
    int saved_error = errno;
    if (close(descriptor) != 0 && !failed) {
        failed = 1;
        saved_error = errno;
    }
    if (!failed && rename(temporary_path, path) != 0) {
        failed = 1;
        saved_error = errno;
    }
    if (failed) {
        unlink(temporary_path);
        fprintf(stderr, "yaza: atomic write failed for '%s': %s\n", path, strerror(saved_error));
        free(temporary_path);
        return 1;
    }
    free(temporary_path);
    return 0;
}

static int64_t yaza_file_append(const char *path, const char *data) {
    FILE *file = fopen(path, "ab");
    if (file == NULL) {
        fprintf(stderr, "yaza: cannot append '%s': %s\n", path, strerror(errno));
        return 1;
    }
    size_t length = strlen(data);
    size_t written = fwrite(data, 1, length, file);
    int close_failed = fclose(file) != 0;
    if (written != length || close_failed) {
        fprintf(stderr, "yaza: failed appending '%s'\n", path);
        return 1;
    }
    return 0;
}

static int64_t yaza_file_write_bytes(const char *path, yaza_bytes data) {
    FILE *file = fopen(path, "wb");
    if (file == NULL) {
        fprintf(stderr, "yaza: cannot write Bytes to '%s': %s\n", path, strerror(errno));
        return 1;
    }
    size_t written = data.length == 0 ? 0 : fwrite(data.data, 1, data.length, file);
    int close_failed = fclose(file) != 0;
    if (written != data.length || close_failed) {
        fprintf(stderr, "yaza: failed writing Bytes to '%s'\n", path);
        return 1;
    }
    return 0;
}

static int64_t yaza_file_append_bytes(const char *path, yaza_bytes data) {
    FILE *file = fopen(path, "ab");
    if (file == NULL) {
        fprintf(stderr, "yaza: cannot append Bytes to '%s': %s\n", path, strerror(errno));
        return 1;
    }
    size_t written = data.length == 0 ? 0 : fwrite(data.data, 1, data.length, file);
    int close_failed = fclose(file) != 0;
    if (written != data.length || close_failed) {
        fprintf(stderr, "yaza: failed appending Bytes to '%s'\n", path);
        return 1;
    }
    return 0;
}

static char *yaza_stdin_read(void) {
    const size_t maximum = 1024 * 1024;
    size_t capacity = 4096;
    size_t length = 0;
    char *buffer = (char *)malloc(capacity + 1);
    if (buffer == NULL) {
        fprintf(stderr, "yaza: out of memory reading stdin\n");
        exit(1);
    }
    for (;;) {
        if (length == capacity) {
            if (capacity == maximum) {
                char extra;
                ssize_t amount;
                do {
                    amount = read(STDIN_FILENO, &extra, 1);
                } while (amount < 0 && errno == EINTR);
                if (amount == 0) break;
                if (amount < 0) {
                    fprintf(stderr, "yaza: could not finish reading stdin: %s\n", strerror(errno));
                    free(buffer);
                    exit(1);
                }
                fprintf(stderr, "yaza: stdin exceeds the 1 MiB Text limit\n");
                free(buffer);
                exit(1);
            }
            size_t next_capacity = capacity > maximum / 2 ? maximum : capacity * 2;
            char *grown = (char *)realloc(buffer, next_capacity + 1);
            if (grown == NULL) {
                fprintf(stderr, "yaza: out of memory growing stdin buffer\n");
                free(buffer);
                exit(1);
            }
            buffer = grown;
            capacity = next_capacity;
        }
        ssize_t amount = read(STDIN_FILENO, buffer + length, capacity - length);
        if (amount < 0 && errno == EINTR) continue;
        if (amount < 0) {
            fprintf(stderr, "yaza: could not read stdin: %s\n", strerror(errno));
            free(buffer);
            exit(1);
        }
        if (amount == 0) break;
        if (memchr(buffer + length, '\0', (size_t)amount) != NULL) {
            fprintf(stderr, "yaza: stdin contains binary NUL bytes; Text cannot represent binary data\n");
            free(buffer);
            exit(1);
        }
        length += (size_t)amount;
    }
    buffer[length] = '\0';
    return buffer;
}

static yaza_bytes yaza_stdin_read_bytes(void) {
    const size_t maximum = 1024 * 1024;
    size_t capacity = 4096, length = 0;
    unsigned char *buffer = (unsigned char *)malloc(capacity);
    if (buffer == NULL) {
        fprintf(stderr, "yaza: out of memory reading stdin Bytes\n");
        exit(1);
    }
    for (;;) {
        if (length == capacity) {
            if (capacity == maximum) {
                unsigned char extra;
                ssize_t amount;
                do { amount = read(STDIN_FILENO, &extra, 1); } while (amount < 0 && errno == EINTR);
                if (amount == 0) break;
                if (amount < 0) {
                    fprintf(stderr, "yaza: could not finish reading stdin Bytes: %s\n", strerror(errno));
                    free(buffer);
                    exit(1);
                }
                fprintf(stderr, "yaza: stdin exceeds the 1 MiB Bytes limit\n");
                free(buffer);
                exit(1);
            }
            size_t next_capacity = capacity > maximum / 2 ? maximum : capacity * 2;
            unsigned char *grown = (unsigned char *)realloc(buffer, next_capacity);
            if (grown == NULL) {
                fprintf(stderr, "yaza: out of memory growing stdin Bytes buffer\n");
                free(buffer);
                exit(1);
            }
            buffer = grown;
            capacity = next_capacity;
        }
        ssize_t amount = read(STDIN_FILENO, buffer + length, capacity - length);
        if (amount < 0 && errno == EINTR) continue;
        if (amount < 0) {
            fprintf(stderr, "yaza: could not read stdin Bytes: %s\n", strerror(errno));
            free(buffer);
            exit(1);
        }
        if (amount == 0) break;
        length += (size_t)amount;
    }
    if (length == 0) { free(buffer); buffer = NULL; }
    else {
        unsigned char *resized = (unsigned char *)realloc(buffer, length);
        if (resized != NULL) buffer = resized;
    }
    return (yaza_bytes){buffer, length};
}

static int64_t yaza_process(char *arguments[]) {
    /* Preserve parent output order before the child inherits the same streams. */
    if (fflush(NULL) != 0) {
        fprintf(stderr, "yaza: could not flush output before starting a process: %s\n", strerror(errno));
        return 126;
    }
    pid_t child = fork();
    if (child < 0) {
        fprintf(stderr, "yaza: could not start process: %s\n", strerror(errno));
        return 126;
    }
    if (child == 0) {
        execvp(arguments[0], arguments);
        fprintf(stderr, "yaza: could not execute '%s': %s\n", arguments[0], strerror(errno));
        _exit(errno == ENOENT ? 127 : 126);
    }
    int status = 0;
    while (waitpid(child, &status, 0) < 0) {
        if (errno != EINTR) {
            fprintf(stderr, "yaza: could not wait for process: %s\n", strerror(errno));
            return 126;
        }
    }
    if (WIFEXITED(status)) return WEXITSTATUS(status);
    if (WIFSIGNALED(status)) return 128 + WTERMSIG(status);
    return 126;
}

static bool yaza_process_arguments_valid(const char *command, const yaza_text_list *arguments) {
    if (command == NULL || command[0] == '\0') return false;
    size_t command_length = strlen(command);
    if (command_length > 8192) return false;
    size_t total_bytes = command_length + 1;
    size_t count = arguments == NULL ? 0 : arguments->length;
    if (count > 256 || (count > 0 && arguments->items == NULL)) return false;
    for (size_t index = 0; index < count; index++) {
        const char *argument = arguments->items[index];
        if (argument == NULL) return false;
        size_t argument_length = strlen(argument);
        if (argument_length > 8192 || argument_length + 1 > 131072 - total_bytes) return false;
        total_bytes += argument_length + 1;
    }
    return true;
}

static int64_t yaza_process_list(const char *command, const yaza_text_list *arguments) {
    if (!yaza_process_arguments_valid(command, arguments)) return 125;
    size_t count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(count + 2, sizeof(char *));
    if (process_arguments == NULL) {
        fprintf(stderr, "yaza: out of memory preparing process arguments\n");
        return 126;
    }
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < count; index++) {
        process_arguments[index + 1] = arguments->items[index];
    }
    int64_t result = yaza_process(process_arguments);
    free(process_arguments);
    return result;
}

static int64_t yaza_monotonic_milliseconds(void);

static void yaza_terminate_process_group(pid_t process_group) {
    if (kill(-process_group, SIGTERM) != 0) return;
    struct timespec interval = {0, 10000000L};
    int64_t grace_started = yaza_monotonic_milliseconds();
    while (grace_started >= 0) {
        if (kill(-process_group, 0) != 0 && errno == ESRCH) return;
        int64_t now = yaza_monotonic_milliseconds();
        if (now < 0 || now - grace_started >= 100) break;
        (void)nanosleep(&interval, NULL);
    }
    (void)kill(-process_group, SIGKILL);
}

static int64_t yaza_process_timeout_internal(char *arguments[], int64_t timeout_ms,
                                             const char *working_directory,
                                             bool terminate_group_after_exit,
                                             bool redirect_stdout_to_stderr,
                                             char *const process_environment[],
                                             bool use_environment_allowlist) {
    if (timeout_ms < 1 || timeout_ms > 3600000) {
        fprintf(stderr, "yaza: process timeout must be between 1 and 3600000 milliseconds\n");
        return 125;
    }
    int64_t started = yaza_monotonic_milliseconds();
    if (started < 0) {
        fprintf(stderr, "yaza: monotonic clock is unavailable for process timeout\n");
        return 126;
    }
    pid_t child = fork();
    if (child < 0) {
        fprintf(stderr, "yaza: could not start process: %s\n", strerror(errno));
        return 126;
    }
    if (child == 0) {
        (void)setpgid(0, 0);
        if (working_directory != NULL && chdir(working_directory) != 0) {
            fprintf(stderr, "yaza: cannot change child working directory to '%s': %s\n",
                    working_directory, strerror(errno));
            _exit(126);
        }
        if (redirect_stdout_to_stderr && dup2(STDERR_FILENO, STDOUT_FILENO) < 0) {
            fprintf(stderr, "yaza: cannot redirect child standard output: %s\n", strerror(errno));
            _exit(126);
        }
        if (use_environment_allowlist) yaza_exec_search_path(arguments[0], arguments, process_environment);
        else execvp(arguments[0], arguments);
        fprintf(stderr, "yaza: could not execute '%s': %s\n", arguments[0], strerror(errno));
        _exit(errno == ENOENT ? 127 : 126);
    }
    (void)setpgid(child, child);
    struct timespec interval = {0, 10000000L};
    int status = 0;
    for (;;) {
        pid_t waited = waitpid(child, &status, WNOHANG);
        if (waited == child) {
            int64_t child_status = 126;
            if (WIFEXITED(status)) child_status = WEXITSTATUS(status);
            else if (WIFSIGNALED(status)) child_status = 128 + WTERMSIG(status);
            if (terminate_group_after_exit) yaza_terminate_process_group(child);
            return child_status;
        }
        if (waited < 0 && errno != EINTR) {
            fprintf(stderr, "yaza: could not wait for process: %s\n", strerror(errno));
            (void)kill(-child, SIGKILL);
            (void)waitpid(child, NULL, 0);
            return 126;
        }
        int64_t now = yaza_monotonic_milliseconds();
        if (now < 0 || now - started >= timeout_ms) {
            (void)kill(-child, SIGTERM);
            int64_t grace_started = yaza_monotonic_milliseconds();
            while (waitpid(child, &status, WNOHANG) == 0) {
                int64_t grace_now = yaza_monotonic_milliseconds();
                if (grace_now < 0 || grace_now - grace_started >= 100) break;
                (void)nanosleep(&interval, NULL);
            }
            (void)kill(-child, SIGKILL);
            while (waitpid(child, &status, 0) < 0 && errno == EINTR) {}
            return 124;
        }
        (void)nanosleep(&interval, NULL);
    }
}

static int64_t yaza_process_timeout(char *arguments[], int64_t timeout_ms) {
    return yaza_process_timeout_internal(arguments, timeout_ms, NULL, false, false, NULL, false);
}

static int64_t yaza_process_timeout_list(const char *command, const yaza_text_list *arguments,
                                         int64_t timeout_ms) {
    if (!yaza_process_arguments_valid(command, arguments)) return 125;
    size_t count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(count + 2, sizeof(char *));
    if (process_arguments == NULL) {
        fprintf(stderr, "yaza: out of memory preparing process arguments\n");
        return 126;
    }
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < count; index++) process_arguments[index + 1] = arguments->items[index];
    int64_t result = yaza_process_timeout(process_arguments, timeout_ms);
    free(process_arguments);
    return result;
}

static int64_t yaza_process_timeout_cwd_list(const char *command, const yaza_text_list *arguments,
                                             int64_t timeout_ms, const char *working_directory) {
    if (!yaza_process_arguments_valid(command, arguments)) return 125;
    size_t count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(count + 2, sizeof(char *));
    if (process_arguments == NULL) {
        fprintf(stderr, "yaza: out of memory preparing process arguments\n");
        return 126;
    }
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < count; index++) process_arguments[index + 1] = arguments->items[index];
    int64_t result = yaza_process_timeout_internal(process_arguments, timeout_ms, working_directory, true, false, NULL, false);
    free(process_arguments);
    return result;
}

static int64_t yaza_process_timeout_stderr_list(const char *command, const yaza_text_list *arguments,
                                               int64_t timeout_ms) {
    if (!yaza_process_arguments_valid(command, arguments)) return 125;
    size_t count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(count + 2, sizeof(char *));
    if (process_arguments == NULL) {
        fprintf(stderr, "yaza: out of memory preparing process arguments\n");
        return 126;
    }
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < count; index++) process_arguments[index + 1] = arguments->items[index];
    int64_t result = yaza_process_timeout_internal(process_arguments, timeout_ms, NULL, false, true, NULL, false);
    free(process_arguments);
    return result;
}

static int64_t yaza_process_timeout_cwd_stderr_list(const char *command, const yaza_text_list *arguments,
                                                   int64_t timeout_ms, const char *working_directory) {
    if (!yaza_process_arguments_valid(command, arguments)) return 125;
    size_t count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(count + 2, sizeof(char *));
    if (process_arguments == NULL) {
        fprintf(stderr, "yaza: out of memory preparing process arguments\n");
        return 126;
    }
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < count; index++) process_arguments[index + 1] = arguments->items[index];
    int64_t result = yaza_process_timeout_internal(process_arguments, timeout_ms, working_directory, true, true, NULL, false);
    free(process_arguments);
    return result;
}

typedef struct {
    char *data;
    size_t length;
    size_t capacity;
} yaza_process_output;

static bool yaza_process_output_append(yaza_process_output *output, const char *data, size_t length) {
    if (length > SIZE_MAX - output->length - 1) return false;
    size_t required = output->length + length + 1;
    if (required > output->capacity) {
        size_t capacity = output->capacity == 0 ? 256 : output->capacity;
        while (capacity < required) {
            if (capacity > SIZE_MAX / 2) { capacity = required; break; }
            capacity *= 2;
        }
        char *grown = (char *)realloc(output->data, capacity);
        if (grown == NULL) return false;
        output->data = grown;
        output->capacity = capacity;
    }
    memcpy(output->data + output->length, data, length);
    output->length += length;
    output->data[output->length] = '\0';
    return true;
}

static bool yaza_process_environment_name_allowed(const char *name, size_t name_length) {
    static const char *blocked_names[] = {
        "GCONV_PATH", "GLIBC_TUNABLES", NULL
    };
    if (name == NULL || (name_length >= 3 && memcmp(name, "LD_", 3) == 0) ||
        (name_length >= 5 && memcmp(name, "DYLD_", 5) == 0)) return false;
    for (size_t index = 0; blocked_names[index] != NULL; index++) {
        size_t blocked_length = strlen(blocked_names[index]);
        if (name_length == blocked_length && memcmp(name, blocked_names[index], blocked_length) == 0)
            return false;
    }
    return true;
}

static bool yaza_process_search_path_valid(const char *path) {
    if (path == NULL || path[0] == '\0') return path != NULL;
    const char *cursor = path;
    for (;;) {
        const char *separator = strchr(cursor, ':');
        size_t directory_length = separator == NULL ? strlen(cursor) : (size_t)(separator - cursor);
        if (directory_length == 0 || directory_length >= PATH_MAX || cursor[0] != '/') return false;
        size_t segment_start = 1;
        for (size_t index = 1; index <= directory_length; index++) {
            if (index == directory_length || cursor[index] == '/') {
                size_t segment_length = index - segment_start;
                if ((segment_length == 1 && cursor[segment_start] == '.') ||
                    (segment_length == 2 && cursor[segment_start] == '.' && cursor[segment_start + 1] == '.')) return false;
                segment_start = index + 1;
            }
        }
        if (separator == NULL) return true;
        cursor = separator + 1;
        if (*cursor == '\0') return false;
    }
}

static bool yaza_process_environment_valid(const yaza_text_list *environment) {
    if (environment == NULL || environment->length > 256 ||
        (environment->length > 0 && environment->items == NULL)) return false;
    size_t total_bytes = 0;
    for (size_t index = 0; index < environment->length; index++) {
        const char *entry = environment->items[index];
        if (entry == NULL) return false;
        const char *equals = strchr(entry, '=');
        if (equals == NULL || equals == entry || strlen(entry) > 8192) return false;
        size_t name_length = (size_t)(equals - entry);
        if (!(isalpha((unsigned char)entry[0]) || entry[0] == '_')) return false;
        for (size_t character = 1; character < name_length; character++) {
            unsigned char value = (unsigned char)entry[character];
            if (!isalnum(value) && value != '_') return false;
        }
        if (!yaza_process_environment_name_allowed(entry, name_length)) return false;
        if (name_length == 4 && memcmp(entry, "PATH", 4) == 0 && !yaza_process_search_path_valid(equals + 1)) return false;
        if (strlen(entry) + 1 > 131072 - total_bytes) return false;
        total_bytes += strlen(entry) + 1;
        for (size_t earlier = 0; earlier < index; earlier++) {
            const char *previous_equals = strchr(environment->items[earlier], '=');
            size_t previous_name_length = (size_t)(previous_equals - environment->items[earlier]);
            if (previous_name_length == name_length && memcmp(environment->items[earlier], entry, name_length) == 0)
                return false;
        }
    }
    return true;
}

static char **yaza_process_environment_copy(const yaza_text_list *environment) {
    if (!yaza_process_environment_valid(environment)) return NULL;
    size_t count = environment->length;
    char **copy = (char **)calloc(count + 1, sizeof(char *));
    if (copy == NULL) return NULL;
    for (size_t index = 0; index < count; index++) copy[index] = environment->items[index];
    return copy;
}

static const char *yaza_process_environment_value(char *const environment[], const char *name) {
    size_t name_length = strlen(name);
    for (size_t index = 0; environment != NULL && environment[index] != NULL; index++) {
        if (strncmp(environment[index], name, name_length) == 0 && environment[index][name_length] == '=')
            return environment[index] + name_length + 1;
    }
    return NULL;
}

static void yaza_exec_search_path(const char *command, char *const arguments[], char *const environment[]) {
    if (strchr(command, '/') != NULL) {
        execve(command, arguments, environment);
        return;
    }
    const char *path = yaza_process_environment_value(environment, "PATH");
    if (path == NULL) path = "/usr/bin:/bin";
    bool denied = false;
    const char *cursor = path;
    while (*cursor != '\0') {
        const char *separator = strchr(cursor, ':');
        size_t directory_length = separator == NULL ? strlen(cursor) : (size_t)(separator - cursor);
        if (directory_length > 0 && directory_length < PATH_MAX) {
            char candidate[PATH_MAX];
            int written = snprintf(candidate, sizeof(candidate), "%.*s/%s", (int)directory_length, cursor, command);
            if (written > 0 && (size_t)written < sizeof(candidate)) {
                execve(candidate, arguments, environment);
                if (errno == EACCES) denied = true;
                else if (errno != ENOENT && errno != ENOTDIR) return;
            }
        }
        if (separator == NULL) break;
        cursor = separator + 1;
    }
    errno = denied ? EACCES : ENOENT;
}

static int64_t yaza_process_explicit_environment(const char *command, const yaza_text_list *arguments,
                                                const yaza_text_list *environment) {
    if (!yaza_process_arguments_valid(command, arguments) || !yaza_process_environment_valid(environment)) return 125;
    size_t argument_count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(argument_count + 2, sizeof(char *));
    char **process_environment = yaza_process_environment_copy(environment);
    if (process_arguments == NULL || process_environment == NULL) {
        free(process_arguments);
        free(process_environment);
        return 126;
    }
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < argument_count; index++) {
        if (arguments->items[index] == NULL) {
            free(process_arguments);
            free(process_environment);
            return 125;
        }
        process_arguments[index + 1] = arguments->items[index];
    }
    if (fflush(NULL) != 0) {
        free(process_arguments);
        free(process_environment);
        return 126;
    }
    pid_t child = fork();
    if (child < 0) {
        free(process_arguments);
        free(process_environment);
        return 126;
    }
    if (child == 0) {
        yaza_exec_search_path(command, process_arguments, process_environment);
        _exit(errno == ENOENT ? 127 : 126);
    }
    int status = 0;
    while (waitpid(child, &status, 0) < 0) {
        if (errno != EINTR) {
            free(process_arguments);
            free(process_environment);
            return 126;
        }
    }
    free(process_arguments);
    free(process_environment);
    if (WIFEXITED(status)) return WEXITSTATUS(status);
    if (WIFSIGNALED(status)) return 128 + WTERMSIG(status);
    return 126;
}

static int64_t yaza_process_env_list(const char *command, const yaza_text_list *arguments,
                                    const yaza_text_list *environment) {
    return yaza_process_explicit_environment(command, arguments, environment);
}

static int64_t yaza_process_timeout_env_list(const char *command, const yaza_text_list *arguments,
                                             const yaza_text_list *environment, int64_t timeout_ms) {
    if (!yaza_process_arguments_valid(command, arguments) || timeout_ms < 1 || timeout_ms > 3600000 ||
        !yaza_process_environment_valid(environment)) return 125;
    size_t argument_count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(argument_count + 2, sizeof(char *));
    char **process_environment = yaza_process_environment_copy(environment);
    if (process_arguments == NULL || process_environment == NULL) {
        free(process_arguments);
        free(process_environment);
        return 126;
    }
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < argument_count; index++) {
        if (arguments->items[index] == NULL) {
            free(process_arguments);
            free(process_environment);
            return 125;
        }
        process_arguments[index + 1] = arguments->items[index];
    }
    int64_t result = yaza_process_timeout_internal(process_arguments, timeout_ms, NULL, false, false,
                                                  process_environment, true);
    free(process_arguments);
    free(process_environment);
    return result;
}

static yaza_text_list *yaza_process_capture_result(const char *outcome, int64_t exit_code,
                                                   const char *stdout_text, const char *stderr_text) {
    yaza_text_list *result = yaza_text_list_new();
    char code[32];
    snprintf(code, sizeof(code), "%lld", (long long)exit_code);
    yaza_list_push(result, outcome);
    yaza_list_push(result, code);
    yaza_list_push(result, stdout_text == NULL ? "" : stdout_text);
    yaza_list_push(result, stderr_text == NULL ? "" : stderr_text);
    return result;
}

static yaza_text_list *yaza_process_capture(const char *command, const yaza_text_list *arguments,
                                            const yaza_text_list *environment, int64_t timeout_ms,
                                            int64_t max_output_bytes, bool use_environment_allowlist) {
    if (!yaza_process_arguments_valid(command, arguments) || timeout_ms < 1 || timeout_ms > 3600000 ||
        max_output_bytes < 1 || max_output_bytes > 16777216 ||
        (use_environment_allowlist && !yaza_process_environment_valid(environment))) {
        return yaza_process_capture_result("invalid_input", 125, "", "invalid process capture arguments or environment allowlist");
    }
    size_t argument_count = arguments == NULL ? 0 : arguments->length;
    char **process_arguments = (char **)calloc(argument_count + 2, sizeof(char *));
    char **process_environment = NULL;
    if (process_arguments == NULL) return yaza_process_capture_result("capture_error", 126, "", "out of memory preparing process arguments");
    process_arguments[0] = (char *)command;
    for (size_t index = 0; index < argument_count; index++) process_arguments[index + 1] = arguments->items[index];
    if (use_environment_allowlist) {
        size_t environment_count = environment == NULL ? 0 : environment->length;
        process_environment = (char **)calloc(environment_count + 1, sizeof(char *));
        if (process_environment == NULL) {
            free(process_arguments);
            return yaza_process_capture_result("capture_error", 126, "", "out of memory preparing child environment");
        }
        for (size_t index = 0; index < environment_count; index++) process_environment[index] = environment->items[index];
    }

    int stdout_pipe[2] = {-1, -1};
    int stderr_pipe[2] = {-1, -1};
    if (pipe(stdout_pipe) != 0 || pipe(stderr_pipe) != 0) {
        int saved_errno = errno;
        if (stdout_pipe[0] >= 0) close(stdout_pipe[0]);
        if (stdout_pipe[1] >= 0) close(stdout_pipe[1]);
        if (stderr_pipe[0] >= 0) close(stderr_pipe[0]);
        if (stderr_pipe[1] >= 0) close(stderr_pipe[1]);
        free(process_environment);
        free(process_arguments);
        return yaza_process_capture_result("capture_error", 126, "", strerror(saved_errno));
    }
    for (int index = 0; index < 2; index++) {
        (void)fcntl(stdout_pipe[index], F_SETFD, FD_CLOEXEC);
        (void)fcntl(stderr_pipe[index], F_SETFD, FD_CLOEXEC);
    }

    int64_t started = yaza_monotonic_milliseconds();
    if (started < 0) {
        close(stdout_pipe[0]); close(stdout_pipe[1]); close(stderr_pipe[0]); close(stderr_pipe[1]);
        free(process_environment); free(process_arguments);
        return yaza_process_capture_result("capture_error", 126, "", "monotonic clock is unavailable");
    }
    pid_t child = fork();
    if (child < 0) {
        int saved_errno = errno;
        close(stdout_pipe[0]); close(stdout_pipe[1]); close(stderr_pipe[0]); close(stderr_pipe[1]);
        free(process_environment); free(process_arguments);
        return yaza_process_capture_result("capture_error", 126, "", strerror(saved_errno));
    }
    if (child == 0) {
        (void)setpgid(0, 0);
        close(stdout_pipe[0]); close(stderr_pipe[0]);
        if (dup2(stdout_pipe[1], STDOUT_FILENO) < 0 || dup2(stderr_pipe[1], STDERR_FILENO) < 0) _exit(126);
        close(stdout_pipe[1]); close(stderr_pipe[1]);
        if (use_environment_allowlist) yaza_exec_search_path(command, process_arguments, process_environment);
        else execvp(command, process_arguments);
        dprintf(STDERR_FILENO, "could not execute child process: %s\n", strerror(errno));
        _exit(errno == ENOENT ? 127 : 126);
    }
    (void)setpgid(child, child);
    close(stdout_pipe[1]); close(stderr_pipe[1]);
    (void)fcntl(stdout_pipe[0], F_SETFL, fcntl(stdout_pipe[0], F_GETFL) | O_NONBLOCK);
    (void)fcntl(stderr_pipe[0], F_SETFL, fcntl(stderr_pipe[0], F_GETFL) | O_NONBLOCK);
    free(process_environment);
    free(process_arguments);

    yaza_process_output output = {0};
    yaza_process_output error_output = {0};
    bool stdout_open = true, stderr_open = true, child_reaped = false;
    bool timed_out = false, output_limited = false, binary_output = false;
    bool stdout_binary = false, stderr_binary = false, io_failed = false;
    bool termination_sent = false, kill_sent = false;
    int64_t termination_started = 0;
    int child_status = 0;
    size_t output_total = 0;
    while (stdout_open || stderr_open || !child_reaped) {
        int64_t now = yaza_monotonic_milliseconds();
        if (!termination_sent && (now < 0 || now - started >= timeout_ms)) {
            timed_out = now >= 0;
            if (now < 0) io_failed = true;
            termination_sent = true;
            termination_started = now;
            if (now < 0) {
                kill_sent = true;
                (void)kill(-child, SIGKILL);
            } else {
                (void)kill(-child, SIGTERM);
            }
        }
        if (termination_sent && !kill_sent && now >= 0 && termination_started >= 0 && now - termination_started >= 100) {
            kill_sent = true;
            (void)kill(-child, SIGKILL);
        }
        struct pollfd descriptors[2];
        nfds_t descriptor_count = 0;
        if (stdout_open) descriptors[descriptor_count++] = (struct pollfd){stdout_pipe[0], POLLIN | POLLHUP, 0};
        if (stderr_open) descriptors[descriptor_count++] = (struct pollfd){stderr_pipe[0], POLLIN | POLLHUP, 0};
        int poll_status = descriptor_count > 0 ? poll(descriptors, descriptor_count, 10) : 0;
        if (descriptor_count == 0 && !child_reaped) {
            struct timespec short_pause = {0, 10000000L};
            (void)nanosleep(&short_pause, NULL);
        }
        if (poll_status < 0 && errno != EINTR) {
            io_failed = true;
            if (!termination_sent) {
                termination_sent = true;
                termination_started = yaza_monotonic_milliseconds();
                if (termination_started < 0) {
                    kill_sent = true;
                    (void)kill(-child, SIGKILL);
                } else {
                    (void)kill(-child, SIGTERM);
                }
            }
        }
        if (poll_status > 0) {
            for (nfds_t index = 0; index < descriptor_count; index++) {
                if ((descriptors[index].revents & (POLLIN | POLLHUP | POLLERR)) == 0) continue;
                int descriptor = descriptors[index].fd;
                bool is_stdout = descriptor == stdout_pipe[0];
                char chunk[4096];
                for (;;) {
                    ssize_t amount = read(descriptor, chunk, sizeof(chunk));
                    if (amount == 0) {
                        close(descriptor);
                        if (is_stdout) stdout_open = false; else stderr_open = false;
                        break;
                    }
                    if (amount < 0) {
                        if (errno == EINTR) continue;
                        if (errno == EAGAIN || errno == EWOULDBLOCK) break;
                        io_failed = true;
                        close(descriptor);
                        if (is_stdout) stdout_open = false; else stderr_open = false;
                        break;
                    }
                    size_t chunk_length = (size_t)amount;
                    size_t remaining = (size_t)max_output_bytes - output_total;
                    size_t keep = chunk_length < remaining ? chunk_length : remaining;
                    output_total += keep;
                    if (keep < chunk_length) output_limited = true;
                    if (memchr(chunk, '\0', chunk_length) != NULL) {
                        binary_output = true;
                        if (is_stdout) stdout_binary = true; else stderr_binary = true;
                    } else if (!output_limited && !io_failed) {
                        yaza_process_output *target = is_stdout ? &output : &error_output;
                        if (keep > 0 && !yaza_process_output_append(target, chunk, keep)) {
                            io_failed = true;
                        }
                    }
                    if ((output_limited || binary_output || io_failed) && !termination_sent) {
                        termination_sent = true;
                        termination_started = yaza_monotonic_milliseconds();
                        if (termination_started < 0) {
                            io_failed = true;
                            kill_sent = true;
                            (void)kill(-child, SIGKILL);
                        } else {
                            (void)kill(-child, SIGTERM);
                        }
                    }
                }
            }
        }
        if (!child_reaped) {
            pid_t waited = waitpid(child, &child_status, WNOHANG);
            if (waited == child) child_reaped = true;
            else if (waited < 0 && errno != EINTR) {
                io_failed = true;
                child_reaped = true;
            }
        }
    }
    if (!child_reaped) while (waitpid(child, &child_status, 0) < 0 && errno == EINTR) {}
    int64_t exit_code = 126;
    if (WIFEXITED(child_status)) exit_code = WEXITSTATUS(child_status);
    else if (WIFSIGNALED(child_status)) exit_code = 128 + WTERMSIG(child_status);
    if (timed_out) exit_code = 124;
    else if (output_limited || binary_output || io_failed) exit_code = 125;
    const char *stdout_text = output.data == NULL ? "" : output.data;
    const char *stderr_text = error_output.data == NULL ? "" : error_output.data;
    const char *outcome = "exited";
    char *binary_marker = NULL;
    char *limit_marker = NULL;
    char *io_marker = NULL;
    if (binary_output) {
        binary_marker = yaza_copy_text("<binary output omitted: Text cannot contain NUL bytes>");
        if (stdout_binary) stdout_text = binary_marker;
        if (stderr_binary) stderr_text = binary_marker;
    }
    if (output_limited) {
        limit_marker = yaza_copy_text("<output limit reached>");
        stderr_text = limit_marker;
    }
    if (io_failed) {
        io_marker = yaza_copy_text("<failed while capturing child process output>");
        stderr_text = io_marker;
    }
    if (timed_out) outcome = "timed_out";
    else if (output_limited) outcome = "output_limit";
    else if (binary_output) outcome = "binary_output";
    else if (io_failed) outcome = "capture_error";
    yaza_text_list *result = yaza_process_capture_result(outcome, exit_code, stdout_text, stderr_text);
    free(binary_marker); free(limit_marker); free(io_marker);
    free(output.data); free(error_output.data);
    if (stdout_open) close(stdout_pipe[0]);
    if (stderr_open) close(stderr_pipe[0]);
    return result;
}

static yaza_text_list *yaza_process_capture_list(const char *command, const yaza_text_list *arguments,
                                                 int64_t timeout_ms, int64_t max_output_bytes) {
    return yaza_process_capture(command, arguments, NULL, timeout_ms, max_output_bytes, false);
}

static yaza_text_list *yaza_process_capture_env_list(const char *command, const yaza_text_list *arguments,
                                                     const yaza_text_list *environment, int64_t timeout_ms,
                                                     int64_t max_output_bytes) {
    return yaza_process_capture(command, arguments, environment, timeout_ms, max_output_bytes, true);
}

typedef struct {
    const char *method;
    const char *path;
    const char *body;
    const char *metadata;
    const char *handler_name;
    int success_status;
    int auth_policy;
    int64_t rate_limit_requests;
    int64_t rate_limit_window_ms;
    uint64_t rate_limit_scope_id;
    char cors_origin[512];
    char body_schema[4096];
} yaza_http_route;

typedef struct {
    int status_code;
    const char *body;
    bool owns_body;
} yaza_http_handler_result;

typedef yaza_http_handler_result (*yaza_http_handler_dispatch_fn)(const char *handler_name);
static yaza_http_handler_dispatch_fn yaza_http_handler_dispatch = NULL;
typedef int64_t (*yaza_http_startup_handler_fn)(void);
typedef bool (*yaza_http_readiness_handler_fn)(void);
static yaza_http_startup_handler_fn yaza_http_startup_handler = NULL;
static yaza_http_readiness_handler_fn yaza_http_readiness_handler = NULL;

typedef struct {
    char kind[16];
    char name[128];
    char value_type[128];
    char default_value[256];
    bool required;
    bool has_default;
} yaza_http_parameter;

typedef struct yaza_http_resource yaza_http_resource;

typedef struct {
    const yaza_http_route *route;
    const char *path;
    const char *query;
    const char *request;
    const char *body;
    int client_fd;
    yaza_http_resource *resource;
    const yaza_http_parameter *parameters;
    size_t parameter_count;
    const char *verified_jwt_claims;
} yaza_http_request_context;

typedef struct {
    char field[256];
    char code[64];
} yaza_http_validation_error;

#define YAZA_HTTP_MAX_JSON_FIELDS 64

typedef bool (*yaza_http_body_shape_decode_fn)(const char *body, void *output,
                                               const char *path_prefix,
                                               yaza_http_validation_error *error);
typedef bool (*yaza_http_body_shape_validate_fn)(const char *shape_name, const char *body,
                                                 yaza_http_validation_error *error);
static yaza_http_body_shape_validate_fn yaza_http_body_shape_validate = NULL;
/* Handler ambient accessors are thread-local so concurrent request handlers cannot cross-bind. */
static _Thread_local const yaza_http_request_context *yaza_http_active_request = NULL;
static _Thread_local int yaza_http_handler_response_status = 0;
static _Thread_local const atomic_bool *yaza_http_active_cancelled = NULL;

static bool yaza_http_request_cancelled(void) {
    const atomic_bool *cancelled = yaza_http_active_cancelled;
    return cancelled != NULL && atomic_load_explicit(cancelled, memory_order_acquire);
}

static int64_t yaza_http_set_response_status(int64_t status) {
    if (yaza_http_active_request == NULL || status < 200 || status > 599) return 0;
    if (yaza_http_active_request->route != NULL &&
        yaza_http_active_request->route->success_status > 0 &&
        status != yaza_http_active_request->route->success_status) return 0;
    switch (status) {
        case 200: case 201: case 202: case 204:
        case 400: case 401: case 403: case 404: case 405: case 409:
        case 410: case 413: case 415: case 422: case 429: case 431:
        case 500: case 501: case 503: case 507:
            yaza_http_handler_response_status = (int)status;
            return 1;
        default:
            return 0;
    }
}

static void yaza_http_validation_path(char *output, size_t capacity,
                                      const char *prefix, const char *field) {
    if (output == NULL || capacity == 0) return;
    if (field == NULL) field = "";
    if (prefix == NULL || *prefix == '\0') snprintf(output, capacity, "%s", *field == '\0' ? "$" : field);
    else if (*field == '\0') snprintf(output, capacity, "%s", prefix);
    else snprintf(output, capacity, "%s.%s", prefix, field);
}

static void yaza_http_validation_error_set(yaza_http_validation_error *error,
                                            const char *path, const char *code) {
    if (error == NULL) return;
    snprintf(error->field, sizeof(error->field), "%s", path == NULL || *path == '\0' ? "$" : path);
    snprintf(error->code, sizeof(error->code), "%s", code == NULL || *code == '\0' ? "invalid_body" : code);
}

static void yaza_http_validation_error_set_child(yaza_http_validation_error *error,
                                                  const char *prefix, const char *field,
                                                  const char *code) {
    if (error == NULL) return;
    char path[sizeof(error->field)];
    yaza_http_validation_path(path, sizeof(path), prefix, field);
    yaza_http_validation_error_set(error, path, code);
}

static bool yaza_http_validation_path_index(char *output, size_t capacity,
                                           const char *prefix, size_t index) {
    if (output == NULL || capacity == 0 || prefix == NULL || *prefix == '\0' ||
        index >= YAZA_HTTP_MAX_JSON_FIELDS) return false;
    int written = snprintf(output, capacity, "%s[%zu]", prefix, index);
    return written >= 0 && (size_t)written < capacity && written <= 128;
}

static void yaza_http_validation_error_set_index(yaza_http_validation_error *error,
                                                 const char *prefix, size_t index,
                                                 const char *code) {
    char path[256];
    if (yaza_http_validation_path_index(path, sizeof(path), prefix, index))
        yaza_http_validation_error_set(error, path, code);
    else
        yaza_http_validation_error_set(error, prefix, code);
}

#define YAZA_REGEX_PATTERN_MAX_BYTES 128U
#define YAZA_REGEX_ATOM_MAX 64U
#define YAZA_REGEX_INPUT_MAX_BYTES 1023U

typedef struct yaza_regex_atom {
    unsigned char characters[16];
    unsigned char quantifier; /* 0: one, '?': zero or one, '*': zero or more, '+': one or more */
} yaza_regex_atom;

/* A deliberately bounded, full-match regular-expression subset. It has no
 * groups, alternation, backreferences, or backtracking, so matching work is
 * bounded by pattern atoms times input bytes. */
static bool yaza_regex_parse(const char *pattern, yaza_regex_atom *atoms, size_t *atom_count) {
    if (pattern == NULL || atoms == NULL || atom_count == NULL) return false;
    size_t length = strlen(pattern);
    if (length < 2 || length > YAZA_REGEX_PATTERN_MAX_BYTES || pattern[0] != '^' || pattern[length - 1] != '$' || strchr(pattern, '|') != NULL) return false;
    size_t cursor = 1;
    size_t end = length - 1;
    size_t count = 0;
    while (cursor < end) {
        if (count >= YAZA_REGEX_ATOM_MAX) return false;
        yaza_regex_atom *atom = &atoms[count];
        memset(atom, 0, sizeof(*atom));
        unsigned char current = (unsigned char)pattern[cursor++];
        if (current == '[') {
            bool negate = false;
            bool closed = false;
            size_t members = 0;
            if (cursor < end && pattern[cursor] == '^') {
                negate = true;
                cursor++;
            }
            while (cursor < end && !closed) {
                if (pattern[cursor] == ']') {
                    closed = true;
                    cursor++;
                } else {
                    unsigned char first = (unsigned char)pattern[cursor++];
                    if (first == '\\') {
                        if (cursor >= end) return false;
                        first = (unsigned char)pattern[cursor++];
                        if (isalnum(first) || first == '|') return false;
                    }
                    if (first == 0 || first >= 128) return false;
                    unsigned char last = first;
                    if (cursor + 1 < end && pattern[cursor] == '-' && pattern[cursor + 1] != ']') {
                        cursor++;
                        last = (unsigned char)pattern[cursor++];
                        if (last == '\\') {
                            if (cursor >= end) return false;
                            last = (unsigned char)pattern[cursor++];
                            if (isalnum(last) || last == '|') return false;
                        }
                        if (last >= 128 || first > last) return false;
                    }
                    for (unsigned int value = first; value <= last; value++) {
                        atom->characters[value >> 3] |= (unsigned char)(1U << (value & 7U));
                    }
                    members++;
                }
            }
            if (!closed || members == 0) return false;
            if (negate) {
                for (size_t index = 0; index < sizeof(atom->characters); index++) atom->characters[index] = (unsigned char)~atom->characters[index];
                atom->characters[0] &= (unsigned char)~1U; /* Text values cannot contain NUL. */
            }
        } else if (current == '.') {
            for (unsigned int value = 1; value < 128; value++) {
                atom->characters[value >> 3] |= (unsigned char)(1U << (value & 7U));
            }
        } else {
            if (current == '\\') {
                if (cursor >= end) return false;
                current = (unsigned char)pattern[cursor++];
                if (isalnum(current) || current == '|') return false;
            } else if (current == ']' || current == '^' || current == '$' || current == '*' ||
                       current == '+' || current == '?' || current == '|' || current == '(' ||
                       current == ')' || current == '{' || current == '}') {
                return false;
            }
            if (current == 0 || current >= 128) return false;
            atom->characters[current >> 3] |= (unsigned char)(1U << (current & 7U));
        }

        if (cursor < end && (pattern[cursor] == '?' || pattern[cursor] == '*' || pattern[cursor] == '+')) {
            atom->quantifier = (unsigned char)pattern[cursor++];
            if (cursor < end && (pattern[cursor] == '?' || pattern[cursor] == '*' || pattern[cursor] == '+')) return false;
        }
        count++;
    }
    *atom_count = count;
    return true;
}

static bool yaza_regex_pattern_valid_native(const char *pattern) {
    yaza_regex_atom atoms[YAZA_REGEX_ATOM_MAX];
    size_t atom_count = 0;
    return yaza_regex_parse(pattern, atoms, &atom_count);
}

static bool yaza_regex_atom_matches(const yaza_regex_atom *atom, unsigned char value) {
    if (value == 0 || value >= 128) return false;
    return (atom->characters[value >> 3] & (unsigned char)(1U << (value & 7U))) != 0;
}

static bool yaza_regex_pattern_matches_native(const char *pattern, const char *value) {
    yaza_regex_atom atoms[YAZA_REGEX_ATOM_MAX];
    size_t atom_count = 0;
    if (value == NULL || !yaza_regex_parse(pattern, atoms, &atom_count)) return false;
    size_t length = strlen(value);
    if (length > YAZA_REGEX_INPUT_MAX_BYTES) return false;
    for (size_t index = 0; index < length; index++) {
        if ((unsigned char)value[index] >= 128) return false;
    }

    bool current[YAZA_REGEX_INPUT_MAX_BYTES + 1] = {false};
    bool next[YAZA_REGEX_INPUT_MAX_BYTES + 1];
    current[0] = true;
    for (size_t atom_index = 0; atom_index < atom_count; atom_index++) {
        memset(next, 0, sizeof(next));
        unsigned char quantifier = atoms[atom_index].quantifier;
        if (quantifier == '*') {
            for (size_t position = 0; position <= length; position++) {
                next[position] = current[position] ||
                    (position > 0 && next[position - 1] && yaza_regex_atom_matches(&atoms[atom_index], (unsigned char)value[position - 1]));
            }
        } else if (quantifier == '+') {
            for (size_t position = 1; position <= length; position++) {
                bool matches = yaza_regex_atom_matches(&atoms[atom_index], (unsigned char)value[position - 1]);
                next[position] = matches && (current[position - 1] || next[position - 1]);
            }
        } else if (quantifier == '?') {
            for (size_t position = 0; position <= length; position++) {
                next[position] = current[position] ||
                    (position > 0 && current[position - 1] && yaza_regex_atom_matches(&atoms[atom_index], (unsigned char)value[position - 1]));
            }
        } else {
            for (size_t position = 1; position <= length; position++) {
                next[position] = current[position - 1] && yaza_regex_atom_matches(&atoms[atom_index], (unsigned char)value[position - 1]);
            }
        }
        memcpy(current, next, sizeof(current));
    }
    return current[length];
}

/* Conservative ASCII mailbox syntax check for request validation. This does
 * not prove mailbox existence and intentionally rejects quoted local parts
 * and internationalized addresses until YAZA defines normalization rules. */
static bool yaza_http_email_valid(const char *value) {
    if (value == NULL) return false;
    size_t length = strlen(value);
    if (length == 0 || length > 254) return false;

    size_t at = SIZE_MAX;
    for (size_t i = 0; i < length; i++) {
        unsigned char ch = (unsigned char)value[i];
        if (ch < 33 || ch > 126) return false;
        if (ch == '@') {
            if (at != SIZE_MAX) return false;
            at = i;
        }
    }
    if (at == SIZE_MAX || at == 0 || at > 64 || at + 1 >= length) return false;

    /* Accept dot-atom local parts, not quoted strings or comments. */
    bool previous_dot = true;
    for (size_t i = 0; i < at; i++) {
        unsigned char ch = (unsigned char)value[i];
        bool alpha = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
        bool digit = ch >= '0' && ch <= '9';
        if (ch == '.') {
            if (previous_dot) return false;
            previous_dot = true;
            continue;
        }
        if (!(alpha || digit || strchr("!#$%&'*+-/=?^_`{|}~", ch) != NULL)) return false;
        previous_dot = false;
    }
    if (previous_dot) return false;

    /* Require DNS-style labels and a multi-label domain. */
    size_t label_length = 0;
    size_t labels = 0;
    size_t final_label_length = 0;
    for (size_t i = at + 1; i <= length; i++) {
        if (i == length || value[i] == '.') {
            if (label_length == 0 || label_length > 63 || value[i - 1] == '-') return false;
            labels++;
            final_label_length = label_length;
            label_length = 0;
            continue;
        }
        unsigned char ch = (unsigned char)value[i];
        bool alpha = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
        bool digit = ch >= '0' && ch <= '9';
        if (!(alpha || digit || ch == '-')) return false;
        if (label_length == 0 && ch == '-') return false;
        label_length++;
    }
    return labels >= 2 && final_label_length >= 2;
}

/* JSON's number grammar includes fractions and exponents. Inspect the decimal
 * spelling directly so a Float64 rounding step cannot turn a fraction into an
 * integer before validation. Keep the accepted range inside IEEE-754's safe
 * integer interval so every accepted value is exact in a Float64 field. */
static bool yaza_http_json_number_is_integer(const char *text) {
    if (text == NULL || *text == '\0') return false;
    const unsigned char *cursor = (const unsigned char *)text;
    bool negative = false;
    if (*cursor == '-') {
        negative = true;
        cursor++;
    }

    char digits[1024];
    size_t digit_count = 0;
    size_t fractional_digits = 0;
    if (*cursor < '0' || *cursor > '9') return false;
    if (*cursor == '0' && cursor[1] >= '0' && cursor[1] <= '9') return false;
    while (*cursor >= '0' && *cursor <= '9') {
        if (digit_count >= sizeof(digits)) return false;
        digits[digit_count++] = (char)*cursor++;
    }
    if (*cursor == '.') {
        cursor++;
        if (*cursor < '0' || *cursor > '9') return false;
        while (*cursor >= '0' && *cursor <= '9') {
            if (digit_count >= sizeof(digits)) return false;
            digits[digit_count++] = (char)*cursor++;
            fractional_digits++;
        }
    }

    int64_t exponent = 0;
    if (*cursor == 'e' || *cursor == 'E') {
        cursor++;
        bool exponent_negative = false;
        if (*cursor == '+' || *cursor == '-') {
            exponent_negative = *cursor == '-';
            cursor++;
        }
        if (*cursor < '0' || *cursor > '9') return false;
        while (*cursor >= '0' && *cursor <= '9') {
            int digit = *cursor++ - '0';
            if (exponent < 1000000) {
                exponent = exponent > (1000000 - digit) / 10
                    ? 1000000
                    : exponent * 10 + digit;
            }
        }
        if (exponent_negative) exponent = -exponent;
    }
    if (*cursor != '\0') return false;

    size_t first_nonzero = 0;
    while (first_nonzero < digit_count && digits[first_nonzero] == '0') first_nonzero++;
    if (first_nonzero == digit_count) return true;
    if (first_nonzero > 0) {
        memmove(digits, digits + first_nonzero, digit_count - first_nonzero);
        digit_count -= first_nonzero;
    }

    int64_t scale = exponent - (int64_t)fractional_digits;
    while (scale < 0 && digit_count > 0 && digits[digit_count - 1] == '0') {
        digit_count--;
        scale++;
    }
    if (scale < 0 || scale > 16 || digit_count + (size_t)scale > 16) return false;

    uint64_t limit = UINT64_C(9007199254740991);
    uint64_t magnitude = 0;
    for (size_t index = 0; index < digit_count; index++) {
        uint64_t digit = (uint64_t)(digits[index] - '0');
        if (magnitude > (limit - digit) / 10) return false;
        magnitude = magnitude * 10 + digit;
    }
    for (int64_t index = 0; index < scale; index++) {
        if (magnitude > limit / 10) return false;
        magnitude *= 10;
    }
    return true;
}

static bool yaza_http_method_token_valid(const char *method) {
    if (method == NULL || *method == '\0') return false;
    size_t length = 0;
    for (const unsigned char *cursor = (const unsigned char *)method; *cursor != '\0'; cursor++) {
        if (++length > 32U) return false;
        if ((*cursor >= 'A' && *cursor <= 'Z') || (*cursor >= 'a' && *cursor <= 'z') ||
            (*cursor >= '0' && *cursor <= '9') || strchr("!#$%&'*+-.^_`|~", *cursor) != NULL) continue;
        return false;
    }
    return true;
}

#define YAZA_HTTP_ALLOW_MAX_BYTES 1024U

static bool yaza_http_allow_add(char *allow, size_t capacity, const char *method) {
    if (allow == NULL || capacity == 0 || !yaza_http_method_token_valid(method)) return false;
    size_t method_length = strlen(method);
    const char *cursor = allow;
    while (*cursor != '\0') {
        const char *end = strchr(cursor, ',');
        size_t length = end == NULL ? strlen(cursor) : (size_t)(end - cursor);
        while (length > 0 && *cursor == ' ') { cursor++; length--; }
        if (length == method_length && memcmp(cursor, method, method_length) == 0) return true;
        if (end == NULL) break;
        cursor = end + 1;
    }
    size_t current_length = strlen(allow);
    size_t separator_length = current_length == 0 ? 0 : 2;
    if (current_length + separator_length + method_length + 1 > capacity) return false;
    if (separator_length > 0) {
        memcpy(allow + current_length, ", ", separator_length);
        current_length += separator_length;
    }
    memcpy(allow + current_length, method, method_length + 1);
    return true;
}

static bool yaza_http_path_matches(const char *pattern, const char *path) {
    while (*pattern != '\0' && *path != '\0') {
        if (*pattern == '{') {
            const char *end = strchr(pattern, '}');
            if (end == NULL || end == pattern + 1 || *path == '/') return false;
            while (*path != '\0' && *path != '/') path++;
            pattern = end + 1;
        } else {
            if (*pattern != *path) return false;
            pattern++;
            path++;
        }
    }
    return *pattern == '\0' && *path == '\0';
}

static const yaza_http_route *yaza_http_route_for_method(const yaza_http_route *routes,
                                                        size_t route_count,
                                                        const char *path,
                                                        const char *method) {
    if (routes == NULL || path == NULL || method == NULL) return NULL;
    for (size_t index = 0; index < route_count; index++) {
        if (strcmp(routes[index].method, method) == 0 &&
            yaza_http_path_matches(routes[index].path, path)) return &routes[index];
    }
    if (strcmp(method, "HEAD") == 0) {
        for (size_t index = 0; index < route_count; index++) {
            if (strcmp(routes[index].method, "GET") == 0 &&
                yaza_http_path_matches(routes[index].path, path)) return &routes[index];
        }
    }
    return NULL;
}

static const yaza_http_route *yaza_http_route_for_path_policy(const yaza_http_route *routes,
                                                              size_t route_count,
                                                              const char *path) {
    if (routes == NULL || path == NULL) return NULL;
    const yaza_http_route *selected = NULL;
    int selected_priority = -1;
    for (size_t index = 0; index < route_count; index++) {
        if (!yaza_http_path_matches(routes[index].path, path)) continue;
        int priority = routes[index].auth_policy == 3 ? 4 :
            (routes[index].auth_policy == 2 ? 3 :
             (routes[index].auth_policy == 0 ? 2 : 1));
        if (priority > selected_priority) {
            selected = &routes[index];
            selected_priority = priority;
        }
    }
    return selected;
}

static int64_t yaza_monotonic_milliseconds(void);

#define YAZA_HTTP_RESPONSE_WRITE_TIMEOUT_DEFAULT_MS 5000
#define YAZA_HTTP_REQUEST_TIMEOUT_DEFAULT_MS 5000
#define YAZA_HTTP_KEEP_ALIVE_TIMEOUT_DEFAULT_MS 5000
#define YAZA_HTTP_SHUTDOWN_GRACE_DEFAULT_MS 5000
#define YAZA_HTTP_MAX_REQUESTS_PER_CONNECTION 100
#define YAZA_HTTP_RESPONSE_MAX_BYTES (16U * 1024U * 1024U)
#define YAZA_HTTP_RESPONSE_PENDING_MAX_BYTES (64U * 1024U * 1024U)
#define YAZA_HTTP_WRITE_QUANTUM_BYTES (64U * 1024U)

static int64_t yaza_http_request_timeout_ms = YAZA_HTTP_REQUEST_TIMEOUT_DEFAULT_MS;
static int64_t yaza_http_keep_alive_timeout_ms = YAZA_HTTP_KEEP_ALIVE_TIMEOUT_DEFAULT_MS;
static int64_t yaza_http_shutdown_grace_ms = YAZA_HTTP_SHUTDOWN_GRACE_DEFAULT_MS;
static int64_t yaza_http_response_write_timeout_ms = YAZA_HTTP_RESPONSE_WRITE_TIMEOUT_DEFAULT_MS;
static atomic_size_t yaza_http_worker_response_bytes = 0;

typedef struct yaza_http_connection yaza_http_connection;
static _Thread_local yaza_http_connection *yaza_http_active_connection = NULL;
static size_t yaza_http_pending_response_bytes = 0;
static int yaza_http_queue_response(int client_fd, const char *header, size_t header_length,
                                   const char *body, size_t body_length, int status);

static int yaza_http_send_all(int socket_fd, const char *data, size_t length) {
    size_t sent = 0;
    int64_t started_ms = yaza_monotonic_milliseconds();
    if (started_ms < 0 || started_ms > INT64_MAX - yaza_http_response_write_timeout_ms) return -1;
    int64_t deadline_ms = started_ms + yaza_http_response_write_timeout_ms;
    while (sent < length) {
        ssize_t count = send(socket_fd, data + sent, length - sent, 0);
        if (count < 0 && errno == EINTR) continue;
        if (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
            int64_t now_ms = yaza_monotonic_milliseconds();
            if (now_ms < 0 || now_ms >= deadline_ms) return -1;
            struct pollfd writable = {socket_fd, POLLOUT, 0};
            int wait_ms = (int)(deadline_ms - now_ms);
            int poll_status = poll(&writable, 1, wait_ms);
            if (poll_status < 0 && errno == EINTR) continue;
            if (poll_status <= 0 || (writable.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) return -1;
            continue;
        }
        if (count <= 0) return -1;
        sent += (size_t)count;
    }
    return 0;
}

static _Thread_local char yaza_http_cors_response_origin[512];
static _Thread_local char yaza_http_cors_allow_headers[1024] = "Accept, Authorization, Content-Type";
static _Thread_local bool yaza_http_cors_preflight_active = false;
static _Thread_local bool yaza_http_response_keep_alive = false;
static _Thread_local bool yaza_http_head_request = false;
static volatile sig_atomic_t yaza_http_shutdown_requested = 0;
static _Thread_local char yaza_http_current_method[16] = "unknown";
static _Thread_local char yaza_http_current_path[2048] = "unknown";
static _Thread_local char yaza_http_current_request_id[33] = "";
static int yaza_http_request_random_fd = -1;
static _Thread_local int64_t yaza_http_current_started_ms = 0;
static _Thread_local int64_t yaza_http_retry_after_seconds = 1;
static const int yaza_http_metric_status_codes[] = {200, 201, 204, 400, 401, 403, 404, 405, 409, 413, 415, 422, 429, 431, 500, 503, 507};
static uint64_t yaza_http_metric_status_counts[sizeof(yaza_http_metric_status_codes) / sizeof(yaza_http_metric_status_codes[0])];

#define YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT 1024
#define YAZA_HTTP_RATE_LIMIT_TOKEN_SCALE 1000000LL
typedef struct {
    uint32_t remote_ipv4;
    uint64_t scope_id;
    int64_t request_capacity;
    int64_t window_ms;
    int64_t tokens_scaled;
    int64_t last_refill_ms;
    int64_t last_seen_ms;
    int64_t refill_remainder;
    bool occupied;
} yaza_http_rate_limit_bucket;
static yaza_http_rate_limit_bucket yaza_http_rate_limit_buckets[YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT];

static uint64_t yaza_http_rate_limit_scope_id(const char *scope, int64_t request_capacity, int64_t window_ms) {
    if (scope == NULL || *scope == '\0' || request_capacity < 1 || window_ms < 1) return 0;
    uint64_t hash = UINT64_C(14695981039346656037);
    for (const unsigned char *cursor = (const unsigned char *)scope; *cursor != '\0'; cursor++) {
        hash ^= *cursor;
        hash *= UINT64_C(1099511628211);
    }
    hash ^= (uint64_t)request_capacity;
    hash *= UINT64_C(1099511628211);
    hash ^= (uint64_t)window_ms;
    hash *= UINT64_C(1099511628211);
    return hash == 0 ? UINT64_C(1) : hash;
}

static bool yaza_http_rate_limit_allow(uint32_t remote_ipv4, uint64_t scope_id, int64_t now_ms,
                                       int64_t request_capacity, int64_t window_ms,
                                       int64_t *retry_after_seconds) {
    if (retry_after_seconds == NULL || request_capacity < 1 || request_capacity > 100000 ||
        window_ms < 1000 || window_ms > 3600000 || now_ms < 0) return false;
    *retry_after_seconds = 1;
    const int64_t full_tokens = request_capacity * YAZA_HTTP_RATE_LIMIT_TOKEN_SCALE;
    size_t slot = YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT;
    size_t empty_slot = YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT;
    int64_t earliest_expiry_ms = INT64_MAX;
    for (size_t index = 0; index < YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT; index++) {
        yaza_http_rate_limit_bucket *candidate = &yaza_http_rate_limit_buckets[index];
        if (!candidate->occupied) {
            if (empty_slot == YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT) empty_slot = index;
            continue;
        }
        if (candidate->remote_ipv4 == remote_ipv4 && candidate->scope_id == scope_id &&
            candidate->request_capacity == request_capacity && candidate->window_ms == window_ms) {
            slot = index;
            break;
        }
        int64_t age = now_ms >= candidate->last_seen_ms ? now_ms - candidate->last_seen_ms : 0;
        if (age >= candidate->window_ms && empty_slot == YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT)
            empty_slot = index;
        int64_t expiry = candidate->last_seen_ms <= INT64_MAX - candidate->window_ms
            ? candidate->last_seen_ms + candidate->window_ms : INT64_MAX;
        if (expiry < earliest_expiry_ms) earliest_expiry_ms = expiry;
    }
    if (slot == YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT) {
        if (empty_slot == YAZA_HTTP_RATE_LIMIT_BUCKET_COUNT) {
            int64_t wait_ms = earliest_expiry_ms > now_ms ? earliest_expiry_ms - now_ms : 1;
            *retry_after_seconds = wait_ms / 1000 + (wait_ms % 1000 != 0);
            if (*retry_after_seconds < 1) *retry_after_seconds = 1;
            return false;
        }
        slot = empty_slot;
        yaza_http_rate_limit_buckets[slot] = (yaza_http_rate_limit_bucket){
            .remote_ipv4 = remote_ipv4,
            .scope_id = scope_id,
            .request_capacity = request_capacity,
            .window_ms = window_ms,
            .tokens_scaled = full_tokens,
            .last_refill_ms = now_ms,
            .last_seen_ms = now_ms,
            .refill_remainder = 0,
            .occupied = true
        };
    }

    yaza_http_rate_limit_bucket *bucket = &yaza_http_rate_limit_buckets[slot];
    int64_t elapsed_ms = now_ms >= bucket->last_refill_ms ? now_ms - bucket->last_refill_ms : 0;
    if (elapsed_ms > window_ms) elapsed_ms = window_ms;
    int64_t refill_numerator = elapsed_ms * request_capacity * YAZA_HTTP_RATE_LIMIT_TOKEN_SCALE +
        bucket->refill_remainder;
    int64_t refill_scaled = refill_numerator / window_ms;
    bucket->refill_remainder = refill_numerator % window_ms;
    bucket->last_refill_ms = now_ms;
    if (refill_scaled >= full_tokens - bucket->tokens_scaled) {
        bucket->tokens_scaled = full_tokens;
        bucket->refill_remainder = 0;
    } else {
        bucket->tokens_scaled += refill_scaled;
    }
    if (bucket->tokens_scaled >= YAZA_HTTP_RATE_LIMIT_TOKEN_SCALE) {
        bucket->tokens_scaled -= YAZA_HTTP_RATE_LIMIT_TOKEN_SCALE;
        bucket->last_seen_ms = now_ms;
        return true;
    }

    int64_t needed_scaled = YAZA_HTTP_RATE_LIMIT_TOKEN_SCALE - bucket->tokens_scaled;
    int64_t denominator = request_capacity * YAZA_HTTP_RATE_LIMIT_TOKEN_SCALE;
    int64_t retry_ms = (needed_scaled * window_ms + denominator - 1) / denominator;
    *retry_after_seconds = retry_ms / 1000 + (retry_ms % 1000 != 0);
    if (*retry_after_seconds < 1) *retry_after_seconds = 1;
    return false;
}

static void yaza_json_write_string(FILE *stream, const char *value) {
    fputc('"', stream);
    for (const unsigned char *cursor = (const unsigned char *)value; *cursor != '\0'; cursor++) {
        if (*cursor == '"' || *cursor == '\\') {
            fputc('\\', stream);
            fputc(*cursor, stream);
        } else if (*cursor < 0x20) {
            fprintf(stream, "\\u%04x", (unsigned int)*cursor);
        } else {
            fputc(*cursor, stream);
        }
    }
    fputc('"', stream);
}

static char *yaza_json_quote_text(const char *value) {
    if (value == NULL) value = "";
    size_t length = strlen(value);
    if (length > (SIZE_MAX - 3) / 6) {
        fprintf(stderr, "yaza: Text is too large to encode as a JSON string\n");
        exit(1);
    }
    size_t capacity = length * 6 + 3;
    char *encoded = (char *)malloc(capacity);
    if (encoded == NULL) {
        fprintf(stderr, "yaza: memory limit exceeded while encoding a JSON string\n");
        exit(1);
    }
    static const char hex[] = "0123456789abcdef";
    size_t used = 0;
    encoded[used++] = '"';
    for (const unsigned char *cursor = (const unsigned char *)value; *cursor != '\0'; cursor++) {
        unsigned char character = *cursor;
        if (character == '"' || character == '\\') {
            encoded[used++] = '\\';
            encoded[used++] = (char)character;
        } else if (character == '\b') {
            encoded[used++] = '\\'; encoded[used++] = 'b';
        } else if (character == '\f') {
            encoded[used++] = '\\'; encoded[used++] = 'f';
        } else if (character == '\n') {
            encoded[used++] = '\\'; encoded[used++] = 'n';
        } else if (character == '\r') {
            encoded[used++] = '\\'; encoded[used++] = 'r';
        } else if (character == '\t') {
            encoded[used++] = '\\'; encoded[used++] = 't';
        } else if (character < 0x20) {
            encoded[used++] = '\\'; encoded[used++] = 'u';
            encoded[used++] = '0'; encoded[used++] = '0';
            encoded[used++] = hex[character >> 4];
            encoded[used++] = hex[character & 0x0f];
        } else {
            encoded[used++] = (char)character;
        }
    }
    encoded[used++] = '"';
    encoded[used] = '\0';
    return encoded;
}

static bool yaza_http_json_append_n(char *output, size_t capacity, size_t *used,
                                    const char *value, size_t length) {
    if (output == NULL || used == NULL || value == NULL || *used >= capacity ||
        length > capacity - *used - 1) return false;
    if (length > 0) memcpy(output + *used, value, length);
    *used += length;
    output[*used] = '\0';
    return true;
}

static bool yaza_http_json_append(char *output, size_t capacity, size_t *used,
                                  const char *value) {
    return value != NULL && yaza_http_json_append_n(output, capacity, used, value, strlen(value));
}

static bool yaza_http_json_append_quoted(char *output, size_t capacity, size_t *used,
                                         const char *value) {
    if (value == NULL) value = "";
    if (!yaza_http_json_append(output, capacity, used, "\"")) return false;
    static const char hex[] = "0123456789abcdef";
    for (const unsigned char *cursor = (const unsigned char *)value; *cursor != '\0'; cursor++) {
        const unsigned char character = *cursor;
        if (character == '"' || character == '\\') {
            const char escaped[2] = {'\\', (char)character};
            if (!yaza_http_json_append_n(output, capacity, used, escaped, sizeof(escaped))) return false;
        } else if (character == '\b') {
            if (!yaza_http_json_append(output, capacity, used, "\\b")) return false;
        } else if (character == '\f') {
            if (!yaza_http_json_append(output, capacity, used, "\\f")) return false;
        } else if (character == '\n') {
            if (!yaza_http_json_append(output, capacity, used, "\\n")) return false;
        } else if (character == '\r') {
            if (!yaza_http_json_append(output, capacity, used, "\\r")) return false;
        } else if (character == '\t') {
            if (!yaza_http_json_append(output, capacity, used, "\\t")) return false;
        } else if (character < 0x20) {
            char escaped[6] = {'\\', 'u', '0', '0', hex[character >> 4], hex[character & 0x0f]};
            if (!yaza_http_json_append_n(output, capacity, used, escaped, sizeof(escaped))) return false;
        } else if (!yaza_http_json_append_n(output, capacity, used, (const char *)cursor, 1)) {
            return false;
        }
    }
    return yaza_http_json_append(output, capacity, used, "\"");
}

static bool yaza_http_json_append_int64(char *output, size_t capacity, size_t *used,
                                        int64_t value) {
    char number[32];
    int length = snprintf(number, sizeof(number), "%lld", (long long)value);
    return length > 0 && (size_t)length < sizeof(number) &&
           yaza_http_json_append_n(output, capacity, used, number, (size_t)length);
}

static bool yaza_http_json_append_float64(char *output, size_t capacity, size_t *used,
                                          double value) {
    if (!isfinite(value)) return false;
    char number[64];
    int length = snprintf(number, sizeof(number), "%.17g", value);
    return length > 0 && (size_t)length < sizeof(number) &&
           yaza_http_json_append_n(output, capacity, used, number, (size_t)length);
}

static bool yaza_http_json_append_boolean(char *output, size_t capacity, size_t *used,
                                          bool value) {
    return yaza_http_json_append(output, capacity, used, value ? "true" : "false");
}

static bool yaza_http_json_append_text_list(char *output, size_t capacity, size_t *used,
                                            const yaza_text_list *value) {
    if (value == NULL || value->length > value->capacity ||
        (value->length > 0 && value->items == NULL) ||
        !yaza_http_json_append(output, capacity, used, "[")) return false;
    for (size_t index = 0; index < value->length; index++) {
        if ((index > 0 && !yaza_http_json_append(output, capacity, used, ",")) ||
            !yaza_http_json_append_quoted(output, capacity, used, value->items[index])) return false;
    }
    return yaza_http_json_append(output, capacity, used, "]");
}

static bool yaza_http_json_append_typed_list(char *output, size_t capacity, size_t *used,
                                             const yaza_typed_list *value, const char *item_type) {
    if (value == NULL || item_type == NULL || value->element_type == NULL ||
        strcmp(value->element_type, item_type) != 0 || value->length > YAZA_HTTP_MAX_JSON_FIELDS ||
        value->length > value->capacity || (value->length > 0 && value->items == NULL)) return false;
    size_t element_size = 0;
    if (strcmp(item_type, "Text") == 0) element_size = sizeof(const char *);
    else if (strcmp(item_type, "Number") == 0) element_size = sizeof(int64_t);
    else if (strcmp(item_type, "Int32") == 0) element_size = sizeof(int32_t);
    else if (strcmp(item_type, "Float64") == 0) element_size = sizeof(double);
    else if (strcmp(item_type, "Boolean") == 0) element_size = sizeof(bool);
    else return false;
    if (value->element_size != element_size || !yaza_http_json_append(output, capacity, used, "[")) return false;
    for (size_t index = 0; index < value->length; index++) {
        const void *item = value->items + index * element_size;
        if (index > 0 && !yaza_http_json_append(output, capacity, used, ",")) return false;
        if (strcmp(item_type, "Text") == 0) {
            const char *text = *(const char *const *)item;
            if (text == NULL || !yaza_http_json_append_quoted(output, capacity, used, text)) return false;
        } else if (strcmp(item_type, "Number") == 0) {
            if (!yaza_http_json_append_int64(output, capacity, used, *(const int64_t *)item)) return false;
        } else if (strcmp(item_type, "Int32") == 0) {
            if (!yaza_http_json_append_int64(output, capacity, used, (int64_t)*(const int32_t *)item)) return false;
        } else if (strcmp(item_type, "Float64") == 0) {
            if (!yaza_http_json_append_float64(output, capacity, used, *(const double *)item)) return false;
        } else if (!yaza_http_json_append_boolean(output, capacity, used, *(const bool *)item)) {
            return false;
        }
    }
    return yaza_http_json_append(output, capacity, used, "]");
}

static bool yaza_http_error_field_path_valid(const char *field) {
    if (field == NULL) return false;
    size_t length = strnlen(field, 129U);
    if (length == 0 || length > 128U) return false;
    if (length == 1 && field[0] == '$') return true;
    const unsigned char *cursor = (const unsigned char *)field;
    while (*cursor != '\0') {
        bool first_letter = (*cursor >= 'A' && *cursor <= 'Z') ||
                            (*cursor >= 'a' && *cursor <= 'z') || *cursor == '_';
        if (!first_letter) return false;
        cursor++;
        while ((*cursor >= 'A' && *cursor <= 'Z') || (*cursor >= 'a' && *cursor <= 'z') ||
               (*cursor >= '0' && *cursor <= '9') || *cursor == '_') cursor++;
        while (*cursor == '[') {
            cursor++;
            if (*cursor < '0' || *cursor > '9') return false;
            size_t index = 0;
            bool leading_zero = *cursor == '0';
            size_t digits = 0;
            while (*cursor >= '0' && *cursor <= '9') {
                index = index * 10U + (size_t)(*cursor - '0');
                if (index >= YAZA_HTTP_MAX_JSON_FIELDS || ++digits > 2U) return false;
                cursor++;
            }
            if ((leading_zero && digits != 1U) || *cursor != ']') return false;
            cursor++;
        }
        if (*cursor == '\0') return true;
        if (*cursor != '.') return false;
        cursor++;
        if (*cursor == '\0') return false;
    }
    return false;
}

static yaza_http_handler_result yaza_http_api_validation_field_error(const char *field) {
    static const char fallback[] = "{\"error\":{\"type\":\"validation_error\",\"code\":\"invalid_input\"}}";
    if (!yaza_http_error_field_path_valid(field)) return (yaza_http_handler_result){422, fallback};
    static const char prefix[] = "{\"error\":{\"type\":\"validation_error\",\"code\":\"invalid_input\",\"field\":\"";
    static const char suffix[] = "\"}}";
    size_t field_length = strlen(field);
    size_t body_length = sizeof(prefix) - 1 + field_length + sizeof(suffix);
    char *body = (char *)malloc(body_length);
    if (body == NULL) return (yaza_http_handler_result){500, "{\"error\":\"Internal Server Error\"}"};
    memcpy(body, prefix, sizeof(prefix) - 1);
    memcpy(body + sizeof(prefix) - 1, field, field_length);
    memcpy(body + sizeof(prefix) - 1 + field_length, suffix, sizeof(suffix));
    return (yaza_http_handler_result){422, body, true};
}

static yaza_http_handler_result yaza_http_api_validation_errors(const yaza_text_list *errors) {
    static const char fallback[] = "{\"error\":{\"type\":\"validation_error\",\"code\":\"validation_failed\"}}";
    if (errors == NULL || errors->length > 64U || errors->length > errors->capacity ||
        (errors->length > 0 && errors->items == NULL))
        return (yaza_http_handler_result){422, fallback};
    /* Each accepted field path is at most 128 bytes. Reserve its quotes and
       separator too, so every documented 64-field error fits without losing
       the paths to the generic fallback. */
    size_t body_capacity = 128U + errors->length * 131U;
    char *body = (char *)malloc(body_capacity);
    if (body == NULL) return (yaza_http_handler_result){500, "{\"error\":\"Internal Server Error\"}"};
    body[0] = '\0';
    size_t used = 0;
    if (!yaza_http_json_append(body, body_capacity, &used,
        "{\"error\":{\"type\":\"validation_error\",\"code\":\"validation_failed\",\"fields\":[")) {
        free(body);
        return (yaza_http_handler_result){422, fallback};
    }
    for (size_t index = 0; index < errors->length; index++) {
        if (!yaza_http_error_field_path_valid(errors->items[index]) ||
            (index > 0 && !yaza_http_json_append(body, body_capacity, &used, ",")) ||
            !yaza_http_json_append_quoted(body, body_capacity, &used, errors->items[index])) {
            free(body);
            return (yaza_http_handler_result){422, fallback};
        }
    }
    if (!yaza_http_json_append(body, body_capacity, &used, "]}}")) {
        free(body);
        return (yaza_http_handler_result){422, fallback};
    }
    return (yaza_http_handler_result){422, body, true};
}

static void yaza_http_log_string(const char *value) {
    yaza_json_write_string(stderr, value);
}

static bool yaza_log_key_is_sensitive(const char *key) {
    static const char *sensitive_parts[] = {
        "password", "passwd", "secret", "token", "authorization", "cookie",
        "api_key", "apikey", "access_key", "private_key", "credential",
        "database_url", "email", "phone", "address", "national_id", "ssn"
    };
    for (const char *cursor = key; *cursor != '\0'; cursor++) {
        for (size_t index = 0; index < sizeof(sensitive_parts) / sizeof(sensitive_parts[0]); index++) {
            size_t length = strlen(sensitive_parts[index]);
            if (strncasecmp(cursor, sensitive_parts[index], length) == 0) return true;
        }
    }
    return false;
}

static int64_t yaza_log_event(const char *level, const char *event, const yaza_text_list *fields) {
    if (level == NULL || event == NULL ||
        !(strcmp(level, "debug") == 0 || strcmp(level, "info") == 0 ||
          strcmp(level, "warn") == 0 || strcmp(level, "error") == 0)) {
        fprintf(stderr, "yaza logger: level must be debug, info, warn, or error\n");
        return 1;
    }

    size_t count = fields == NULL ? 0 : fields->length;
    if (count % 2 != 0 || count > 128 || event[0] == '\0') {
        fprintf(stderr, "yaza logger: event must be non-empty and fields must contain at most 64 key/value pairs\n");
        return 1;
    }

    size_t total_bytes = strlen(level) + strlen(event);
    if (total_bytes > 8192 || !yaza_utf8_valid((const unsigned char *)level, strlen(level)) ||
        !yaza_utf8_valid((const unsigned char *)event, strlen(event))) {
        fprintf(stderr, "yaza logger: event data exceeds limits or is not valid UTF-8\n");
        return 1;
    }
    for (size_t index = 0; index < count; index += 2) {
        const char *key = fields->items[index];
        const char *value = fields->items[index + 1];
        size_t key_length = strlen(key);
        size_t value_length = strlen(value);
        if (key_length == 0 || key_length > 128 || value_length > 4096 ||
            key_length > 8192 - total_bytes || value_length > 8192 - total_bytes - key_length ||
            !yaza_utf8_valid((const unsigned char *)key, key_length) ||
            !yaza_utf8_valid((const unsigned char *)value, value_length)) {
            fprintf(stderr, "yaza logger: invalid or oversized field; event was not written\n");
            return 1;
        }
        total_bytes += key_length + value_length;
        for (size_t previous = 0; previous < index; previous += 2) {
            if (strcmp(fields->items[previous], key) == 0) {
                fprintf(stderr, "yaza logger: duplicate field name; event was not written\n");
                return 1;
            }
        }
    }

    struct timespec now;
    struct tm utc;
    char timestamp[40];
    char seconds[24];
    if (clock_gettime(CLOCK_REALTIME, &now) != 0 || gmtime_r(&now.tv_sec, &utc) == NULL ||
        strftime(seconds, sizeof(seconds), "%Y-%m-%dT%H:%M:%S", &utc) == 0) {
        fprintf(stderr, "yaza logger: could not obtain a UTC timestamp\n");
        return 1;
    }
    int timestamp_length = snprintf(timestamp, sizeof(timestamp), "%s.%09ldZ", seconds, now.tv_nsec);
    if (timestamp_length < 0 || (size_t)timestamp_length >= sizeof(timestamp) ||
        now.tv_nsec < 0 || now.tv_nsec >= 1000000000L) {
        fprintf(stderr, "yaza logger: could not format a UTC timestamp\n");
        return 1;
    }

    fputs("{\"timestamp\":", stderr);
    yaza_json_write_string(stderr, timestamp);
    fputs(",\"level\":", stderr);
    yaza_json_write_string(stderr, level);
    fputs(",\"event\":", stderr);
    yaza_json_write_string(stderr, event);
    fputs(",\"fields\":{", stderr);
    for (size_t index = 0; index < count; index += 2) {
        if (index != 0) fputc(',', stderr);
        const char *key = fields->items[index];
        const char *value = yaza_log_key_is_sensitive(key) ? "[REDACTED]" : fields->items[index + 1];
        yaza_json_write_string(stderr, key);
        fputc(':', stderr);
        yaza_json_write_string(stderr, value);
    }
    fputs("}}\n", stderr);
    if (fflush(stderr) != 0) return 1;
    return 0;
}

static void yaza_http_assign_request_id(void) {
    static const char hex[] = "0123456789abcdef";
    unsigned char random[16];
    if (yaza_http_request_random_fd < 0) {
        yaza_http_request_random_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
        if (yaza_http_request_random_fd < 0) {
            fprintf(stderr, "yaza: operating-system random source is unavailable for HTTP request IDs: %s\n",
                    strerror(errno));
            exit(1);
        }
    }
    size_t offset = 0;
    while (offset < sizeof(random)) {
        ssize_t received = read(yaza_http_request_random_fd, random + offset, sizeof(random) - offset);
        if (received > 0) {
            offset += (size_t)received;
        } else if (received < 0 && errno == EINTR) {
            continue;
        } else {
            int read_error = received == 0 ? EIO : errno;
            close(yaza_http_request_random_fd);
            yaza_http_request_random_fd = -1;
            fprintf(stderr, "yaza: operating-system random source failed for HTTP request IDs: %s\n",
                    strerror(read_error));
            exit(1);
        }
    }
    for (size_t index = 0; index < sizeof(random); index++) {
        yaza_http_current_request_id[index * 2] = hex[random[index] >> 4];
        yaza_http_current_request_id[index * 2 + 1] = hex[random[index] & 0x0f];
    }
    yaza_http_current_request_id[32] = '\0';
}

static void yaza_http_log_response(int status) {
    for (size_t index = 0; index < sizeof(yaza_http_metric_status_codes) / sizeof(yaza_http_metric_status_codes[0]); index++) {
        if (yaza_http_metric_status_codes[index] == status && yaza_http_metric_status_counts[index] < UINT64_MAX) {
            yaza_http_metric_status_counts[index]++;
            break;
        }
    }
    int64_t now = yaza_monotonic_milliseconds();
    int64_t duration = now >= yaza_http_current_started_ms
        ? now - yaza_http_current_started_ms : 0;
    char safe_path[2048];
    snprintf(safe_path, sizeof(safe_path), "%s", yaza_http_current_path);
    char *query_start = strchr(safe_path, '?');
    if (query_start != NULL) *query_start = '\0';
    fputs("{\"level\":\"info\",\"event\":\"http_request\",\"request_id\":", stderr);
    yaza_http_log_string(yaza_http_current_request_id);
    fputs(",\"method\":", stderr);
    yaza_http_log_string(yaza_http_current_method);
    fputs(",\"path\":", stderr);
    yaza_http_log_string(safe_path);
    fprintf(stderr, ",\"status\":%d,\"duration_ms\":%lld}\n", status, (long long)duration);
    fflush(stderr);
}

static const char *yaza_http_standard_error_type(int status) {
    switch (status) {
        case 400: return "bad_request";
        case 401: case 423: return "authentication_error";
        case 403: return "authorization_error";
        case 402: return "billing_error";
        case 404: case 410: return "not_found";
        case 405: case 413: case 415: case 431: case 501: return "request_error";
        case 409: return "conflict";
        case 412: return "precondition_error";
        case 422: return "validation_error";
        case 429: return "rate_limit_error";
        case 500: return "internal_error";
        case 502: return "external_service_error";
        case 503: return "service_unavailable";
        case 504: return "timeout_error";
        case 507: return "storage_error";
        default: return "http_error";
    }
}

static const char *yaza_http_standard_error_code(int status) {
    switch (status) {
        case 400: return "bad_request";
        case 401: return "unauthorized";
        case 402: return "payment_required";
        case 403: return "forbidden";
        case 404: return "not_found";
        case 405: return "method_not_allowed";
        case 409: return "conflict";
        case 410: return "gone";
        case 412: return "precondition_failed";
        case 413: return "payload_too_large";
        case 415: return "unsupported_media_type";
        case 422: return "invalid_input";
        case 423: return "locked_out";
        case 429: return "rate_limited";
        case 431: return "headers_too_large";
        case 500: return "internal_error";
        case 501: return "not_implemented";
        case 502: return "external_service_error";
        case 503: return "unavailable";
        case 504: return "timeout";
        case 507: return "insufficient_storage";
        default: return "request_failed";
    }
}

static const char *yaza_http_standard_error_body(int status) {
    const char *type = yaza_http_standard_error_type(status);
    const char *code = yaza_http_standard_error_code(status);
    static _Thread_local char body[192];
    int length = snprintf(body, sizeof(body), "{\"error\":{\"type\":\"%s\",\"code\":\"%s\"}}", type, code);
    if (length < 0 || (size_t)length >= sizeof(body))
        return "{\"error\":{\"type\":\"internal_error\",\"code\":\"internal_error\"}}";
    return body;
}

static bool yaza_http_error_body_is_structured(const char *body) {
    if (body == NULL) return false;
    const char *error_key = strstr(body, "\"error\"");
    if (error_key == NULL) return false;
    const char *cursor = error_key + sizeof("\"error\"") - 1;
    while (*cursor != '\0' && isspace((unsigned char)*cursor)) cursor++;
    if (*cursor++ != ':') return false;
    while (*cursor != '\0' && isspace((unsigned char)*cursor)) cursor++;
    return *cursor == '{';
}

static const char *yaza_http_canonical_error_body(int status, const char *content_type,
                                                  const char *body) {
    if (status == 503 && body != NULL &&
        strcmp(body, "{\"status\":\"not_ready\",\"dependency\":\"postgresql\"}") == 0) {
        return body;
    }
    if (status < 400 || content_type == NULL ||
        strncmp(content_type, "application/json", sizeof("application/json") - 1) != 0 ||
        yaza_http_error_body_is_structured(body)) return body;
    return yaza_http_standard_error_body(status);
}

static void yaza_http_respond_content_with_allow(int client_fd, int status, const char *reason,
                                                const char *content_type, const char *body,
                                                const char *allow_methods) {
    body = yaza_http_canonical_error_body(status, content_type, body);
    if (body == NULL) body = yaza_http_standard_error_body(status);
    char header[4096];
    size_t representation_body_length = status == 204 ? 0 : strlen(body);
    size_t transmitted_body_length = status == 204 || yaza_http_head_request
        ? 0 : representation_body_length;
    char representation_headers[YAZA_HTTP_ALLOW_MAX_BYTES + 256U] = {0};
    if (status != 204) {
        int representation_length = snprintf(representation_headers, sizeof(representation_headers),
            "Content-Type: %s\r\nContent-Length: %zu\r\n", content_type, representation_body_length);
        if (representation_length < 0 || (size_t)representation_length >= sizeof(representation_headers)) return;
    }
    if (allow_methods != NULL && *allow_methods != '\0') {
        size_t used = strlen(representation_headers);
        int allow_length = snprintf(representation_headers + used, sizeof(representation_headers) - used,
                                    "Allow: %s\r\n", allow_methods);
        if (allow_length < 0 || (size_t)allow_length >= sizeof(representation_headers) - used) return;
    }
    int header_length;
    char connection_headers[96] = "Connection: close\r\n";
    if (yaza_http_response_keep_alive && !yaza_http_shutdown_requested) {
        int64_t keep_alive_seconds = (yaza_http_keep_alive_timeout_ms + 999) / 1000;
        int connection_length = snprintf(connection_headers, sizeof(connection_headers),
            "Connection: keep-alive\r\nKeep-Alive: timeout=%lld, max=%d\r\n",
            (long long)keep_alive_seconds, YAZA_HTTP_MAX_REQUESTS_PER_CONNECTION);
        if (connection_length < 0 || (size_t)connection_length >= sizeof(connection_headers)) return;
    }
    const char *authentication_challenge = status == 401 ? "WWW-Authenticate: Bearer\r\n" : "";
    char retry_after[64] = "";
    if (status == 429 || status == 503) {
        int retry_length = snprintf(retry_after, sizeof(retry_after), "Retry-After: %lld\r\n",
                                    (long long)yaza_http_retry_after_seconds);
        if (retry_length < 0 || (size_t)retry_length >= sizeof(retry_after)) return;
    }
    if (yaza_http_cors_response_origin[0] != '\0' && yaza_http_cors_preflight_active) {
        header_length = snprintf(
            header, sizeof(header),
            "HTTP/1.1 %d %s\r\n%sX-Request-ID: %s\r\nConnection: close\r\nX-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nCache-Control: no-store\r\nAccess-Control-Allow-Origin: %s\r\nAccess-Control-Expose-Headers: X-Request-ID\r\nVary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers\r\nAccess-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS\r\nAccess-Control-Allow-Headers: %s\r\nAccess-Control-Max-Age: 600\r\n\r\n",
            status, reason, representation_headers, yaza_http_current_request_id,
            yaza_http_cors_response_origin, yaza_http_cors_allow_headers
        );
    } else if (yaza_http_cors_response_origin[0] != '\0') {
        header_length = snprintf(
            header, sizeof(header),
            "HTTP/1.1 %d %s\r\n%sX-Request-ID: %s\r\n%s%s%sX-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nCache-Control: no-store\r\nAccess-Control-Allow-Origin: %s\r\nAccess-Control-Expose-Headers: X-Request-ID\r\nVary: Origin\r\n\r\n",
            status, reason, representation_headers, yaza_http_current_request_id, connection_headers,
            authentication_challenge, retry_after, yaza_http_cors_response_origin
        );
    } else {
        header_length = snprintf(
            header, sizeof(header),
            "HTTP/1.1 %d %s\r\n%sX-Request-ID: %s\r\n%s%s%sX-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nCache-Control: no-store\r\nVary: Origin\r\n\r\n",
            status, reason, representation_headers, yaza_http_current_request_id, connection_headers,
            authentication_challenge, retry_after
        );
    }
    if (header_length <= 0 || (size_t)header_length >= sizeof(header)) return;
    int queued = yaza_http_queue_response(client_fd, header, (size_t)header_length,
                                         body, transmitted_body_length, status);
    if (queued > 0) {
        yaza_http_log_response(status);
        return;
    }
    if (queued < 0) {
        yaza_http_response_keep_alive = false;
        return;
    }
    if (yaza_http_send_all(client_fd, header, (size_t)header_length) != 0 ||
        yaza_http_send_all(client_fd, body, transmitted_body_length) != 0) {
        yaza_http_response_keep_alive = false;
        return;
    }
    yaza_http_log_response(status);
}

static void yaza_http_respond_content(int client_fd, int status, const char *reason,
                                     const char *content_type, const char *body) {
    yaza_http_respond_content_with_allow(client_fd, status, reason, content_type, body, NULL);
}

static void yaza_http_respond(int client_fd, int status, const char *reason, const char *body) {
    yaza_http_respond_content(client_fd, status, reason, "application/json; charset=utf-8", body);
}

static void yaza_http_respond_method_not_allowed(int client_fd, const char *allow_methods) {
    yaza_http_respond_content_with_allow(client_fd, 405, "Method Not Allowed",
                                         "application/json; charset=utf-8",
                                         "{\"error\":\"Method Not Allowed\"}", allow_methods);
}

static void yaza_http_respond_typed_error(int client_fd, int status, const char *reason,
                                          const yaza_http_validation_error *error) {
    const char *field = error != NULL && error->field[0] != '\0' ? error->field : "$";
    const char *code = error != NULL && error->code[0] != '\0' ? error->code : "invalid_body";
    if (!yaza_http_error_field_path_valid(field)) field = "$";
    bool valid_code = *code != '\0';
    size_t code_length = 0;
    for (const unsigned char *cursor = (const unsigned char *)code; *cursor != '\0'; cursor++) {
        if (++code_length > 64U || ((*cursor < 'a' || *cursor > 'z') &&
            (*cursor < '0' || *cursor > '9') && *cursor != '_')) valid_code = false;
    }
    if (!valid_code) code = "invalid_body";
    char body[768];
    int length = snprintf(body, sizeof(body),
        "{\"error\":{\"type\":\"validation_error\",\"field\":\"%s\",\"code\":\"%s\"}}",
        field, code);
    if (length < 0 || (size_t)length >= sizeof(body)) {
        yaza_http_respond(client_fd, status, reason,
                          "{\"error\":{\"type\":\"validation_error\",\"field\":\"$\",\"code\":\"invalid_body\"}}");
        return;
    }
    yaza_http_respond(client_fd, status, reason, body);
}

static void yaza_http_respond_validation_error(int client_fd,
                                               const yaza_http_validation_error *error) {
    yaza_http_respond_typed_error(client_fd, 422, "Unprocessable Content", error);
}

static void yaza_http_respond_unauthorized(int client_fd) {
    const bool previous_keep_alive = yaza_http_response_keep_alive;
    yaza_http_response_keep_alive = false;
    yaza_http_respond(client_fd, 401, "Unauthorized", yaza_http_standard_error_body(401));
    yaza_http_response_keep_alive = previous_keep_alive;
}

static void yaza_http_respond_token_expired(int client_fd) {
    const bool previous_keep_alive = yaza_http_response_keep_alive;
    yaza_http_response_keep_alive = false;
    yaza_http_respond(client_fd, 401, "Unauthorized",
                      "{\"error\":{\"type\":\"authentication_error\",\"code\":\"token_expired\"}}");
    yaza_http_response_keep_alive = previous_keep_alive;
}

#define YAZA_HTTP_MAX_RESOURCES 32
#define YAZA_HTTP_MAX_RECORDS 512
#define YAZA_HTTP_MAX_JSON_DEPTH 128
#define YAZA_HTTP_REQUEST_CAPACITY 65536
#define YAZA_HTTP_REQUEST_EOF (-9)
#define YAZA_HTTP_MAX_HEADER_BYTES 16384
#define YAZA_HTTP_MAX_HEADER_COUNT 64
#define YAZA_HTTP_MAX_ALLOWED_HOSTS 32U
#define YAZA_HTTP_ALLOWED_HOST_LIST_MAX_BYTES 4096U
#define YAZA_HTTP_ALLOWED_HOST_MAX_BYTES 253U
#define YAZA_IO_MAX_EVENTS 128
#define YAZA_HTTP_DEFAULT_CONNECTIONS 64
#define YAZA_HTTP_MAX_CONNECTIONS (YAZA_IO_MAX_EVENTS - 1U)
#define YAZA_HTTP_STARTUP_ROUTE_DISPLAY_MAX 24U
#define YAZA_HTTP_API_TOKEN_MAX_BYTES 1024
#define YAZA_HTTP_API_TOKEN_MIN_BYTES 32U
#define YAZA_HTTP_API_TOKEN_MAX_ACTIVE 2U
#define YAZA_HTTP_JWT_MAX_TOKEN_BYTES 8192U
#define YAZA_HTTP_JWT_MAX_SEGMENT_BYTES 6144U
#define YAZA_HTTP_JWT_MAX_SECRET_BYTES 4096U
#define YAZA_HTTP_POLL_INTERVAL_MS 100
#define YAZA_HTTP_ACCEPT_BACKOFF_MS 1000
#define YAZA_IO_MAX_TASK_WAITERS YAZA_SCHEDULER_MAX_TASKS

typedef enum {
    YAZA_HTTP_ACCEPT_ERROR_DRAIN,
    YAZA_HTTP_ACCEPT_ERROR_RETRY,
    YAZA_HTTP_ACCEPT_ERROR_BACKOFF,
    YAZA_HTTP_ACCEPT_ERROR_FATAL
} yaza_http_accept_error_action;

static yaza_http_accept_error_action yaza_http_classify_accept_error(int error_number) {
    if (error_number == EAGAIN || error_number == EWOULDBLOCK)
        return YAZA_HTTP_ACCEPT_ERROR_DRAIN;
    if (error_number == EINTR || error_number == ECONNABORTED)
        return YAZA_HTTP_ACCEPT_ERROR_RETRY;
    if (error_number == EMFILE || error_number == ENFILE)
        return YAZA_HTTP_ACCEPT_ERROR_BACKOFF;
#ifdef EPROTO
    if (error_number == EPROTO) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
#ifdef ENETDOWN
    if (error_number == ENETDOWN) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
#ifdef ENONET
    if (error_number == ENONET) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
#ifdef EHOSTDOWN
    if (error_number == EHOSTDOWN) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
#ifdef ENETUNREACH
    if (error_number == ENETUNREACH) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
#ifdef EHOSTUNREACH
    if (error_number == EHOSTUNREACH) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
#ifdef EOPNOTSUPP
    if (error_number == EOPNOTSUPP) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
#ifdef ENOPROTOOPT
    if (error_number == ENOPROTOOPT) return YAZA_HTTP_ACCEPT_ERROR_RETRY;
#endif
    return YAZA_HTTP_ACCEPT_ERROR_FATAL;
}

static char yaza_http_allowed_hosts[YAZA_HTTP_MAX_ALLOWED_HOSTS][YAZA_HTTP_ALLOWED_HOST_MAX_BYTES + 1U];
static size_t yaza_http_allowed_host_count = 0;

static char *yaza_http_json_serialize_typed_list_response(const yaza_typed_list *value,
                                                           const char *item_type) {
    char *output = (char *)malloc(YAZA_HTTP_REQUEST_CAPACITY);
    if (output == NULL) return NULL;
    output[0] = '\0';
    size_t used = 0;
    if (!yaza_http_json_append_typed_list(output, YAZA_HTTP_REQUEST_CAPACITY, &used,
                                          value, item_type)) {
        free(output);
        return NULL;
    }
    return output;
}

#define YAZA_IO_READABLE 1U
#define YAZA_IO_WRITABLE 2U
#define YAZA_IO_ERROR 4U
#define YAZA_IO_HANGUP 8U

typedef struct {
    int fd;
    uint32_t events;
    uint64_t token;
} yaza_io_event;

typedef struct {
    bool occupied;
    int fd;
    uint64_t token;
    uint64_t task_id;
} yaza_io_task_waiter;

typedef struct {
    int fd;
    int listener_fd;
    uint64_t next_token;
    yaza_io_task_waiter task_waiters[YAZA_IO_MAX_TASK_WAITERS];
} yaza_io_driver;

static const char *yaza_io_backend_name(void) {
#if defined(__APPLE__)
    return "kqueue";
#elif defined(__linux__)
    return "epoll (level-triggered)";
#else
    return "unsupported";
#endif
}

static bool yaza_io_driver_open(yaza_io_driver *driver) {
    if (driver == NULL) return false;
    driver->listener_fd = -1;
#if defined(__APPLE__)
    driver->fd = kqueue();
    if (driver->fd < 0) return false;
    int flags = fcntl(driver->fd, F_GETFD, 0);
    if (flags < 0 || fcntl(driver->fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
        close(driver->fd);
        driver->fd = -1;
        return false;
    }
#elif defined(__linux__)
    driver->fd = epoll_create1(EPOLL_CLOEXEC);
    if (driver->fd < 0) return false;
#else
    driver->fd = -1;
    errno = ENOTSUP;
    return false;
#endif
    driver->next_token = 1;
    memset(driver->task_waiters, 0, sizeof(driver->task_waiters));
    return true;
}

static void yaza_io_driver_close(yaza_io_driver *driver) {
    if (driver == NULL) return;
    if (driver->fd >= 0) close(driver->fd);
    driver->fd = -1;
    driver->listener_fd = -1;
    memset(driver->task_waiters, 0, sizeof(driver->task_waiters));
}

static uint64_t yaza_io_allocate_token(yaza_io_driver *driver) {
    if (driver == NULL || driver->fd < 0 || driver->next_token == 0) return 0;
    return driver->next_token++;
}

static bool yaza_io_watch_read(yaza_io_driver *driver, int fd, uint64_t token) {
    if (driver == NULL || driver->fd < 0 || fd < 0) return false;
    if (token == 0 && driver->listener_fd >= 0 && driver->listener_fd != fd) {
        errno = EEXIST;
        return false;
    }
#if defined(__APPLE__)
    struct kevent change;
    EV_SET(&change, (uintptr_t)fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0,
           (void *)(uintptr_t)token);
    if (kevent(driver->fd, &change, 1, NULL, 0, NULL) != 0) return false;
    if (token == 0) driver->listener_fd = fd;
    return true;
#elif defined(__linux__)
    struct epoll_event change;
    memset(&change, 0, sizeof(change));
    change.events = EPOLLIN;
#ifdef EPOLLRDHUP
    change.events |= EPOLLRDHUP;
#endif
    change.data.u64 = token;
    if (epoll_ctl(driver->fd, EPOLL_CTL_ADD, fd, &change) != 0) {
        if (errno != EEXIST || epoll_ctl(driver->fd, EPOLL_CTL_MOD, fd, &change) != 0) {
            return false;
        }
    }
    if (token == 0) driver->listener_fd = fd;
    return true;
#else
    (void)token;
    errno = ENOTSUP;
    return false;
#endif
}

static bool yaza_io_watch_write(yaza_io_driver *driver, int fd, uint64_t token) {
    if (driver == NULL || driver->fd < 0 || fd < 0 || token == 0) return false;
#if defined(__APPLE__)
    struct kevent change;
    EV_SET(&change, (uintptr_t)fd, EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0,
           (void *)(uintptr_t)token);
    return kevent(driver->fd, &change, 1, NULL, 0, NULL) == 0;
#elif defined(__linux__)
    struct epoll_event change;
    memset(&change, 0, sizeof(change));
    change.events = EPOLLOUT;
    change.data.u64 = token;
    if (epoll_ctl(driver->fd, EPOLL_CTL_ADD, fd, &change) == 0) return true;
    if (errno != EEXIST) return false;
    return epoll_ctl(driver->fd, EPOLL_CTL_MOD, fd, &change) == 0;
#else
    (void)token;
    errno = ENOTSUP;
    return false;
#endif
}

static bool yaza_io_unwatch(yaza_io_driver *driver, int fd) {
    if (driver == NULL || driver->fd < 0 || fd < 0) return false;
    bool removed = false;
#if defined(__APPLE__)
    struct kevent change;
    EV_SET(&change, (uintptr_t)fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
    removed = kevent(driver->fd, &change, 1, NULL, 0, NULL) == 0 ||
              errno == ENOENT || errno == EBADF;
#elif defined(__linux__)
    removed = epoll_ctl(driver->fd, EPOLL_CTL_DEL, fd, NULL) == 0 ||
              errno == ENOENT || errno == EBADF;
#else
    errno = ENOTSUP;
    return false;
#endif
    if (removed && driver->listener_fd == fd) driver->listener_fd = -1;
    return removed;
}

static bool yaza_io_unwatch_write(yaza_io_driver *driver, int fd) {
    if (driver == NULL || driver->fd < 0 || fd < 0) return false;
#if defined(__APPLE__)
    struct kevent change;
    EV_SET(&change, (uintptr_t)fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
    if (kevent(driver->fd, &change, 1, NULL, 0, NULL) == 0) return true;
    return errno == ENOENT || errno == EBADF;
#elif defined(__linux__)
    if (epoll_ctl(driver->fd, EPOLL_CTL_DEL, fd, NULL) == 0) return true;
    return errno == ENOENT || errno == EBADF;
#else
    errno = ENOTSUP;
    return false;
#endif
}

static int yaza_io_wait(yaza_io_driver *driver, yaza_io_event *events,
                        size_t capacity, int timeout_ms) {
    if (driver == NULL || driver->fd < 0 || events == NULL || capacity == 0 ||
        capacity > YAZA_IO_MAX_EVENTS || timeout_ms < 0) {
        errno = EINVAL;
        return -1;
    }
#if defined(__APPLE__)
    struct kevent native_events[YAZA_IO_MAX_EVENTS];
    struct timespec timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000000L};
    int count = kevent(driver->fd, NULL, 0, native_events, (int)capacity, &timeout);
    if (count < 0) return -1;
    for (int index = 0; index < count; index++) {
        uint32_t flags = 0;
        if (native_events[index].filter == EVFILT_READ) flags |= YAZA_IO_READABLE;
        if (native_events[index].filter == EVFILT_WRITE) flags |= YAZA_IO_WRITABLE;
        if ((native_events[index].flags & EV_EOF) != 0) flags |= YAZA_IO_HANGUP;
        if ((native_events[index].flags & EV_ERROR) != 0) flags |= YAZA_IO_ERROR;
        events[index] = (yaza_io_event){(int)native_events[index].ident, flags,
                                        (uint64_t)(uintptr_t)native_events[index].udata};
    }
    return count;
#elif defined(__linux__)
    struct epoll_event native_events[YAZA_IO_MAX_EVENTS];
    int count = epoll_wait(driver->fd, native_events, (int)capacity, timeout_ms);
    if (count < 0) return -1;
    for (int index = 0; index < count; index++) {
        uint32_t flags = 0;
        if ((native_events[index].events & (EPOLLIN | EPOLLPRI)) != 0) flags |= YAZA_IO_READABLE;
        if ((native_events[index].events & EPOLLOUT) != 0) flags |= YAZA_IO_WRITABLE;
        if ((native_events[index].events & EPOLLERR) != 0) flags |= YAZA_IO_ERROR;
        if ((native_events[index].events & (EPOLLHUP
#ifdef EPOLLRDHUP
                                            | EPOLLRDHUP
#endif
                                            )) != 0) flags |= YAZA_IO_HANGUP;
        uint64_t token = native_events[index].data.u64;
        int event_fd = token == 0 ? driver->listener_fd : -1;
        events[index] = (yaza_io_event){event_fd, flags, token};
    }
    return count;
#else
    errno = ENOTSUP;
    return -1;
#endif
}

static bool yaza_io_wait_task_read(yaza_io_driver *driver, yaza_scheduler *scheduler,
                                   uint64_t task_id, int fd, uint64_t *token_out) {
    if (driver == NULL || scheduler == NULL || fd < 0 || task_id == 0 || token_out == NULL ||
        scheduler->current_task_id != task_id) return false;
    yaza_scheduler_task *task = yaza_scheduler_find(scheduler, task_id, NULL);
    if (task == NULL || task->state != YAZA_TASK_RUNNING) return false;
    size_t free_slot = YAZA_IO_MAX_TASK_WAITERS;
    for (size_t index = 0; index < YAZA_IO_MAX_TASK_WAITERS; index++) {
        yaza_io_task_waiter *waiter = &driver->task_waiters[index];
        if (!waiter->occupied) {
            if (free_slot == YAZA_IO_MAX_TASK_WAITERS) free_slot = index;
            continue;
        }
        if (waiter->fd == fd || waiter->task_id == task_id) return false;
    }
    if (free_slot == YAZA_IO_MAX_TASK_WAITERS) return false;
    uint64_t token = yaza_io_allocate_token(driver);
    if (token == 0 || !yaza_io_watch_read(driver, fd, token)) return false;
    driver->task_waiters[free_slot] = (yaza_io_task_waiter){true, fd, token, task_id};
    *token_out = token;
    return true;
}

static bool yaza_io_cancel_task_wait(yaza_io_driver *driver, uint64_t task_id) {
    if (driver == NULL || task_id == 0) return false;
    for (size_t index = 0; index < YAZA_IO_MAX_TASK_WAITERS; index++) {
        yaza_io_task_waiter *waiter = &driver->task_waiters[index];
        if (!waiter->occupied || waiter->task_id != task_id) continue;
        bool removed = yaza_io_unwatch(driver, waiter->fd);
        memset(waiter, 0, sizeof(*waiter));
        return removed;
    }
    return false;
}

static size_t yaza_io_dispatch_task_waits(yaza_io_driver *driver, yaza_scheduler *scheduler,
                                          const yaza_io_event *events, size_t event_count) {
    if (driver == NULL || scheduler == NULL || (events == NULL && event_count != 0)) return 0;
    size_t woken = 0;
    for (size_t event_index = 0; event_index < event_count; event_index++) {
        for (size_t waiter_index = 0; waiter_index < YAZA_IO_MAX_TASK_WAITERS; waiter_index++) {
            yaza_io_task_waiter *waiter = &driver->task_waiters[waiter_index];
            if (!waiter->occupied || waiter->token != events[event_index].token ||
                (events[event_index].fd >= 0 && waiter->fd != events[event_index].fd)) continue;
            uint64_t task_id = waiter->task_id;
            (void)yaza_io_unwatch(driver, waiter->fd);
            memset(waiter, 0, sizeof(*waiter));
            if (yaza_scheduler_wake(scheduler, task_id)) woken++;
            break;
        }
    }
    return woken;
}

static size_t yaza_io_prune_task_waits(yaza_io_driver *driver, const yaza_scheduler *scheduler) {
    if (driver == NULL || scheduler == NULL) return 0;
    size_t removed = 0;
    for (size_t index = 0; index < YAZA_IO_MAX_TASK_WAITERS; index++) {
        yaza_io_task_waiter *waiter = &driver->task_waiters[index];
        if (!waiter->occupied || yaza_scheduler_state(scheduler, waiter->task_id) == YAZA_TASK_WAITING)
            continue;
        (void)yaza_io_unwatch(driver, waiter->fd);
        memset(waiter, 0, sizeof(*waiter));
        removed++;
    }
    return removed;
}

struct yaza_http_connection {
    int fd;
    uint32_t remote_ipv4;
    uint64_t generation;
    uint64_t reader_task_id;
    yaza_io_driver *io_driver;
    size_t used;
    int64_t last_activity_ms;
    int64_t request_started_at_ms;
    size_t requests_served;
    int request_status;
    size_t request_length;
    const char *request_body;
    bool request_keep_alive;
    bool request_ready;
    char *response_buffer;
    size_t response_length;
    size_t response_offset;
    int response_status;
    int64_t response_started_ms;
    uint64_t response_write_token;
    bool response_pending;
    bool response_waiting;
    bool response_failed;
    bool response_keep_alive;
    bool worker_pending;
    atomic_bool *worker_cancelled;
    char overwritten_pipeline_byte;
    bool has_overwritten_pipeline_byte;
    bool has_buffered_pipeline;
    char method[16];
    char path[2048];
    char request_id[33];
    char request_cors_origin[512];
    char request[YAZA_HTTP_REQUEST_CAPACITY];
};

typedef struct {
    yaza_http_connection *connection;
    uint64_t connection_generation;
    const yaza_http_route *route;
    yaza_http_request_context request_context;
    atomic_bool cancelled;
    int64_t started_ms;
    char method[16];
    char path[2048];
    char query[2048];
    char request_id[33];
    char cors_origin[512];
    char request[YAZA_HTTP_REQUEST_CAPACITY];
    char body[YAZA_HTTP_REQUEST_CAPACITY];
    unsigned char verified_jwt_claims[YAZA_HTTP_JWT_MAX_SEGMENT_BYTES + 1U];
    yaza_http_parameter parameters[YAZA_HTTP_MAX_JSON_FIELDS];
} yaza_http_handler_job;

typedef struct {
    int status_code;
    int handler_response_status;
    char *body;
    size_t body_length;
    bool body_budget_reserved;
} yaza_http_handler_output;

typedef struct {
    yaza_http_connection *connection;
    uint64_t connection_generation;
    atomic_bool cancelled;
    int64_t started_ms;
    char method[16];
    char path[2048];
    char request_id[33];
    char cors_origin[512];
} yaza_http_readiness_job;

typedef struct {
    bool ready;
} yaza_http_readiness_output;

static int yaza_http_queue_response(int client_fd, const char *header, size_t header_length,
                                    const char *body, size_t body_length, int status) {
    yaza_http_connection *connection = yaza_http_active_connection;
    if (connection == NULL || connection->fd != client_fd) return 0;
    if (connection->response_pending || header == NULL || (body == NULL && body_length != 0) ||
        header_length > YAZA_HTTP_RESPONSE_MAX_BYTES ||
        body_length > YAZA_HTTP_RESPONSE_MAX_BYTES - header_length) {
        connection->response_failed = true;
        return -1;
    }
    size_t length = header_length + body_length;
    if (length > YAZA_HTTP_RESPONSE_PENDING_MAX_BYTES - yaza_http_pending_response_bytes) {
        connection->response_failed = true;
        return -1;
    }
    char *buffer = (char *)malloc(length == 0 ? 1 : length);
    if (buffer == NULL) {
        connection->response_failed = true;
        return -1;
    }
    memcpy(buffer, header, header_length);
    if (body_length != 0) memcpy(buffer + header_length, body, body_length);
    int64_t now_ms = yaza_monotonic_milliseconds();
    if (now_ms < 0 || now_ms > INT64_MAX - yaza_http_response_write_timeout_ms) {
        free(buffer);
        connection->response_failed = true;
        return -1;
    }
    connection->response_buffer = buffer;
    connection->response_length = length;
    connection->response_offset = 0;
    connection->response_status = status;
    connection->response_started_ms = now_ms;
    connection->response_write_token = 0;
    connection->response_pending = true;
    connection->response_waiting = false;
    connection->response_failed = false;
    connection->response_keep_alive = yaza_http_response_keep_alive && !yaza_http_shutdown_requested;
    yaza_http_pending_response_bytes += length;
    return 1;
}

static void yaza_http_connection_reset(yaza_io_driver *driver, yaza_scheduler *scheduler,
                                       yaza_http_connection *connections, size_t index) {
    if (connections[index].worker_cancelled != NULL)
        atomic_store_explicit(connections[index].worker_cancelled, true, memory_order_release);
    uint64_t reader_task_id = connections[index].reader_task_id;
    if (reader_task_id != 0) {
        (void)yaza_io_cancel_task_wait(driver, reader_task_id);
        if (scheduler != NULL) {
            (void)yaza_scheduler_cancel(scheduler, reader_task_id);
            int64_t now_ms = yaza_monotonic_milliseconds();
            uint64_t now_ns = now_ms > 0 ? (uint64_t)now_ms * UINT64_C(1000000) : 0;
            (void)yaza_scheduler_run(scheduler, now_ns, YAZA_SCHEDULER_MAX_TASKS);
            if (!yaza_scheduler_reap(scheduler, reader_task_id))
                fprintf(stderr, "yaza: could not reap HTTP connection reader task\n");
        }
    }
    if (connections[index].fd >= 0) {
        (void)yaza_io_unwatch(driver, connections[index].fd);
        (void)yaza_io_unwatch_write(driver, connections[index].fd);
        close(connections[index].fd);
    }
    if (connections[index].response_buffer != NULL) {
        if (connections[index].response_length <= yaza_http_pending_response_bytes)
            yaza_http_pending_response_bytes -= connections[index].response_length;
        else
            yaza_http_pending_response_bytes = 0;
        free(connections[index].response_buffer);
    }
    connections[index].fd = -1;
    connections[index].remote_ipv4 = 0;
    connections[index].reader_task_id = 0;
    connections[index].io_driver = NULL;
    connections[index].used = 0;
    connections[index].last_activity_ms = 0;
    connections[index].request_started_at_ms = 0;
    connections[index].requests_served = 0;
    connections[index].request_status = 0;
    connections[index].request_length = 0;
    connections[index].request_body = NULL;
    connections[index].request_keep_alive = false;
    connections[index].request_ready = false;
    connections[index].response_buffer = NULL;
    connections[index].response_length = 0;
    connections[index].response_offset = 0;
    connections[index].response_status = 0;
    connections[index].response_started_ms = 0;
    connections[index].response_write_token = 0;
    connections[index].response_pending = false;
    connections[index].response_waiting = false;
    connections[index].response_failed = false;
    connections[index].response_keep_alive = false;
    connections[index].worker_pending = false;
    connections[index].worker_cancelled = NULL;
    connections[index].overwritten_pipeline_byte = '\0';
    connections[index].has_overwritten_pipeline_byte = false;
    connections[index].has_buffered_pipeline = false;
    connections[index].method[0] = '\0';
    connections[index].path[0] = '\0';
    connections[index].request_id[0] = '\0';
    connections[index].request_cors_origin[0] = '\0';
    connections[index].request[0] = '\0';
}

static bool yaza_http_worker_timeout_response(yaza_io_driver *driver,
        yaza_scheduler *scheduler, yaza_http_connection *connections, size_t index) {
    yaza_http_connection *connection = &connections[index];
    if (connection->fd < 0 || !connection->worker_pending) return false;
    if (connection->generation == UINT64_MAX) {
        yaza_http_connection_reset(driver, scheduler, connections, index);
        return true;
    }
    if (connection->worker_cancelled != NULL)
        atomic_store_explicit(connection->worker_cancelled, true, memory_order_release);
    connection->worker_pending = false;
    connection->worker_cancelled = NULL;
    connection->generation++;

    yaza_http_connection *previous_connection = yaza_http_active_connection;
    bool previous_keep_alive = yaza_http_response_keep_alive;
    bool previous_head_request = yaza_http_head_request;
    bool previous_cors_preflight = yaza_http_cors_preflight_active;
    int64_t previous_retry_after = yaza_http_retry_after_seconds;
    int64_t previous_started_ms = yaza_http_current_started_ms;
    char previous_cors_origin[sizeof(yaza_http_cors_response_origin)];
    char previous_method[sizeof(yaza_http_current_method)];
    char previous_path[sizeof(yaza_http_current_path)];
    char previous_request_id[sizeof(yaza_http_current_request_id)];
    memcpy(previous_cors_origin, yaza_http_cors_response_origin, sizeof(previous_cors_origin));
    memcpy(previous_method, yaza_http_current_method, sizeof(previous_method));
    memcpy(previous_path, yaza_http_current_path, sizeof(previous_path));
    memcpy(previous_request_id, yaza_http_current_request_id, sizeof(previous_request_id));

    yaza_http_active_connection = connection;
    yaza_http_response_keep_alive = false;
    yaza_http_head_request = strcmp(connection->method, "HEAD") == 0;
    yaza_http_cors_preflight_active = false;
    yaza_http_retry_after_seconds = 1;
    yaza_http_current_started_ms = connection->request_started_at_ms;
    snprintf(yaza_http_cors_response_origin, sizeof(yaza_http_cors_response_origin), "%s",
             connection->request_cors_origin);
    snprintf(yaza_http_current_method, sizeof(yaza_http_current_method), "%s", connection->method);
    snprintf(yaza_http_current_path, sizeof(yaza_http_current_path), "%s", connection->path);
    snprintf(yaza_http_current_request_id, sizeof(yaza_http_current_request_id), "%s",
             connection->request_id);
    yaza_http_respond(connection->fd, 504, "Gateway Timeout",
        "{\"error\":{\"type\":\"timeout_error\",\"code\":\"request_timeout\"}}");

    yaza_http_active_connection = previous_connection;
    yaza_http_response_keep_alive = previous_keep_alive;
    yaza_http_head_request = previous_head_request;
    yaza_http_cors_preflight_active = previous_cors_preflight;
    yaza_http_retry_after_seconds = previous_retry_after;
    yaza_http_current_started_ms = previous_started_ms;
    memcpy(yaza_http_cors_response_origin, previous_cors_origin, sizeof(previous_cors_origin));
    memcpy(yaza_http_current_method, previous_method, sizeof(previous_method));
    memcpy(yaza_http_current_path, previous_path, sizeof(previous_path));
    memcpy(yaza_http_current_request_id, previous_request_id, sizeof(previous_request_id));

    if (connection->response_failed)
        yaza_http_connection_reset(driver, scheduler, connections, index);
    return true;
}

static uint64_t yaza_http_requests_total = 0;
static uint64_t yaza_http_connections_rejected_total = 0;
static uint64_t yaza_http_accept_backoffs_total = 0;

static void yaza_http_request_shutdown(int signal_number) {
    (void)signal_number;
    yaza_http_shutdown_requested = 1;
}

static bool yaza_http_parse_port(const char *text, int64_t *port) {
    if (text == NULL || *text == '\0') return false;
    uint64_t value = 0;
    for (const unsigned char *cursor = (const unsigned char *)text; *cursor != '\0'; cursor++) {
        if (!isdigit(*cursor)) return false;
        uint64_t digit = (uint64_t)(*cursor - '0');
        if (value > (65535 - digit) / 10) return false;
        value = value * 10 + digit;
    }
    if (value == 0) return false;
    *port = (int64_t)value;
    return true;
}

static bool yaza_http_parse_bounded_positive(const char *text, int64_t minimum,
                                             int64_t maximum, int64_t *value_out) {
    if (text == NULL || *text == '\0' || value_out == NULL || minimum < 1 || maximum < minimum)
        return false;
    uint64_t value = 0;
    for (const unsigned char *cursor = (const unsigned char *)text; *cursor != '\0'; cursor++) {
        if (*cursor < '0' || *cursor > '9') return false;
        uint64_t digit = (uint64_t)(*cursor - '0');
        if (value > ((uint64_t)maximum - digit) / 10) return false;
        value = value * 10 + digit;
    }
    if (value < (uint64_t)minimum || value > (uint64_t)maximum) return false;
    *value_out = (int64_t)value;
    return true;
}

static bool yaza_http_origin_is_valid(const char *origin) {
    const char *authority = NULL;
    if (strncasecmp(origin, "https://", 8) == 0) authority = origin + 8;
    else if (strncasecmp(origin, "http://", 7) == 0) authority = origin + 7;
    if (authority == NULL || *authority == '\0') return false;
    for (const unsigned char *cursor = (const unsigned char *)authority; *cursor != '\0'; cursor++) {
        if (!isalnum(*cursor) && strchr(".-:[]", *cursor) == NULL) return false;
    }
    return true;
}

static bool yaza_dotenv_key_allowed(const char *name) {
    static const char *reserved_names[] = {
        "PATH", "HOME", "SHELL", "IFS", "ENV", "BASH_ENV", "ZDOTDIR",
        "TMPDIR", "TMP", "TEMP", "CC", "CXX", "CPP", "CFLAGS", "CPPFLAGS",
        "LDFLAGS", "SDKROOT", "DEVELOPER_DIR", "YAZA_STDLIB_DIR", "YAZA_RUNTIME_DIR",
        "YAZA_ARGON2_ROOT", "YAZA_TEST_CLI", "YAZA_BOOTSTRAP", "YAZA_CC", "YAZA_CLANG",
        "YAZA_BUILD_MODE", "YAZA_SANITIZE", "ASAN_OPTIONS", "LSAN_OPTIONS",
        "UBSAN_OPTIONS", "TSAN_OPTIONS", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP",
        "NODE_OPTIONS", "NODE_PATH", "RUBYOPT", "RUBYLIB", "PERL5OPT", "PERL5LIB",
        "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "CLASSPATH", "GCONV_PATH", "LOCPATH",
        "NLSPATH", "GLIBC_TUNABLES", "LIBPATH", "SHLIB_PATH", "CPATH", "C_INCLUDE_PATH",
        "CPLUS_INCLUDE_PATH", "OBJC_INCLUDE_PATH", "LIBRARY_PATH", "COMPILER_PATH",
        "GCC_EXEC_PREFIX", "CLANG_CONFIG_FILE_SYSTEM_DIR",
        NULL
    };
    if (name == NULL || !yaza_process_environment_name_allowed(name, strlen(name)) ||
        strncmp(name, "YAZA_TEST_", 10) == 0)
        return false;
    for (size_t index = 0; reserved_names[index] != NULL; index++)
        if (strcmp(name, reserved_names[index]) == 0) return false;
    return true;
}

static void yaza_load_dotenv(void) {
    enum { YAZA_DOTENV_MAX_BYTES = 1024 * 1024 };
    int descriptor = open(".env", O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
    if (descriptor < 0) {
        if (errno != ENOENT) fprintf(stderr, "yaza: cannot securely open .env: %s\n", strerror(errno));
        return;
    }
    struct stat file_status;
    if (fstat(descriptor, &file_status) != 0 || !S_ISREG(file_status.st_mode) ||
        file_status.st_uid != geteuid() || file_status.st_size < 0 ||
        file_status.st_size > YAZA_DOTENV_MAX_BYTES || (file_status.st_mode & S_IRUSR) == 0 ||
        (file_status.st_mode & (S_IRWXG | S_IRWXO | S_IXUSR | S_ISUID | S_ISGID | S_ISVTX)) != 0) {
        close(descriptor);
        fprintf(stderr, "yaza: refusing unsafe .env; require a regular file owned by this user, mode 0400 or 0600, and at most 1 MiB\n");
        return;
    }
    char *contents = (char *)malloc((size_t)YAZA_DOTENV_MAX_BYTES + 1);
    if (contents == NULL) {
        close(descriptor);
        fprintf(stderr, "yaza: cannot allocate bounded .env input\n");
        return;
    }
    size_t contents_length = 0;
    bool read_failed = false;
    while (contents_length < (size_t)YAZA_DOTENV_MAX_BYTES + 1) {
        ssize_t amount = read(descriptor, contents + contents_length,
                              (size_t)YAZA_DOTENV_MAX_BYTES + 1 - contents_length);
        if (amount > 0) contents_length += (size_t)amount;
        else if (amount == 0) break;
        else if (errno != EINTR) { read_failed = true; break; }
    }
    close(descriptor);
    if (read_failed || contents_length > (size_t)YAZA_DOTENV_MAX_BYTES ||
        memchr(contents, '\0', contents_length) != NULL) {
        free(contents);
        fprintf(stderr, "yaza: refusing unreadable, oversized, or binary .env file\n");
        return;
    }

    size_t line_number = 0;
    size_t cursor = 0;
    while (cursor < contents_length) {
        line_number++;
        size_t line_start = cursor;
        while (cursor < contents_length && contents[cursor] != '\n') cursor++;
        size_t length = cursor - line_start;
        if (cursor < contents_length) cursor++;
        if (length > 0 && contents[line_start + length - 1] == '\r') length--;
        if (length >= 4096) {
            fprintf(stderr, "yaza: ignoring oversized .env line %zu\n", line_number);
            continue;
        }
        char line[4096];
        memcpy(line, contents + line_start, length);
        line[length] = '\0';
        char *entry = line;
        while (*entry != '\0' && isspace((unsigned char)*entry)) entry++;
        if (*entry == '\0' || *entry == '#') continue;
        char *equals = strchr(entry, '=');
        if (equals == NULL || equals == entry) {
            fprintf(stderr, "yaza: ignoring invalid .env line %zu\n", line_number);
            continue;
        }
        size_t name_length = (size_t)(equals - entry);
        bool valid_name = name_length < 256 &&
            (isalpha((unsigned char)entry[0]) || entry[0] == '_');
        for (size_t index = 1; valid_name && index < name_length; index++) {
            unsigned char character = (unsigned char)entry[index];
            if (!isalnum(character) && character != '_') valid_name = false;
        }
        if (!valid_name) {
            fprintf(stderr, "yaza: ignoring invalid .env key on line %zu\n", line_number);
            continue;
        }
        char name[256];
        memcpy(name, entry, name_length);
        name[name_length] = '\0';
        if (!yaza_dotenv_key_allowed(name)) {
            fprintf(stderr, "yaza: ignoring reserved .env key on line %zu\n", line_number);
            continue;
        }
        if (getenv(name) != NULL) continue;
        char *value = equals + 1;
        while (*value != '\0' && isspace((unsigned char)*value)) value++;
        char *end = value + strlen(value);
        while (end > value && isspace((unsigned char)end[-1])) end--;
        *end = '\0';
        size_t value_length = (size_t)(end - value);
        if (value_length > 0 && (*value == '\'' || *value == '"')) {
            if (value_length < 2 || value[value_length - 1] != *value) {
                fprintf(stderr, "yaza: ignoring unmatched quote in .env line %zu\n", line_number);
                continue;
            }
            value[value_length - 1] = '\0';
            value++;
        }
        if (setenv(name, value, 0) != 0)
            fprintf(stderr, "yaza: cannot load .env key %s: %s\n", name, strerror(errno));
    }
    free(contents);
}

static char *yaza_env_get(const char *name) {
    const char *value = getenv(name);
    return yaza_copy_text(value == NULL ? "" : value);
}

static int64_t yaza_env_set(const char *name, const char *value) {
    if (name == NULL || *name == '\0' || strchr(name, '=') != NULL || value == NULL) return 1;
    return setenv(name, value, 1) == 0 ? 0 : 1;
}

static int yaza_hex_value(unsigned char value) {
    if (value >= '0' && value <= '9') return value - '0';
    if (value >= 'a' && value <= 'f') return value - 'a' + 10;
    if (value >= 'A' && value <= 'F') return value - 'A' + 10;
    return -1;
}

static int64_t yaza_monotonic_milliseconds(void) {
    struct timespec now;
    if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) return -1;
    return (int64_t)now.tv_sec * 1000 + (int64_t)(now.tv_nsec / 1000000);
}

#define YAZA_NET_MAX_SOCKETS 128
#define YAZA_NET_READ_LIMIT (1024U * 1024U)
#define YAZA_NET_WRITE_LIMIT (64U * 1024U * 1024U)
#define YAZA_NET_TIMEOUT_MAX 3600000

typedef struct {
    atomic_bool active;
    int fd;
    atomic_int_fast64_t handle;
    pthread_mutex_t operation_mutex;
    bool tls_active;
    int64_t tls_deadline_ms;
#if defined(YAZA_WITH_TLS) && defined(__APPLE__)
    SSLContextRef tls_context;
#elif defined(YAZA_WITH_TLS) && defined(__linux__)
    SSL_CTX *tls_context;
    SSL *tls_session;
#endif
} yaza_net_socket;

static yaza_net_socket yaza_net_sockets[YAZA_NET_MAX_SOCKETS];
static int64_t yaza_net_next_handle = 1;
static pthread_mutex_t yaza_net_registry_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_once_t yaza_net_socket_mutexes_once = PTHREAD_ONCE_INIT;
static bool yaza_net_socket_mutexes_ready = false;

static void yaza_net_socket_mutexes_initialize(void) {
    size_t initialized = 0;
    for (; initialized < YAZA_NET_MAX_SOCKETS; initialized++) {
        atomic_init(&yaza_net_sockets[initialized].active, false);
        atomic_init(&yaza_net_sockets[initialized].handle, 0);
        yaza_net_sockets[initialized].fd = -1;
        if (pthread_mutex_init(&yaza_net_sockets[initialized].operation_mutex, NULL) != 0) break;
    }
    if (initialized == YAZA_NET_MAX_SOCKETS) {
        yaza_net_socket_mutexes_ready = true;
        return;
    }
    for (size_t index = 0; index < initialized; index++)
        pthread_mutex_destroy(&yaza_net_sockets[index].operation_mutex);
}

static bool yaza_net_socket_mutexes_ensure(void) {
    return pthread_once(&yaza_net_socket_mutexes_once, yaza_net_socket_mutexes_initialize) == 0 &&
        yaza_net_socket_mutexes_ready;
}

static yaza_result yaza_net_error(const char *message) {
    return yaza_result_err(yaza_option_some_text(yaza_copy_text(message)));
}

/* Returns the matching slot with its operation mutex held. Distinct sockets can
 * make progress concurrently; calls targeting one socket are serialized. */
static int yaza_net_lock_socket(int64_t handle) {
    if (handle <= 0 || !yaza_net_socket_mutexes_ensure()) return -1;
    for (size_t index = 0; index < YAZA_NET_MAX_SOCKETS; index++) {
        if (!atomic_load_explicit(&yaza_net_sockets[index].active, memory_order_acquire) ||
            atomic_load_explicit(&yaza_net_sockets[index].handle, memory_order_relaxed) != handle)
            continue;
        if (pthread_mutex_lock(&yaza_net_sockets[index].operation_mutex) != 0) return -1;
        if (atomic_load_explicit(&yaza_net_sockets[index].active, memory_order_acquire) &&
            atomic_load_explicit(&yaza_net_sockets[index].handle, memory_order_relaxed) == handle)
            return (int)index;
        pthread_mutex_unlock(&yaza_net_sockets[index].operation_mutex);
    }
    return -1;
}

static void yaza_net_unlock_socket(int slot) {
    if (slot >= 0 && (size_t)slot < YAZA_NET_MAX_SOCKETS)
        pthread_mutex_unlock(&yaza_net_sockets[slot].operation_mutex);
}

static bool yaza_net_handle_is_open(int64_t handle) {
    int slot = yaza_net_lock_socket(handle);
    if (slot < 0) return false;
    yaza_net_unlock_socket(slot);
    return true;
}

#if defined(YAZA_WITH_TLS)
static void yaza_net_tls_release(yaza_net_socket *socket) {
    if (socket == NULL) return;
#if defined(__APPLE__)
    if (socket->tls_context != NULL) CFRelease(socket->tls_context);
    socket->tls_context = NULL;
#elif defined(__linux__)
    if (socket->tls_session != NULL) SSL_free(socket->tls_session);
    if (socket->tls_context != NULL) SSL_CTX_free(socket->tls_context);
    socket->tls_session = NULL;
    socket->tls_context = NULL;
#endif
    socket->tls_active = false;
    socket->tls_deadline_ms = 0;
}
#else
static void yaza_net_tls_release(yaza_net_socket *socket) { (void)socket; }
#endif

static void yaza_net_abort_socket(int slot) {
    if (slot < 0 || (size_t)slot >= YAZA_NET_MAX_SOCKETS) return;
    yaza_net_socket *socket = &yaza_net_sockets[slot];
    atomic_store_explicit(&socket->active, false, memory_order_release);
    yaza_net_tls_release(socket);
    if (socket->fd >= 0) close(socket->fd);
    socket->fd = -1;
}

#define YAZA_NET_CANCEL_POLL_SLICE_MS 50

static int yaza_net_wait(int fd, short events, int64_t timeout_ms) {
    if (fd < 0 || timeout_ms < 1) return -1;
    int64_t started = yaza_monotonic_milliseconds();
    if (started < 0) return -1;
    int64_t deadline = started + timeout_ms;
    for (;;) {
        if (yaza_http_request_cancelled()) return -2;
        int64_t now = yaza_monotonic_milliseconds();
        if (now < 0) return -1;
        int64_t remaining = deadline - now;
        if (remaining <= 0) return 0;
        if (remaining > INT_MAX) remaining = INT_MAX;
        if (yaza_http_active_cancelled != NULL &&
            remaining > YAZA_NET_CANCEL_POLL_SLICE_MS)
            remaining = YAZA_NET_CANCEL_POLL_SLICE_MS;
        struct pollfd descriptor = {fd, events, 0};
        int result = poll(&descriptor, 1, (int)remaining);
        if (result > 0) {
            if (yaza_http_request_cancelled()) return -2;
            return descriptor.revents & POLLNVAL ? -1 : 1;
        }
        if (result == 0) {
            if (yaza_http_request_cancelled()) return -2;
            continue;
        }
        if (errno != EINTR) return -1;
    }
}

static yaza_result yaza_net_connect(const char *host, int64_t port, int64_t timeout_ms) {
    if (host == NULL || host[0] == '\0' || strlen(host) > 253)
        return yaza_net_error("network connect requires a host of 1 to 253 bytes");
    if (port < 1 || port > 65535)
        return yaza_net_error("network port must be between 1 and 65535");
    if (timeout_ms < 1 || timeout_ms > YAZA_NET_TIMEOUT_MAX)
        return yaza_net_error("network timeout must be between 1 and 3600000 milliseconds");
    if (!yaza_net_socket_mutexes_ensure())
        return yaza_net_error("network socket registry is unavailable");

    char service[6];
    int service_length = snprintf(service, sizeof(service), "%lld", (long long)port);
    if (service_length <= 0 || (size_t)service_length >= sizeof(service))
        return yaza_net_error("network port is invalid");
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    struct addrinfo *addresses = NULL;
    if (getaddrinfo(host, service, &hints, &addresses) != 0)
        return yaza_net_error("network address lookup failed");

    int64_t started = yaza_monotonic_milliseconds();
    if (started < 0) {
        freeaddrinfo(addresses);
        return yaza_net_error("network clock is unavailable");
    }
    int64_t deadline = started + timeout_ms;
    int connected_fd = -1;
    for (struct addrinfo *address = addresses; address != NULL; address = address->ai_next) {
        if (yaza_http_request_cancelled()) break;
        int64_t now = yaza_monotonic_milliseconds();
        if (now < 0 || now >= deadline) break;
        int fd = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
        if (fd < 0) continue;
        int flags = fcntl(fd, F_GETFL, 0);
        if (flags < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) {
            close(fd);
            continue;
        }
#if defined(SO_NOSIGPIPE)
        int no_sigpipe = 1;
        (void)setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe));
#endif
        int status = connect(fd, address->ai_addr, address->ai_addrlen);
        if (status != 0 && errno != EINPROGRESS && errno != EWOULDBLOCK && errno != EINTR) {
            close(fd);
            continue;
        }
        if (status != 0) {
            int64_t now = yaza_monotonic_milliseconds();
            int64_t remaining = now < 0 ? 0 : deadline - now;
            int ready = remaining > 0 ? yaza_net_wait(fd, POLLOUT, remaining) : 0;
            int socket_error = 0;
            socklen_t error_length = sizeof(socket_error);
            if (ready <= 0 || getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &error_length) != 0 || socket_error != 0) {
                close(fd);
                continue;
            }
        }
        connected_fd = fd;
        break;
    }
    freeaddrinfo(addresses);
    if (connected_fd < 0)
        return yaza_net_error("TCP connection failed or timed out");

    if (pthread_mutex_lock(&yaza_net_registry_mutex) != 0) {
        close(connected_fd);
        return yaza_net_error("network socket registry is unavailable");
    }
    if (yaza_net_next_handle <= 0 || yaza_net_next_handle == INT64_MAX) {
        pthread_mutex_unlock(&yaza_net_registry_mutex);
        close(connected_fd);
        return yaza_net_error("network socket handle space is exhausted");
    }
    size_t free_slot = YAZA_NET_MAX_SOCKETS;
    for (size_t index = 0; index < YAZA_NET_MAX_SOCKETS; index++) {
        if (atomic_load_explicit(&yaza_net_sockets[index].active, memory_order_acquire)) continue;
        if (pthread_mutex_lock(&yaza_net_sockets[index].operation_mutex) != 0) continue;
        if (!atomic_load_explicit(&yaza_net_sockets[index].active, memory_order_acquire)) {
            free_slot = index;
            break;
        }
        pthread_mutex_unlock(&yaza_net_sockets[index].operation_mutex);
    }
    if (free_slot == YAZA_NET_MAX_SOCKETS) {
        pthread_mutex_unlock(&yaza_net_registry_mutex);
        close(connected_fd);
        return yaza_net_error("network socket capacity is full");
    }
    int64_t handle = yaza_net_next_handle++;
    yaza_net_sockets[free_slot].fd = connected_fd;
    yaza_net_sockets[free_slot].tls_active = false;
    yaza_net_sockets[free_slot].tls_deadline_ms = 0;
#if defined(YAZA_WITH_TLS) && defined(__APPLE__)
    yaza_net_sockets[free_slot].tls_context = NULL;
#elif defined(YAZA_WITH_TLS) && defined(__linux__)
    yaza_net_sockets[free_slot].tls_context = NULL;
    yaza_net_sockets[free_slot].tls_session = NULL;
#endif
    atomic_store_explicit(&yaza_net_sockets[free_slot].handle, handle, memory_order_relaxed);
    atomic_store_explicit(&yaza_net_sockets[free_slot].active, true, memory_order_release);
    pthread_mutex_unlock(&yaza_net_sockets[free_slot].operation_mutex);
    pthread_mutex_unlock(&yaza_net_registry_mutex);
    return yaza_result_ok(yaza_option_some_number(handle));
}

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
#if defined(YAZA_WITH_TLS) && defined(__APPLE__)
static OSStatus yaza_net_tls_read_callback(SSLConnectionRef connection, void *data, size_t *data_length) {
    yaza_net_socket *socket = (yaza_net_socket *)connection;
    if (socket == NULL || data_length == NULL) return errSSLInternal;
    size_t capacity = *data_length;
    *data_length = 0;
    int64_t now = yaza_monotonic_milliseconds();
    int64_t remaining = now < 0 ? 0 : socket->tls_deadline_ms - now;
    int ready = remaining > 0 ? yaza_net_wait(socket->fd, POLLIN, remaining) : 0;
    if (ready <= 0) return errSSLWouldBlock;
    ssize_t count;
    do { count = recv(socket->fd, data, capacity, 0); }
    while (count < 0 && errno == EINTR);
    if (count == 0) return errSSLClosedGraceful;
    if (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return errSSLWouldBlock;
    if (count < 0) return errSSLNetworkTimeout;
    *data_length = (size_t)count;
    return noErr;
}

static OSStatus yaza_net_tls_write_callback(SSLConnectionRef connection, const void *data, size_t *data_length) {
    yaza_net_socket *socket = (yaza_net_socket *)connection;
    if (socket == NULL || data_length == NULL) return errSSLInternal;
    size_t requested = *data_length;
    *data_length = 0;
    int64_t now = yaza_monotonic_milliseconds();
    int64_t remaining = now < 0 ? 0 : socket->tls_deadline_ms - now;
    int ready = remaining > 0 ? yaza_net_wait(socket->fd, POLLOUT, remaining) : 0;
    if (ready <= 0) return errSSLWouldBlock;
    int send_flags = 0;
#if defined(MSG_NOSIGNAL)
    send_flags = MSG_NOSIGNAL;
#endif
    ssize_t count;
    do { count = send(socket->fd, data, requested, send_flags); }
    while (count < 0 && errno == EINTR);
    if (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return errSSLWouldBlock;
    if (count <= 0) return errSSLNetworkTimeout;
    *data_length = (size_t)count;
    return noErr;
}

static CFArrayRef yaza_net_tls_load_ca_certificates(const char *path) {
    if (path == NULL || path[0] == '\0' || strnlen(path, 4097) > 4096) return NULL;
    int open_flags = O_RDONLY | O_CLOEXEC;
#ifdef O_NOFOLLOW
    open_flags |= O_NOFOLLOW;
#endif
    int descriptor = open(path, open_flags);
    if (descriptor < 0) return NULL;
    struct stat status;
    if (fstat(descriptor, &status) != 0 || !S_ISREG(status.st_mode) ||
        status.st_size < 1 || status.st_size > 1024 * 1024) {
        close(descriptor);
        return NULL;
    }
    size_t length = (size_t)status.st_size;
    unsigned char *contents = (unsigned char *)malloc(length);
    if (contents == NULL) { close(descriptor); return NULL; }
    size_t offset = 0;
    while (offset < length) {
        ssize_t amount = read(descriptor, contents + offset, length - offset);
        if (amount < 0 && errno == EINTR) continue;
        if (amount <= 0) {
            yaza_secure_wipe(contents, length);
            free(contents);
            close(descriptor);
            return NULL;
        }
        offset += (size_t)amount;
    }
    close(descriptor);
    CFDataRef data = CFDataCreate(kCFAllocatorDefault, contents, (CFIndex)length);
    yaza_secure_wipe(contents, length);
    free(contents);
    if (data == NULL) return NULL;
    SecExternalFormat format = kSecFormatPEMSequence;
    SecExternalItemType item_type = kSecItemTypeAggregate;
    CFArrayRef certificates = NULL;
    OSStatus import_status = SecItemImport(data, NULL, &format, &item_type, 0,
                                           NULL, NULL, &certificates);
    CFRelease(data);
    if (import_status != errSecSuccess || certificates == NULL) {
        if (certificates != NULL) CFRelease(certificates);
        return NULL;
    }
    CFIndex count = CFArrayGetCount(certificates);
    if (count < 1 || count > 32) {
        CFRelease(certificates);
        return NULL;
    }
    for (CFIndex index = 0; index < count; index++) {
        const void *item = CFArrayGetValueAtIndex(certificates, index);
        if (item == NULL || CFGetTypeID(item) != SecCertificateGetTypeID()) {
            CFRelease(certificates);
            return NULL;
        }
    }
    return certificates;
}

static bool yaza_net_tls_verify_peer(SSLContextRef context, const char *hostname,
                                     const char *root_cert_file) {
    SecTrustRef trust = NULL;
    if (SSLCopyPeerTrust(context, &trust) != noErr || trust == NULL) return false;
    CFArrayRef anchors = NULL;
    if (root_cert_file != NULL && root_cert_file[0] != '\0') {
        anchors = yaza_net_tls_load_ca_certificates(root_cert_file);
        if (anchors == NULL ||
            SecTrustSetAnchorCertificates(trust, anchors) != errSecSuccess ||
            SecTrustSetAnchorCertificatesOnly(trust, true) != errSecSuccess) {
            if (anchors != NULL) CFRelease(anchors);
            CFRelease(trust);
            return false;
        }
    }
    CFStringRef host = CFStringCreateWithCString(kCFAllocatorDefault, hostname, kCFStringEncodingUTF8);
    if (host == NULL) {
        if (anchors != NULL) CFRelease(anchors);
        CFRelease(trust);
        return false;
    }
    SecPolicyRef policy = SecPolicyCreateSSL(true, host);
    CFRelease(host);
    if (policy == NULL) {
        if (anchors != NULL) CFRelease(anchors);
        CFRelease(trust);
        return false;
    }
    bool valid = SecTrustSetPolicies(trust, policy) == errSecSuccess &&
                 SecTrustSetNetworkFetchAllowed(trust, false) == errSecSuccess;
    CFRelease(policy);
    if (valid) valid = SecTrustEvaluateWithError(trust, NULL);
    if (anchors != NULL) CFRelease(anchors);
    CFRelease(trust);
    return valid;
}
#endif

#if defined(YAZA_WITH_TLS)
static yaza_result yaza_net_tls_client_on_socket(int slot, const char *hostname,
                                                const char *root_cert_file, int64_t timeout_ms) {
    if (hostname == NULL || hostname[0] == '\0' || strlen(hostname) > 253)
        return yaza_net_error("TLS requires a hostname of 1 to 253 bytes");
    if (root_cert_file == NULL || strnlen(root_cert_file, 4097) > 4096)
        return yaza_net_error("TLS root certificate path exceeds 4096 bytes");
    if (timeout_ms < 1 || timeout_ms > YAZA_NET_TIMEOUT_MAX)
        return yaza_net_error("TLS timeout must be between 1 and 3600000 milliseconds");
    yaza_net_socket *socket = &yaza_net_sockets[slot];
    if (socket->tls_active) return yaza_net_error("TLS is already active on this socket");
    int64_t now = yaza_monotonic_milliseconds();
    if (now < 0) return yaza_net_error("TLS clock is unavailable");
    socket->tls_deadline_ms = now + timeout_ms;
#if defined(__APPLE__)
    SSLContextRef context = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType);
    if (context == NULL) { yaza_net_abort_socket(slot); return yaza_net_error("TLS context creation failed"); }
    socket->tls_context = context;
    OSStatus status = SSLSetIOFuncs(context, yaza_net_tls_read_callback, yaza_net_tls_write_callback);
    if (status == noErr) status = SSLSetConnection(context, (SSLConnectionRef)socket);
    if (status == noErr) status = SSLSetPeerDomainName(context, hostname, strlen(hostname));
    if (status == noErr) status = SSLSetProtocolVersionMin(context, kTLSProtocol12);
    if (status == noErr) status = SSLSetSessionOption(context, kSSLSessionOptionBreakOnServerAuth, true);
    if (status != noErr) { yaza_net_abort_socket(slot); return yaza_net_error("TLS client configuration failed"); }
    for (;;) {
        status = SSLHandshake(context);
        if (status == errSSLServerAuthCompleted) {
            if (!yaza_net_tls_verify_peer(context, hostname, root_cert_file)) {
                yaza_net_abort_socket(slot);
                return yaza_net_error("TLS certificate chain or hostname verification failed");
            }
            status = SSLSetSessionOption(context, kSSLSessionOptionBreakOnServerAuth, false);
            if (status != noErr) break;
            continue;
        }
        if (status == noErr) break;
        if (status != errSSLWouldBlock) break;
        now = yaza_monotonic_milliseconds();
        if (now < 0 || now >= socket->tls_deadline_ms) break;
    }
    if (status != noErr) { yaza_net_abort_socket(slot); return yaza_net_error("TLS handshake failed or timed out"); }
#elif defined(__linux__)
    SSL_CTX *context = SSL_CTX_new(TLS_client_method());
    if (context == NULL || SSL_CTX_set_min_proto_version(context, TLS1_2_VERSION) != 1 ||
        ((root_cert_file[0] == '\0')
            ? SSL_CTX_set_default_verify_paths(context) != 1
            : SSL_CTX_load_verify_locations(context, root_cert_file, NULL) != 1)) {
        if (context != NULL) SSL_CTX_free(context);
        yaza_net_abort_socket(slot);
        return yaza_net_error("TLS provider or system trust store initialization failed");
    }
    SSL_CTX_set_verify(context, SSL_VERIFY_PEER, NULL);
    SSL *session = SSL_new(context);
    if (session == NULL || SSL_set_fd(session, socket->fd) != 1 ||
        SSL_set_tlsext_host_name(session, hostname) != 1 || SSL_set1_host(session, hostname) != 1) {
        if (session != NULL) SSL_free(session);
        SSL_CTX_free(context);
        yaza_net_abort_socket(slot);
        return yaza_net_error("TLS client configuration failed");
    }
    socket->tls_context = context;
    socket->tls_session = session;
    for (;;) {
        int result = SSL_connect(session);
        if (result == 1) break;
        int error = SSL_get_error(session, result);
        short event = error == SSL_ERROR_WANT_READ ? POLLIN : error == SSL_ERROR_WANT_WRITE ? POLLOUT : 0;
        now = yaza_monotonic_milliseconds();
        int64_t remaining = now < 0 ? 0 : socket->tls_deadline_ms - now;
        if (event == 0 || remaining <= 0 || yaza_net_wait(socket->fd, event, remaining) <= 0) {
            yaza_net_abort_socket(slot);
            return yaza_net_error("TLS certificate verification or handshake failed");
        }
    }
    if (SSL_get_verify_result(session) != X509_V_OK) {
        yaza_net_abort_socket(slot);
        return yaza_net_error("TLS certificate chain or hostname verification failed");
    }
#endif
    socket->tls_active = true;
    socket->tls_deadline_ms = 0;
    return yaza_result_ok(yaza_option_some_boolean(true));
}

static yaza_result yaza_net_tls_client_with_ca(int64_t handle, const char *hostname,
                                               const char *root_cert_file, int64_t timeout_ms) {
    int slot = yaza_net_lock_socket(handle);
    if (slot < 0) return yaza_net_error("TLS requires an open TCP socket");
    yaza_result result = yaza_net_tls_client_on_socket(slot, hostname, root_cert_file, timeout_ms);
    yaza_net_unlock_socket(slot);
    return result;
}

static yaza_result yaza_net_tls_client(int64_t handle, const char *hostname, int64_t timeout_ms) {
    return yaza_net_tls_client_with_ca(handle, hostname, "", timeout_ms);
}

static bool yaza_net_tls_is_active(int64_t handle) {
    int slot = yaza_net_lock_socket(handle);
    if (slot < 0) return false;
    bool active = yaza_net_sockets[slot].tls_active;
    yaza_net_unlock_socket(slot);
    return active;
}
#endif

static bool yaza_socket_peer_is_loopback(int fd) {
    if (fd < 0) return false;
    struct sockaddr_storage peer;
    memset(&peer, 0, sizeof(peer));
    socklen_t peer_length = sizeof(peer);
    if (getpeername(fd, (struct sockaddr *)&peer, &peer_length) != 0) return false;
    if (peer.ss_family == AF_INET) {
        const struct sockaddr_in *address = (const struct sockaddr_in *)&peer;
        return (ntohl(address->sin_addr.s_addr) & 0xff000000U) == 0x7f000000U;
    }
    if (peer.ss_family == AF_INET6) {
        const struct sockaddr_in6 *address = (const struct sockaddr_in6 *)&peer;
        if (IN6_IS_ADDR_LOOPBACK(&address->sin6_addr)) return true;
        if (IN6_IS_ADDR_V4MAPPED(&address->sin6_addr))
            return address->sin6_addr.s6_addr[12] == 127;
    }
    return false;
}

static bool yaza_net_peer_is_loopback(int64_t handle) {
    int slot = yaza_net_lock_socket(handle);
    if (slot < 0) return false;
    bool loopback = yaza_socket_peer_is_loopback(yaza_net_sockets[slot].fd);
    yaza_net_unlock_socket(slot);
    return loopback;
}

static yaza_result yaza_net_read_fail(unsigned char *buffer, const char *message) {
    yaza_memory_free(buffer);
    return yaza_net_error(message);
}

static yaza_result yaza_net_read_finish(unsigned char *buffer, size_t count, size_t capacity) {
    if (count > capacity) return yaza_net_read_fail(buffer, "network read returned more bytes than requested");
    if (count == 0) {
        yaza_memory_free(buffer);
        return yaza_result_ok(yaza_option_some_bytes((yaza_bytes){NULL, 0}));
    }
    unsigned char *right_sized = (unsigned char *)yaza_memory_realloc(buffer, count);
    if (right_sized == NULL) return yaza_net_read_fail(buffer, "network read could not retain the received bytes");
    return yaza_result_ok(yaza_option_some_bytes((yaza_bytes){right_sized, count}));
}

static yaza_result yaza_net_read_on_socket(int slot, int64_t maximum_bytes, int64_t timeout_ms) {
    if (maximum_bytes < 1 || maximum_bytes > YAZA_NET_READ_LIMIT)
        return yaza_net_error("network read size must be between 1 and 1048576 bytes");
    if (timeout_ms < 1 || timeout_ms > YAZA_NET_TIMEOUT_MAX)
        return yaza_net_error("network timeout must be between 1 and 3600000 milliseconds");
    if (yaza_http_request_cancelled())
        return yaza_net_error("network read cancelled with request");
    unsigned char *buffer = (unsigned char *)yaza_memory_malloc((size_t)maximum_bytes);
    if (buffer == NULL) return yaza_net_error("network read exceeded the active memory budget");
#if defined(YAZA_WITH_TLS) && defined(__APPLE__)
    if (yaza_net_sockets[slot].tls_active) {
        yaza_net_sockets[slot].tls_deadline_ms = yaza_monotonic_milliseconds() + timeout_ms;
        size_t count = 0;
        OSStatus status = SSLRead(yaza_net_sockets[slot].tls_context, buffer, (size_t)maximum_bytes, &count);
        yaza_net_sockets[slot].tls_deadline_ms = 0;
        if (status == errSSLClosedGraceful || status == errSSLClosedAbort)
            return yaza_net_read_finish(buffer, 0, (size_t)maximum_bytes);
        if (yaza_http_request_cancelled())
            return yaza_net_read_fail(buffer, "TLS read cancelled with request");
        if (status != noErr && !(status == errSSLWouldBlock && count > 0))
            return yaza_net_read_fail(buffer, status == errSSLWouldBlock ? "TLS read timed out" : "TLS read failed");
        return yaza_net_read_finish(buffer, count, (size_t)maximum_bytes);
    }
#elif defined(YAZA_WITH_TLS) && defined(__linux__)
    if (yaza_net_sockets[slot].tls_active) {
        int64_t started = yaza_monotonic_milliseconds();
        if (started < 0) return yaza_net_read_fail(buffer, "network clock is unavailable");
        int64_t deadline = started + timeout_ms;
        for (;;) {
            if (yaza_http_request_cancelled())
                return yaza_net_read_fail(buffer, "TLS read cancelled with request");
            int count = SSL_read(yaza_net_sockets[slot].tls_session, buffer, (int)maximum_bytes);
            if (count > 0) return yaza_net_read_finish(buffer, (size_t)count, (size_t)maximum_bytes);
            int error = SSL_get_error(yaza_net_sockets[slot].tls_session, count);
            if (error == SSL_ERROR_ZERO_RETURN) return yaza_net_read_finish(buffer, 0, (size_t)maximum_bytes);
            short event = error == SSL_ERROR_WANT_READ ? POLLIN : error == SSL_ERROR_WANT_WRITE ? POLLOUT : 0;
            int64_t now = yaza_monotonic_milliseconds();
            int64_t remaining = now < 0 ? 0 : deadline - now;
            if (event == 0) return yaza_net_read_fail(buffer, "TLS read failed");
            if (remaining <= 0) return yaza_net_read_fail(buffer, "TLS read timed out");
            int ready = yaza_net_wait(yaza_net_sockets[slot].fd, event, remaining);
            if (ready == -2) return yaza_net_read_fail(buffer, "TLS read cancelled with request");
            if (ready == 0) return yaza_net_read_fail(buffer, "TLS read timed out");
            if (ready < 0) return yaza_net_read_fail(buffer, "TLS read poll failed");
        }
    }
#endif
    int ready = yaza_net_wait(yaza_net_sockets[slot].fd, POLLIN, timeout_ms);
    if (ready == 0) return yaza_net_read_fail(buffer, "network read timed out");
    if (ready == -2) return yaza_net_read_fail(buffer, "network read cancelled with request");
    if (ready < 0) return yaza_net_read_fail(buffer, "network read poll failed");
    ssize_t count;
    do {
        count = recv(yaza_net_sockets[slot].fd, buffer, (size_t)maximum_bytes, 0);
    } while (count < 0 && errno == EINTR);
    if (count == 0) return yaza_net_read_finish(buffer, 0, (size_t)maximum_bytes);
    if (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
        return yaza_net_read_fail(buffer, "network read timed out");
    if (count < 0) return yaza_net_read_fail(buffer, "network read failed");
    return yaza_net_read_finish(buffer, (size_t)count, (size_t)maximum_bytes);
}

static yaza_result yaza_net_read(int64_t handle, int64_t maximum_bytes, int64_t timeout_ms) {
    int slot = yaza_net_lock_socket(handle);
    if (slot < 0) return yaza_net_error("network socket handle is invalid or closed");
    yaza_result result = yaza_net_read_on_socket(slot, maximum_bytes, timeout_ms);
    yaza_net_unlock_socket(slot);
    return result;
}

static yaza_result yaza_net_write_all_on_socket(int slot, yaza_bytes data, int64_t timeout_ms) {
    if (data.length > YAZA_NET_WRITE_LIMIT)
        return yaza_net_error("network write exceeds the 64 MiB limit");
    if (timeout_ms < 1 || timeout_ms > YAZA_NET_TIMEOUT_MAX)
        return yaza_net_error("network timeout must be between 1 and 3600000 milliseconds");
    if (yaza_http_request_cancelled())
        return yaza_net_error("network write cancelled with request");
    int64_t started = yaza_monotonic_milliseconds();
    if (started < 0) return yaza_net_error("network clock is unavailable");
    int64_t deadline = started + timeout_ms;
#if defined(YAZA_WITH_TLS) && defined(__APPLE__)
    if (yaza_net_sockets[slot].tls_active) {
        yaza_net_sockets[slot].tls_deadline_ms = deadline;
        size_t offset = 0;
        while (offset < data.length) {
            if (yaza_http_request_cancelled()) {
                yaza_net_sockets[slot].tls_deadline_ms = 0;
                return yaza_net_error("TLS write cancelled with request");
            }
            size_t written = 0;
            OSStatus status = SSLWrite(yaza_net_sockets[slot].tls_context, data.data + offset, data.length - offset, &written);
            if (written > 0) offset += written;
            if (status == errSSLWouldBlock && written > 0) continue;
            if (status != noErr || written == 0) {
                yaza_net_sockets[slot].tls_deadline_ms = 0;
                return yaza_net_error(status == errSSLWouldBlock ? "TLS write timed out" : "TLS write failed");
            }
        }
        yaza_net_sockets[slot].tls_deadline_ms = 0;
        return yaza_result_ok(yaza_option_some_boolean(true));
    }
#elif defined(YAZA_WITH_TLS) && defined(__linux__)
    if (yaza_net_sockets[slot].tls_active) {
        size_t offset = 0;
        while (offset < data.length) {
            if (yaza_http_request_cancelled())
                return yaza_net_error("TLS write cancelled with request");
            size_t remaining_data = data.length - offset;
            int requested = remaining_data > INT_MAX ? INT_MAX : (int)remaining_data;
            int written = SSL_write(yaza_net_sockets[slot].tls_session, data.data + offset, requested);
            if (written > 0) { offset += (size_t)written; continue; }
            int error = SSL_get_error(yaza_net_sockets[slot].tls_session, written);
            short event = error == SSL_ERROR_WANT_READ ? POLLIN : error == SSL_ERROR_WANT_WRITE ? POLLOUT : 0;
            int64_t now = yaza_monotonic_milliseconds();
            int64_t remaining = now < 0 ? 0 : deadline - now;
            if (event == 0 || remaining <= 0 || yaza_net_wait(yaza_net_sockets[slot].fd, event, remaining) <= 0)
                return yaza_net_error("TLS write failed or timed out");
        }
        return yaza_result_ok(yaza_option_some_boolean(true));
    }
#endif
    size_t offset = 0;
    while (offset < data.length) {
        if (yaza_http_request_cancelled())
            return yaza_net_error("network write cancelled with request");
        int64_t now = yaza_monotonic_milliseconds();
        int64_t remaining = now < 0 ? 0 : deadline - now;
        int ready = remaining > 0 ? yaza_net_wait(yaza_net_sockets[slot].fd, POLLOUT, remaining) : 0;
        if (ready == 0) return yaza_net_error("network write timed out");
        if (ready == -2) return yaza_net_error("network write cancelled with request");
        if (ready < 0) return yaza_net_error("network write poll failed");
        int send_flags = 0;
#if defined(MSG_NOSIGNAL)
        send_flags = MSG_NOSIGNAL;
#endif
        ssize_t count = send(yaza_net_sockets[slot].fd, data.data + offset, data.length - offset, send_flags);
        if (count < 0 && errno == EINTR) continue;
        if (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue;
        if (count <= 0) return yaza_net_error("network write failed");
        offset += (size_t)count;
    }
    return yaza_result_ok(yaza_option_some_boolean(true));
}

static yaza_result yaza_net_write_all(int64_t handle, yaza_bytes data, int64_t timeout_ms) {
    int slot = yaza_net_lock_socket(handle);
    if (slot < 0) return yaza_net_error("network socket handle is invalid or closed");
    yaza_result result = yaza_net_write_all_on_socket(slot, data, timeout_ms);
    yaza_net_unlock_socket(slot);
    return result;
}

#if defined(__clang__)
#pragma clang diagnostic pop
#endif

static int64_t yaza_net_close(int64_t handle) {
    int slot = yaza_net_lock_socket(handle);
    if (slot < 0) return 1;
    int fd = yaza_net_sockets[slot].fd;
    yaza_net_tls_release(&yaza_net_sockets[slot]);
    atomic_store_explicit(&yaza_net_sockets[slot].active, false, memory_order_release);
    yaza_net_sockets[slot].fd = -1;
    int close_status = close(fd) == 0 ? 0 : 1;
    yaza_net_unlock_socket(slot);
    return close_status;
}

static void yaza_net_shutdown(void) {
    if (!yaza_net_socket_mutexes_ensure()) return;
    for (size_t index = 0; index < YAZA_NET_MAX_SOCKETS; index++) {
        if (pthread_mutex_lock(&yaza_net_sockets[index].operation_mutex) != 0) continue;
        if (atomic_load_explicit(&yaza_net_sockets[index].active, memory_order_acquire)) {
            yaza_net_tls_release(&yaza_net_sockets[index]);
            close(yaza_net_sockets[index].fd);
            atomic_store_explicit(&yaza_net_sockets[index].active, false, memory_order_release);
            yaza_net_sockets[index].fd = -1;
        }
        pthread_mutex_unlock(&yaza_net_sockets[index].operation_mutex);
    }
}

#define YAZA_PG_POOL_CAPACITY 128
#define YAZA_PG_POOL_KEY_BYTES 32
#define YAZA_PG_POOL_MAX_PER_KEY 64
#define YAZA_PG_POOL_MAX_WAIT_MS 300000
#define YAZA_PG_POOL_MAX_IDLE_MS 86400000
#define YAZA_PG_POOL_WAIT_SLICE_MS 50

enum {
    YAZA_PG_POOL_FREE = 0,
    YAZA_PG_POOL_CONNECTING = 1,
    YAZA_PG_POOL_LEASED = 2,
    YAZA_PG_POOL_IDLE = 3
};

typedef struct {
    int state;
    int64_t lease_id;
    unsigned char key[YAZA_PG_POOL_KEY_BYTES];
    int64_t handle;
    int64_t idle_since_ms;
    int64_t last_idle_since_ms;
    int64_t idle_timeout_ms;
} yaza_pg_pool_slot;

static yaza_pg_pool_slot yaza_pg_pool_slots[YAZA_PG_POOL_CAPACITY];
static pthread_mutex_t yaza_pg_pool_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t yaza_pg_pool_changed = PTHREAD_COND_INITIALIZER;
static int64_t yaza_pg_pool_next_lease = 1;
static bool yaza_pg_pool_closing = false;

static yaza_result yaza_pg_pool_error(const char *message) {
    return yaza_result_err(yaza_option_some_text(yaza_copy_text(message)));
}

static int yaza_pg_pool_find_lease_locked(int64_t lease_id) {
    if (lease_id <= 0) return -1;
    for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++)
        if (yaza_pg_pool_slots[index].state != YAZA_PG_POOL_FREE &&
            yaza_pg_pool_slots[index].lease_id == lease_id)
            return (int)index;
    return -1;
}

static void yaza_pg_pool_clear_locked(size_t index) {
    if (index >= YAZA_PG_POOL_CAPACITY) return;
    memset(&yaza_pg_pool_slots[index], 0, sizeof(yaza_pg_pool_slots[index]));
}

static int yaza_pg_pool_cond_wait(int64_t wait_ms) {
    if (wait_ms < 1) return ETIMEDOUT;
    if (wait_ms > YAZA_PG_POOL_WAIT_SLICE_MS) wait_ms = YAZA_PG_POOL_WAIT_SLICE_MS;
    struct timespec until;
    if (clock_gettime(CLOCK_REALTIME, &until) != 0) return EINVAL;
    until.tv_sec += (time_t)(wait_ms / 1000);
    until.tv_nsec += (long)(wait_ms % 1000) * 1000000L;
    if (until.tv_nsec >= 1000000000L) {
        until.tv_sec++;
        until.tv_nsec -= 1000000000L;
    }
    return pthread_cond_timedwait(&yaza_pg_pool_changed, &yaza_pg_pool_mutex, &until);
}

static yaza_result yaza_pg_pool_checkout(yaza_bytes key, int64_t maximum,
                                         int64_t acquire_timeout_ms, int64_t idle_timeout_ms) {
    if (key.length != YAZA_PG_POOL_KEY_BYTES || key.data == NULL)
        return yaza_pg_pool_error("postgres pool: identity must be a 32-byte SHA-256 digest");
    if (maximum < 1 || maximum > YAZA_PG_POOL_MAX_PER_KEY)
        return yaza_pg_pool_error("postgres pool: per-database size must be between 1 and 64");
    if (acquire_timeout_ms < 1 || acquire_timeout_ms > YAZA_PG_POOL_MAX_WAIT_MS)
        return yaza_pg_pool_error("postgres pool: acquisition timeout must be between 1 and 300000 milliseconds");
    if (idle_timeout_ms < 1 || idle_timeout_ms > YAZA_PG_POOL_MAX_IDLE_MS)
        return yaza_pg_pool_error("postgres pool: idle timeout must be between 1 and 86400000 milliseconds");

    int64_t started = yaza_monotonic_milliseconds();
    if (started < 0 || started > INT64_MAX - acquire_timeout_ms)
        return yaza_pg_pool_error("postgres pool: monotonic clock is unavailable");
    int64_t deadline = started + acquire_timeout_ms;

    for (;;) {
        /* API workers may be cancelled while waiting for another request to
         * release a database lease. Do not occupy a worker until the full
         * acquisition timeout after its request has already expired. */
        if (yaza_http_request_cancelled())
            return yaza_pg_pool_error("postgres pool: acquisition cancelled with request");
        int64_t expired_handles[YAZA_PG_POOL_CAPACITY];
        size_t expired_count = 0;
        int64_t lease_id = 0;
        int64_t now = yaza_monotonic_milliseconds();
        if (now < 0) return yaza_pg_pool_error("postgres pool: monotonic clock is unavailable");

        pthread_mutex_lock(&yaza_pg_pool_mutex);
        if (yaza_pg_pool_closing) {
            pthread_mutex_unlock(&yaza_pg_pool_mutex);
            return yaza_pg_pool_error("postgres pool: runtime is shutting down");
        }

        for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++) {
            yaza_pg_pool_slot *slot = &yaza_pg_pool_slots[index];
            if (slot->state == YAZA_PG_POOL_IDLE && slot->idle_timeout_ms > 0 &&
                now >= slot->idle_since_ms && now - slot->idle_since_ms >= slot->idle_timeout_ms) {
                if (slot->handle > 0 && expired_count < YAZA_PG_POOL_CAPACITY)
                    expired_handles[expired_count++] = slot->handle;
                yaza_pg_pool_clear_locked(index);
            }
        }

        int idle_slot = -1;
        size_t matching_count = 0;
        size_t free_slot = YAZA_PG_POOL_CAPACITY;
        for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++) {
            yaza_pg_pool_slot *slot = &yaza_pg_pool_slots[index];
            if (slot->state == YAZA_PG_POOL_FREE) {
                if (free_slot == YAZA_PG_POOL_CAPACITY) free_slot = index;
                continue;
            }
            if (memcmp(slot->key, key.data, YAZA_PG_POOL_KEY_BYTES) == 0) {
                matching_count++;
                if (slot->state == YAZA_PG_POOL_IDLE && idle_slot < 0) idle_slot = (int)index;
            }
        }

        if (yaza_pg_pool_next_lease <= 0 || yaza_pg_pool_next_lease == INT64_MAX) {
            pthread_mutex_unlock(&yaza_pg_pool_mutex);
            for (size_t index = 0; index < expired_count; index++) (void)yaza_net_close(expired_handles[index]);
            return yaza_pg_pool_error("postgres pool: lease identifier space is exhausted");
        }

        if (idle_slot >= 0) {
            yaza_pg_pool_slot *slot = &yaza_pg_pool_slots[idle_slot];
            slot->state = YAZA_PG_POOL_LEASED;
            slot->last_idle_since_ms = slot->idle_since_ms;
            slot->idle_since_ms = 0;
            slot->lease_id = yaza_pg_pool_next_lease++;
            int64_t connection_handle = slot->handle;
            pthread_mutex_unlock(&yaza_pg_pool_mutex);
            for (size_t index = 0; index < expired_count; index++) (void)yaza_net_close(expired_handles[index]);
            return yaza_result_ok(yaza_option_some_number(connection_handle));
        }

        if (matching_count < (size_t)maximum && free_slot < YAZA_PG_POOL_CAPACITY) {
            yaza_pg_pool_slot *slot = &yaza_pg_pool_slots[free_slot];
            memset(slot, 0, sizeof(*slot));
            slot->state = YAZA_PG_POOL_CONNECTING;
            slot->lease_id = yaza_pg_pool_next_lease++;
            slot->idle_timeout_ms = idle_timeout_ms;
            memcpy(slot->key, key.data, YAZA_PG_POOL_KEY_BYTES);
            lease_id = -slot->lease_id;
            pthread_mutex_unlock(&yaza_pg_pool_mutex);
            for (size_t index = 0; index < expired_count; index++) (void)yaza_net_close(expired_handles[index]);
            return yaza_result_ok(yaza_option_some_number(lease_id));
        }

        int64_t remaining = deadline - now;
        if (remaining <= 0) {
            pthread_mutex_unlock(&yaza_pg_pool_mutex);
            for (size_t index = 0; index < expired_count; index++) (void)yaza_net_close(expired_handles[index]);
            return yaza_pg_pool_error("postgres pool: acquisition timed out at the configured size limit");
        }
        int wait_status = yaza_pg_pool_cond_wait(remaining);
        pthread_mutex_unlock(&yaza_pg_pool_mutex);
        for (size_t index = 0; index < expired_count; index++) (void)yaza_net_close(expired_handles[index]);
        if (wait_status != 0 && wait_status != ETIMEDOUT)
            return yaza_pg_pool_error("postgres pool: acquisition wait failed");
    }
}

static bool yaza_pg_pool_read_limit(const char *name, int64_t default_value,
                                    int64_t minimum, int64_t maximum, int64_t *output) {
    if (name == NULL || output == NULL) return false;
    const char *value = getenv(name);
    if (value == NULL || value[0] == '\0') {
        *output = default_value;
        return true;
    }
    size_t length = strnlen(value, 11);
    if (length == 0 || length > 10) return false;
    int64_t parsed = 0;
    for (size_t index = 0; index < length; index++) {
        unsigned char byte = (unsigned char)value[index];
        if (byte < '0' || byte > '9') return false;
        int64_t digit = (int64_t)(byte - '0');
        if (parsed > (maximum - digit) / 10) return false;
        parsed = parsed * 10 + digit;
    }
    if (parsed < minimum || parsed > maximum) return false;
    *output = parsed;
    return true;
}

static yaza_result yaza_pg_pool_checkout_environment(yaza_bytes key) {
    int64_t maximum = 8;
    int64_t acquire_timeout_ms = 5000;
    int64_t idle_timeout_ms = 60000;
    if (!yaza_pg_pool_read_limit("YAZA_PG_POOL_SIZE", 8, 1, YAZA_PG_POOL_MAX_PER_KEY, &maximum) ||
        !yaza_pg_pool_read_limit("YAZA_PG_POOL_ACQUIRE_TIMEOUT_MS", 5000, 1, YAZA_PG_POOL_MAX_WAIT_MS, &acquire_timeout_ms) ||
        !yaza_pg_pool_read_limit("YAZA_PG_POOL_IDLE_TIMEOUT_MS", 60000, 1, YAZA_PG_POOL_MAX_IDLE_MS, &idle_timeout_ms))
        return yaza_pg_pool_error("postgres pool: configuration is outside a supported positive integer range");
    return yaza_pg_pool_checkout(key, maximum, acquire_timeout_ms, idle_timeout_ms);
}

static yaza_bytes yaza_pg_pool_environment_identity(void) {
    static const char *names[] = {
        "DATABASE_URL", "PGHOST", "PGPORT", "PGUSER", "PGDATABASE", "PGPASSWORD",
        "PGSSLMODE", "PGSSLROOTCERT", "PGAPPNAME", "PGOPTIONS", "PGTARGETSESSIONATTRS",
        "PGCHANNELBINDING", "PGGSSENCMODE"
    };
    unsigned char material[65536];
    size_t cursor = 0;
    for (size_t index = 0; index < sizeof(names) / sizeof(names[0]); index++) {
        const char *value = getenv(names[index]);
        if (value == NULL) value = "";
        size_t length = strnlen(value, 8193);
        if (length > 8192 || cursor > sizeof(material) - 4 ||
            length > sizeof(material) - cursor - 4) {
            yaza_secure_wipe(material, sizeof(material));
            return (yaza_bytes){NULL, 0};
        }
        uint32_t size = (uint32_t)length;
        material[cursor++] = (unsigned char)(size >> 24);
        material[cursor++] = (unsigned char)(size >> 16);
        material[cursor++] = (unsigned char)(size >> 8);
        material[cursor++] = (unsigned char)size;
        if (length != 0) memcpy(material + cursor, value, length);
        cursor += length;
    }
    yaza_bytes digest = yaza_crypto_sha256((yaza_bytes){material, cursor});
    yaza_secure_wipe(material, sizeof(material));
    return digest;
}

static bool yaza_pg_pool_attach(int64_t reservation_token, int64_t handle) {
    if (reservation_token >= 0 || reservation_token == INT64_MIN || handle <= 0) return false;
    pthread_mutex_lock(&yaza_pg_pool_mutex);
    int slot_index = yaza_pg_pool_find_lease_locked(-reservation_token);
    bool attached = slot_index >= 0 && !yaza_pg_pool_closing &&
                    yaza_pg_pool_slots[slot_index].state == YAZA_PG_POOL_CONNECTING;
    if (attached) {
        yaza_pg_pool_slots[slot_index].state = YAZA_PG_POOL_LEASED;
        yaza_pg_pool_slots[slot_index].handle = handle;
    }
    pthread_cond_broadcast(&yaza_pg_pool_changed);
    pthread_mutex_unlock(&yaza_pg_pool_mutex);
    return attached;
}

static bool yaza_pg_pool_needs_ping(int64_t connection_handle, int64_t interval_ms) {
    if (interval_ms < 1 || interval_ms > YAZA_PG_POOL_MAX_IDLE_MS) return true;
    int64_t now = yaza_monotonic_milliseconds();
    if (now < 0) return true;
    pthread_mutex_lock(&yaza_pg_pool_mutex);
    int slot_index = -1;
    if (connection_handle > 0) {
        for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++) {
            if (yaza_pg_pool_slots[index].state == YAZA_PG_POOL_LEASED &&
                yaza_pg_pool_slots[index].handle == connection_handle) {
                slot_index = (int)index;
                break;
            }
        }
    }
    bool needs_ping = slot_index < 0;
    if (slot_index >= 0) {
        int64_t idle_since = yaza_pg_pool_slots[slot_index].last_idle_since_ms;
        needs_ping = idle_since > 0 && (now < idle_since || now - idle_since >= interval_ms);
    }
    pthread_mutex_unlock(&yaza_pg_pool_mutex);
    return needs_ping;
}

static bool yaza_pg_pool_release(int64_t connection_or_reservation, bool healthy) {
    int64_t close_handle = 0;
    bool released = false;
    int64_t now = yaza_monotonic_milliseconds();
    pthread_mutex_lock(&yaza_pg_pool_mutex);
    int slot_index = -1;
    if (connection_or_reservation < 0 && connection_or_reservation != INT64_MIN) {
        slot_index = yaza_pg_pool_find_lease_locked(-connection_or_reservation);
        if (slot_index >= 0 && yaza_pg_pool_slots[slot_index].state != YAZA_PG_POOL_CONNECTING)
            slot_index = -1;
    } else if (connection_or_reservation > 0) {
        for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++) {
            if (yaza_pg_pool_slots[index].state == YAZA_PG_POOL_LEASED &&
                yaza_pg_pool_slots[index].handle == connection_or_reservation) {
                slot_index = (int)index;
                break;
            }
        }
    }
    if (slot_index >= 0) {
        yaza_pg_pool_slot *slot = &yaza_pg_pool_slots[slot_index];
        if (healthy && !yaza_pg_pool_closing && slot->state == YAZA_PG_POOL_LEASED &&
            slot->handle > 0 && now >= 0 && yaza_net_handle_is_open(slot->handle)) {
            slot->state = YAZA_PG_POOL_IDLE;
            slot->lease_id = 0;
            slot->idle_since_ms = now;
            slot->last_idle_since_ms = now;
            released = true;
        } else {
            close_handle = slot->handle;
            yaza_pg_pool_clear_locked((size_t)slot_index);
            released = true;
        }
        pthread_cond_broadcast(&yaza_pg_pool_changed);
    }
    pthread_mutex_unlock(&yaza_pg_pool_mutex);
    if (close_handle > 0) (void)yaza_net_close(close_handle);
    return released;
}

typedef struct {
    size_t connections;
    size_t idle;
    size_t leased;
    size_t connecting;
} yaza_pg_pool_counts;

static bool yaza_pg_pool_snapshot(yaza_bytes key, yaza_pg_pool_counts *output) {
    if (output == NULL) return false;
    memset(output, 0, sizeof(*output));
    if (key.length != YAZA_PG_POOL_KEY_BYTES || key.data == NULL) return false;
    pthread_mutex_lock(&yaza_pg_pool_mutex);
    for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++) {
        const yaza_pg_pool_slot *slot = &yaza_pg_pool_slots[index];
        if (slot->state == YAZA_PG_POOL_FREE ||
            memcmp(slot->key, key.data, YAZA_PG_POOL_KEY_BYTES) != 0) continue;
        output->connections++;
        if (slot->state == YAZA_PG_POOL_IDLE) output->idle++;
        else if (slot->state == YAZA_PG_POOL_LEASED) output->leased++;
        else if (slot->state == YAZA_PG_POOL_CONNECTING) output->connecting++;
    }
    pthread_mutex_unlock(&yaza_pg_pool_mutex);
    return true;
}

static char *yaza_pg_pool_stats(yaza_bytes key) {
    yaza_pg_pool_counts counts;
    if (!yaza_pg_pool_snapshot(key, &counts)) return yaza_copy_text("{}");
    char output[192];
    int length = snprintf(output, sizeof(output),
                          "{\"connections\":%zu,\"idle\":%zu,\"leased\":%zu,\"connecting\":%zu}",
                          counts.connections, counts.idle, counts.leased, counts.connecting);
    if (length < 0 || (size_t)length >= sizeof(output)) return yaza_copy_text("{}");
    return yaza_copy_text(output);
}

static void yaza_pg_pool_shutdown(int64_t timeout_ms) {
    if (timeout_ms < 0 || timeout_ms > YAZA_PG_POOL_MAX_WAIT_MS) timeout_ms = 0;
    int64_t started = yaza_monotonic_milliseconds();
    int64_t deadline = started < 0 || started > INT64_MAX - timeout_ms ? started : started + timeout_ms;
    int64_t close_handles[YAZA_PG_POOL_CAPACITY];
    size_t close_count = 0;
    pthread_mutex_lock(&yaza_pg_pool_mutex);
    yaza_pg_pool_closing = true;
    pthread_cond_broadcast(&yaza_pg_pool_changed);
    for (;;) {
        bool active_lease = false;
        for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++) {
            int state = yaza_pg_pool_slots[index].state;
            if (state == YAZA_PG_POOL_CONNECTING || state == YAZA_PG_POOL_LEASED) {
                active_lease = true;
                break;
            }
        }
        if (!active_lease) break;
        int64_t now = yaza_monotonic_milliseconds();
        if (timeout_ms == 0 || now < 0 || now >= deadline) break;
        int wait_status = yaza_pg_pool_cond_wait(deadline - now);
        if (wait_status != 0 && wait_status != ETIMEDOUT) break;
    }
    for (size_t index = 0; index < YAZA_PG_POOL_CAPACITY; index++) {
        if (yaza_pg_pool_slots[index].handle > 0 && close_count < YAZA_PG_POOL_CAPACITY)
            close_handles[close_count++] = yaza_pg_pool_slots[index].handle;
        yaza_pg_pool_clear_locked(index);
    }
    pthread_cond_broadcast(&yaza_pg_pool_changed);
    pthread_mutex_unlock(&yaza_pg_pool_mutex);
    for (size_t index = 0; index < close_count; index++) (void)yaza_net_close(close_handles[index]);
}

struct yaza_http_resource {
    char *path;
    char *schema;
    char *items[YAZA_HTTP_MAX_RECORDS];
    size_t count;
    size_t next_id;
};

/* Shared by worker-dispatched in-memory repositories; socket state remains event-loop-owned. */
static pthread_mutex_t yaza_http_resources_mutex = PTHREAD_MUTEX_INITIALIZER;

static bool yaza_json_object_id(const char *json, char *output, size_t capacity);

#ifdef YAZA_WITH_POSTGRES
static PGconn *yaza_http_database = NULL;

static bool yaza_pg_result_is_tuples(PGresult *result) {
    return result != NULL && PQresultStatus(result) == PGRES_TUPLES_OK;
}

static bool yaza_pg_result_is_command(PGresult *result) {
    return result != NULL && PQresultStatus(result) == PGRES_COMMAND_OK;
}

static bool yaza_pg_copy_option(PQconninfoOption *options, const char *name,
                                char *output, size_t capacity, bool *present) {
    if (capacity == 0 || present == NULL) return false;
    output[0] = '\0';
    *present = false;
    for (PQconninfoOption *option = options; option != NULL && option->keyword != NULL; option++) {
        if (strcmp(option->keyword, name) != 0 || option->val == NULL) continue;
        size_t length = strlen(option->val);
        if (length >= capacity) return false;
        memcpy(output, option->val, length + 1);
        *present = true;
        return true;
    }
    return true;
}

static bool yaza_pg_ip_text_is_loopback(const char *value) {
    if (value == NULL || *value == '\0') return false;
    struct in_addr ipv4;
    if (inet_pton(AF_INET, value, &ipv4) == 1)
        return (ntohl(ipv4.s_addr) & 0xff000000U) == 0x7f000000U;
    struct in6_addr ipv6;
    if (inet_pton(AF_INET6, value, &ipv6) == 1) {
        if (IN6_IS_ADDR_LOOPBACK(&ipv6)) return true;
        if (IN6_IS_ADDR_V4MAPPED(&ipv6)) return ipv6.s6_addr[12] == 127;
    }
    return false;
}

static bool yaza_pg_requested_host_is_loopback(const char *host, const char *hostaddr) {
    if (host == NULL) return false;
    bool host_is_loopback = yaza_pg_ip_text_is_loopback(host) ||
        (strcmp(host, "localhost") == 0 && yaza_pg_ip_text_is_loopback(hostaddr));
    if (!host_is_loopback) return false;
    return hostaddr == NULL || *hostaddr == '\0' || yaza_pg_ip_text_is_loopback(hostaddr);
}

static bool yaza_pg_connection_policy(const char *database_url, char *sslmode,
                                     size_t sslmode_capacity) {
    char *parse_error = NULL;
    PQconninfoOption *options = PQconninfoParse(database_url, &parse_error);
    if (options == NULL) {
        if (parse_error != NULL) PQfreemem(parse_error);
        return false;
    }

    char requested_mode[64] = "";
    char requested_host[256] = "";
    char requested_hostaddr[64] = "";
    bool has_mode = false;
    bool has_host = false;
    bool has_hostaddr = false;
    bool parsed = yaza_pg_copy_option(options, "sslmode", requested_mode, sizeof(requested_mode), &has_mode) &&
        yaza_pg_copy_option(options, "host", requested_host, sizeof(requested_host), &has_host) &&
        yaza_pg_copy_option(options, "hostaddr", requested_hostaddr, sizeof(requested_hostaddr), &has_hostaddr);
    PQconninfoFree(options);
    if (!parsed) return false;

    if (!has_mode || requested_mode[0] == '\0') {
        const char *environment_mode = getenv("PGSSLMODE");
        if (environment_mode != NULL && *environment_mode != '\0') {
            size_t length = strlen(environment_mode);
            if (length >= sizeof(requested_mode)) return false;
            memcpy(requested_mode, environment_mode, length + 1);
        } else {
            memcpy(requested_mode, "prefer", sizeof("prefer"));
        }
    }

    if (!has_host || requested_host[0] == '\0') {
        const char *environment_host = getenv("PGHOST");
        if (environment_host != NULL && *environment_host != '\0') {
            size_t length = strlen(environment_host);
            if (length >= sizeof(requested_host)) return false;
            memcpy(requested_host, environment_host, length + 1);
        }
    }
    if (!has_hostaddr || requested_hostaddr[0] == '\0') {
        const char *environment_hostaddr = getenv("PGHOSTADDR");
        if (environment_hostaddr != NULL && *environment_hostaddr != '\0') {
            size_t length = strlen(environment_hostaddr);
            if (length >= sizeof(requested_hostaddr)) return false;
            memcpy(requested_hostaddr, environment_hostaddr, length + 1);
        }
    }

    if (strlen(requested_mode) >= sslmode_capacity) return false;
    memcpy(sslmode, requested_mode, strlen(requested_mode) + 1);
    if (strcmp(requested_mode, "disable") == 0)
        return yaza_pg_requested_host_is_loopback(requested_host, requested_hostaddr);
    return strcmp(requested_mode, "verify-full") == 0;
}

static bool yaza_pg_connected_security_policy(PGconn *connection, const char *sslmode) {
    if (strcmp(sslmode, "disable") == 0)
        return PQsslInUse(connection) == 0 && yaza_socket_peer_is_loopback(PQsocket(connection));
    if (strcmp(sslmode, "verify-full") == 0)
        return PQsslInUse(connection) != 0;
    return false;
}

static void yaza_pg_log_failure(PGresult *result) {
    const char *state = result == NULL ? NULL : PQresultErrorField(result, PG_DIAG_SQLSTATE);
    fprintf(stderr, "YAZA PostgreSQL error (SQLSTATE %s)\n", state == NULL ? "unknown" : state);
}

static PGresult *yaza_pg_query(const char *sql, int parameter_count, const char *const *values) {
    if (yaza_http_database == NULL || PQstatus(yaza_http_database) != CONNECTION_OK) return NULL;
    PGresult *result = PQexecParams(yaza_http_database, sql, parameter_count, NULL, values, NULL, NULL, 0);
    if (!yaza_pg_result_is_tuples(result) && !yaza_pg_result_is_command(result)) yaza_pg_log_failure(result);
    return result;
}

static char *yaza_pg_load_one(const char *resource, const char *id) {
    const char *values[] = {resource, id};
    PGresult *result = yaza_pg_query(
        "SELECT payload::text FROM yaza_api_records WHERE resource = $1 AND id = $2",
        2, values);
    if (!yaza_pg_result_is_tuples(result) || PQntuples(result) == 0) {
        if (result != NULL) PQclear(result);
        return NULL;
    }
    char *payload = yaza_copy_text(PQgetvalue(result, 0, 0));
    PQclear(result);
    return payload;
}

static bool yaza_pg_seed(yaza_http_resource *resource) {
    for (size_t index = 0; index < resource->count; index++) {
        char id[128];
        if (!yaza_json_object_id(resource->items[index], id, sizeof(id))) continue;
        const char *values[] = {resource->path, id, resource->items[index]};
        PGresult *result = yaza_pg_query(
            "INSERT INTO yaza_api_records(resource, id, payload) VALUES ($1, $2, $3::jsonb) ON CONFLICT (resource, id) DO NOTHING",
            3, values);
        bool ok = yaza_pg_result_is_command(result);
        if (result != NULL) PQclear(result);
        if (!ok) return false;
    }
    return true;
}

static bool yaza_pg_connect(const char *database_url, yaza_http_resource *resources, size_t resource_count) {
    char sslmode[64];
    if (!yaza_pg_connection_policy(database_url, sslmode, sizeof(sslmode))) {
        fprintf(stderr,
                "YAZA PostgreSQL connection rejected by transport policy; use sslmode=verify-full remotely or explicit sslmode=disable on loopback (details redacted)\n");
        return false;
    }
    const char *keys[] = {"dbname", "connect_timeout", NULL};
    const char *values[] = {database_url, "5", NULL};
    yaza_http_database = PQconnectdbParams(keys, values, 1);
    if (yaza_http_database == NULL || PQstatus(yaza_http_database) != CONNECTION_OK) {
        fprintf(stderr, "YAZA PostgreSQL connection failed; verify DATABASE_URL and database availability (details redacted)\n");
        if (yaza_http_database != NULL) {
            PQfinish(yaza_http_database);
            yaza_http_database = NULL;
        }
        return false;
    }
    if (!yaza_pg_connected_security_policy(yaza_http_database, sslmode)) {
        fprintf(stderr, "YAZA PostgreSQL connection rejected by transport policy after peer verification (details redacted)\n");
        PQfinish(yaza_http_database);
        yaza_http_database = NULL;
        return false;
    }
    PGresult *timeouts = PQexec(yaza_http_database,
        "SET statement_timeout = '3000ms'; SET lock_timeout = '2000ms'; SET idle_in_transaction_session_timeout = '10000ms'");
    bool timeouts_set = yaza_pg_result_is_command(timeouts);
    if (timeouts != NULL) PQclear(timeouts);
    if (!timeouts_set) {
        fprintf(stderr, "YAZA could not configure PostgreSQL statement and transaction timeouts\n");
        PQfinish(yaza_http_database);
        yaza_http_database = NULL;
        return false;
    }
    PGresult *result = PQexec(yaza_http_database,
        "SELECT to_regclass('public.yaza_api_records') IS NOT NULL");
    bool migrated = yaza_pg_result_is_tuples(result) && PQntuples(result) == 1 &&
        strcmp(PQgetvalue(result, 0, 0), "t") == 0;
    if (result != NULL) PQclear(result);
    if (!migrated) {
        fprintf(stderr, "YAZA PostgreSQL schema is missing; run `yaza db migrate` from the project directory\n");
        PQfinish(yaza_http_database);
        yaza_http_database = NULL;
        return false;
    }
    for (size_t index = 0; index < resource_count; index++) {
        if (!yaza_pg_seed(&resources[index])) {
            fprintf(stderr, "YAZA could not initialize the PostgreSQL sample data\n");
            PQfinish(yaza_http_database);
            yaza_http_database = NULL;
            return false;
        }
    }
    return true;
}
#endif

typedef struct {
    const char *key;
    size_t key_length;
    const char *value;
    size_t value_length;
    char name[128];
    bool used;
} yaza_json_field;

static const char *yaza_json_skip_space(const char *cursor) {
    while (*cursor != '\0' && isspace((unsigned char)*cursor)) cursor++;
    return cursor;
}

static const char *yaza_json_skip_string(const char *cursor) {
    if (*cursor != '"') return NULL;
    const char *start = cursor;
    cursor++;
    while (*cursor != '\0') {
        unsigned char value = (unsigned char)*cursor;
        if (value == '"') {
            size_t content_length = (size_t)(cursor - start - 1);
            return yaza_utf8_valid((const unsigned char *)start + 1, content_length) ? cursor + 1 : NULL;
        }
        if (value < 0x20) return NULL;
        if (value != '\\') { cursor++; continue; }
        cursor++;
        if (*cursor == '\0') return NULL;
        if (strchr("\"\\/bfnrt", *cursor) != NULL) { cursor++; continue; }
        if (*cursor != 'u') return NULL;
        uint32_t codepoint = 0;
        for (int digit = 0; digit < 4; digit++) {
            cursor++;
            int hex = yaza_hex_value((unsigned char)*cursor);
            if (hex < 0) return NULL;
            codepoint = (codepoint << 4) | (uint32_t)hex;
        }
        cursor++;
        if (codepoint >= 0xd800 && codepoint <= 0xdbff) {
            if (*cursor != '\\' || cursor[1] != 'u') return NULL;
            cursor += 2;
            uint32_t low_surrogate = 0;
            for (int digit = 0; digit < 4; digit++) {
                if (*cursor == '\0') return NULL;
                int hex = yaza_hex_value((unsigned char)*cursor++);
                if (hex < 0) return NULL;
                low_surrogate = (low_surrogate << 4) | (uint32_t)hex;
            }
            if (low_surrogate < 0xdc00 || low_surrogate > 0xdfff) return NULL;
        } else if (codepoint >= 0xdc00 && codepoint <= 0xdfff) {
            return NULL;
        }
    }
    return NULL;
}

static bool yaza_json_append_codepoint(char *output, size_t capacity, size_t *used, uint32_t codepoint) {
    unsigned char encoded[4];
    size_t length;
    if (codepoint == 0) return false;
    if (codepoint <= 0x7f) {
        encoded[0] = (unsigned char)codepoint;
        length = 1;
    } else if (codepoint <= 0x7ff) {
        encoded[0] = (unsigned char)(0xc0 | (codepoint >> 6));
        encoded[1] = (unsigned char)(0x80 | (codepoint & 0x3f));
        length = 2;
    } else if (codepoint <= 0xffff && (codepoint < 0xd800 || codepoint > 0xdfff)) {
        encoded[0] = (unsigned char)(0xe0 | (codepoint >> 12));
        encoded[1] = (unsigned char)(0x80 | ((codepoint >> 6) & 0x3f));
        encoded[2] = (unsigned char)(0x80 | (codepoint & 0x3f));
        length = 3;
    } else if (codepoint <= 0x10ffff) {
        encoded[0] = (unsigned char)(0xf0 | (codepoint >> 18));
        encoded[1] = (unsigned char)(0x80 | ((codepoint >> 12) & 0x3f));
        encoded[2] = (unsigned char)(0x80 | ((codepoint >> 6) & 0x3f));
        encoded[3] = (unsigned char)(0x80 | (codepoint & 0x3f));
        length = 4;
    } else {
        return false;
    }
    if (length >= capacity || *used > capacity - length - 1) return false;
    memcpy(output + *used, encoded, length);
    *used += length;
    return true;
}

static bool yaza_json_decode_string(const char *json, size_t length, char *output, size_t capacity) {
    if (json == NULL || output == NULL || capacity == 0 || length < 2 ||
        json[0] != '"' || json[length - 1] != '"') return false;
    size_t used = 0;
    size_t index = 1;
    size_t end = length - 1;
    while (index < end) {
        unsigned char character = (unsigned char)json[index++];
        if (character != '\\') {
            if (used + 1 >= capacity) return false;
            output[used++] = (char)character;
            continue;
        }
        if (index >= end) return false;
        unsigned char escaped = (unsigned char)json[index++];
        if (escaped == '"' || escaped == '\\' || escaped == '/') character = escaped;
        else if (escaped == 'b') character = '\b';
        else if (escaped == 'f') character = '\f';
        else if (escaped == 'n') character = '\n';
        else if (escaped == 'r') character = '\r';
        else if (escaped == 't') character = '\t';
        else if (escaped == 'u') {
            uint32_t codepoint = 0;
            for (int digit = 0; digit < 4; digit++) {
                if (index >= end) return false;
                int hex = yaza_hex_value((unsigned char)json[index++]);
                if (hex < 0) return false;
                codepoint = (codepoint << 4) | (uint32_t)hex;
            }
            if (codepoint >= 0xd800 && codepoint <= 0xdbff) {
                if (end - index < 6 || json[index] != '\\' || json[index + 1] != 'u') return false;
                index += 2;
                uint32_t low_surrogate = 0;
                for (int digit = 0; digit < 4; digit++) {
                    int hex = yaza_hex_value((unsigned char)json[index++]);
                    if (hex < 0) return false;
                    low_surrogate = (low_surrogate << 4) | (uint32_t)hex;
                }
                if (low_surrogate < 0xdc00 || low_surrogate > 0xdfff) return false;
                codepoint = 0x10000 + ((codepoint - 0xd800) << 10) + (low_surrogate - 0xdc00);
            } else if (codepoint >= 0xdc00 && codepoint <= 0xdfff) {
                return false;
            }
            if (codepoint == 0) return false;
            if (!yaza_json_append_codepoint(output, capacity, &used, codepoint)) return false;
            continue;
        } else {
            return false;
        }
        if (character == 0 || used + 1 >= capacity) return false;
        output[used++] = (char)character;
    }
    output[used] = '\0';
    return yaza_utf8_valid((const unsigned char *)output, used);
}

static const char *yaza_json_skip_value_depth(const char *cursor, size_t depth) {
    if (depth >= YAZA_HTTP_MAX_JSON_DEPTH) return NULL;
    cursor = yaza_json_skip_space(cursor);
    if (*cursor == '"') return yaza_json_skip_string(cursor);
    if (*cursor == '{') {
        cursor++;
        cursor = yaza_json_skip_space(cursor);
        if (*cursor == '}') return cursor + 1;
        char keys[YAZA_HTTP_MAX_JSON_FIELDS][128];
        size_t key_count = 0;
        for (;;) {
            if (*cursor != '"' || key_count == YAZA_HTTP_MAX_JSON_FIELDS) return NULL;
            const char *key_start = cursor;
            const char *key_end = yaza_json_skip_string(cursor);
            if (key_end == NULL) return NULL;
            size_t key_length = (size_t)(key_end - key_start);
            if (!yaza_json_decode_string(key_start, key_length, keys[key_count], sizeof(keys[key_count]))) return NULL;
            for (size_t prior = 0; prior < key_count; prior++) {
                if (strcmp(keys[prior], keys[key_count]) == 0) return NULL;
            }
            key_count++;
            cursor = yaza_json_skip_space(key_end);
            if (*cursor != ':') return NULL;
            cursor = yaza_json_skip_value_depth(cursor + 1, depth + 1);
            if (cursor == NULL) return NULL;
            cursor = yaza_json_skip_space(cursor);
            if (*cursor == '}') return cursor + 1;
            if (*cursor != ',') return NULL;
            cursor = yaza_json_skip_space(cursor + 1);
        }
    }
    if (*cursor == '[') {
        cursor = yaza_json_skip_space(cursor + 1);
        if (*cursor == ']') return cursor + 1;
        for (;;) {
            cursor = yaza_json_skip_value_depth(cursor, depth + 1);
            if (cursor == NULL) return NULL;
            cursor = yaza_json_skip_space(cursor);
            if (*cursor == ']') return cursor + 1;
            if (*cursor != ',') return NULL;
            cursor = yaza_json_skip_space(cursor + 1);
        }
    }
    if (strncmp(cursor, "true", 4) == 0) return cursor + 4;
    if (strncmp(cursor, "false", 5) == 0) return cursor + 5;
    if (strncmp(cursor, "null", 4) == 0) return cursor + 4;

    const char *number = cursor;
    if (*number == '-') number++;
    if (*number == '0') {
        number++;
        if (isdigit((unsigned char)*number)) return NULL;
    } else {
        if (*number < '1' || *number > '9') return NULL;
        do { number++; } while (isdigit((unsigned char)*number));
    }
    if (*number == '.') {
        number++;
        if (!isdigit((unsigned char)*number)) return NULL;
        do { number++; } while (isdigit((unsigned char)*number));
    }
    if (*number == 'e' || *number == 'E') {
        number++;
        if (*number == '+' || *number == '-') number++;
        if (!isdigit((unsigned char)*number)) return NULL;
        do { number++; } while (isdigit((unsigned char)*number));
    }
    return number;
}

static const char *yaza_json_skip_value(const char *cursor) {
    return yaza_json_skip_value_depth(cursor, 0);
}

static int yaza_json_object_fields(const char *json, yaza_json_field *fields, size_t capacity) {
    const char *cursor = yaza_json_skip_space(json);
    if (*cursor != '{') return -1;
    cursor++;
    size_t count = 0;
    for (;;) {
        cursor = yaza_json_skip_space(cursor);
        if (*cursor == '}') return *yaza_json_skip_space(cursor + 1) == '\0' ? (int)count : -1;
        if (*cursor != '"' || count == capacity) return -1;
        const char *key_start = cursor;
        const char *key_end = yaza_json_skip_string(cursor);
        if (key_end == NULL) return -1;
        size_t key_length = (size_t)(key_end - key_start);
        if (!yaza_json_decode_string(key_start, key_length, fields[count].name, sizeof(fields[count].name))) return -1;
        for (size_t prior = 0; prior < count; prior++)
            if (strcmp(fields[prior].name, fields[count].name) == 0) return -1;
        fields[count].key = key_start;
        fields[count].key_length = key_length;
        cursor = yaza_json_skip_space(key_end);
        if (*cursor != ':') return -1;
        cursor = yaza_json_skip_space(cursor + 1);
        const char *value_end = yaza_json_skip_value(cursor);
        if (value_end == NULL) return -1;
        fields[count].value = cursor;
        fields[count].value_length = (size_t)(value_end - cursor);
        fields[count].used = false;
        count++;
        cursor = yaza_json_skip_space(value_end);
        if (*cursor == '}') return (int)count;
        if (*cursor != ',') return -1;
        cursor++;
    }
}

static char yaza_json_value_kind(const char *value) {
    value = yaza_json_skip_space(value);
    if (*value == '"') return 's';
    if (*value == '{') return 'o';
    if (*value == '[') return 'a';
    if (*value == 't' || *value == 'f') return 'b';
    if (*value == 'n') return 'n';
    if (*value == '-' || isdigit((unsigned char)*value)) return 'd';
    return '?';
}

static const yaza_json_field *yaza_json_snapshot_find_field(const yaza_json_field *fields,
                                                             int count, const char *name) {
    for (int index = 0; index < count; index++)
        if (strcmp(fields[index].name, name) == 0) return &fields[index];
    return NULL;
}

static bool yaza_json_snapshot_text_is_valid(const yaza_json_field *field, bool require_nonempty) {
    if (field == NULL || yaza_json_value_kind(field->value) != 's' || field->value_length < 2) return false;
    if (require_nonempty && field->value_length == 2) return false;
    for (size_t index = 1; index + 1 < field->value_length; index++) {
        if (field->value[index] != '\\') continue;
        index++;
        if (index + 4 < field->value_length && field->value[index] == 'u' &&
            field->value[index + 1] == '0' && field->value[index + 2] == '0' &&
            field->value[index + 3] == '0' && field->value[index + 4] == '0') return false;
        if (field->value[index] == 'u') index += 4;
    }
    return true;
}

static bool yaza_json_snapshot_object_from_span(const char *json, size_t length,
                                                yaza_json_field *fields, int *field_count,
                                                char **owned_object) {
    if (json == NULL || fields == NULL || field_count == NULL || owned_object == NULL ||
        length == 0 || length > YAZA_MAX_BYTES)
        return false;
    char *object = (char *)malloc(length + 1);
    if (object == NULL) return false;
    memcpy(object, json, length);
    object[length] = '\0';
    *field_count = yaza_json_object_fields(object, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (*field_count < 0) {
        free(object);
        return false;
    }
    *owned_object = object;
    return true;
}

static bool yaza_json_snapshot_validate_columns(const yaza_json_field *field);
static bool yaza_json_snapshot_validate_constraints(const yaza_json_field *field);

static bool yaza_json_snapshot_validate_object_array(const yaza_json_field *array_field,
                                                      const char *object_kind) {
    if (array_field == NULL || yaza_json_value_kind(array_field->value) != 'a') return false;
    const char *cursor = yaza_json_skip_space(array_field->value);
    const char *end = cursor + array_field->value_length;
    if (cursor >= end || *cursor != '[') return false;
    cursor = yaza_json_skip_space(cursor + 1);
    while (cursor < end && *cursor != ']') {
        const char *item_end = yaza_json_skip_value(cursor);
        if (item_end == NULL || item_end > end || yaza_json_value_kind(cursor) != 'o') return false;
        yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
        int count = 0;
        char *object_storage = NULL;
        if (!yaza_json_snapshot_object_from_span(cursor, (size_t)(item_end - cursor), fields, &count, &object_storage)) return false;

        bool valid = false;
        if (strcmp(object_kind, "table") == 0 && count == 4) {
            const yaza_json_field *schema = yaza_json_snapshot_find_field(fields, count, "schema");
            const yaza_json_field *name = yaza_json_snapshot_find_field(fields, count, "name");
            const yaza_json_field *columns = yaza_json_snapshot_find_field(fields, count, "columns");
            const yaza_json_field *constraints = yaza_json_snapshot_find_field(fields, count, "constraints");
            valid = yaza_json_snapshot_text_is_valid(schema, true) &&
                yaza_json_snapshot_text_is_valid(name, true) &&
                yaza_json_snapshot_validate_columns(columns) &&
                yaza_json_snapshot_validate_constraints(constraints);
        } else if (strcmp(object_kind, "column") == 0 && count == 4) {
            const yaza_json_field *name = yaza_json_snapshot_find_field(fields, count, "name");
            const yaza_json_field *type = yaza_json_snapshot_find_field(fields, count, "type");
            const yaza_json_field *nullable = yaza_json_snapshot_find_field(fields, count, "nullable");
            const yaza_json_field *default_value = yaza_json_snapshot_find_field(fields, count, "default");
            valid = yaza_json_snapshot_text_is_valid(name, true) &&
                yaza_json_snapshot_text_is_valid(type, true) && nullable != NULL &&
                yaza_json_value_kind(nullable->value) == 'b' && default_value != NULL &&
                (yaza_json_value_kind(default_value->value) == 'n' ||
                 yaza_json_snapshot_text_is_valid(default_value, false));
        } else if (strcmp(object_kind, "constraint") == 0 && count == 6) {
            const yaza_json_field *name = yaza_json_snapshot_find_field(fields, count, "name");
            const yaza_json_field *kind = yaza_json_snapshot_find_field(fields, count, "kind");
            const yaza_json_field *definition = yaza_json_snapshot_find_field(fields, count, "definition");
            const yaza_json_field *deferrable = yaza_json_snapshot_find_field(fields, count, "deferrable");
            const yaza_json_field *deferred = yaza_json_snapshot_find_field(fields, count, "initially_deferred");
            const yaza_json_field *validated = yaza_json_snapshot_find_field(fields, count, "validated");
            char decoded_kind[32];
            const char *allowed_kinds[] = {"primary_key", "unique", "foreign_key", "check", "exclusion"};
            bool kind_valid = false;
            if (kind != NULL && kind->value_length < sizeof(decoded_kind) &&
                yaza_json_decode_string(kind->value, kind->value_length, decoded_kind, sizeof(decoded_kind))) {
                for (size_t index = 0; index < sizeof(allowed_kinds) / sizeof(allowed_kinds[0]); index++)
                    if (strcmp(decoded_kind, allowed_kinds[index]) == 0) kind_valid = true;
            }
            valid = yaza_json_snapshot_text_is_valid(name, true) && kind_valid &&
                yaza_json_snapshot_text_is_valid(definition, true) && deferrable != NULL &&
                deferred != NULL && validated != NULL && yaza_json_value_kind(deferrable->value) == 'b' &&
                yaza_json_value_kind(deferred->value) == 'b' && yaza_json_value_kind(validated->value) == 'b';
        }
        free(object_storage);
        if (!valid) return false;
        cursor = yaza_json_skip_space(item_end);
        if (cursor >= end) return false;
        if (*cursor == ',') cursor = yaza_json_skip_space(cursor + 1);
        else if (*cursor != ']') return false;
    }
    if (cursor >= end || *cursor != ']') return false;
    cursor++;
    return cursor == end;
}

static bool yaza_json_snapshot_validate_columns(const yaza_json_field *field) {
    return yaza_json_snapshot_validate_object_array(field, "column");
}

static bool yaza_json_snapshot_validate_constraints(const yaza_json_field *field) {
    return yaza_json_snapshot_validate_object_array(field, "constraint");
}

static bool yaza_json_snapshot_validate_tables(const yaza_json_field *field) {
    return yaza_json_snapshot_validate_object_array(field, "table");
}

static bool yaza_json_snapshot_sha256_is_valid(const yaza_json_field *field) {
    if (field == NULL || yaza_json_value_kind(field->value) != 's' || field->value_length != 66)
        return false;
    for (size_t index = 1; index < 65; index++) {
        unsigned char value = (unsigned char)field->value[index];
        if (!((value >= '0' && value <= '9') || (value >= 'a' && value <= 'f'))) return false;
    }
    return true;
}

static char *yaza_postgres_schema_snapshot_error(const char *json) {
    if (json == NULL) return "snapshot is missing";
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int count = yaza_json_object_fields(json, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (count != 4) return "expected a format-version-2 object with format_version, postgres_major_version, migration_fingerprint, and tables";
    const yaza_json_field *format = yaza_json_snapshot_find_field(fields, count, "format_version");
    const yaza_json_field *version = yaza_json_snapshot_find_field(fields, count, "postgres_major_version");
    const yaza_json_field *migration_fingerprint = yaza_json_snapshot_find_field(fields, count, "migration_fingerprint");
    const yaza_json_field *tables = yaza_json_snapshot_find_field(fields, count, "tables");
    if (format == NULL || format->value_length != 1 || format->value[0] != '2')
        return "unsupported or missing format_version (supported version: 2)";
    if (!yaza_json_snapshot_sha256_is_valid(migration_fingerprint))
        return "migration_fingerprint must be a lowercase SHA-256 hexadecimal string";
    char version_text[32];
    if (version == NULL || version->value_length >= sizeof(version_text) ||
        !yaza_json_decode_string(version->value, version->value_length, version_text, sizeof(version_text)))
        return "postgres_major_version must be a PostgreSQL major-version string";
    size_t version_length = strlen(version_text);
    if (version_length == 0 || version_text[0] < '1' || version_text[0] > '9')
        return "postgres_major_version has an invalid value";
    bool seen_dot = false;
    for (size_t index = 0; index < version_length; index++) {
        if (version_text[index] == '.' && !seen_dot && index > 0 && index + 1 < version_length) {
            seen_dot = true;
            continue;
        }
        if (version_text[index] < '0' || version_text[index] > '9')
            return "postgres_major_version has an invalid value";
    }
    if (!yaza_json_snapshot_validate_tables(tables))
        return "tables must contain valid table, column, and constraint records for snapshot format 2";
    return "";
}

static bool yaza_postgres_schema_snapshot_matches_migrations(const char *json,
                                                              const char *expected_fingerprint) {
    if (json == NULL || expected_fingerprint == NULL || strlen(expected_fingerprint) != 64) return false;
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int count = yaza_json_object_fields(json, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (count != 4) return false;
    const yaza_json_field *fingerprint = yaza_json_snapshot_find_field(fields, count, "migration_fingerprint");
    if (!yaza_json_snapshot_sha256_is_valid(fingerprint)) return false;
    char actual[65];
    if (!yaza_json_decode_string(fingerprint->value, fingerprint->value_length, actual, sizeof(actual))) return false;
    return strcmp(actual, expected_fingerprint) == 0;
}

static bool yaza_json_object_matches_schema(const char *json, const char *schema,
                                            bool partial, bool allow_id,
                                            yaza_http_validation_error *error) {
    yaza_json_field values[YAZA_HTTP_MAX_JSON_FIELDS];
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int value_count = yaza_json_object_fields(json, values, YAZA_HTTP_MAX_JSON_FIELDS);
    int field_count = yaza_json_object_fields(schema, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (value_count < 0 || field_count < 0) {
        yaza_http_validation_error_set(error, "$", "invalid_object");
        return false;
    }

    for (int index = 0; index < value_count; index++) {
        int field_index = -1;
        for (int candidate = 0; candidate < field_count; candidate++) {
            if (strcmp(values[index].name, fields[candidate].name) == 0) {
                field_index = candidate;
                break;
            }
        }
        if (field_index < 0) {
            yaza_http_validation_error_set(error, "$", "unknown_field");
            return false;
        }
        if (strcmp(values[index].name, "id") == 0 && !allow_id) {
            yaza_http_validation_error_set_child(error, "", "id", "invalid_value");
            return false;
        }
        if (yaza_json_value_kind(values[index].value) !=
            yaza_json_value_kind(fields[field_index].value)) {
            yaza_http_validation_error_set_child(error, "", fields[field_index].name, "invalid_type");
            return false;
        }
    }

    if (!partial) {
        for (int field_index = 0; field_index < field_count; field_index++) {
            if (strcmp(fields[field_index].name, "id") == 0) continue;
            bool found = false;
            for (int index = 0; index < value_count; index++) {
                if (strcmp(values[index].name, fields[field_index].name) == 0) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                yaza_http_validation_error_set_child(error, "", fields[field_index].name, "required");
                return false;
            }
        }
    }
    return true;
}

static bool yaza_json_field_text(const yaza_json_field *field, char *output, size_t capacity) {
    const char *value = yaza_json_skip_space(field->value);
    size_t length = field->value_length;
    if (length == 0 || capacity == 0) return false;
    if (*value == '"') {
        if (length < 2 || value[length - 1] != '"') return false;
        value++;
        length -= 2;
        size_t written = 0;
        for (size_t index = 0; index < length; index++) {
            if (value[index] == '\\') {
                if (index + 1 >= length || written + 1 >= capacity) return false;
                index++;
                char escaped = value[index];
                if (escaped == '"' || escaped == '\\' || escaped == '/') output[written++] = escaped;
                else return false;
            } else {
                if (written + 1 >= capacity) return false;
                output[written++] = value[index];
            }
        }
        output[written] = '\0';
        return true;
    }
    if (length >= capacity) return false;
    memcpy(output, value, length);
    output[length] = '\0';
    return true;
}

static bool yaza_http_json_text_list(const yaza_json_field *field, yaza_text_list **output,
                                     const char *field_path,
                                     yaza_http_validation_error *error) {
    if (field == NULL || output == NULL || field->value == NULL) {
        yaza_http_validation_error_set(error, field_path, "invalid_type");
        return false;
    }
    const char *cursor = yaza_json_skip_space(field->value);
    const char *end = field->value + field->value_length;
    if (cursor >= end || *cursor != '[') {
        yaza_http_validation_error_set(error, field_path, "invalid_type");
        return false;
    }
    cursor++;
    yaza_text_list *items = yaza_text_list_new();
    for (;;) {
        cursor = yaza_json_skip_space(cursor);
        if (cursor > end) {
            yaza_http_validation_error_set(error, field_path, "invalid_value");
            return false;
        }
        if (cursor < end && *cursor == ']') {
            cursor++;
            if (yaza_json_skip_space(cursor) != end) {
                yaza_http_validation_error_set(error, field_path, "invalid_value");
                return false;
            }
            *output = items;
            return true;
        }
        if (items->length >= YAZA_HTTP_MAX_JSON_FIELDS) {
            yaza_http_validation_error_set(error, field_path, "max_items");
            return false;
        }
        if (cursor >= end || *cursor != '"') {
            yaza_http_validation_error_set_index(error, field_path, items->length, "invalid_type");
            return false;
        }
        const char *value_end = yaza_json_skip_value(cursor);
        if (value_end == NULL || value_end > end || yaza_json_value_kind(cursor) != 's') {
            yaza_http_validation_error_set_index(error, field_path, items->length, "invalid_type");
            return false;
        }
        char value[1024];
        if (!yaza_json_decode_string(cursor, (size_t)(value_end - cursor), value, sizeof(value))) {
            yaza_http_validation_error_set_index(error, field_path, items->length, "invalid_value");
            return false;
        }
        if (yaza_list_push(items, value) != 0) {
            yaza_http_validation_error_set(error, field_path, "invalid_value");
            return false;
        }
        cursor = yaza_json_skip_space(value_end);
        if (cursor >= end) {
            yaza_http_validation_error_set(error, field_path, "invalid_value");
            return false;
        }
        if (*cursor == ',') {
            cursor++;
            continue;
        }
        if (*cursor == ']') {
            cursor++;
            if (yaza_json_skip_space(cursor) != end) {
                yaza_http_validation_error_set(error, field_path, "invalid_value");
                return false;
            }
            *output = items;
            return true;
        }
        yaza_http_validation_error_set(error, field_path, "invalid_value");
        return false;
    }
}

static size_t yaza_utf8_character_count(const char *text) {
    if (text == NULL) return 0;
    size_t count = 0;
    const unsigned char *cursor = (const unsigned char *)text;
    while (*cursor != '\0') {
        if ((*cursor & 0xc0) != 0x80) count++;
        cursor++;
    }
    return count;
}

static bool yaza_http_value_matches(const char *value, const char *value_type) {
    if (strcmp(value_type, "Text") == 0) return true;
    if (strcmp(value_type, "Boolean") == 0) return strcmp(value, "true") == 0 || strcmp(value, "false") == 0;
    if (strcmp(value_type, "Float64") == 0) {
        if (!yaza_float64_text_valid(value)) return false;
        errno = 0;
        char *end = NULL;
        double parsed = strtod(value, &end);
        return errno == 0 && end != value && *end == '\0' && isfinite(parsed);
    }
    bool int32_value = strcmp(value_type, "Int32") == 0;
    if ((!int32_value && strcmp(value_type, "Number") != 0) || *value == '\0') return false;
    const unsigned char *cursor = (const unsigned char *)value;
    if (*cursor == '-') cursor++;
    if (!isdigit(*cursor)) return false;
    while (isdigit(*cursor)) cursor++;
    if (*cursor != '\0') return false;
    errno = 0;
    char *end = NULL;
    long long parsed = strtoll(value, &end, 10);
    if (errno != 0 || end == value || *end != '\0') return false;
    return !int32_value || (parsed >= INT32_MIN && parsed <= INT32_MAX);
}

static bool yaza_http_json_typed_list(const yaza_json_field *field, const char *item_type,
                                     yaza_typed_list **output, const char *field_path,
                                     yaza_http_validation_error *error) {
    if (field == NULL || field->value == NULL || item_type == NULL || output == NULL) {
        yaza_http_validation_error_set(error, field_path, "invalid_type");
        return false;
    }
    size_t element_size = 0;
    if (strcmp(item_type, "Text") == 0) element_size = sizeof(const char *);
    else if (strcmp(item_type, "Number") == 0) element_size = sizeof(int64_t);
    else if (strcmp(item_type, "Int32") == 0) element_size = sizeof(int32_t);
    else if (strcmp(item_type, "Float64") == 0) element_size = sizeof(double);
    else if (strcmp(item_type, "Boolean") == 0) element_size = sizeof(bool);
    else {
        yaza_http_validation_error_set(error, field_path, "invalid_type");
        return false;
    }
    const char *cursor = yaza_json_skip_space(field->value);
    const char *end = field->value + field->value_length;
    if (cursor >= end || *cursor != '[') {
        yaza_http_validation_error_set(error, field_path, "invalid_type");
        return false;
    }
    yaza_typed_list *items = yaza_typed_list_new(element_size, item_type);
    cursor = yaza_json_skip_space(cursor + 1);
    size_t count = 0;
    while (cursor < end && *cursor != ']') {
        if (count >= YAZA_HTTP_MAX_JSON_FIELDS) {
            yaza_http_validation_error_set(error, field_path, "max_items");
            return false;
        }
        const char *item_end = yaza_json_skip_value(cursor);
        if (item_end == NULL || item_end <= cursor || item_end > end) {
            yaza_http_validation_error_set(error, field_path, "invalid_value");
            return false;
        }
        size_t item_length = (size_t)(item_end - cursor);
        char scalar[1024];
        if (strcmp(item_type, "Text") == 0) {
            if (yaza_json_value_kind(cursor) != 's') {
                yaza_http_validation_error_set_index(error, field_path, count, "invalid_type");
                return false;
            }
            if (!yaza_json_decode_string(cursor, item_length, scalar, sizeof(scalar))) {
                yaza_http_validation_error_set_index(error, field_path, count, "invalid_value");
                return false;
            }
            const char *text = yaza_copy_text(scalar);
            yaza_typed_list_push(items, &text, element_size, item_type);
        } else {
            char expected_kind = strcmp(item_type, "Boolean") == 0 ? 'b' : 'd';
            if (yaza_json_value_kind(cursor) != expected_kind) {
                yaza_http_validation_error_set_index(error, field_path, count, "invalid_type");
                return false;
            }
            if (item_length >= sizeof(scalar)) {
                yaza_http_validation_error_set_index(error, field_path, count, "invalid_value");
                return false;
            }
            memcpy(scalar, cursor, item_length);
            scalar[item_length] = '\0';
            if (!yaza_http_value_matches(scalar, item_type)) {
                yaza_http_validation_error_set_index(error, field_path, count, "invalid_value");
                return false;
            }
            if (strcmp(item_type, "Number") == 0) {
                int64_t value = (int64_t)strtoll(scalar, NULL, 10);
                yaza_typed_list_push(items, &value, element_size, item_type);
            } else if (strcmp(item_type, "Int32") == 0) {
                int32_t value = (int32_t)strtol(scalar, NULL, 10);
                yaza_typed_list_push(items, &value, element_size, item_type);
            } else if (strcmp(item_type, "Float64") == 0) {
                double value = strtod(scalar, NULL);
                yaza_typed_list_push(items, &value, element_size, item_type);
            } else {
                bool value = strcmp(scalar, "true") == 0;
                yaza_typed_list_push(items, &value, element_size, item_type);
            }
        }
        count++;
        cursor = yaza_json_skip_space(item_end);
        if (cursor >= end) return false;
        if (*cursor == ',') cursor = yaza_json_skip_space(cursor + 1);
        else if (*cursor != ']') return false;
    }
    if (cursor >= end || *cursor != ']' || yaza_json_skip_space(cursor + 1) != end) {
        yaza_http_validation_error_set(error, field_path, "invalid_value");
        return false;
    }
    *output = items;
    return true;
}

static const yaza_json_field *yaza_http_json_field_find(const yaza_json_field *fields, int count, const char *name) {
    for (int index = 0; index < count; index++)
        if (strcmp(fields[index].name, name) == 0) return &fields[index];
    return NULL;
}

static int yaza_http_metadata_success_status(const char *metadata) {
    if (metadata == NULL || *metadata == '\0') return 0;
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int count = yaza_json_object_fields(metadata, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (count < 0) return -1;
    const yaza_json_field *field = yaza_http_json_field_find(fields, count, "responseStatus");
    if (field == NULL) return 0;
    if (yaza_json_value_kind(field->value) != 'd' || field->value_length != 3) return -1;
    char text[4];
    memcpy(text, field->value, 3);
    text[3] = '\0';
    if (!yaza_http_value_matches(text, "Number")) return -1;
    int status = atoi(text);
    return status == 200 || status == 201 || status == 202 || status == 204 ? status : -1;
}

static int yaza_http_metadata_auth_policy(const char *metadata) {
    if (metadata == NULL || *metadata == '\0') return 0;
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int count = yaza_json_object_fields(metadata, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (count < 0) return -1;
    const yaza_json_field *field = yaza_http_json_field_find(fields, count, "auth");
    if (field == NULL) return 0;
    char policy[16];
    if (!yaza_json_field_text(field, policy, sizeof(policy))) return -1;
    if (strcmp(policy, "public") == 0) return 1;
    if (strcmp(policy, "required") == 0) return 2;
    if (strcmp(policy, "jwt") == 0) return 3;
    return -1;
}

static bool yaza_http_metadata_cors_origin(const char *metadata, char *output, size_t capacity) {
    if (output == NULL || capacity == 0) return false;
    output[0] = '\0';
    if (metadata == NULL || *metadata == '\0') return true;
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int count = yaza_json_object_fields(metadata, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (count < 0) return false;
    const yaza_json_field *field = yaza_http_json_field_find(fields, count, "corsOrigin");
    if (field == NULL) return true;
    if (yaza_json_value_kind(field->value) != 's' ||
        !yaza_json_field_text(field, output, capacity) ||
        !yaza_http_origin_is_valid(output)) {
        output[0] = '\0';
        return false;
    }
    return true;
}

static bool yaza_http_metadata_rate_limit(const char *metadata, int64_t *request_capacity,
                                          int64_t *window_ms, uint64_t *scope_id) {
    if (request_capacity == NULL || window_ms == NULL || scope_id == NULL) return false;
    *request_capacity = 0;
    *window_ms = 0;
    *scope_id = 0;
    if (metadata == NULL || *metadata == '\0') return true;
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int count = yaza_json_object_fields(metadata, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (count < 0) return false;
    const yaza_json_field *requests_field = yaza_http_json_field_find(fields, count, "rateLimitRequests");
    const yaza_json_field *window_field = yaza_http_json_field_find(fields, count, "rateLimitWindowMs");
    const yaza_json_field *scope_field = yaza_http_json_field_find(fields, count, "rateLimitScope");
    if (requests_field == NULL && window_field == NULL && scope_field == NULL) return true;
    if (requests_field == NULL || window_field == NULL || scope_field == NULL ||
        yaza_json_value_kind(requests_field->value) != 'd' ||
        yaza_json_value_kind(window_field->value) != 'd') return false;
    char requests_text[16];
    char window_text[16];
    char scope[2048];
    if (requests_field->value_length >= sizeof(requests_text) ||
        window_field->value_length >= sizeof(window_text) ||
        !yaza_json_field_text(scope_field, scope, sizeof(scope)) || scope[0] != '/') return false;
    memcpy(requests_text, requests_field->value, requests_field->value_length);
    requests_text[requests_field->value_length] = '\0';
    memcpy(window_text, window_field->value, window_field->value_length);
    window_text[window_field->value_length] = '\0';
    int64_t requests = 0;
    int64_t window = 0;
    if (!yaza_http_parse_bounded_positive(requests_text, 1, 100000, &requests) ||
        !yaza_http_parse_bounded_positive(window_text, 1000, 3600000, &window)) return false;
    uint64_t policy_id = yaza_http_rate_limit_scope_id(scope, requests, window);
    if (policy_id == 0) return false;
    *request_capacity = requests;
    *window_ms = window;
    *scope_id = policy_id;
    return true;
}

static char *yaza_http_json_copy_field_value(const yaza_json_field *field) {
    if (field == NULL || field->value == NULL || field->value_length >= YAZA_HTTP_REQUEST_CAPACITY) return NULL;
    char *copy = (char *)malloc(field->value_length + 1);
    if (copy == NULL) return NULL;
    memcpy(copy, field->value, field->value_length);
    copy[field->value_length] = '\0';
    return copy;
}

static bool yaza_http_handler_json_response_valid(const char *body) {
    if (body == NULL) return false;
    size_t length = 0;
    while (length < YAZA_HTTP_REQUEST_CAPACITY && body[length] != '\0') length++;
    if (length == 0 || length >= YAZA_HTTP_REQUEST_CAPACITY) return false;
    const char *end = yaza_json_skip_value(body);
    return end != NULL && *yaza_json_skip_space(end) == '\0';
}

static bool yaza_http_worker_response_reserve(size_t bytes) {
    size_t current = atomic_load_explicit(&yaza_http_worker_response_bytes, memory_order_relaxed);
    for (;;) {
        if (current > YAZA_HTTP_RESPONSE_PENDING_MAX_BYTES ||
            bytes > YAZA_HTTP_RESPONSE_PENDING_MAX_BYTES - current) return false;
        if (atomic_compare_exchange_weak_explicit(&yaza_http_worker_response_bytes,
                &current, current + bytes, memory_order_acq_rel, memory_order_relaxed)) return true;
    }
}

static void yaza_http_worker_response_release(const yaza_http_handler_output *output) {
    if (output != NULL && output->body_budget_reserved)
        atomic_fetch_sub_explicit(&yaza_http_worker_response_bytes, output->body_length,
                                  memory_order_acq_rel);
}

static int yaza_http_handler_worker_run(void *opaque, const atomic_bool *cancelled,
                                        int64_t deadline_ms, void **result_out) {
    yaza_http_handler_job *job = (yaza_http_handler_job *)opaque;
    if (job == NULL || result_out == NULL || yaza_http_handler_dispatch == NULL) return EINVAL;
    if (deadline_ms > 0) {
        int64_t now_ms = yaza_monotonic_milliseconds();
        if (now_ms < 0) return EIO;
        if (now_ms >= deadline_ms) return ETIMEDOUT;
    }
    if ((cancelled != NULL && atomic_load_explicit(cancelled, memory_order_acquire)) ||
        atomic_load_explicit(&job->cancelled, memory_order_acquire)) return ECANCELED;

    yaza_http_handler_output *output = (yaza_http_handler_output *)yaza_system_calloc(1, sizeof(*output));
    if (output == NULL) return ENOMEM;
    yaza_memory_arena request_arena;
    yaza_memory_arena_init(&request_arena, YAZA_REQUEST_MEMORY_LIMIT);
    yaza_memory_arena *previous_arena = yaza_memory_arena_enter(&request_arena);

    const yaza_http_request_context *previous_request = yaza_http_active_request;
    int previous_response_status = yaza_http_handler_response_status;
    const atomic_bool *previous_cancelled = yaza_http_active_cancelled;
    yaza_http_connection *previous_connection = yaza_http_active_connection;
    bool previous_keep_alive = yaza_http_response_keep_alive;
    bool previous_head_request = yaza_http_head_request;
    int64_t previous_started_ms = yaza_http_current_started_ms;
    char previous_method[sizeof(yaza_http_current_method)];
    char previous_path[sizeof(yaza_http_current_path)];
    char previous_request_id[sizeof(yaza_http_current_request_id)];
    memcpy(previous_method, yaza_http_current_method, sizeof(previous_method));
    memcpy(previous_path, yaza_http_current_path, sizeof(previous_path));
    memcpy(previous_request_id, yaza_http_current_request_id, sizeof(previous_request_id));

    yaza_http_active_request = &job->request_context;
    yaza_http_handler_response_status = 0;
    yaza_http_active_cancelled = &job->cancelled;
    yaza_http_active_connection = NULL;
    yaza_http_response_keep_alive = false;
    yaza_http_head_request = false;
    yaza_http_current_started_ms = job->started_ms;
    snprintf(yaza_http_current_method, sizeof(yaza_http_current_method), "%s", job->method);
    snprintf(yaza_http_current_path, sizeof(yaza_http_current_path), "%s", job->path);
    snprintf(yaza_http_current_request_id, sizeof(yaza_http_current_request_id), "%s", job->request_id);

    yaza_http_handler_result handler_result = yaza_http_handler_dispatch(job->route->handler_name);
    int handler_status = 0;
    if (deadline_ms > 0) {
        int64_t finished_ms = yaza_monotonic_milliseconds();
        if (finished_ms < 0) handler_status = EIO;
        else if (finished_ms >= deadline_ms) handler_status = ETIMEDOUT;
    }
    if (handler_status == 0 &&
        ((cancelled != NULL && atomic_load_explicit(cancelled, memory_order_acquire)) ||
         atomic_load_explicit(&job->cancelled, memory_order_acquire))) handler_status = ECANCELED;
    output->status_code = handler_result.status_code;
    output->handler_response_status = yaza_http_handler_response_status;
    size_t handler_body_length = 0;
    if (handler_status == 0 && handler_result.body != NULL) {
        handler_body_length = strnlen(handler_result.body, YAZA_HTTP_RESPONSE_MAX_BYTES + 1U);
        if (handler_body_length <= YAZA_HTTP_RESPONSE_MAX_BYTES &&
            yaza_http_worker_response_reserve(handler_body_length)) {
            output->body_length = handler_body_length;
            output->body_budget_reserved = true;
            output->body = (char *)yaza_system_malloc(handler_body_length + 1U);
            if (output->body != NULL)
                memcpy(output->body, handler_result.body, handler_body_length + 1U);
        }
    }
    if (handler_result.owns_body) free((void *)handler_result.body);

    yaza_http_active_request = previous_request;
    yaza_http_handler_response_status = previous_response_status;
    yaza_http_active_cancelled = previous_cancelled;
    yaza_http_active_connection = previous_connection;
    yaza_http_response_keep_alive = previous_keep_alive;
    yaza_http_head_request = previous_head_request;
    yaza_http_current_started_ms = previous_started_ms;
    memcpy(yaza_http_current_method, previous_method, sizeof(previous_method));
    memcpy(yaza_http_current_path, previous_path, sizeof(previous_path));
    memcpy(yaza_http_current_request_id, previous_request_id, sizeof(previous_request_id));
    yaza_memory_arena_leave(&request_arena, previous_arena);

    if (handler_status != 0) {
        yaza_system_free(output);
        return handler_status;
    }

    if (handler_result.body != NULL && output->body == NULL) {
        yaza_http_worker_response_release(output);
        yaza_system_free(output);
        return handler_body_length > YAZA_HTTP_RESPONSE_MAX_BYTES ? EOVERFLOW : ENOBUFS;
    }
    *result_out = output;
    return 0;
}

static const char *yaza_http_handler_status_reason(int status) {
    switch (status) {
        case 201: return "Created";
        case 202: return "Accepted";
        case 204: return "No Content";
        case 402: return "Payment Required";
        case 400: return "Bad Request";
        case 401: return "Unauthorized";
        case 403: return "Forbidden";
        case 404: return "Not Found";
        case 405: return "Method Not Allowed";
        case 409: return "Conflict";
        case 410: return "Gone";
        case 412: return "Precondition Failed";
        case 413: return "Payload Too Large";
        case 415: return "Unsupported Media Type";
        case 423: return "Locked";
        case 422: return "Unprocessable Content";
        case 429: return "Too Many Requests";
        case 431: return "Request Header Fields Too Large";
        case 500: return "Internal Server Error";
        case 501: return "Not Implemented";
        case 502: return "Bad Gateway";
        case 503: return "Service Unavailable";
        case 504: return "Gateway Timeout";
        case 507: return "Insufficient Storage";
        default: return "OK";
    }
}

static void yaza_http_handler_worker_complete(void *opaque, int work_status, void *result_value) {
    yaza_http_handler_job *job = (yaza_http_handler_job *)opaque;
    yaza_http_handler_output *output = (yaza_http_handler_output *)result_value;
    if (job == NULL) {
        if (output != NULL) {
            yaza_http_worker_response_release(output);
            yaza_system_free(output->body);
            yaza_system_free(output);
        }
        return;
    }
    yaza_http_connection *connection = job->connection;
    bool connection_matches = connection != NULL && connection->fd >= 0 &&
        connection->generation == job->connection_generation &&
        connection->worker_pending && connection->worker_cancelled == &job->cancelled;
    if (connection_matches) {
        connection->worker_pending = false;
        connection->worker_cancelled = NULL;

        yaza_http_connection *previous_connection = yaza_http_active_connection;
        bool previous_keep_alive = yaza_http_response_keep_alive;
        bool previous_head_request = yaza_http_head_request;
        bool previous_cors_preflight = yaza_http_cors_preflight_active;
        int64_t previous_retry_after = yaza_http_retry_after_seconds;
        int64_t previous_started_ms = yaza_http_current_started_ms;
        char previous_cors_origin[sizeof(yaza_http_cors_response_origin)];
        char previous_method[sizeof(yaza_http_current_method)];
        char previous_path[sizeof(yaza_http_current_path)];
        char previous_request_id[sizeof(yaza_http_current_request_id)];
        memcpy(previous_cors_origin, yaza_http_cors_response_origin, sizeof(previous_cors_origin));
        memcpy(previous_method, yaza_http_current_method, sizeof(previous_method));
        memcpy(previous_path, yaza_http_current_path, sizeof(previous_path));
        memcpy(previous_request_id, yaza_http_current_request_id, sizeof(previous_request_id));

        yaza_http_active_connection = connection;
        yaza_http_response_keep_alive = connection->request_keep_alive &&
            connection->requests_served + 1 < YAZA_HTTP_MAX_REQUESTS_PER_CONNECTION &&
            !yaza_http_shutdown_requested;
        yaza_http_head_request = strcmp(job->method, "HEAD") == 0;
        yaza_http_cors_preflight_active = false;
        yaza_http_retry_after_seconds = 1;
        yaza_http_current_started_ms = connection->request_started_at_ms;
        snprintf(yaza_http_cors_response_origin, sizeof(yaza_http_cors_response_origin), "%s", job->cors_origin);
        snprintf(yaza_http_current_method, sizeof(yaza_http_current_method), "%s", job->method);
        snprintf(yaza_http_current_path, sizeof(yaza_http_current_path), "%s", job->path);
        snprintf(yaza_http_current_request_id, sizeof(yaza_http_current_request_id), "%s", job->request_id);

        int response_status = work_status == ETIMEDOUT ? 504 :
            work_status == EOVERFLOW ? 500 : work_status != 0 ? 503 :
            output != NULL ? output->status_code : 500;
        if (work_status == 0 && output != NULL) {
            if (response_status == 0) response_status = output->handler_response_status;
            if (response_status == 0) response_status = job->route->success_status;
            if (response_status == 0) response_status = strcmp(job->route->method, "POST") == 0 ? 201 : 200;
            if (response_status != 204 &&
                (!yaza_http_handler_json_response_valid(output->body) || output->body == NULL)) {
                response_status = 500;
                yaza_http_respond(connection->fd, response_status, "Internal Server Error",
                                 "{\"error\":\"Invalid handler response\"}");
            } else {
                const char *response_body = response_status == 204 ? "" : output->body;
                yaza_http_respond_content(connection->fd, response_status,
                    yaza_http_handler_status_reason(response_status),
                    "application/json; charset=utf-8", response_body);
            }
        } else {
            const char *body = work_status == ETIMEDOUT
                ? "{\"error\":{\"type\":\"timeout_error\",\"code\":\"request_timeout\"}}"
                : work_status == EOVERFLOW
                    ? "{\"error\":{\"type\":\"internal_error\",\"code\":\"response_too_large\"}}"
                    : "{\"error\":{\"type\":\"unavailable_error\",\"code\":\"handler_unavailable\"}}";
            yaza_http_respond(connection->fd, response_status,
                              yaza_http_handler_status_reason(response_status), body);
        }

        yaza_http_active_connection = previous_connection;
        yaza_http_response_keep_alive = previous_keep_alive;
        yaza_http_head_request = previous_head_request;
        yaza_http_cors_preflight_active = previous_cors_preflight;
        yaza_http_retry_after_seconds = previous_retry_after;
        yaza_http_current_started_ms = previous_started_ms;
        memcpy(yaza_http_cors_response_origin, previous_cors_origin, sizeof(previous_cors_origin));
        memcpy(yaza_http_current_method, previous_method, sizeof(previous_method));
        memcpy(yaza_http_current_path, previous_path, sizeof(previous_path));
        memcpy(yaza_http_current_request_id, previous_request_id, sizeof(previous_request_id));
    }
    if (output != NULL) {
        yaza_http_worker_response_release(output);
        yaza_system_free(output->body);
        yaza_system_free(output);
    }
    yaza_system_free(job);
}

static int yaza_http_readiness_worker_run(void *opaque, const atomic_bool *cancelled,
                                          int64_t deadline_ms, void **result_out) {
    yaza_http_readiness_job *job = (yaza_http_readiness_job *)opaque;
    if (job == NULL || result_out == NULL || yaza_http_readiness_handler == NULL) return EINVAL;
    int64_t now_ms = yaza_monotonic_milliseconds();
    if (now_ms < 0) return EIO;
    if (deadline_ms > 0 && now_ms >= deadline_ms) return ETIMEDOUT;
    if ((cancelled != NULL && atomic_load_explicit(cancelled, memory_order_acquire)) ||
        atomic_load_explicit(&job->cancelled, memory_order_acquire)) return ECANCELED;

    yaza_http_readiness_output *output =
        (yaza_http_readiness_output *)yaza_system_calloc(1, sizeof(*output));
    if (output == NULL) return ENOMEM;
    yaza_memory_arena request_arena;
    yaza_memory_arena_init(&request_arena, YAZA_REQUEST_MEMORY_LIMIT);
    yaza_memory_arena *previous_arena = yaza_memory_arena_enter(&request_arena);
    const atomic_bool *previous_cancelled = yaza_http_active_cancelled;
    yaza_http_active_cancelled = &job->cancelled;
    output->ready = yaza_http_readiness_handler();
    yaza_http_active_cancelled = previous_cancelled;
    yaza_memory_arena_leave(&request_arena, previous_arena);
    yaza_memory_arena_reset(&request_arena);

    now_ms = yaza_monotonic_milliseconds();
    if (now_ms < 0) {
        yaza_system_free(output);
        return EIO;
    }
    if (deadline_ms > 0 && now_ms >= deadline_ms) {
        yaza_system_free(output);
        return ETIMEDOUT;
    }
    if ((cancelled != NULL && atomic_load_explicit(cancelled, memory_order_acquire)) ||
        atomic_load_explicit(&job->cancelled, memory_order_acquire)) {
        yaza_system_free(output);
        return ECANCELED;
    }
    *result_out = output;
    return 0;
}

static void yaza_http_readiness_worker_complete(void *opaque, int work_status,
                                                 void *result_value) {
    yaza_http_readiness_job *job = (yaza_http_readiness_job *)opaque;
    yaza_http_readiness_output *output = (yaza_http_readiness_output *)result_value;
    if (job == NULL) {
        yaza_system_free(output);
        return;
    }
    yaza_http_connection *connection = job->connection;
    bool connection_matches = connection != NULL && connection->fd >= 0 &&
        connection->generation == job->connection_generation &&
        connection->worker_pending && connection->worker_cancelled == &job->cancelled;
    if (connection_matches) {
        connection->worker_pending = false;
        connection->worker_cancelled = NULL;

        yaza_http_connection *previous_connection = yaza_http_active_connection;
        bool previous_keep_alive = yaza_http_response_keep_alive;
        bool previous_head_request = yaza_http_head_request;
        bool previous_cors_preflight = yaza_http_cors_preflight_active;
        int64_t previous_retry_after = yaza_http_retry_after_seconds;
        int64_t previous_started_ms = yaza_http_current_started_ms;
        char previous_cors_origin[sizeof(yaza_http_cors_response_origin)];
        char previous_method[sizeof(yaza_http_current_method)];
        char previous_path[sizeof(yaza_http_current_path)];
        char previous_request_id[sizeof(yaza_http_current_request_id)];
        memcpy(previous_cors_origin, yaza_http_cors_response_origin, sizeof(previous_cors_origin));
        memcpy(previous_method, yaza_http_current_method, sizeof(previous_method));
        memcpy(previous_path, yaza_http_current_path, sizeof(previous_path));
        memcpy(previous_request_id, yaza_http_current_request_id, sizeof(previous_request_id));

        yaza_http_active_connection = connection;
        yaza_http_response_keep_alive = connection->request_keep_alive &&
            connection->requests_served + 1 < YAZA_HTTP_MAX_REQUESTS_PER_CONNECTION &&
            !yaza_http_shutdown_requested;
        yaza_http_head_request = strcmp(job->method, "HEAD") == 0;
        yaza_http_cors_preflight_active = false;
        yaza_http_retry_after_seconds = 1;
        yaza_http_current_started_ms = job->started_ms;
        snprintf(yaza_http_cors_response_origin, sizeof(yaza_http_cors_response_origin), "%s",
                 job->cors_origin);
        snprintf(yaza_http_current_method, sizeof(yaza_http_current_method), "%s", job->method);
        snprintf(yaza_http_current_path, sizeof(yaza_http_current_path), "%s", job->path);
        snprintf(yaza_http_current_request_id, sizeof(yaza_http_current_request_id), "%s",
                 job->request_id);

        int response_status = work_status == ETIMEDOUT ? 504 :
            (work_status != 0 || output == NULL || !output->ready) ? 503 : 200;
        const char *body = response_status == 200
            ? "{\"status\":\"ok\"}"
            : response_status == 504
                ? "{\"error\":{\"type\":\"timeout_error\",\"code\":\"readiness_timeout\"}}"
                : "{\"status\":\"not_ready\",\"dependency\":\"postgresql\"}";
        yaza_http_respond_content(connection->fd, response_status,
            yaza_http_handler_status_reason(response_status),
            "application/json; charset=utf-8", body);

        yaza_http_active_connection = previous_connection;
        yaza_http_response_keep_alive = previous_keep_alive;
        yaza_http_head_request = previous_head_request;
        yaza_http_cors_preflight_active = previous_cors_preflight;
        yaza_http_retry_after_seconds = previous_retry_after;
        yaza_http_current_started_ms = previous_started_ms;
        memcpy(yaza_http_cors_response_origin, previous_cors_origin, sizeof(previous_cors_origin));
        memcpy(yaza_http_current_method, previous_method, sizeof(previous_method));
        memcpy(yaza_http_current_path, previous_path, sizeof(previous_path));
        memcpy(yaza_http_current_request_id, previous_request_id, sizeof(previous_request_id));
    }
    yaza_system_free(output);
    yaza_system_free(job);
}

static yaza_http_readiness_job *yaza_http_readiness_job_create(
        yaza_http_connection *connection, const char *method, const char *path,
        const char *cors_origin) {
    if (connection == NULL || method == NULL || path == NULL ||
        strlen(method) >= sizeof(((yaza_http_readiness_job *)0)->method) ||
        strlen(path) >= sizeof(((yaza_http_readiness_job *)0)->path)) return NULL;
    yaza_http_readiness_job *job =
        (yaza_http_readiness_job *)yaza_system_calloc(1, sizeof(*job));
    if (job == NULL) return NULL;
    job->connection = connection;
    job->connection_generation = connection->generation;
    job->started_ms = connection->request_started_at_ms;
    atomic_init(&job->cancelled, false);
    memcpy(job->method, method, strlen(method) + 1);
    memcpy(job->path, path, strlen(path) + 1);
    snprintf(job->request_id, sizeof(job->request_id), "%s", yaza_http_current_request_id);
    if (cors_origin != NULL && strlen(cors_origin) < sizeof(job->cors_origin))
        memcpy(job->cors_origin, cors_origin, strlen(cors_origin) + 1);
    return job;
}

static yaza_http_handler_job *yaza_http_handler_job_create(
        yaza_http_connection *connection, const yaza_http_route *route,
        const char *method, const char *path, const char *query,
        const char *request, const char *body, int client_fd,
        yaza_http_resource *resource, const yaza_http_parameter *parameters,
        size_t parameter_count, const unsigned char *verified_jwt_claims,
        const char *cors_origin) {
    if (connection == NULL || route == NULL || method == NULL || path == NULL || request == NULL ||
        parameter_count > YAZA_HTTP_MAX_JSON_FIELDS ||
        (parameters == NULL && parameter_count != 0)) return NULL;
    size_t request_length = strnlen(request, YAZA_HTTP_REQUEST_CAPACITY);
    size_t body_length = body == NULL ? 0 : strnlen(body, YAZA_HTTP_REQUEST_CAPACITY);
    size_t claims_length = verified_jwt_claims == NULL ? 0 :
        strnlen((const char *)verified_jwt_claims, YAZA_HTTP_JWT_MAX_SEGMENT_BYTES + 1U);
    if (request_length >= YAZA_HTTP_REQUEST_CAPACITY || body_length >= YAZA_HTTP_REQUEST_CAPACITY ||
        claims_length > YAZA_HTTP_JWT_MAX_SEGMENT_BYTES ||
        strlen(method) >= sizeof(((yaza_http_handler_job *)0)->method) ||
        strlen(path) >= sizeof(((yaza_http_handler_job *)0)->path) ||
        (query != NULL && strlen(query) >= sizeof(((yaza_http_handler_job *)0)->query))) return NULL;
    yaza_http_handler_job *job = (yaza_http_handler_job *)yaza_system_calloc(1, sizeof(*job));
    if (job == NULL) return NULL;
    job->connection = connection;
    job->connection_generation = connection->generation;
    job->route = route;
    job->started_ms = connection->request_started_at_ms;
    atomic_init(&job->cancelled, false);
    memcpy(job->method, method, strlen(method) + 1);
    memcpy(job->path, path, strlen(path) + 1);
    if (query != NULL) memcpy(job->query, query, strlen(query) + 1);
    memcpy(job->request, request, request_length + 1);
    if (body != NULL) memcpy(job->body, body, body_length + 1);
    if (verified_jwt_claims != NULL)
        memcpy(job->verified_jwt_claims, verified_jwt_claims, claims_length + 1);
    if (cors_origin != NULL && strlen(cors_origin) < sizeof(job->cors_origin))
        memcpy(job->cors_origin, cors_origin, strlen(cors_origin) + 1);
    snprintf(job->request_id, sizeof(job->request_id), "%s", yaza_http_current_request_id);
    if (parameter_count != 0)
        memcpy(job->parameters, parameters, parameter_count * sizeof(*parameters));
    job->request_context = (yaza_http_request_context){
        route, job->path, query == NULL ? NULL : job->query, job->request,
        body == NULL ? NULL : job->body, client_fd, resource,
        job->parameters, parameter_count,
        verified_jwt_claims == NULL ? NULL : (const char *)job->verified_jwt_claims
    };
    return job;
}

static bool yaza_http_controller_body_schema(const char *metadata, char *output, size_t capacity) {
    output[0] = '\0';
    if (metadata == NULL || *metadata == '\0') return true;
    yaza_json_field root_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int root_count = yaza_json_object_fields(metadata, root_fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (root_count < 0) return false;
    const yaza_json_field *body_field = yaza_http_json_field_find(root_fields, root_count, "body");
    if (body_field == NULL || yaza_json_value_kind(body_field->value) == 'n') return true;
    if (yaza_json_value_kind(body_field->value) != 'o' || body_field->value_length >= capacity) return false;
    memcpy(output, body_field->value, body_field->value_length);
    output[body_field->value_length] = '\0';
    yaza_json_field body_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    return yaza_json_object_fields(output, body_fields, YAZA_HTTP_MAX_JSON_FIELDS) >= 0;
}

static bool yaza_http_controller_parameters(const char *metadata, yaza_http_parameter *parameters,
                                            size_t capacity, size_t *parameter_count) {
    *parameter_count = 0;
    if (metadata == NULL || *metadata == '\0') return true;
    yaza_json_field root_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int root_count = yaza_json_object_fields(metadata, root_fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (root_count < 0) return false;
    const yaza_json_field *params_field = yaza_http_json_field_find(root_fields, root_count, "params");
    if (params_field == NULL || yaza_json_value_kind(params_field->value) != 'a') return false;
    const char *cursor = yaza_json_skip_space(params_field->value);
    if (*cursor != '[') return false;
    cursor++;
    for (;;) {
        cursor = yaza_json_skip_space(cursor);
        if (*cursor == ']') return true;
        if (*cursor != '{' || *parameter_count == capacity) return false;
        const char *end = yaza_json_skip_value(cursor);
        if (end == NULL || (size_t)(end - cursor) >= 2048) return false;
        char object[2048];
        size_t object_length = (size_t)(end - cursor);
        memcpy(object, cursor, object_length);
        object[object_length] = '\0';
        yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
        int field_count = yaza_json_object_fields(object, fields, YAZA_HTTP_MAX_JSON_FIELDS);
        if (field_count < 0) return false;
        const yaza_json_field *kind_field = yaza_http_json_field_find(fields, field_count, "kind");
        const yaza_json_field *name_field = yaza_http_json_field_find(fields, field_count, "name");
        const yaza_json_field *type_field = yaza_http_json_field_find(fields, field_count, "type");
        const yaza_json_field *required_field = yaza_http_json_field_find(fields, field_count, "required");
        const yaza_json_field *default_field = yaza_http_json_field_find(fields, field_count, "default");
        yaza_http_parameter parameter = {0};
        char required[8];
        if (kind_field == NULL || name_field == NULL || type_field == NULL ||
            required_field == NULL || default_field == NULL ||
            !yaza_json_field_text(kind_field, parameter.kind, sizeof(parameter.kind)) ||
            !yaza_json_field_text(name_field, parameter.name, sizeof(parameter.name)) ||
            !yaza_json_field_text(type_field, parameter.value_type, sizeof(parameter.value_type)) ||
            !yaza_json_field_text(required_field, required, sizeof(required))) return false;
        bool scalar_type = strcmp(parameter.value_type, "Text") == 0 ||
            strcmp(parameter.value_type, "Number") == 0 || strcmp(parameter.value_type, "Int32") == 0 ||
            strcmp(parameter.value_type, "Float64") == 0 || strcmp(parameter.value_type, "Boolean") == 0;
        if ((strcmp(parameter.kind, "path") != 0 && strcmp(parameter.kind, "query") != 0 &&
             strcmp(parameter.kind, "header") != 0 && strcmp(parameter.kind, "body") != 0) || *parameter.name == '\0' ||
            (!scalar_type && strcmp(parameter.kind, "body") != 0) ||
            (strcmp(parameter.kind, "header") == 0 && strcmp(parameter.value_type, "Text") != 0) ||
            (strcmp(required, "true") != 0 && strcmp(required, "false") != 0)) return false;
        parameter.required = strcmp(required, "true") == 0;
        parameter.has_default = yaza_json_value_kind(default_field->value) != 'n';
        if (parameter.has_default) {
            if (!yaza_json_field_text(default_field, parameter.default_value, sizeof(parameter.default_value)) ||
                !yaza_http_value_matches(parameter.default_value, parameter.value_type)) return false;
        } else if (!parameter.required) {
            return false;
        }
        for (size_t prior = 0; prior < *parameter_count; prior++) {
            bool same_name = strcmp(parameter.kind, "header") == 0
                ? strcasecmp(parameters[prior].name, parameter.name) == 0
                : strcmp(parameters[prior].name, parameter.name) == 0;
            if (same_name && strcmp(parameters[prior].kind, parameter.kind) == 0) return false;
        }
        parameters[(*parameter_count)++] = parameter;
        cursor = yaza_json_skip_space(end);
        if (*cursor == ']') return true;
        if (*cursor != ',') return false;
        cursor++;
    }
}

static const yaza_http_parameter *yaza_http_parameter_find(const yaza_http_parameter *parameters,
                                                           size_t count, const char *kind, const char *name) {
    for (size_t index = 0; index < count; index++) {
        bool same_name = strcmp(kind, "header") == 0
            ? strcasecmp(parameters[index].name, name) == 0
            : strcmp(parameters[index].name, name) == 0;
        if (strcmp(parameters[index].kind, kind) == 0 && same_name) return &parameters[index];
    }
    return NULL;
}

static bool yaza_http_body_field_value(const char *body_schema, const char *body, const char *name,
                                       const char *expected_type, char *output, size_t capacity) {
    if (body_schema == NULL || body == NULL || name == NULL || expected_type == NULL ||
        output == NULL || capacity == 0) return false;
    yaza_json_field schema_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    yaza_json_field body_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int schema_count = yaza_json_object_fields(body_schema, schema_fields, YAZA_HTTP_MAX_JSON_FIELDS);
    int body_count = yaza_json_object_fields(body, body_fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (schema_count < 0 || body_count < 0) return false;
    const yaza_json_field *schema_field = yaza_http_json_field_find(schema_fields, schema_count, name);
    const yaza_json_field *body_field = yaza_http_json_field_find(body_fields, body_count, name);
    if (schema_field == NULL || body_field == NULL) return false;
    char expected_kind = strcmp(expected_type, "Text") == 0 ? 's' :
                         strcmp(expected_type, "Boolean") == 0 ? 'b' : 'd';
    if (yaza_json_value_kind(schema_field->value) != expected_kind ||
        yaza_json_value_kind(body_field->value) != expected_kind) return false;
    bool copied = false;
    if (expected_kind == 's') {
        copied = yaza_json_decode_string(body_field->value, body_field->value_length, output, capacity);
    } else if (body_field->value_length < capacity) {
        memcpy(output, body_field->value, body_field->value_length);
        output[body_field->value_length] = '\0';
        copied = true;
    }
    return copied && yaza_http_value_matches(output, expected_type);
}

static bool yaza_http_body_parameters_valid(const yaza_http_route *route, const char *body,
                                            const yaza_http_parameter *parameters, size_t count,
                                            yaza_http_validation_error *error) {
    if (route == NULL) {
        yaza_http_validation_error_set(error, "$", "invalid_contract");
        return false;
    }
    if (route->body_schema[0] == '\0') {
        bool valid = body == NULL || *body == '\0';
        if (!valid) yaza_http_validation_error_set(error, "$", "unexpected_body");
        return valid;
    }
    if (body == NULL) {
        yaza_http_validation_error_set(error, "$", "required_body");
        return false;
    }
    bool has_shape_body = false;
    for (size_t index = 0; index < count; index++) {
        const yaza_http_parameter *parameter = &parameters[index];
        if (strcmp(parameter->kind, "body") == 0 &&
            strcmp(parameter->value_type, "Text") != 0 && strcmp(parameter->value_type, "Number") != 0 &&
            strcmp(parameter->value_type, "Int32") != 0 && strcmp(parameter->value_type, "Float64") != 0 &&
            strcmp(parameter->value_type, "Boolean") != 0) has_shape_body = true;
    }
    bool partial_body = route->method != NULL && strcmp(route->method, "PATCH") == 0;
    if (!has_shape_body && !yaza_json_object_matches_schema(body, route->body_schema, partial_body, false, error)) return false;
    yaza_json_field request_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int request_field_count = yaza_json_object_fields(body, request_fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (request_field_count < 0) return false;
    for (size_t index = 0; index < count; index++) {
        const yaza_http_parameter *parameter = &parameters[index];
        if (strcmp(parameter->kind, "body") != 0) continue;
        if (strcmp(parameter->value_type, "Text") == 0 || strcmp(parameter->value_type, "Number") == 0 ||
            strcmp(parameter->value_type, "Int32") == 0 || strcmp(parameter->value_type, "Float64") == 0 ||
            strcmp(parameter->value_type, "Boolean") == 0) {
            if (partial_body && yaza_http_json_field_find(request_fields, request_field_count, parameter->name) == NULL)
                continue;
            char value[1024];
            if (!yaza_http_body_field_value(route->body_schema, body, parameter->name,
                                           parameter->value_type, value, sizeof(value))) {
                yaza_http_validation_error_set_child(error, "", parameter->name, "invalid_value");
                return false;
            }
        } else if (yaza_http_body_shape_validate == NULL ||
                   !yaza_http_body_shape_validate(parameter->value_type, body, error)) {
            return false;
        }
    }
    return true;
}

static bool yaza_http_route_body_contract_valid(const yaza_http_route *route) {
    if (route == NULL) return false;
    yaza_http_parameter parameters[YAZA_HTTP_MAX_JSON_FIELDS];
    size_t parameter_count = 0;
    if (!yaza_http_controller_parameters(route->metadata, parameters,
                                         YAZA_HTTP_MAX_JSON_FIELDS, &parameter_count)) return false;
    for (size_t index = 0; index < parameter_count; index++) {
        const yaza_http_parameter *parameter = &parameters[index];
        if (strcmp(parameter->kind, "body") != 0) continue;
        if (route->body_schema[0] == '\0') return false;
        if (strcmp(parameter->value_type, "Text") == 0 || strcmp(parameter->value_type, "Number") == 0 ||
            strcmp(parameter->value_type, "Int32") == 0 || strcmp(parameter->value_type, "Float64") == 0 ||
            strcmp(parameter->value_type, "Boolean") == 0) {
            char sample_value[1024];
            if (!yaza_http_body_field_value(route->body_schema, route->body_schema, parameter->name,
                                            parameter->value_type, sample_value, sizeof(sample_value))) return false;
        } else if (yaza_http_body_shape_validate == NULL ||
                   !yaza_http_body_shape_validate(parameter->value_type, route->body_schema, NULL)) {
            return false;
        }
    }
    return true;
}

static yaza_option yaza_http_request_shape_as(const char *name, const char *expected_type,
                                              size_t shape_size, yaza_http_body_shape_decode_fn decode) {
    if (yaza_http_active_request == NULL || yaza_http_active_request->route == NULL || name == NULL ||
        expected_type == NULL || shape_size == 0 || decode == NULL ||
        yaza_http_active_request->body == NULL) return yaza_option_none();
    yaza_http_parameter parameters[YAZA_HTTP_MAX_JSON_FIELDS];
    size_t parameter_count = 0;
    if (!yaza_http_controller_parameters(yaza_http_active_request->route->metadata, parameters,
                                         YAZA_HTTP_MAX_JSON_FIELDS, &parameter_count)) return yaza_option_none();
    const yaza_http_parameter *parameter = yaza_http_parameter_find(parameters, parameter_count, "body", name);
    if (parameter == NULL || strcmp(parameter->value_type, expected_type) != 0) return yaza_option_none();
    void *value = calloc(1, shape_size);
    if (value == NULL) return yaza_option_none();
    if (!decode(yaza_http_active_request->body, value, "", NULL)) {
        free(value);
        return yaza_option_none();
    }
    yaza_option result = yaza_option_some_custom(value, shape_size, expected_type);
    free(value);
    return result;
}

static bool yaza_http_path_parameter_value(const char *pattern, const char *path, const char *name,
                                           char *output, size_t capacity, bool *found) {
    *found = false;
    while (*pattern != '\0') {
        if (*pattern == '{') {
            const char *end = strchr(pattern, '}');
            if (end == NULL || end == pattern + 1) return false;
            size_t name_length = (size_t)(end - pattern - 1);
            const char *value_end = strchr(path, '/');
            if (value_end == NULL) value_end = path + strlen(path);
            if (name_length == strlen(name) && memcmp(pattern + 1, name, name_length) == 0) {
                size_t value_length = (size_t)(value_end - path);
                if (value_length == 0 || value_length >= capacity) return false;
                memcpy(output, path, value_length);
                output[value_length] = '\0';
                *found = true;
            }
            pattern = end + 1;
            path = value_end;
        } else {
            if (*pattern != *path) return false;
            pattern++;
            path++;
        }
    }
    return *path == '\0';
}

static bool yaza_http_decode_component(const char *source, size_t length, char *destination,
                                       size_t capacity, bool plus_as_space) {
    if (source == NULL || destination == NULL || capacity == 0) return false;
    size_t used = 0;
    for (size_t index = 0; index < length; index++) {
        unsigned char character = (unsigned char)source[index];
        if (character == '%') {
            if (index + 2 >= length) return false;
            int high = yaza_hex_value((unsigned char)source[index + 1]);
            int low = yaza_hex_value((unsigned char)source[index + 2]);
            if (high < 0 || low < 0) return false;
            character = (unsigned char)((high << 4) | low);
            index += 2;
        } else if (plus_as_space && character == '+') {
            character = ' ';
        }
        if (character == '\0' || character < 0x20 || character == 0x7f || used + 1 >= capacity) return false;
        destination[used++] = (char)character;
    }
    destination[used] = '\0';
    return true;
}

static bool yaza_http_query_parameter_value(const char *query, const char *name,
                                            char *output, size_t capacity, bool *found) {
    *found = false;
    if (query == NULL || *query == '\0') return true;
    const char *cursor = query;
    while (*cursor != '\0') {
        const char *key = cursor;
        while (*cursor != '\0' && *cursor != '=' && *cursor != '&') cursor++;
        size_t key_length = (size_t)(cursor - key);
        if (key_length == 0 || *cursor != '=') return false;
        cursor++;
        const char *value = cursor;
        while (*cursor != '\0' && *cursor != '&') cursor++;
        size_t value_length = (size_t)(cursor - value);
        char decoded_name[128];
        char decoded_value[1024];
        if (!yaza_http_decode_component(key, key_length, decoded_name, sizeof(decoded_name), true) ||
            !yaza_http_decode_component(value, value_length, decoded_value, sizeof(decoded_value), true)) return false;
        if (strcmp(decoded_name, name) == 0) {
            if (*found || strlen(decoded_value) >= capacity) return false;
            memcpy(output, decoded_value, strlen(decoded_value) + 1);
            *found = true;
        }
        if (*cursor == '&') cursor++;
    }
    return true;
}

static bool yaza_http_header_parameter_value(const char *request, const char *name,
                                             char *output, size_t capacity, bool *found) {
    *found = false;
    const char *line = strstr(request, "\r\n");
    const char *headers_end = strstr(request, "\r\n\r\n");
    if (line == NULL || headers_end == NULL) return false;
    line += 2;
    while (line < headers_end) {
        const char *end = strstr(line, "\r\n");
        if (end == NULL || end > headers_end) return false;
        const char *colon = memchr(line, ':', (size_t)(end - line));
        if (colon == NULL) return false;
        size_t header_name_length = (size_t)(colon - line);
        if (header_name_length == strlen(name) && strncasecmp(line, name, header_name_length) == 0) {
            if (*found) return false;
            const char *value = colon + 1;
            while (value < end && (*value == ' ' || *value == '\t')) value++;
            const char *value_end = end;
            while (value_end > value && (value_end[-1] == ' ' || value_end[-1] == '\t')) value_end--;
            size_t value_length = (size_t)(value_end - value);
            if (value_length >= capacity) return false;
            memcpy(output, value, value_length);
            output[value_length] = '\0';
            *found = true;
        }
        line = end + 2;
    }
    return true;
}

static bool yaza_http_cors_header_token_valid(const char *name, size_t length) {
    if (name == NULL || length == 0) return false;
    for (size_t index = 0; index < length; index++) {
        unsigned char character = (unsigned char)name[index];
        bool alpha_numeric = (character >= 'A' && character <= 'Z') ||
            (character >= 'a' && character <= 'z') || (character >= '0' && character <= '9');
        if (!alpha_numeric && strchr("!#$%&'*+-.^_`|~", (int)character) == NULL) return false;
    }
    return true;
}

static bool yaza_http_cors_requested_header_allowed(const char *name, size_t length,
                                                    const yaza_http_route *route,
                                                    const yaza_http_parameter *parameters,
                                                    size_t parameter_count) {
    if ((length == 6 && strncasecmp(name, "Accept", length) == 0) ||
        (length == 13 && strncasecmp(name, "Authorization", length) == 0) ||
        (length == 12 && strncasecmp(name, "Content-Type", length) == 0)) return true;
    if (route == NULL) return false;
    for (size_t index = 0; index < parameter_count; index++) {
        if (strcmp(parameters[index].kind, "header") == 0 &&
            strlen(parameters[index].name) == length &&
            strncasecmp(parameters[index].name, name, length) == 0) return true;
    }
    return false;
}

static bool yaza_http_cors_requested_headers_valid(const char *request,
                                                   const yaza_http_route *route,
                                                   char *allowed_headers,
                                                   size_t allowed_headers_capacity) {
    if (allowed_headers == NULL || allowed_headers_capacity == 0) return false;
    static const char default_headers[] = "Accept, Authorization, Content-Type";
    char requested[1024];
    bool found = false;
    if (!yaza_http_header_parameter_value(request, "Access-Control-Request-Headers",
                                         requested, sizeof(requested), &found)) return false;
    if (!found || requested[0] == '\0') {
        size_t default_length = sizeof(default_headers) - 1;
        if (default_length >= allowed_headers_capacity) return false;
        memcpy(allowed_headers, default_headers, default_length + 1);
        return true;
    }
    yaza_http_parameter parameters[YAZA_HTTP_MAX_HEADER_COUNT];
    size_t parameter_count = 0;
    if (route != NULL && !yaza_http_controller_parameters(route->metadata, parameters,
            YAZA_HTTP_MAX_HEADER_COUNT, &parameter_count)) return false;
    size_t allowed_length = 0;
    const char *cursor = requested;
    for (;;) {
        while (*cursor == ' ' || *cursor == '\t') cursor++;
        const char *start = cursor;
        while (*cursor != '\0' && *cursor != ',') cursor++;
        const char *end = cursor;
        while (end > start && (end[-1] == ' ' || end[-1] == '\t')) end--;
        size_t name_length = (size_t)(end - start);
        if (!yaza_http_cors_header_token_valid(start, name_length) ||
            !yaza_http_cors_requested_header_allowed(start, name_length, route,
                                                     parameters, parameter_count)) return false;
        size_t separator_length = allowed_length == 0 ? 0 : 2;
        if (separator_length > allowed_headers_capacity - allowed_length - 1 ||
            name_length > allowed_headers_capacity - allowed_length - separator_length - 1) return false;
        if (separator_length != 0) {
            memcpy(allowed_headers + allowed_length, ", ", separator_length);
            allowed_length += separator_length;
        }
        memcpy(allowed_headers + allowed_length, start, name_length);
        allowed_length += name_length;
        allowed_headers[allowed_length] = '\0';
        if (*cursor == '\0') break;
        cursor++;
        if (*cursor == '\0') return false;
    }
    return allowed_length != 0;
}

static bool yaza_http_bearer_token_valid(const char *token) {
    if (token == NULL) return false;
    size_t length = strnlen(token, YAZA_HTTP_API_TOKEN_MAX_BYTES + 1U);
    if (length < YAZA_HTTP_API_TOKEN_MIN_BYTES ||
        length > YAZA_HTTP_API_TOKEN_MAX_BYTES) return false;
    bool padding = false;
    size_t token_characters = 0;
    for (size_t index = 0; index < length; index++) {
        unsigned char character = (unsigned char)token[index];
        if (character == '=') {
            padding = true;
            continue;
        }
        bool allowed = (character >= 'A' && character <= 'Z') ||
                       (character >= 'a' && character <= 'z') ||
                       (character >= '0' && character <= '9') ||
                       character == '-' || character == '.' || character == '_' ||
                       character == '~' || character == '+' || character == '/';
        if (padding || !allowed) return false;
        token_characters++;
    }
    return token_characters > 0;
}

static bool yaza_http_bearer_authenticated(const char *request,
                                          const char *const *expected_tokens,
                                          const size_t *expected_lengths,
                                          size_t expected_count) {
    char authorization[2048] = {0};
    char provided_token[YAZA_HTTP_API_TOKEN_MAX_BYTES + 1] = {0};
    char expected_token_padded[YAZA_HTTP_API_TOKEN_MAX_BYTES + 1] = {0};
    bool found = false;
    bool authenticated = false;
    if (request != NULL && expected_tokens != NULL && expected_lengths != NULL &&
        expected_count > 0 && expected_count <= YAZA_HTTP_API_TOKEN_MAX_ACTIVE &&
        yaza_http_header_parameter_value(request, "Authorization", authorization,
                                         sizeof(authorization), &found) && found &&
        strncasecmp(authorization, "Bearer", 6) == 0 && authorization[6] == ' ') {
        size_t token_offset = 6;
        while (authorization[token_offset] == ' ') token_offset++;
        size_t authorization_length = strnlen(authorization, sizeof(authorization));
        if (token_offset < authorization_length) {
            const char *provided = authorization + token_offset;
            size_t provided_length = authorization_length - token_offset;
            if (provided_length > 0 && provided_length <= YAZA_HTTP_API_TOKEN_MAX_BYTES) {
                memcpy(provided_token, provided, provided_length);
                for (size_t token_index = 0; token_index < expected_count; token_index++) {
                    size_t expected_length = expected_lengths[token_index];
                    bool expected_valid = expected_tokens[token_index] != NULL &&
                        expected_length > 0 && expected_length <= YAZA_HTTP_API_TOKEN_MAX_BYTES;
                    if (expected_valid)
                        memcpy(expected_token_padded, expected_tokens[token_index], expected_length);
                    volatile uint64_t difference = (uint64_t)(provided_length ^
                        (expected_valid ? expected_length : 0U));
                    for (size_t index = 0; index < YAZA_HTTP_API_TOKEN_MAX_BYTES; index++)
                        difference |= (uint64_t)((unsigned char)provided_token[index] ^
                                                 (unsigned char)expected_token_padded[index]);
                    bool token_matches = expected_valid && difference == 0;
                    authenticated = authenticated | token_matches;
                    yaza_secure_wipe(expected_token_padded, sizeof(expected_token_padded));
                }
            }
        }
    }
    yaza_secure_wipe(provided_token, sizeof(provided_token));
    yaza_secure_wipe(expected_token_padded, sizeof(expected_token_padded));
    yaza_secure_wipe(authorization, sizeof(authorization));
    return authenticated;
}

static int yaza_http_jwt_base64url_value(unsigned char character) {
    if (character >= 'A' && character <= 'Z') return (int)(character - 'A');
    if (character >= 'a' && character <= 'z') return (int)(character - 'a') + 26;
    if (character >= '0' && character <= '9') return (int)(character - '0') + 52;
    if (character == '-') return 62;
    if (character == '_') return 63;
    return -1;
}

static bool yaza_http_jwt_base64url_decode(const char *encoded, size_t encoded_length,
                                           unsigned char *decoded, size_t decoded_capacity,
                                           size_t *decoded_length) {
    if (encoded == NULL || decoded == NULL || decoded_length == NULL || encoded_length == 0 ||
        encoded_length > YAZA_HTTP_JWT_MAX_SEGMENT_BYTES || encoded_length % 4U == 1U)
        return false;
    size_t expected_length = (encoded_length * 6U) / 8U;
    if (expected_length >= decoded_capacity) return false;
    uint32_t accumulator = 0;
    unsigned int bit_count = 0;
    size_t written = 0;
    for (size_t index = 0; index < encoded_length; index++) {
        int value = yaza_http_jwt_base64url_value((unsigned char)encoded[index]);
        if (value < 0) return false;
        accumulator = (accumulator << 6) | (uint32_t)value;
        bit_count += 6;
        if (bit_count >= 8) {
            bit_count -= 8;
            decoded[written++] = (unsigned char)((accumulator >> bit_count) & 0xffU);
            accumulator &= bit_count == 0 ? 0U : ((1U << bit_count) - 1U);
        }
    }
    if (written != expected_length || accumulator != 0) return false;
    decoded[written] = 0;
    *decoded_length = written;
    return true;
}

static bool yaza_http_jwt_numeric_date(const yaza_json_field *field, int64_t *result) {
    if (field == NULL || result == NULL || yaza_json_value_kind(field->value) != 'd' ||
        field->value_length == 0 || field->value_length > 19U || field->value[0] == '-')
        return false;
    int64_t value = 0;
    for (size_t index = 0; index < field->value_length; index++) {
        unsigned char character = (unsigned char)field->value[index];
        if (character < '0' || character > '9') return false;
        int digit = (int)(character - '0');
        if (value > (INT64_MAX - digit) / 10) return false;
        value = value * 10 + digit;
    }
    *result = value;
    return true;
}

static bool yaza_http_jwt_expected_text_valid(const char *value) {
    if (value == NULL) return false;
    size_t length = strnlen(value, 513U);
    if (length == 0 || length > 512U) return false;
    for (size_t index = 0; index < length; index++) {
        unsigned char character = (unsigned char)value[index];
        if (character < 0x21U || character == 0x7fU) return false;
    }
    return true;
}

static bool yaza_http_jwt_audience_matches(const yaza_json_field *field,
                                           const char *expected_audience) {
    if (field == NULL || field->value == NULL || expected_audience == NULL) return false;
    const char *cursor = yaza_json_skip_space(field->value);
    const char *end = field->value + field->value_length;
    if (cursor >= end) return false;
    if (*cursor == '"') {
        const char *value_end = yaza_json_skip_value(cursor);
        char audience[1024];
        bool valid = value_end != NULL && value_end <= end &&
            yaza_json_skip_space(value_end) == end &&
            yaza_json_decode_string(cursor, (size_t)(value_end - cursor),
                                    audience, sizeof(audience));
        bool matches = valid && strcmp(audience, expected_audience) == 0;
        yaza_secure_wipe(audience, sizeof(audience));
        return matches;
    }
    if (*cursor != '[') return false;
    cursor++;
    bool found_value = false;
    bool matched = false;
    for (;;) {
        cursor = yaza_json_skip_space(cursor);
        if (cursor >= end || *cursor != '"') return false;
        const char *value_end = yaza_json_skip_value(cursor);
        if (value_end == NULL || value_end > end) return false;
        char audience[1024] = {0};
        bool valid = yaza_json_decode_string(cursor, (size_t)(value_end - cursor),
                                             audience, sizeof(audience));
        if (!valid || audience[0] == '\0') {
            yaza_secure_wipe(audience, sizeof(audience));
            return false;
        }
        if (strcmp(audience, expected_audience) == 0) matched = true;
        found_value = true;
        yaza_secure_wipe(audience, sizeof(audience));
        cursor = yaza_json_skip_space(value_end);
        if (cursor >= end) return false;
        if (*cursor == ']') {
            cursor = yaza_json_skip_space(cursor + 1);
            return found_value && matched && cursor == end;
        }
        if (*cursor != ',') return false;
        cursor++;
        cursor = yaza_json_skip_space(cursor);
        if (cursor >= end || *cursor == ']') return false;
    }
}

static bool yaza_http_jwt_hmac_sha256(const unsigned char *key, size_t key_length,
                                      const unsigned char *message, size_t message_length,
                                      unsigned char digest[32]) {
    if (key == NULL || key_length < 32U || key_length > YAZA_HTTP_JWT_MAX_SECRET_BYTES ||
        message == NULL || digest == NULL) return false;
#if defined(__APPLE__)
    CCHmac(kCCHmacAlgSHA256, key, key_length, message, message_length, digest);
    return true;
#else
    unsigned int digest_length = 0;
    return HMAC(EVP_sha256(), key, (int)key_length, message, message_length,
                digest, &digest_length) != NULL && digest_length == 32U;
#endif
}

/* YAZA's initial access-token profile is intentionally narrow: compact JWS,
   HS256, typ=JWT, one configured audience matched against a string or string array,
   required iss/aud/exp, and optional
   integer nbf/iat. Unsupported JOSE headers and non-canonical base64url fail closed. */
static int yaza_http_jwt_authenticated(const char *request, const char *secret,
                                       const char *expected_issuer,
                                       const char *expected_audience,
                                       unsigned char *verified_claims,
                                       size_t verified_claims_capacity) {
    int result = 0;
    char authorization[YAZA_HTTP_JWT_MAX_TOKEN_BYTES + 16U] = {0};
    unsigned char header_json[YAZA_HTTP_JWT_MAX_SEGMENT_BYTES + 1U] = {0};
    unsigned char payload_json[YAZA_HTTP_JWT_MAX_SEGMENT_BYTES + 1U] = {0};
    unsigned char signature[64] = {0};
    unsigned char expected_signature[32] = {0};
    bool found = false;
    if (verified_claims != NULL && verified_claims_capacity > 0) verified_claims[0] = '\0';
    if (request == NULL || secret == NULL || expected_issuer == NULL || expected_audience == NULL ||
        verified_claims == NULL || verified_claims_capacity < YAZA_HTTP_JWT_MAX_SEGMENT_BYTES + 1U ||
        !yaza_http_jwt_expected_text_valid(expected_issuer) ||
        !yaza_http_jwt_expected_text_valid(expected_audience)) goto cleanup;
    size_t secret_length = strnlen(secret, YAZA_HTTP_JWT_MAX_SECRET_BYTES + 1U);
    if (secret_length < 32U || secret_length > YAZA_HTTP_JWT_MAX_SECRET_BYTES) goto cleanup;
    if (!yaza_http_header_parameter_value(request, "Authorization", authorization,
                                         sizeof(authorization), &found) || !found) goto cleanup;
    size_t authorization_length = strnlen(authorization, sizeof(authorization));
    if (authorization_length < 8U || strncasecmp(authorization, "Bearer ", 7U) != 0) goto cleanup;
    size_t token_offset = 7U;
    while (token_offset < authorization_length && authorization[token_offset] == ' ') token_offset++;
    size_t token_length = authorization_length - token_offset;
    if (token_length == 0 || token_length > YAZA_HTTP_JWT_MAX_TOKEN_BYTES) goto cleanup;
    const char *token = authorization + token_offset;
    const char *first_dot = memchr(token, '.', token_length);
    if (first_dot == NULL) goto cleanup;
    size_t header_length = (size_t)(first_dot - token);
    size_t remaining_length = token_length - header_length - 1U;
    const char *second_dot = memchr(first_dot + 1, '.', remaining_length);
    if (second_dot == NULL || memchr(second_dot + 1, '.', token_length - (size_t)(second_dot + 1 - token)) != NULL)
        goto cleanup;
    size_t payload_length = (size_t)(second_dot - first_dot - 1);
    size_t signature_length = token_length - (size_t)(second_dot + 1 - token);
    if (header_length == 0 || payload_length == 0 || signature_length == 0) goto cleanup;
    size_t decoded_header_length = 0;
    if (!yaza_http_jwt_base64url_decode(token, header_length, header_json,
                                        sizeof(header_json), &decoded_header_length)) goto cleanup;
    yaza_json_field header_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int header_count = yaza_json_object_fields((const char *)header_json, header_fields,
                                               YAZA_HTTP_MAX_JSON_FIELDS);
    if (header_count != 2) goto cleanup;
    const yaza_json_field *algorithm_field = yaza_http_json_field_find(header_fields, header_count, "alg");
    const yaza_json_field *type_field = yaza_http_json_field_find(header_fields, header_count, "typ");
    char algorithm[16] = {0};
    char token_type[16] = {0};
    if (algorithm_field == NULL || type_field == NULL ||
        !yaza_json_field_text(algorithm_field, algorithm, sizeof(algorithm)) ||
        !yaza_json_field_text(type_field, token_type, sizeof(token_type)) ||
        strcmp(algorithm, "HS256") != 0 || strcmp(token_type, "JWT") != 0) goto cleanup;

    size_t decoded_signature_length = 0;
    if (!yaza_http_jwt_base64url_decode(second_dot + 1, signature_length, signature,
                                        sizeof(signature), &decoded_signature_length) ||
        decoded_signature_length != sizeof(expected_signature)) goto cleanup;
    size_t signed_length = (size_t)(second_dot - token);
    if (!yaza_http_jwt_hmac_sha256((const unsigned char *)secret, secret_length,
                                   (const unsigned char *)token, signed_length,
                                   expected_signature)) goto cleanup;
    unsigned char signature_difference = 0;
    for (size_t index = 0; index < sizeof(expected_signature); index++)
        signature_difference |= (unsigned char)(signature[index] ^ expected_signature[index]);
    if (signature_difference != 0) goto cleanup;

    size_t decoded_payload_length = 0;
    if (!yaza_http_jwt_base64url_decode(first_dot + 1, payload_length, payload_json,
                                        sizeof(payload_json), &decoded_payload_length)) goto cleanup;
    yaza_json_field claims[YAZA_HTTP_MAX_JSON_FIELDS];
    int claim_count = yaza_json_object_fields((const char *)payload_json, claims,
                                              YAZA_HTTP_MAX_JSON_FIELDS);
    if (claim_count < 0) goto cleanup;
    const yaza_json_field *issuer_field = yaza_http_json_field_find(claims, claim_count, "iss");
    const yaza_json_field *audience_field = yaza_http_json_field_find(claims, claim_count, "aud");
    const yaza_json_field *expiration_field = yaza_http_json_field_find(claims, claim_count, "exp");
    const yaza_json_field *subject_field = yaza_http_json_field_find(claims, claim_count, "sub");
    char issuer[513] = {0};
    if (issuer_field == NULL || audience_field == NULL ||
        !yaza_json_field_text(issuer_field, issuer, sizeof(issuer)) ||
        strcmp(issuer, expected_issuer) != 0 ||
        !yaza_http_jwt_audience_matches(audience_field, expected_audience)) goto cleanup;
    int64_t expiration = 0;
    int64_t not_before = 0;
    int64_t issued_at = 0;
    if (!yaza_http_jwt_numeric_date(expiration_field, &expiration)) goto cleanup;
    const yaza_json_field *not_before_field = yaza_http_json_field_find(claims, claim_count, "nbf");
    if (not_before_field != NULL &&
        (!yaza_http_jwt_numeric_date(not_before_field, &not_before))) goto cleanup;
    const yaza_json_field *issued_at_field = yaza_http_json_field_find(claims, claim_count, "iat");
    if (issued_at_field != NULL && !yaza_http_jwt_numeric_date(issued_at_field, &issued_at)) goto cleanup;
    if (subject_field != NULL) {
        char subject[1024] = {0};
        if (yaza_json_value_kind(subject_field->value) != 's' ||
            !yaza_json_decode_string(subject_field->value, subject_field->value_length,
                                     subject, sizeof(subject))) {
            yaza_secure_wipe(subject, sizeof(subject));
            goto cleanup;
        }
        yaza_secure_wipe(subject, sizeof(subject));
    }
    struct timespec now;
    if (clock_gettime(CLOCK_REALTIME, &now) != 0 || now.tv_sec < 0) goto cleanup;
    if ((not_before_field != NULL && not_before > (int64_t)now.tv_sec) ||
        (issued_at_field != NULL && issued_at > (int64_t)now.tv_sec)) goto cleanup;
    result = expiration <= (int64_t)now.tv_sec ? 2 : 1;
    if (result == 1) {
        if (decoded_payload_length + 1U > verified_claims_capacity) {
            result = 0;
            goto cleanup;
        }
        memcpy(verified_claims, payload_json, decoded_payload_length + 1U);
    }
cleanup:
    yaza_secure_wipe(authorization, sizeof(authorization));
    yaza_secure_wipe(header_json, sizeof(header_json));
    yaza_secure_wipe(payload_json, sizeof(payload_json));
    yaza_secure_wipe(signature, sizeof(signature));
    yaza_secure_wipe(expected_signature, sizeof(expected_signature));
    return result;
}

static bool yaza_http_host_valid(const char *value, size_t length) {
    if (value == NULL || length == 0 || length > 255) return false;
    const char *host_start = value;
    const char *host_end = value + length;
    char port[16] = "";
    if (*host_start == '[') {
        const char *close = memchr(host_start + 1, ']', (size_t)(host_end - host_start - 1));
        if (close == NULL || close == host_start + 1) return false;
        char address[INET6_ADDRSTRLEN];
        size_t address_length = (size_t)(close - host_start - 1);
        if (address_length >= sizeof(address)) return false;
        memcpy(address, host_start + 1, address_length);
        address[address_length] = '\0';
        struct in6_addr parsed_address;
        if (inet_pton(AF_INET6, address, &parsed_address) != 1) return false;
        host_start = close + 1;
        if (host_start == host_end) return true;
        if (*host_start++ != ':' || host_start == host_end || (size_t)(host_end - host_start) >= sizeof(port)) return false;
        memcpy(port, host_start, (size_t)(host_end - host_start));
        port[host_end - host_start] = '\0';
        int64_t parsed_port = 0;
        return yaza_http_parse_port(port, &parsed_port);
    }

    const char *colon = memchr(host_start, ':', (size_t)(host_end - host_start));
    if (colon != NULL) {
        if (memchr(colon + 1, ':', (size_t)(host_end - colon - 1)) != NULL ||
            colon + 1 == host_end || (size_t)(host_end - colon - 1) >= sizeof(port)) return false;
        memcpy(port, colon + 1, (size_t)(host_end - colon - 1));
        port[host_end - colon - 1] = '\0';
        int64_t parsed_port = 0;
        if (!yaza_http_parse_port(port, &parsed_port)) return false;
        host_end = colon;
    }
    if (host_start == host_end || (size_t)(host_end - host_start) > 253) return false;
    size_t label_length = 0;
    bool previous_hyphen = false;
    for (const unsigned char *cursor = (const unsigned char *)host_start;
         cursor < (const unsigned char *)host_end; cursor++) {
        unsigned char character = *cursor;
        if (character == '.') {
            if (label_length == 0 || previous_hyphen) return false;
            label_length = 0;
            previous_hyphen = false;
            continue;
        }
        if (!isalnum(character) && character != '-') return false;
        if (label_length == 0 && character == '-') return false;
        if (++label_length > 63) return false;
        previous_hyphen = character == '-';
    }
    return label_length > 0 && !previous_hyphen;
}

static bool yaza_http_allowed_host_entry_add(const char *value, size_t length) {
    if (value == NULL || length == 0 || length > YAZA_HTTP_ALLOWED_HOST_MAX_BYTES ||
        !yaza_http_host_valid(value, length)) return false;
    if (value[0] == '[') {
        if (value[length - 1] != ']') return false;
    } else if (memchr(value, ':', length) != NULL) {
        /* Configure host names, not authorities; request ports are ignored. */
        return false;
    }
    for (size_t index = 0; index < length; index++)
        if ((unsigned char)value[index] > 0x7fU) return false;
    for (size_t index = 0; index < yaza_http_allowed_host_count; index++) {
        if (strlen(yaza_http_allowed_hosts[index]) == length &&
            strncasecmp(yaza_http_allowed_hosts[index], value, length) == 0) return true;
    }
    if (yaza_http_allowed_host_count == YAZA_HTTP_MAX_ALLOWED_HOSTS) return false;
    char *destination = yaza_http_allowed_hosts[yaza_http_allowed_host_count++];
    for (size_t index = 0; index < length; index++)
        destination[index] = (char)tolower((unsigned char)value[index]);
    destination[length] = '\0';
    return true;
}

static bool yaza_http_allowed_hosts_configure(const char *listen_host, bool loopback_bind) {
    yaza_http_allowed_host_count = 0;
    const char *configured = getenv("YAZA_ALLOWED_HOSTS");
    if (configured == NULL) {
        if (!loopback_bind ||
            !yaza_http_allowed_host_entry_add("127.0.0.1", sizeof("127.0.0.1") - 1U) ||
            !yaza_http_allowed_host_entry_add("localhost", sizeof("localhost") - 1U) ||
            !yaza_http_allowed_host_entry_add(listen_host, strlen(listen_host))) return false;
        return true;
    }
    size_t configured_length = strnlen(configured, YAZA_HTTP_ALLOWED_HOST_LIST_MAX_BYTES + 1U);
    if (configured_length == 0 || configured_length > YAZA_HTTP_ALLOWED_HOST_LIST_MAX_BYTES) return false;
    size_t start = 0;
    for (size_t index = 0; index <= configured_length; index++) {
        if (index != configured_length && configured[index] != ',') continue;
        size_t left = start;
        size_t right = index;
        while (left < right && (configured[left] == ' ' || configured[left] == '\t')) left++;
        while (right > left && (configured[right - 1] == ' ' || configured[right - 1] == '\t')) right--;
        if (!yaza_http_allowed_host_entry_add(configured + left, right - left)) return false;
        start = index + 1U;
    }
    return yaza_http_allowed_host_count > 0;
}

static bool yaza_http_host_allowed(const char *value, size_t length) {
    if (value == NULL || length == 0 || !yaza_http_host_valid(value, length)) return false;
    const char *host_end = value + length;
    if (*value == '[') {
        const char *close = memchr(value + 1, ']', length - 1U);
        if (close == NULL) return false;
        host_end = close + 1;
    } else {
        const char *colon = memchr(value, ':', length);
        if (colon != NULL) host_end = colon;
    }
    size_t host_length = (size_t)(host_end - value);
    for (size_t index = 0; index < yaza_http_allowed_host_count; index++) {
        if (strlen(yaza_http_allowed_hosts[index]) == host_length &&
            strncasecmp(yaza_http_allowed_hosts[index], value, host_length) == 0) return true;
    }
    return false;
}

static bool yaza_http_json_content_type(const char *value, size_t length) {
    static const char media_type[] = "application/json";
    if (value == NULL || length < sizeof(media_type) - 1 ||
        strncasecmp(value, media_type, sizeof(media_type) - 1) != 0) return false;
    size_t offset = sizeof(media_type) - 1;
    while (offset < length && (value[offset] == ' ' || value[offset] == '\t')) offset++;
    if (offset == length) return true;
    if (value[offset++] != ';') return false;
    if (offset == length) return false;
    for (; offset < length; offset++) {
        unsigned char character = (unsigned char)value[offset];
        if (character < 0x20 || character > 0x7e) return false;
    }
    return true;
}

static bool yaza_http_decode_path(char *target) {
    char *query = strchr(target, '?');
    char *path_end = query == NULL ? target + strlen(target) : query;
    size_t length = (size_t)(path_end - target);
    size_t read_index = 0;
    size_t write_index = 0;
    while (read_index < length) {
        unsigned char character = (unsigned char)target[read_index++];
        if (character == '%') {
            if (read_index + 1 >= length) return false;
            int high = yaza_hex_value((unsigned char)target[read_index]);
            int low = yaza_hex_value((unsigned char)target[read_index + 1]);
            if (high < 0 || low < 0) return false;
            character = (unsigned char)((high << 4) | low);
            read_index += 2;
            if (character == '/' || character == '\\' || character == '?' || character == '#') return false;
        }
        if (character == '\0' || character < 0x20 || character > 0x7e || character == '#' || character == '\\') return false;
        target[write_index++] = (char)character;
    }
    memmove(target + write_index, path_end, strlen(path_end) + 1);
    return true;
}

static bool yaza_http_bound_parameters_valid(const yaza_http_parameter *parameters, size_t count,
                                            const char *route_pattern, const char *path,
                                            const char *query, const char *request,
                                            yaza_http_validation_error *error) {
    if (query != NULL && *query != '\0') {
        const char *cursor = query;
        while (*cursor != '\0') {
            const char *key = cursor;
            while (*cursor != '\0' && *cursor != '=' && *cursor != '&') cursor++;
            size_t key_length = (size_t)(cursor - key);
            if (key_length == 0 || *cursor != '=') {
                yaza_http_validation_error_set(error, "$", "invalid_query");
                return false;
            }
            char name[128];
            if (!yaza_http_decode_component(key, key_length, name, sizeof(name), true)) {
                yaza_http_validation_error_set(error, "$", "invalid_query");
                return false;
            }
            if (yaza_http_parameter_find(parameters, count, "query", name) == NULL) {
                yaza_http_validation_error_set(error, "$", "unknown_field");
                return false;
            }
            while (*cursor != '\0' && *cursor != '&') cursor++;
            if (*cursor == '&') cursor++;
        }
    }
    for (size_t index = 0; index < count; index++) {
        const yaza_http_parameter *parameter = &parameters[index];
        if (strcmp(parameter->kind, "body") == 0) continue;
        char value[1024];
        bool found = false;
        bool valid = true;
        if (strcmp(parameter->kind, "path") == 0) {
            valid = yaza_http_path_parameter_value(route_pattern, path, parameter->name, value, sizeof(value), &found);
        } else if (strcmp(parameter->kind, "query") == 0) {
            valid = yaza_http_query_parameter_value(query, parameter->name, value, sizeof(value), &found);
        } else {
            valid = yaza_http_header_parameter_value(request, parameter->name, value, sizeof(value), &found);
        }
        if (!valid) {
            yaza_http_validation_error_set_child(error, "", parameter->name, "invalid_value");
            return false;
        }
        if (!found && parameter->required) {
            yaza_http_validation_error_set_child(error, "", parameter->name, "required");
            return false;
        }
        if (found && !yaza_http_value_matches(value, parameter->value_type)) {
            yaza_http_validation_error_set_child(error, "", parameter->name, "invalid_value");
            return false;
        }
    }
    return true;
}

static yaza_option yaza_http_request_parameter_as(const char *kind, const char *name, const char *expected_type) {
    if (yaza_http_active_request == NULL || yaza_http_active_request->route == NULL ||
        kind == NULL || name == NULL || expected_type == NULL) return yaza_option_none();
    yaza_http_parameter parameters[YAZA_HTTP_MAX_JSON_FIELDS];
    size_t parameter_count = 0;
    if (!yaza_http_controller_parameters(yaza_http_active_request->route->metadata, parameters,
                                         YAZA_HTTP_MAX_JSON_FIELDS, &parameter_count))
        return yaza_option_none();
    const yaza_http_parameter *parameter = yaza_http_parameter_find(parameters, parameter_count, kind, name);
    if (parameter == NULL || strcmp(parameter->value_type, expected_type) != 0) return yaza_option_none();
    char value[1024];
    bool found = false;
    bool valid = false;
    if (strcmp(kind, "path") == 0) {
        valid = yaza_http_path_parameter_value(yaza_http_active_request->route->path,
                                               yaza_http_active_request->path, name,
                                               value, sizeof(value), &found);
    } else if (strcmp(kind, "query") == 0) {
        valid = yaza_http_query_parameter_value(yaza_http_active_request->query, name,
                                               value, sizeof(value), &found);
    } else if (strcmp(kind, "header") == 0) {
        valid = yaza_http_header_parameter_value(yaza_http_active_request->request, name,
                                                value, sizeof(value), &found);
    } else if (strcmp(kind, "body") == 0) {
        valid = yaza_http_body_field_value(yaza_http_active_request->route->body_schema,
                                           yaza_http_active_request->body, name,
                                           expected_type, value, sizeof(value));
        found = valid;
    }
    if (!valid) return yaza_option_none();
    if (!found) {
        if (parameter->required || !parameter->has_default) return yaza_option_none();
        snprintf(value, sizeof(value), "%s", parameter->default_value);
    }
    if (!yaza_http_value_matches(value, expected_type)) return yaza_option_none();
    if (strcmp(expected_type, "Text") == 0)
        return yaza_option_some_text(yaza_copy_text(value));
    if (strcmp(expected_type, "Boolean") == 0)
        return yaza_option_some_boolean(strcmp(value, "true") == 0);
    if (strcmp(expected_type, "Float64") == 0) {
        errno = 0;
        char *end = NULL;
        double parsed = strtod(value, &end);
        if (errno != 0 || end == value || *end != '\0' || !isfinite(parsed)) return yaza_option_none();
        return yaza_option_some_float64(parsed);
    }
    errno = 0;
    char *end = NULL;
    long long parsed = strtoll(value, &end, 10);
    if (errno != 0 || end == value || *end != '\0') return yaza_option_none();
    if (strcmp(expected_type, "Int32") == 0) {
        if (parsed < INT32_MIN || parsed > INT32_MAX) return yaza_option_none();
        return yaza_option_some_int32((int32_t)parsed);
    }
    if (strcmp(expected_type, "Number") == 0)
        return yaza_option_some_number((int64_t)parsed);
    return yaza_option_none();
}

static yaza_option yaza_http_auth_claim_text(const char *name) {
    const yaza_http_request_context *request = yaza_http_active_request;
    if (request == NULL || request->route == NULL || request->route->auth_policy != 3 ||
        request->verified_jwt_claims == NULL || name == NULL) return yaza_option_none();
    size_t name_length = strnlen(name, 129U);
    if (name_length == 0 || name_length > 128U) return yaza_option_none();
    yaza_json_field claims[YAZA_HTTP_MAX_JSON_FIELDS];
    int claim_count = yaza_json_object_fields(request->verified_jwt_claims, claims,
                                              YAZA_HTTP_MAX_JSON_FIELDS);
    if (claim_count < 0) return yaza_option_none();
    const yaza_json_field *claim = yaza_http_json_field_find(claims, claim_count, name);
    if (claim == NULL || yaza_json_value_kind(claim->value) != 's') return yaza_option_none();
    char value[1024];
    if (!yaza_json_decode_string(claim->value, claim->value_length, value, sizeof(value))) {
        yaza_secure_wipe(value, sizeof(value));
        return yaza_option_none();
    }
    char *owned_value = yaza_copy_text(value);
    yaza_secure_wipe(value, sizeof(value));
    if (owned_value == NULL) return yaza_option_none();
    return yaza_option_some_text(owned_value);
}

static bool yaza_json_object_id(const char *json, char *output, size_t capacity) {
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int count = yaza_json_object_fields(json, fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (count < 0) return false;
    for (int index = 0; index < count; index++) {
        if (strcmp(fields[index].name, "id") == 0)
            return yaza_json_field_text(&fields[index], output, capacity);
    }
    return false;
}

static bool yaza_http_resource_base_path(const char *route_path, char *output, size_t capacity) {
    const char *parameter = strchr(route_path, '{');
    size_t length = strlen(route_path);
    if (parameter != NULL) {
        const char *close = strchr(parameter, '}');
        if (close == NULL || close[1] != '\0' || parameter == route_path || parameter[-1] != '/') return false;
        length = (size_t)(parameter - route_path) - 1;
    }
    if (length == 0 || length >= capacity) return false;
    memcpy(output, route_path, length);
    output[length] = '\0';
    return true;
}

static bool yaza_http_id_is_safe(const char *id);

static int yaza_http_resource_load(yaza_http_resource *resource, const char *base_path, const char *json) {
    const char *cursor = yaza_json_skip_space(json);
    if (*cursor != '[') return -1;
    resource->path = yaza_copy_text(base_path);
    if (resource->path == NULL) return -1;
    resource->count = 0;
    resource->next_id = 1;
    cursor++;
    for (;;) {
        cursor = yaza_json_skip_space(cursor);
        if (*cursor == ']') return resource->count > 0 && *yaza_json_skip_space(cursor + 1) == '\0' ? 0 : -1;
        if (resource->count == YAZA_HTTP_MAX_RECORDS) return -1;
        const char *end = yaza_json_skip_value(cursor);
        if (end == NULL || *yaza_json_skip_space(end) != ',' && *yaza_json_skip_space(end) != ']') return -1;
        char *record = (char *)malloc((size_t)(end - cursor) + 1);
        if (record == NULL) return -1;
        memcpy(record, cursor, (size_t)(end - cursor));
        record[end - cursor] = '\0';
        if (resource->count == 0) {
            yaza_json_field schema_fields[YAZA_HTTP_MAX_JSON_FIELDS];
            resource->schema = yaza_copy_text(record);
            int schema_count = resource->schema == NULL ? -1 :
                yaza_json_object_fields(record, schema_fields, YAZA_HTTP_MAX_JSON_FIELDS);
            bool has_text_id = false;
            for (int field = 0; field < schema_count; field++) {
                if (strcmp(schema_fields[field].name, "id") == 0 &&
                    yaza_json_value_kind(schema_fields[field].value) == 's') has_text_id = true;
            }
            if (schema_count < 0 || !has_text_id) {
                free(record);
                return -1;
            }
        } else if (!yaza_json_object_matches_schema(record, resource->schema, false, true, NULL)) {
            free(record);
            return -1;
        }
        char id[128];
        if (!yaza_json_object_id(record, id, sizeof(id)) || !yaza_http_id_is_safe(id)) {
            free(record);
            return -1;
        }
        for (size_t prior = 0; prior < resource->count; prior++) {
            char prior_id[128];
            if (yaza_json_object_id(resource->items[prior], prior_id, sizeof(prior_id)) && strcmp(id, prior_id) == 0) {
                free(record);
                return -1;
            }
        }
        resource->items[resource->count++] = record;
        char *dash = strrchr(id, '-');
        if (dash != NULL && dash[1] != '\0') {
            char *tail = NULL;
            unsigned long value = strtoul(dash + 1, &tail, 10);
            if (tail != dash + 1 && *tail == '\0' && value >= resource->next_id)
                resource->next_id = (size_t)value + 1;
        }
        cursor = yaza_json_skip_space(end);
        if (*cursor == ']') return *yaza_json_skip_space(cursor + 1) == '\0' ? 0 : -1;
        cursor++;
    }
}

static yaza_http_resource *yaza_http_resource_find(yaza_http_resource *resources, size_t count, const char *path) {
    for (size_t index = 0; index < count; index++)
        if (strcmp(resources[index].path, path) == 0) return &resources[index];
    return NULL;
}

static bool yaza_http_resource_item_id(const yaza_http_resource *resource, const char *path, char *id, size_t capacity) {
    size_t base_length = strlen(resource->path);
    if (strncmp(path, resource->path, base_length) != 0 || path[base_length] != '/') return false;
    const char *value = path + base_length + 1;
    if (*value == '\0' || strchr(value, '/') != NULL || strlen(value) >= capacity) return false;
    memcpy(id, value, strlen(value) + 1);
    return true;
}

static int yaza_http_query_pagination(const char *query, size_t *limit, size_t *offset,
                                      const yaza_http_parameter *parameters, size_t parameter_count) {
    if (query == NULL || *query == '\0') return 0;
    const char *cursor = query;
    bool limit_found = false;
    bool offset_found = false;
    while (*cursor != '\0') {
        const char *key = cursor;
        while (*cursor != '\0' && *cursor != '=' && *cursor != '&') cursor++;
        size_t key_length = (size_t)(cursor - key);
        const char *value = NULL;
        size_t value_length = 0;
        if (*cursor == '=') {
            cursor++;
            value = cursor;
            while (*cursor != '\0' && *cursor != '&') cursor++;
            value_length = (size_t)(cursor - value);
        }
        if (key_length == 0 || key_length >= 128) return -1;
        char key_name[128];
        if (!yaza_http_decode_component(key, key_length, key_name, sizeof(key_name), true)) return -1;
        if (yaza_http_parameter_find(parameters, parameter_count, "query", key_name) == NULL ||
            value == NULL || value_length == 0) return -1;
        if (strcmp(key_name, "limit") == 0) {
            char number[32];
            if (limit_found || !yaza_http_decode_component(value, value_length, number, sizeof(number), true) ||
                number[0] == '\0') return -1;
            errno = 0;
            char *end = NULL;
            unsigned long long parsed = strtoull(number, &end, 10);
            if (errno != 0 || end == number || *end != '\0' || parsed == 0 || parsed > 100) return -1;
            *limit = (size_t)parsed;
            limit_found = true;
        } else if (strcmp(key_name, "offset") == 0) {
            char number[32];
            if (offset_found || !yaza_http_decode_component(value, value_length, number, sizeof(number), true) ||
                number[0] == '\0') return -1;
            errno = 0;
            char *end = NULL;
            unsigned long long parsed = strtoull(number, &end, 10);
            if (errno != 0 || end == number || *end != '\0' || parsed > INT32_MAX) return -1;
            *offset = (size_t)parsed;
            offset_found = true;
        } else if (value_length == 0) {
            return -1;
        }
        if (*cursor == '&') cursor++;
    }
    return (limit_found || offset_found) ? 1 : 0;
}

static int yaza_http_record_id_compare(const void *left_value, const void *right_value) {
    const char *left = *(const char *const *)left_value;
    const char *right = *(const char *const *)right_value;
    char left_id[128], right_id[128];
    bool left_has_id = yaza_json_object_id(left, left_id, sizeof(left_id));
    bool right_has_id = yaza_json_object_id(right, right_id, sizeof(right_id));
    if (left_has_id && right_has_id) return strcmp(left_id, right_id);
    return strcmp(left, right);
}

static char *yaza_http_resource_json(const yaza_http_resource *resource, size_t limit, size_t offset) {
    size_t capacity = 3;
    size_t start = offset < resource->count ? offset : resource->count;
    size_t remaining = resource->count - start;
    size_t count = limit < remaining ? limit : remaining;
    const char *ordered[YAZA_HTTP_MAX_RECORDS];
    for (size_t index = 0; index < resource->count; index++) ordered[index] = resource->items[index];
    qsort(ordered, resource->count, sizeof(ordered[0]), yaza_http_record_id_compare);
    for (size_t index = 0; index < count; index++) capacity += strlen(ordered[start + index]) + 1;
    char *json = (char *)malloc(capacity);
    if (json == NULL) return NULL;
    size_t length = 0;
    json[length++] = '[';
    for (size_t index = 0; index < count; index++) {
        if (index > 0) json[length++] = ',';
        size_t item_length = strlen(ordered[start + index]);
        memcpy(json + length, ordered[start + index], item_length);
        length += item_length;
    }
    json[length++] = ']';
    json[length] = '\0';
    return json;
}

static int yaza_http_resource_find_id(const yaza_http_resource *resource, const char *id) {
    for (size_t index = 0; index < resource->count; index++) {
        char item_id[128];
        if (yaza_json_object_id(resource->items[index], item_id, sizeof(item_id)) && strcmp(item_id, id) == 0)
            return (int)index;
    }
    return -1;
}

static yaza_http_resource *yaza_http_resource_for_path(yaza_http_resource *resources, size_t count, const char *path) {
    char id[256];
    if (pthread_mutex_lock(&yaza_http_resources_mutex) != 0) return NULL;
    yaza_http_resource *found = NULL;
    for (size_t index = 0; index < count; index++) {
        if (strcmp(resources[index].path, path) == 0 ||
            yaza_http_resource_item_id(&resources[index], path, id, sizeof(id))) {
            found = &resources[index];
            break;
        }
    }
    pthread_mutex_unlock(&yaza_http_resources_mutex);
    return found;
}

static bool yaza_http_id_is_safe(const char *id) {
    if (*id == '\0') return false;
    for (const unsigned char *cursor = (const unsigned char *)id; *cursor != '\0'; cursor++)
        if (!isalnum(*cursor) && *cursor != '-' && *cursor != '_') return false;
    return true;
}

static bool yaza_http_append(char *buffer, size_t capacity, size_t *length, const char *text, size_t text_length) {
    if (*length + text_length + 1 > capacity) return false;
    memcpy(buffer + *length, text, text_length);
    *length += text_length;
    buffer[*length] = '\0';
    return true;
}

static char *yaza_json_merge_object(const char *original, const char *patch) {
    yaza_json_field old_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    yaza_json_field patch_fields[YAZA_HTTP_MAX_JSON_FIELDS];
    int old_count = yaza_json_object_fields(original, old_fields, YAZA_HTTP_MAX_JSON_FIELDS);
    int patch_count = yaza_json_object_fields(patch, patch_fields, YAZA_HTTP_MAX_JSON_FIELDS);
    if (old_count < 0 || patch_count < 0) return NULL;
    size_t capacity = strlen(original) + strlen(patch) + 16;
    char *merged = (char *)malloc(capacity);
    if (merged == NULL) return NULL;
    size_t length = 0;
    if (!yaza_http_append(merged, capacity, &length, "{", 1)) { free(merged); return NULL; }
    bool first = true;
    for (int index = 0; index < old_count; index++) {
        yaza_json_field *selected = &old_fields[index];
        for (int patch_index = 0; patch_index < patch_count; patch_index++) {
            if (strcmp(old_fields[index].name, patch_fields[patch_index].name) == 0) {
                selected = &patch_fields[patch_index];
                patch_fields[patch_index].used = true;
                break;
            }
        }
        if (!first && !yaza_http_append(merged, capacity, &length, ",", 1)) { free(merged); return NULL; }
        first = false;
        if (!yaza_http_append(merged, capacity, &length, selected->key, selected->key_length) ||
            !yaza_http_append(merged, capacity, &length, ":", 1) ||
            !yaza_http_append(merged, capacity, &length, selected->value, selected->value_length)) { free(merged); return NULL; }
    }
    for (int index = 0; index < patch_count; index++) {
        if (patch_fields[index].used) continue;
        if (!first && !yaza_http_append(merged, capacity, &length, ",", 1)) { free(merged); return NULL; }
        first = false;
        if (!yaza_http_append(merged, capacity, &length, patch_fields[index].key, patch_fields[index].key_length) ||
            !yaza_http_append(merged, capacity, &length, ":", 1) ||
            !yaza_http_append(merged, capacity, &length, patch_fields[index].value, patch_fields[index].value_length)) { free(merged); return NULL; }
    }
    if (!yaza_http_append(merged, capacity, &length, "}", 1)) { free(merged); return NULL; }
    return merged;
}

static yaza_result yaza_http_memory_record_result(bool is_ok, const char *value) {
    if (value == NULL) {
        is_ok = false;
        value = "unavailable";
    }
    size_t length = strlen(value);
    if (length > YAZA_HTTP_RESPONSE_MAX_BYTES) {
        is_ok = false;
        value = "unavailable";
        length = strlen(value);
    }
    char *copy = (char *)malloc(length + 1);
    if (copy == NULL) return yaza_result_err(yaza_option_some_text("unavailable"));
    memcpy(copy, value, length + 1);
    return is_ok ? yaza_result_ok(yaza_option_some_text(copy)) : yaza_result_err(yaza_option_some_text(copy));
}

static yaza_http_resource *yaza_http_memory_active_resource(void) {
    const yaza_http_request_context *request = yaza_http_active_request;
    if (request == NULL || request->route == NULL || request->path == NULL || request->resource == NULL)
        return NULL;
    return request->resource;
}

static yaza_result yaza_http_memory_records_list(int64_t limit, int64_t offset) {
    yaza_http_resource *resource = yaza_http_memory_active_resource();
    if (resource == NULL) return yaza_http_memory_record_result(false, "unavailable");
    if (limit < 1 || limit > 100 || offset < 0 || offset > INT32_MAX)
        return yaza_http_memory_record_result(false, "invalid_pagination");
    if (pthread_mutex_lock(&yaza_http_resources_mutex) != 0)
        return yaza_http_memory_record_result(false, "unavailable");
    char *json = yaza_http_resource_json(resource, (size_t)limit, (size_t)offset);
    if (json == NULL) {
        pthread_mutex_unlock(&yaza_http_resources_mutex);
        return yaza_http_memory_record_result(false, "unavailable");
    }
    yaza_result result = yaza_http_memory_record_result(true, json);
    free(json);
    pthread_mutex_unlock(&yaza_http_resources_mutex);
    return result;
}

static yaza_result yaza_http_memory_records_find(const char *id) {
    yaza_http_resource *resource = yaza_http_memory_active_resource();
    if (resource == NULL) return yaza_http_memory_record_result(false, "unavailable");
    if (id == NULL || !yaza_http_id_is_safe(id))
        return yaza_http_memory_record_result(false, "invalid_id");
    if (pthread_mutex_lock(&yaza_http_resources_mutex) != 0)
        return yaza_http_memory_record_result(false, "unavailable");
    int index = yaza_http_resource_find_id(resource, id);
    yaza_result result = index < 0
        ? yaza_http_memory_record_result(false, "not_found")
        : yaza_http_memory_record_result(true, resource->items[index]);
    pthread_mutex_unlock(&yaza_http_resources_mutex);
    return result;
}

static yaza_result yaza_http_memory_records_create(const char *id, const char *payload) {
    yaza_http_resource *resource = yaza_http_memory_active_resource();
    if (resource == NULL) return yaza_http_memory_record_result(false, "unavailable");
    if (id == NULL || payload == NULL || !yaza_http_id_is_safe(id))
        return yaza_http_memory_record_result(false, "invalid_record");
    if (pthread_mutex_lock(&yaza_http_resources_mutex) != 0)
        return yaza_http_memory_record_result(false, "unavailable");
    yaza_result result;
    if (resource->count >= YAZA_HTTP_MAX_RECORDS) {
        result = yaza_http_memory_record_result(false, "unavailable");
        goto memory_create_done;
    }
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    char payload_id[128];
    yaza_http_validation_error validation_error = {0};
    if (yaza_json_object_fields(payload, fields, YAZA_HTTP_MAX_JSON_FIELDS) < 0 ||
        !yaza_json_object_id(payload, payload_id, sizeof(payload_id)) || strcmp(id, payload_id) != 0 ||
        !yaza_json_object_matches_schema(payload, resource->schema, false, true, &validation_error)) {
        result = yaza_http_memory_record_result(false, "invalid_record");
        goto memory_create_done;
    }
    if (yaza_http_resource_find_id(resource, id) >= 0) {
        result = yaza_http_memory_record_result(false, "already_exists");
        goto memory_create_done;
    }
    size_t length = strlen(payload);
    if (length >= YAZA_HTTP_RESPONSE_MAX_BYTES) {
        result = yaza_http_memory_record_result(false, "unavailable");
        goto memory_create_done;
    }
    char *stored = (char *)malloc(length + 1);
    if (stored == NULL) {
        result = yaza_http_memory_record_result(false, "unavailable");
        goto memory_create_done;
    }
    memcpy(stored, payload, length + 1);
    if (!yaza_memory_transfer(stored, &yaza_program_memory_arena)) {
        free(stored);
        result = yaza_http_memory_record_result(false, "unavailable");
        goto memory_create_done;
    }
    resource->items[resource->count++] = stored;
    result = yaza_http_memory_record_result(true, stored);
memory_create_done:
    pthread_mutex_unlock(&yaza_http_resources_mutex);
    return result;
}

static yaza_result yaza_http_memory_records_update(const char *id, const char *payload, bool is_patch) {
    yaza_http_resource *resource = yaza_http_memory_active_resource();
    if (resource == NULL) return yaza_http_memory_record_result(false, "unavailable");
    if (id == NULL || payload == NULL || !yaza_http_id_is_safe(id))
        return yaza_http_memory_record_result(false, "invalid_record");
    if (pthread_mutex_lock(&yaza_http_resources_mutex) != 0)
        return yaza_http_memory_record_result(false, "unavailable");
    yaza_result result;
    int index = yaza_http_resource_find_id(resource, id);
    if (index < 0) {
        result = yaza_http_memory_record_result(false, "not_found");
        goto memory_update_done;
    }
    yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
    char payload_id[128];
    yaza_http_validation_error validation_error = {0};
    if (yaza_json_object_fields(payload, fields, YAZA_HTTP_MAX_JSON_FIELDS) < 0 ||
        !yaza_json_object_id(payload, payload_id, sizeof(payload_id)) || strcmp(id, payload_id) != 0 ||
        !yaza_json_object_matches_schema(payload, resource->schema, is_patch, true, &validation_error)) {
        result = yaza_http_memory_record_result(false, "invalid_record");
        goto memory_update_done;
    }
    char *updated = yaza_json_merge_object(resource->items[index], payload);
    if (updated == NULL || strlen(updated) >= YAZA_HTTP_RESPONSE_MAX_BYTES) {
        free(updated);
        result = yaza_http_memory_record_result(false, "unavailable");
        goto memory_update_done;
    }
    if (!yaza_memory_transfer(updated, &yaza_program_memory_arena)) {
        free(updated);
        result = yaza_http_memory_record_result(false, "unavailable");
        goto memory_update_done;
    }
    free(resource->items[index]);
    resource->items[index] = updated;
    result = yaza_http_memory_record_result(true, updated);
memory_update_done:
    pthread_mutex_unlock(&yaza_http_resources_mutex);
    return result;
}

static yaza_result yaza_http_memory_records_replace(const char *id, const char *payload) {
    return yaza_http_memory_records_update(id, payload, false);
}

static yaza_result yaza_http_memory_records_patch(const char *id, const char *payload) {
    return yaza_http_memory_records_update(id, payload, true);
}

static yaza_result yaza_http_memory_records_delete(const char *id) {
    yaza_http_resource *resource = yaza_http_memory_active_resource();
    if (resource == NULL) return yaza_http_memory_record_result(false, "unavailable");
    if (id == NULL || !yaza_http_id_is_safe(id))
        return yaza_http_memory_record_result(false, "invalid_id");
    if (pthread_mutex_lock(&yaza_http_resources_mutex) != 0)
        return yaza_http_memory_record_result(false, "unavailable");
    int index = yaza_http_resource_find_id(resource, id);
    if (index < 0) {
        yaza_result result = yaza_http_memory_record_result(false, "not_found");
        pthread_mutex_unlock(&yaza_http_resources_mutex);
        return result;
    }
    free(resource->items[index]);
    for (size_t move = (size_t)index + 1; move < resource->count; move++)
        resource->items[move - 1] = resource->items[move];
    resource->items[resource->count - 1] = NULL;
    resource->count--;
    yaza_result result = yaza_http_memory_record_result(true, "deleted");
    pthread_mutex_unlock(&yaza_http_resources_mutex);
    return result;
}

static void yaza_http_crud_respond(int client_fd, yaza_http_resource *resource, const char *method,
                                   const char *path, const char *query, const char *request_body,
                                   const yaza_http_parameter *parameters, size_t parameter_count,
                                   const char *request_schema) {
    static const char bad_request[] = "{\"error\":\"Bad Request\"}";
    static const char not_found[] = "{\"error\":\"Not Found\"}";
    static const char conflict[] = "{\"error\":\"Conflict\"}";
    static const char unavailable[] = "{\"error\":\"Resource limit reached\"}";
    yaza_http_validation_error validation_error = {0};
    char id[256] = "";
    bool collection = strcmp(path, resource->path) == 0;
    if (!collection && !yaza_http_resource_item_id(resource, path, id, sizeof(id))) {
        yaza_http_respond(client_fd, 404, "Not Found", not_found);
        return;
    }
    if (strcmp(method, "GET") == 0 && collection) {
        size_t limit = resource->count;
        size_t offset = 0;
        const yaza_http_parameter *limit_parameter = yaza_http_parameter_find(parameters, parameter_count, "query", "limit");
        if (limit_parameter != NULL && limit_parameter->has_default) {
            errno = 0;
            char *end = NULL;
            unsigned long long configured = strtoull(limit_parameter->default_value, &end, 10);
            if (errno != 0 || end == limit_parameter->default_value || *end != '\0' || configured == 0 || configured > 100) {
                yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
                return;
            }
            limit = (size_t)configured;
        }
        int query_status = yaza_http_query_pagination(query, &limit, &offset, parameters, parameter_count);
        if (query_status < 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        char *json = yaza_http_resource_json(resource, limit, offset);
        if (json == NULL) yaza_http_respond(client_fd, 500, "Internal Server Error", bad_request);
        else { yaza_http_respond(client_fd, 200, "OK", json); free(json); }
        return;
    }
    if (strcmp(method, "GET") == 0 && !collection) {
        int index = yaza_http_resource_find_id(resource, id);
        if (index < 0) yaza_http_respond(client_fd, 404, "Not Found", not_found);
        else yaza_http_respond(client_fd, 200, "OK", resource->items[index]);
        return;
    }
    if (strcmp(method, "POST") == 0 && collection) {
        yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
        if (request_body == NULL || yaza_json_object_fields(request_body, fields, YAZA_HTTP_MAX_JSON_FIELDS) < 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        const char *schema = request_schema != NULL && *request_schema != '\0' ? request_schema : resource->schema;
        if (!yaza_json_object_matches_schema(request_body, schema, false, false, &validation_error)) {
            yaza_http_respond_validation_error(client_fd, &validation_error);
            return;
        }
        if (resource->count == YAZA_HTTP_MAX_RECORDS) {
            yaza_http_respond(client_fd, 507, "Insufficient Storage", unavailable);
            return;
        }
        char new_id[128];
        bool supplied_id = yaza_json_object_id(request_body, new_id, sizeof(new_id));
        if (!supplied_id) {
            bool duplicate = true;
            do {
                snprintf(new_id, sizeof(new_id), "sku-%03zu", resource->next_id++);
                duplicate = yaza_http_resource_find_id(resource, new_id) >= 0;
            } while (duplicate);
        }
        if (!yaza_http_id_is_safe(new_id)) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        if (yaza_http_resource_find_id(resource, new_id) >= 0) {
            yaza_http_respond(client_fd, 409, "Conflict", conflict);
            return;
        }
        const char *trimmed = yaza_json_skip_space(request_body);
        size_t body_length = strlen(trimmed);
        size_t capacity = body_length + strlen(new_id) + 16;
        char *created = (char *)malloc(capacity);
        if (created == NULL) { yaza_http_respond(client_fd, 500, "Internal Server Error", bad_request); return; }
        if (supplied_id) snprintf(created, capacity, "%s", trimmed);
        else if (body_length == 2) snprintf(created, capacity, "{\"id\":\"%s\"}", new_id);
        else snprintf(created, capacity, "{\"id\":\"%s\",%s", new_id, trimmed + 1);
        if (!yaza_memory_transfer(created, &yaza_program_memory_arena)) {
            free(created);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        resource->items[resource->count++] = created;
        yaza_http_respond(client_fd, 201, "Created", created);
        return;
    }
    if (strcmp(method, "PUT") == 0 && !collection) {
        int index = yaza_http_resource_find_id(resource, id);
        if (index < 0) { yaza_http_respond(client_fd, 404, "Not Found", not_found); return; }
        if (request_body == NULL) { yaza_http_respond(client_fd, 400, "Bad Request", bad_request); return; }
        yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
        if (yaza_json_object_fields(request_body, fields, YAZA_HTTP_MAX_JSON_FIELDS) < 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        const char *schema = request_schema != NULL && *request_schema != '\0' ? request_schema : resource->schema;
        if (!yaza_json_object_matches_schema(request_body, schema, false, false, &validation_error)) {
            yaza_http_respond_validation_error(client_fd, &validation_error);
            return;
        }
        char supplied_id[256];
        if (yaza_json_object_id(request_body, supplied_id, sizeof(supplied_id)) && strcmp(id, supplied_id) != 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        char *updated = yaza_json_merge_object(resource->items[index], request_body);
        if (updated == NULL) { yaza_http_respond(client_fd, 500, "Internal Server Error", bad_request); return; }
        if (!yaza_memory_transfer(updated, &yaza_program_memory_arena)) {
            free(updated);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        free(resource->items[index]);
        resource->items[index] = updated;
        yaza_http_respond(client_fd, 200, "OK", updated);
        return;
    }
    if (strcmp(method, "PATCH") == 0 && !collection) {
        int index = yaza_http_resource_find_id(resource, id);
        if (index < 0) { yaza_http_respond(client_fd, 404, "Not Found", not_found); return; }
        if (request_body == NULL) { yaza_http_respond(client_fd, 400, "Bad Request", bad_request); return; }
        yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
        if (yaza_json_object_fields(request_body, fields, YAZA_HTTP_MAX_JSON_FIELDS) < 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        const char *schema = request_schema != NULL && *request_schema != '\0' ? request_schema : resource->schema;
        if (!yaza_json_object_matches_schema(request_body, schema, true, false, &validation_error)) {
            yaza_http_respond_validation_error(client_fd, &validation_error);
            return;
        }
        char old_id[256], patch_id[256];
        bool has_old_id = yaza_json_object_id(resource->items[index], old_id, sizeof(old_id));
        bool has_patch_id = yaza_json_object_id(request_body, patch_id, sizeof(patch_id));
        if (has_patch_id && (!has_old_id || strcmp(old_id, patch_id) != 0)) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        char *updated = yaza_json_merge_object(resource->items[index], request_body);
        if (updated == NULL) { yaza_http_respond(client_fd, 400, "Bad Request", bad_request); return; }
        if (!yaza_memory_transfer(updated, &yaza_program_memory_arena)) {
            free(updated);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        free(resource->items[index]);
        resource->items[index] = updated;
        yaza_http_respond(client_fd, 200, "OK", updated);
        return;
    }
    if (strcmp(method, "DELETE") == 0 && !collection) {
        int index = yaza_http_resource_find_id(resource, id);
        if (index < 0) { yaza_http_respond(client_fd, 404, "Not Found", not_found); return; }
        free(resource->items[index]);
        for (size_t move = (size_t)index + 1; move < resource->count; move++) resource->items[move - 1] = resource->items[move];
        resource->count--;
        yaza_http_respond(client_fd, 204, "No Content", "");
        return;
    }
    yaza_http_respond_method_not_allowed(client_fd, collection ? "GET, HEAD, POST" : "GET, HEAD, PUT, PATCH, DELETE");
}

#ifdef YAZA_WITH_POSTGRES
static void yaza_http_pg_crud_respond(int client_fd, yaza_http_resource *resource, const char *method,
                                      const char *path, const char *query, const char *request_body,
                                      const yaza_http_parameter *parameters, size_t parameter_count,
                                      const char *request_schema) {
    static const char bad_request[] = "{\"error\":\"Bad Request\"}";
    static const char not_found[] = "{\"error\":\"Not Found\"}";
    static const char conflict[] = "{\"error\":\"Conflict\"}";
    static const char unavailable[] = "{\"error\":\"Service Unavailable\"}";
    yaza_http_validation_error validation_error = {0};
    char id[256] = "";
    bool collection = strcmp(path, resource->path) == 0;
    if (!collection && !yaza_http_resource_item_id(resource, path, id, sizeof(id))) {
        yaza_http_respond(client_fd, 404, "Not Found", not_found);
        return;
    }
    if (strcmp(method, "GET") == 0 && collection) {
        size_t limit = resource->count;
        size_t offset = 0;
        const yaza_http_parameter *limit_parameter = yaza_http_parameter_find(parameters, parameter_count, "query", "limit");
        if (limit_parameter != NULL && limit_parameter->has_default) {
            errno = 0;
            char *end = NULL;
            unsigned long long configured = strtoull(limit_parameter->default_value, &end, 10);
            if (errno != 0 || end == limit_parameter->default_value || *end != '\0' || configured == 0 || configured > 100) {
                yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
                return;
            }
            limit = (size_t)configured;
        }
        int query_status = yaza_http_query_pagination(query, &limit, &offset, parameters, parameter_count);
        if (query_status < 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        char limit_text[32];
        snprintf(limit_text, sizeof(limit_text), "%zu", limit);
        char offset_text[32];
        snprintf(offset_text, sizeof(offset_text), "%zu", offset);
        const char *values[] = {resource->path, limit_text, offset_text};
        PGresult *result = yaza_pg_query(
            "SELECT payload::text FROM yaza_api_records WHERE resource = $1 ORDER BY id LIMIT $2::integer OFFSET $3::integer",
            3, values);
        if (!yaza_pg_result_is_tuples(result)) {
            if (result != NULL) PQclear(result);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        size_t capacity = 3;
        for (int row = 0; row < PQntuples(result); row++) {
            size_t length = (size_t)PQgetlength(result, row, 0);
            if (length > SIZE_MAX - capacity - 1) { PQclear(result); yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable); return; }
            capacity += length + 1;
        }
        char *json = (char *)malloc(capacity);
        if (json == NULL) {
            PQclear(result);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        size_t used = 0;
        json[used++] = '[';
        for (int row = 0; row < PQntuples(result); row++) {
            if (row > 0) json[used++] = ',';
            size_t length = (size_t)PQgetlength(result, row, 0);
            memcpy(json + used, PQgetvalue(result, row, 0), length);
            used += length;
        }
        json[used++] = ']';
        json[used] = '\0';
        PQclear(result);
        yaza_http_respond(client_fd, 200, "OK", json);
        free(json);
        return;
    }
    if (strcmp(method, "GET") == 0 && !collection) {
        const char *values[] = {resource->path, id};
        PGresult *result = yaza_pg_query(
            "SELECT payload::text FROM yaza_api_records WHERE resource = $1 AND id = $2",
            2, values);
        if (!yaza_pg_result_is_tuples(result)) {
            if (result != NULL) PQclear(result);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
        } else if (PQntuples(result) == 0) {
            PQclear(result);
            yaza_http_respond(client_fd, 404, "Not Found", not_found);
        } else {
            yaza_http_respond(client_fd, 200, "OK", PQgetvalue(result, 0, 0));
            PQclear(result);
        }
        return;
    }
    if (strcmp(method, "POST") == 0 && collection) {
        yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
        if (request_body == NULL || yaza_json_object_fields(request_body, fields, YAZA_HTTP_MAX_JSON_FIELDS) < 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        const char *schema = request_schema != NULL && *request_schema != '\0' ? request_schema : resource->schema;
        if (!yaza_json_object_matches_schema(request_body, schema, false, false, &validation_error)) {
            yaza_http_respond_validation_error(client_fd, &validation_error);
            return;
        }
        bool supplied_id = yaza_json_object_id(request_body, id, sizeof(id));
        if (!supplied_id) {
            bool collision = true;
            do {
                snprintf(id, sizeof(id), "sku-%03zu", resource->next_id++);
                const char *lookup_values[] = {resource->path, id};
                PGresult *lookup = yaza_pg_query(
                    "SELECT 1 FROM yaza_api_records WHERE resource = $1 AND id = $2",
                    2, lookup_values);
                if (!yaza_pg_result_is_tuples(lookup)) {
                    if (lookup != NULL) PQclear(lookup);
                    yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
                    return;
                }
                collision = PQntuples(lookup) != 0;
                PQclear(lookup);
            } while (collision);
        }
        if (!yaza_http_id_is_safe(id)) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        const char *trimmed = yaza_json_skip_space(request_body);
        size_t body_length = strlen(trimmed);
        size_t capacity = body_length + strlen(id) + 16;
        char *created = (char *)malloc(capacity);
        if (created == NULL) {
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        if (supplied_id) snprintf(created, capacity, "%s", trimmed);
        else if (body_length == 2) snprintf(created, capacity, "{\"id\":\"%s\"}", id);
        else snprintf(created, capacity, "{\"id\":\"%s\",%s", id, trimmed + 1);
        const char *values[] = {resource->path, id, created};
        PGresult *result = yaza_pg_query(
            "INSERT INTO yaza_api_records(resource, id, payload) VALUES ($1, $2, $3::jsonb)",
            3, values);
        bool saved = yaza_pg_result_is_command(result);
        const char *sql_state = result == NULL ? NULL : PQresultErrorField(result, PG_DIAG_SQLSTATE);
        bool duplicate = sql_state != NULL && strcmp(sql_state, "23505") == 0;
        if (result != NULL) PQclear(result);
        if (duplicate) yaza_http_respond(client_fd, 409, "Conflict", conflict);
        else if (!saved) yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
        else yaza_http_respond(client_fd, 201, "Created", created);
        free(created);
        return;
    }
    if ((strcmp(method, "PUT") == 0 || strcmp(method, "PATCH") == 0) && !collection) {
        bool is_patch = strcmp(method, "PATCH") == 0;
        yaza_json_field fields[YAZA_HTTP_MAX_JSON_FIELDS];
        if (request_body == NULL || yaza_json_object_fields(request_body, fields, YAZA_HTTP_MAX_JSON_FIELDS) < 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        const char *schema = request_schema != NULL && *request_schema != '\0' ? request_schema : resource->schema;
        if (!yaza_json_object_matches_schema(request_body, schema, is_patch, false, &validation_error)) {
            yaza_http_respond_validation_error(client_fd, &validation_error);
            return;
        }
        char supplied_id[256];
        if (yaza_json_object_id(request_body, supplied_id, sizeof(supplied_id)) && strcmp(id, supplied_id) != 0) {
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        PGresult *transaction = PQexec(yaza_http_database, "BEGIN");
        bool transaction_started = yaza_pg_result_is_command(transaction);
        if (transaction != NULL) PQclear(transaction);
        if (!transaction_started) {
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        const char *select_values[] = {resource->path, id};
        PGresult *selected = yaza_pg_query(
            "SELECT payload::text FROM yaza_api_records WHERE resource = $1 AND id = $2 FOR UPDATE",
            2, select_values);
        if (!yaza_pg_result_is_tuples(selected)) {
            if (selected != NULL) PQclear(selected);
            PQexec(yaza_http_database, "ROLLBACK");
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
            return;
        }
        if (PQntuples(selected) == 0) {
            PQclear(selected);
            PQexec(yaza_http_database, "ROLLBACK");
            yaza_http_respond(client_fd, 404, "Not Found", not_found);
            return;
        }
        char *original = yaza_copy_text(PQgetvalue(selected, 0, 0));
        PQclear(selected);
        char *updated = yaza_json_merge_object(original, request_body);
        free(original);
        if (updated == NULL) {
            PQexec(yaza_http_database, "ROLLBACK");
            yaza_http_respond(client_fd, 400, "Bad Request", bad_request);
            return;
        }
        const char *update_values[] = {resource->path, id, updated};
        PGresult *result = yaza_pg_query(
            "UPDATE yaza_api_records SET payload = $3::jsonb, updated_at = clock_timestamp() WHERE resource = $1 AND id = $2",
            3, update_values);
        bool updated_ok = yaza_pg_result_is_command(result);
        if (result != NULL) PQclear(result);
        PGresult *committed = updated_ok ? PQexec(yaza_http_database, "COMMIT") : PQexec(yaza_http_database, "ROLLBACK");
        bool commit_ok = updated_ok && yaza_pg_result_is_command(committed);
        if (committed != NULL) PQclear(committed);
        if (!commit_ok) {
            free(updated);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
        } else {
            yaza_http_respond(client_fd, 200, "OK", updated);
            free(updated);
        }
        return;
    }
    if (strcmp(method, "DELETE") == 0 && !collection) {
        const char *values[] = {resource->path, id};
        PGresult *result = yaza_pg_query(
            "DELETE FROM yaza_api_records WHERE resource = $1 AND id = $2 RETURNING id",
            2, values);
        if (!yaza_pg_result_is_tuples(result)) {
            if (result != NULL) PQclear(result);
            yaza_http_respond(client_fd, 503, "Service Unavailable", unavailable);
        } else if (PQntuples(result) == 0) {
            PQclear(result);
            yaza_http_respond(client_fd, 404, "Not Found", not_found);
        } else {
            PQclear(result);
            yaza_http_respond(client_fd, 204, "No Content", "");
        }
        return;
    }
    yaza_http_respond_method_not_allowed(client_fd, collection ? "GET, HEAD, POST" : "GET, HEAD, PUT, PATCH, DELETE");
}
#endif

#define YAZA_HTTP_MAX_CHUNK_LINE_BYTES 1024

static int yaza_http_parse_chunk_line(const char *request, size_t used, size_t cursor,
                                      size_t *chunk_size, size_t *data_start) {
    size_t line_end = cursor;
    while (line_end + 1 < used && !(request[line_end] == '\r' && request[line_end + 1] == '\n')) {
        line_end++;
        if (line_end - cursor > YAZA_HTTP_MAX_CHUNK_LINE_BYTES) return -1;
    }
    if (line_end + 1 >= used) return used - cursor > YAZA_HTTP_MAX_CHUNK_LINE_BYTES ? -1 : -6;
    size_t digits_end = cursor;
    size_t parsed_size = 0;
    while (digits_end < line_end) {
        unsigned char character = (unsigned char)request[digits_end];
        unsigned digit;
        if (character >= '0' && character <= '9') digit = character - '0';
        else if (character >= 'a' && character <= 'f') digit = character - 'a' + 10;
        else if (character >= 'A' && character <= 'F') digit = character - 'A' + 10;
        else break;
        if (parsed_size > (SIZE_MAX - digit) / 16) return -2;
        parsed_size = parsed_size * 16 + digit;
        digits_end++;
    }
    if (digits_end == cursor) return -1;
    if (digits_end != line_end) {
        if (request[digits_end] != ';' || digits_end + 1 == line_end) return -1;
        for (size_t index = digits_end + 1; index < line_end; index++) {
            unsigned char character = (unsigned char)request[index];
            if ((character < 0x20 && character != '\t') || character == 0x7f) return -1;
        }
    }
    *chunk_size = parsed_size;
    *data_start = line_end + 2;
    return 0;
}

static bool yaza_http_trailer_valid(const char *request, size_t start, size_t end) {
    if (start == end || request[start] == ' ' || request[start] == '\t') return false;
    const char *line = request + start;
    size_t line_length = end - start;
    const char *colon = memchr(line, ':', line_length);
    if (colon == NULL || colon == line) return false;
    size_t name_length = (size_t)(colon - line);
    for (const unsigned char *cursor = (const unsigned char *)line;
         cursor < (const unsigned char *)colon; cursor++) {
        if (!isalnum(*cursor) && strchr("!#$%&'*+-.^_`|~", *cursor) == NULL) return false;
    }
    for (const unsigned char *cursor = (const unsigned char *)colon + 1;
         cursor < (const unsigned char *)line + line_length; cursor++) {
        if ((*cursor < 0x20 && *cursor != '\t') || *cursor == 0x7f) return false;
    }
    static const char *forbidden[] = {
        "Content-Length", "Transfer-Encoding", "Host", "Connection", "Trailer",
        "Authorization", "Content-Type", "Expect", "Origin", "Cookie", "Set-Cookie"
    };
    for (size_t index = 0; index < sizeof(forbidden) / sizeof(forbidden[0]); index++)
        if (name_length == strlen(forbidden[index]) &&
            strncasecmp(line, forbidden[index], name_length) == 0) return false;
    return true;
}

static int yaza_http_chunked_body_extent(const char *request, size_t used, size_t capacity,
                                         size_t header_length, size_t *message_length,
                                         size_t *decoded_length) {
    size_t cursor = header_length;
    size_t decoded = 0;
    size_t trailer_bytes = 0;
    size_t trailer_count = 0;
    for (;;) {
        size_t chunk_size = 0;
        size_t data_start = 0;
        int line_status = yaza_http_parse_chunk_line(request, used, cursor, &chunk_size, &data_start);
        if (line_status != 0) return line_status;
        if (chunk_size == 0) {
            cursor = data_start;
            for (;;) {
                size_t trailer_end = cursor;
                while (trailer_end + 1 < used &&
                       !(request[trailer_end] == '\r' && request[trailer_end + 1] == '\n')) {
                    trailer_end++;
                    if (trailer_end - cursor > YAZA_HTTP_MAX_HEADER_BYTES) return -3;
                }
                if (trailer_end + 1 >= used)
                    return used - cursor > YAZA_HTTP_MAX_HEADER_BYTES ? -3 : -6;
                size_t trailer_length = trailer_end - cursor;
                if (trailer_length == 0) {
                    *message_length = trailer_end + 2;
                    *decoded_length = decoded;
                    return 0;
                }
                if (trailer_length + 2 > YAZA_HTTP_MAX_HEADER_BYTES - trailer_bytes ||
                    ++trailer_count > YAZA_HTTP_MAX_HEADER_COUNT) return -3;
                if (!yaza_http_trailer_valid(request, cursor, trailer_end)) return -1;
                trailer_bytes += trailer_length + 2;
                cursor = trailer_end + 2;
            }
        }
        if (chunk_size > capacity - header_length - 1 - decoded) return -2;
        if (data_start > capacity - 3 || chunk_size > capacity - data_start - 3) return -2;
        size_t chunk_end = data_start + chunk_size;
        if (used < chunk_end + 2) return -6;
        if (request[chunk_end] != '\r' || request[chunk_end + 1] != '\n') return -1;
        decoded += chunk_size;
        cursor = chunk_end + 2;
    }
}

static int yaza_http_read_request(int client_fd, char *request, size_t capacity, char *method, size_t method_capacity,
                                  char *path, size_t path_capacity, const char **body, size_t *used_length,
                                  size_t *request_length, bool *keep_alive,
                                  char *overwritten_pipeline_byte, bool *has_overwritten_pipeline_byte) {
    size_t used = *used_length;
    size_t header_length = 0;
    *body = NULL;
    *request_length = 0;
    *keep_alive = false;
    *has_overwritten_pipeline_byte = false;
    char *header_end = strstr(request, "\r\n\r\n");
    if (header_end != NULL) {
        header_length = (size_t)(header_end - request) + 4;
        if (header_length > YAZA_HTTP_MAX_HEADER_BYTES) return -3;
    }
    while (header_length == 0) {
        if (used + 1 >= capacity) return -2;
        ssize_t received = recv(client_fd, request + used, capacity - used - 1, 0);
        if (received < 0 && errno == EINTR) {
            continue;
        }
        if (received < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
            *used_length = used;
            return -6;
        }
        if (received == 0)
            return used == 0 ? YAZA_HTTP_REQUEST_EOF : -1;
        if (received < 0) return -1;
        used += (size_t)received;
        request[used] = '\0';
        header_end = strstr(request, "\r\n\r\n");
        if (header_end != NULL) {
            header_length = (size_t)(header_end - request) + 4;
            if (header_length > YAZA_HTTP_MAX_HEADER_BYTES) return -3;
        } else if (used >= YAZA_HTTP_MAX_HEADER_BYTES) {
            return -3;
        }
    }

    char *line_end = strstr(request, "\r\n");
    if (line_end == NULL) return -1;
    *line_end = '\0';
    char protocol[16] = {0};
    char extra = '\0';
    int parsed = sscanf(request, "%15s %2047s %15s %c", method, path, protocol, &extra);
    *line_end = '\r';
    if (parsed != 3 || method_capacity < 16 || path_capacity < 2048 ||
        (strcmp(protocol, "HTTP/1.0") != 0 && strcmp(protocol, "HTTP/1.1") != 0)) return -1;
    bool asterisk_options_target = strcmp(method, "OPTIONS") == 0 && strcmp(path, "*") == 0;
    if (path[0] != '/' && !asterisk_options_target) return -1;
    for (const unsigned char *cursor = (const unsigned char *)method; *cursor != '\0'; cursor++)
        if (*cursor < 'A' || *cursor > 'Z') return -1;
    for (const unsigned char *cursor = (const unsigned char *)path; *cursor != '\0'; cursor++)
        if (*cursor < 0x21 || *cursor > 0x7e || *cursor == '#' || *cursor == '\\') return -1;
    if (!yaza_http_decode_path(path)) return -1;

    size_t content_length = 0;
    bool content_length_seen = false;
    bool transfer_encoding_seen = false;
    bool transfer_chunked = false;
    bool host_seen = false;
    bool content_type_seen = false;
    bool content_type_is_json = false;
    bool connection_seen = false;
    bool connection_close = false;
    size_t header_count = 0;
    const char *line = line_end + 2;
    const char *headers_end = request + header_length - 2;
    while (line < headers_end) {
        const char *end = strstr(line, "\r\n");
        if (end == NULL || end > headers_end) return -1;
        if (++header_count > YAZA_HTTP_MAX_HEADER_COUNT) return -1;
        size_t line_length = (size_t)(end - line);
        if (line_length == 0 || *line == ' ' || *line == '\t') return -1;
        const char *colon = memchr(line, ':', line_length);
        if (colon == NULL || colon == line) return -1;
        for (const unsigned char *cursor = (const unsigned char *)line; cursor < (const unsigned char *)colon; cursor++) {
            if (!isalnum(*cursor) && strchr("!#$%&'*+-.^_`|~", *cursor) == NULL) return -1;
        }
        for (const unsigned char *cursor = (const unsigned char *)colon + 1; cursor < (const unsigned char *)end; cursor++)
            if ((*cursor < 0x20 && *cursor != '\t') || *cursor == 0x7f) return -1;
        size_t name_length = (size_t)(colon - line);
        const char *value = colon + 1;
        while (value < end && (*value == ' ' || *value == '\t')) value++;
        if (name_length == 4 && strncasecmp(line, "Host", name_length) == 0) {
            const char *value_end = end;
            while (value_end > value && (value_end[-1] == ' ' || value_end[-1] == '\t')) value_end--;
            if (host_seen || value == value_end ||
                !yaza_http_host_allowed(value, (size_t)(value_end - value))) return -1;
            host_seen = true;
        }
        if (name_length == 12 && strncasecmp(line, "Content-Type", name_length) == 0) {
            if (content_type_seen) return -1;
            content_type_seen = true;
            const char *value_end = end;
            while (value_end > value && (value_end[-1] == ' ' || value_end[-1] == '\t')) value_end--;
            content_type_is_json = yaza_http_json_content_type(value, (size_t)(value_end - value));
        }
        if (name_length == 10 && strncasecmp(line, "Connection", name_length) == 0) {
            if (connection_seen) return -1;
            connection_seen = true;
            const char *connection_end = end;
            while (connection_end > value && (connection_end[-1] == ' ' || connection_end[-1] == '\t')) connection_end--;
            if (value == connection_end) return -1;
            const char *token = value;
            while (token < connection_end) {
                const char *token_end = memchr(token, ',', (size_t)(connection_end - token));
                if (token_end == NULL) token_end = connection_end;
                const char *separator = token_end;
                while (token < token_end && (*token == ' ' || *token == '\t')) token++;
                while (token_end > token && (token_end[-1] == ' ' || token_end[-1] == '\t')) token_end--;
                if (token == token_end) return -1;
                for (const unsigned char *character = (const unsigned char *)token;
                     character < (const unsigned char *)token_end; character++) {
                    if (!isalnum(*character) && strchr("!#$%&'*+-.^_`|~", *character) == NULL) return -1;
                }
                size_t token_length = (size_t)(token_end - token);
                if (token_length == 5 && strncasecmp(token, "close", token_length) == 0) connection_close = true;
                token = separator < connection_end ? separator + 1 : connection_end;
            }
        }
        if ((name_length == 13 && strncasecmp(line, "Authorization", name_length) == 0) ||
            (name_length == 6 && strncasecmp(line, "Origin", name_length) == 0) ||
            (name_length == 12 && strncasecmp(line, "Content-Type", name_length) == 0) ||
            (name_length == 6 && strncasecmp(line, "Expect", name_length) == 0)) {
            for (const char *previous = line_end + 2; previous < line;) {
                const char *previous_end = strstr(previous, "\r\n");
                if (previous_end == NULL || previous_end > line) return -1;
                const char *previous_colon = memchr(previous, ':', (size_t)(previous_end - previous));
                if (previous_colon == NULL) return -1;
                size_t previous_name_length = (size_t)(previous_colon - previous);
                if (previous_name_length == name_length && strncasecmp(previous, line, name_length) == 0) return -1;
                previous = previous_end + 2;
            }
        }
        if (name_length == 14 && strncasecmp(line, "Content-Length", name_length) == 0) {
            if (content_length_seen) return -1;
            content_length_seen = true;
            const char *value = colon + 1;
            while (value < end && (*value == ' ' || *value == '\t')) value++;
            const char *value_end = end;
            while (value_end > value && (value_end[-1] == ' ' || value_end[-1] == '\t')) value_end--;
            if (value == value_end) return -1;
            size_t parsed_length = 0;
            for (const unsigned char *digit = (const unsigned char *)value; digit < (const unsigned char *)value_end; digit++) {
                if (!isdigit(*digit) || parsed_length > (SIZE_MAX - (size_t)(*digit - '0')) / 10) return -1;
                parsed_length = parsed_length * 10 + (size_t)(*digit - '0');
            }
            content_length = parsed_length;
        } else if (name_length == 17 && strncasecmp(line, "Transfer-Encoding", name_length) == 0) {
            if (transfer_encoding_seen) return -1;
            transfer_encoding_seen = true;
            const char *value_end = end;
            while (value_end > value && (value_end[-1] == ' ' || value_end[-1] == '\t')) value_end--;
            if ((size_t)(value_end - value) != 7 || strncasecmp(value, "chunked", 7) != 0) return -1;
            transfer_chunked = true;
        } else if (name_length == 6 && strncasecmp(line, "Expect", name_length) == 0) {
            return -1;
        }
        line = end + 2;
    }
    if (transfer_encoding_seen &&
        (strcmp(protocol, "HTTP/1.1") != 0 || content_length_seen)) return -1;
    if (strcmp(protocol, "HTTP/1.1") == 0 && !host_seen) return -1;
    *keep_alive = strcmp(protocol, "HTTP/1.1") == 0 && !connection_close;
    size_t expected = 0;
    size_t decoded_body_length = 0;
    if (transfer_chunked) {
        int chunk_status = yaza_http_chunked_body_extent(request, used, capacity, header_length,
                                                          &expected, &decoded_body_length);
        while (chunk_status == -6) {
            if (used + 1 >= capacity) return -2;
            ssize_t received = recv(client_fd, request + used, capacity - used - 1, 0);
            if (received < 0 && errno == EINTR) {
                continue;
            }
            if (received < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
                *used_length = used;
                return -6;
            }
            if (received <= 0) return -1;
            used += (size_t)received;
            request[used] = '\0';
            chunk_status = yaza_http_chunked_body_extent(request, used, capacity, header_length,
                                                          &expected, &decoded_body_length);
        }
        if (chunk_status != 0) return chunk_status;
        if (decoded_body_length > 0 && (!content_type_seen || !content_type_is_json)) return -4;
        size_t cursor = header_length;
        size_t output = header_length;
        while (cursor < expected) {
            size_t chunk_size = 0;
            size_t data_start = 0;
            if (yaza_http_parse_chunk_line(request, expected, cursor, &chunk_size, &data_start) != 0) return -1;
            if (chunk_size == 0) break;
            if (memchr(request + data_start, '\0', chunk_size) != NULL) return -1;
            memmove(request + output, request + data_start, chunk_size);
            output += chunk_size;
            cursor = data_start + chunk_size + 2;
        }
        request[header_length + decoded_body_length] = '\0';
    } else {
        if (content_length > 0 && (!content_type_seen || !content_type_is_json)) return -4;
        if (content_length > capacity - header_length - 1) return -2;
        if (content_length > capacity - YAZA_HTTP_MAX_HEADER_BYTES - 1) return -2;
        expected = header_length + content_length;
        while (used < expected) {
            ssize_t received = recv(client_fd, request + used, expected - used, 0);
            if (received < 0 && errno == EINTR) {
                continue;
            }
            if (received < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
                *used_length = used;
                return -6;
            }
            if (received <= 0) return -1;
            used += (size_t)received;
        }
        if (content_length > 0 && memchr(request + header_length, '\0', content_length) != NULL) return -1;
        decoded_body_length = content_length;
    }
    if (used > expected) {
        *overwritten_pipeline_byte = request[expected];
        *has_overwritten_pipeline_byte = true;
    }
    request[expected] = '\0';
    if (decoded_body_length > 0) *body = request + header_length;
    *request_length = expected;
    *used_length = used;
    return 0;
}

static yaza_task_step_result yaza_http_connection_read_step(yaza_scheduler *scheduler,
                                                             yaza_scheduler_task *task,
                                                             void *context) {
    yaza_http_connection *connection = (yaza_http_connection *)context;
    if (connection == NULL || task == NULL || task->cancel_requested)
        return YAZA_TASK_STEP_CANCEL;
    if (connection->reader_task_id != task->id || connection->fd < 0 ||
        connection->io_driver == NULL || connection->request_ready)
        return YAZA_TASK_STEP_CANCEL;

    int64_t now_ms = yaza_monotonic_milliseconds();
    if (now_ms < 0) {
        connection->request_status = -8;
        connection->request_ready = true;
        return YAZA_TASK_STEP_WAIT;
    }
    size_t previous_used = connection->used;
    connection->has_buffered_pipeline = false;
    if (previous_used == 0) connection->request_started_at_ms = now_ms;
    int status = yaza_http_read_request(connection->fd, connection->request,
        YAZA_HTTP_REQUEST_CAPACITY, connection->method, sizeof(connection->method),
        connection->path, sizeof(connection->path), &connection->request_body,
        &connection->used, &connection->request_length, &connection->request_keep_alive,
        &connection->overwritten_pipeline_byte, &connection->has_overwritten_pipeline_byte);
    if (connection->used > previous_used) connection->last_activity_ms = now_ms;
    if (status == -5) return YAZA_TASK_STEP_CANCEL;
    if (status == -6) {
        uint64_t token = 0;
        if (!yaza_io_wait_task_read(connection->io_driver, scheduler, task->id,
                                    connection->fd, &token)) {
            connection->request_status = -8;
            connection->request_ready = true;
        }
        return YAZA_TASK_STEP_WAIT;
    }
    connection->request_status = status;
    connection->request_ready = true;
    return YAZA_TASK_STEP_WAIT;
}

/* Blocked or over-budget response writes resume on native writable readiness. */
static int yaza_http_flush_response(yaza_io_driver *driver, yaza_http_connection *connection) {
    if (driver == NULL || connection == NULL || connection->fd < 0 ||
        !connection->response_pending || connection->response_buffer == NULL) return -1;
    if (connection->response_waiting) return 0;
    size_t flushed = 0;
    while (connection->response_offset < connection->response_length &&
           flushed < YAZA_HTTP_WRITE_QUANTUM_BYTES) {
        size_t write_length = connection->response_length - connection->response_offset;
        size_t quantum_remaining = YAZA_HTTP_WRITE_QUANTUM_BYTES - flushed;
        if (write_length > quantum_remaining) write_length = quantum_remaining;
        ssize_t written = send(connection->fd,
            connection->response_buffer + connection->response_offset,
            write_length, 0);
        if (written < 0 && errno == EINTR) continue;
        if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
            uint64_t token = yaza_io_allocate_token(driver);
            if (token == 0 || !yaza_io_watch_write(driver, connection->fd, token)) {
                connection->response_failed = true;
                return -1;
            }
            connection->response_write_token = token;
            connection->response_waiting = true;
            return 0;
        }
        if (written <= 0) {
            connection->response_failed = true;
            return -1;
        }
        connection->response_offset += (size_t)written;
        flushed += (size_t)written;
    }
    if (connection->response_offset == connection->response_length) return 1;

    /* Yield after the cumulative write budget even when the socket stays writable. */
    uint64_t token = yaza_io_allocate_token(driver);
    if (token == 0 || !yaza_io_watch_write(driver, connection->fd, token)) {
        connection->response_failed = true;
        return -1;
    }
    connection->response_write_token = token;
    connection->response_waiting = true;
    return 0;
}

static void yaza_http_finish_response(yaza_io_driver *driver, yaza_scheduler *scheduler,
                                      yaza_http_connection *connections, size_t index) {
    yaza_http_connection *connection = &connections[index];
    if (connection->response_waiting)
        (void)yaza_io_unwatch_write(driver, connection->fd);
    if (connection->response_buffer != NULL) {
        if (connection->response_length <= yaza_http_pending_response_bytes)
            yaza_http_pending_response_bytes -= connection->response_length;
        else
            yaza_http_pending_response_bytes = 0;
        free(connection->response_buffer);
    }
    bool keep_alive = connection->response_keep_alive && !yaza_http_shutdown_requested;
    connection->response_buffer = NULL;
    connection->response_length = 0;
    connection->response_offset = 0;
    connection->response_status = 0;
    connection->response_started_ms = 0;
    connection->response_write_token = 0;
    connection->response_pending = false;
    connection->response_waiting = false;
    connection->response_failed = false;
    connection->response_keep_alive = false;
    if (!keep_alive) {
        yaza_http_connection_reset(driver, scheduler, connections, index);
        return;
    }
    if (connection->has_overwritten_pipeline_byte &&
        connection->request_length < sizeof(connection->request))
        connection->request[connection->request_length] = connection->overwritten_pipeline_byte;
    size_t remaining = connection->used > connection->request_length
        ? connection->used - connection->request_length : 0;
    if (remaining > 0)
        memmove(connection->request, connection->request + connection->request_length, remaining);
    connection->used = remaining;
    connection->request[remaining] = '\0';
    connection->requests_served++;
    int64_t now_ms = yaza_monotonic_milliseconds();
    connection->last_activity_ms = now_ms >= 0 ? now_ms : 0;
    connection->request_started_at_ms = remaining > 0 ? connection->last_activity_ms : 0;
    connection->has_overwritten_pipeline_byte = false;
    connection->has_buffered_pipeline = remaining > 0;
    if (!yaza_scheduler_wake(scheduler, connection->reader_task_id)) {
        fprintf(stderr, "yaza: could not wake HTTP connection reader after response\n");
        yaza_http_connection_reset(driver, scheduler, connections, index);
    }
}

static void yaza_http_resources_release(yaza_http_resource *resources, size_t count) {
    for (size_t index = 0; index < count; index++) {
        free(resources[index].path);
        free(resources[index].schema);
        for (size_t item = 0; item < resources[index].count; item++) free(resources[index].items[item]);
    }
    free(resources);
}

static int64_t yaza_http_serve(const char *host, int64_t port, const yaza_text_list *route_values) {
    static const char not_found[] = "{\"error\":\"Not Found\"}";
    static const char healthy[] = "{\"status\":\"ok\"}";
    yaza_load_dotenv();
    if (route_values == NULL || route_values->length == 0 || route_values->length % 5 != 0) {
        fprintf(stderr, "yaza: HTTP route table must contain method, path, body, metadata, and handler entries\n");
        return 1;
    }
    size_t route_count = route_values->length / 5;
    size_t route_cors_count = 0;
    yaza_http_route *routes = (yaza_http_route *)calloc(route_count, sizeof(yaza_http_route));
    if (routes == NULL) {
        fprintf(stderr, "yaza: out of memory creating HTTP route table\n");
        return 1;
    }
    for (size_t index = 0; index < route_count; index++) {
        routes[index].method = route_values->items[index * 5];
        routes[index].path = route_values->items[index * 5 + 1];
        routes[index].body = route_values->items[index * 5 + 2];
        routes[index].metadata = route_values->items[index * 5 + 3];
        routes[index].handler_name = route_values->items[index * 5 + 4];
        if (!yaza_http_method_token_valid(routes[index].method)) {
            fprintf(stderr, "yaza: invalid HTTP method token in route table\n");
            free(routes);
            return 1;
        }
        routes[index].success_status = yaza_http_metadata_success_status(routes[index].metadata);
        routes[index].auth_policy = yaza_http_metadata_auth_policy(routes[index].metadata);
        if (!yaza_http_metadata_rate_limit(routes[index].metadata,
                                           &routes[index].rate_limit_requests,
                                           &routes[index].rate_limit_window_ms,
                                           &routes[index].rate_limit_scope_id)) {
            fprintf(stderr, "yaza: invalid declared rate limit for %s %s\n",
                    routes[index].method, routes[index].path);
            free(routes);
            return 1;
        }
        if (routes[index].success_status < 0) {
            fprintf(stderr, "yaza: invalid declared response status for %s %s\n",
                    routes[index].method, routes[index].path);
            free(routes);
            return 1;
        }
        if (routes[index].auth_policy < 0) {
            fprintf(stderr, "yaza: invalid declared authentication policy for %s %s\n",
                    routes[index].method, routes[index].path);
            free(routes);
            return 1;
        }
        if (!yaza_http_metadata_cors_origin(routes[index].metadata,
                                            routes[index].cors_origin,
                                            sizeof(routes[index].cors_origin))) {
            fprintf(stderr, "yaza: invalid declared CORS origin for %s %s\n",
                    routes[index].method, routes[index].path);
            free(routes);
            return 1;
        }
        if (routes[index].cors_origin[0] != '\0') route_cors_count++;
        if (routes[index].handler_name != NULL && *routes[index].handler_name != '\0' &&
            yaza_http_handler_dispatch == NULL) {
            fprintf(stderr, "yaza: executable API route has no generated handler dispatcher\n");
            free(routes);
            return 1;
        }
        if (!yaza_http_controller_body_schema(routes[index].metadata,
                                              routes[index].body_schema,
                                              sizeof(routes[index].body_schema))) {
            fprintf(stderr, "yaza: invalid controller body schema for %s %s\n",
                    routes[index].method, routes[index].path);
            free(routes);
            return 1;
        }
        if (!yaza_http_route_body_contract_valid(&routes[index])) {
            fprintf(stderr, "yaza: typed request body schema does not match its declared fields for %s %s\n",
                    routes[index].method, routes[index].path);
            free(routes);
            return 1;
        }
    }
    yaza_http_resource *resources = (yaza_http_resource *)calloc(YAZA_HTTP_MAX_RESOURCES, sizeof(yaza_http_resource));
    if (resources == NULL) {
        fprintf(stderr, "yaza: out of memory creating HTTP resource store\n");
        free(routes);
        return 1;
    }
    size_t resource_count = 0;
    for (size_t index = 0; index < route_count; index++) {
        char base_path[512];
        if (!yaza_http_resource_base_path(routes[index].path, base_path, sizeof(base_path)) ||
            routes[index].body == NULL || *yaza_json_skip_space(routes[index].body) != '[' ||
            yaza_http_resource_find(resources, resource_count, base_path) != NULL) continue;
        if (resource_count == YAZA_HTTP_MAX_RESOURCES ||
            yaza_http_resource_load(&resources[resource_count], base_path, routes[index].body) != 0) {
            fprintf(stderr, "yaza: invalid or oversized in-memory API resource at %s\n", base_path);
            yaza_http_resources_release(resources, resource_count + (resource_count < YAZA_HTTP_MAX_RESOURCES ? 1 : 0));
            free(routes);
            return 1;
        }
        resource_count++;
    }

    char configured_host[INET_ADDRSTRLEN];
    if (strlen(host) >= sizeof(configured_host)) {
        fprintf(stderr, "yaza: API listen host is too long\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    snprintf(configured_host, sizeof(configured_host), "%s", host);
    const char *host_override = getenv("YAZA_HOST");
    if (host_override != NULL && *host_override != '\0') {
        if (strlen(host_override) >= sizeof(configured_host)) {
            fprintf(stderr, "yaza: YAZA_HOST must be an IPv4 address\n");
            free(routes);
            yaza_http_resources_release(resources, resource_count);
            return 1;
        }
        snprintf(configured_host, sizeof(configured_host), "%s", host_override);
    }
    int64_t configured_port = port;
    const char *port_override = getenv("YAZA_PORT");
    if (port_override != NULL && *port_override != '\0' && !yaza_http_parse_port(port_override, &configured_port)) {
        fprintf(stderr, "yaza: YAZA_PORT must be an integer from 1 to 65535\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    const char *api_token = getenv("YAZA_API_TOKEN");
    const char *api_token_secondary = getenv("YAZA_API_TOKEN_SECONDARY");
    const char *jwt_secret = getenv("YAZA_JWT_SECRET");
    const char *jwt_issuer = getenv("YAZA_JWT_ISSUER");
    const char *jwt_audience = getenv("YAZA_JWT_AUDIENCE");
    size_t jwt_route_count = 0;
    bool all_routes_have_explicit_auth = true;
    size_t api_token_length = 0;
    const char *api_tokens[YAZA_HTTP_API_TOKEN_MAX_ACTIVE] = {NULL, NULL};
    size_t api_token_lengths[YAZA_HTTP_API_TOKEN_MAX_ACTIVE] = {0, 0};
    size_t api_token_count = 0;
    if (api_token != NULL && *api_token == '\0') api_token = NULL;
    if (api_token_secondary != NULL && *api_token_secondary == '\0') api_token_secondary = NULL;
    if (jwt_secret != NULL && *jwt_secret == '\0') jwt_secret = NULL;
    if (jwt_issuer != NULL && *jwt_issuer == '\0') jwt_issuer = NULL;
    if (jwt_audience != NULL && *jwt_audience == '\0') jwt_audience = NULL;
    if (api_token != NULL && !yaza_http_bearer_token_valid(api_token)) {
        fprintf(stderr,
                "yaza: YAZA_API_TOKEN must be %u..%d bytes and use only RFC Bearer token characters\n",
                YAZA_HTTP_API_TOKEN_MIN_BYTES,
                YAZA_HTTP_API_TOKEN_MAX_BYTES);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (api_token != NULL) api_token_length = strlen(api_token);
    if (api_token_secondary != NULL && api_token == NULL) {
        fprintf(stderr, "yaza: YAZA_API_TOKEN_SECONDARY requires YAZA_API_TOKEN\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (api_token_secondary != NULL && !yaza_http_bearer_token_valid(api_token_secondary)) {
        fprintf(stderr,
                "yaza: YAZA_API_TOKEN_SECONDARY must be %u..%d bytes and use only RFC Bearer token characters\n",
                YAZA_HTTP_API_TOKEN_MIN_BYTES,
                YAZA_HTTP_API_TOKEN_MAX_BYTES);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (api_token_secondary != NULL && strcmp(api_token, api_token_secondary) == 0) {
        fprintf(stderr, "yaza: YAZA_API_TOKEN_SECONDARY must differ from YAZA_API_TOKEN\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (api_token != NULL) {
        api_tokens[api_token_count] = api_token;
        api_token_lengths[api_token_count++] = api_token_length;
    }
    if (api_token_secondary != NULL) {
        api_tokens[api_token_count] = api_token_secondary;
        api_token_lengths[api_token_count++] = strlen(api_token_secondary);
    }
    size_t jwt_secret_length = jwt_secret == NULL ? 0 : strnlen(jwt_secret, YAZA_HTTP_JWT_MAX_SECRET_BYTES + 1U);
    if (jwt_secret != NULL && (jwt_secret_length < 32U || jwt_secret_length > YAZA_HTTP_JWT_MAX_SECRET_BYTES)) {
        fprintf(stderr, "yaza: YAZA_JWT_SECRET must be 32..%u bytes\n",
                (unsigned)YAZA_HTTP_JWT_MAX_SECRET_BYTES);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if ((jwt_issuer != NULL && !yaza_http_jwt_expected_text_valid(jwt_issuer)) ||
        (jwt_audience != NULL && !yaza_http_jwt_expected_text_valid(jwt_audience))) {
        fprintf(stderr, "yaza: YAZA_JWT_ISSUER and YAZA_JWT_AUDIENCE must each be 1..512 visible bytes\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    for (size_t index = 0; index < route_count; index++) {
        if (routes[index].auth_policy == 0) all_routes_have_explicit_auth = false;
        if (routes[index].auth_policy == 3) {
            jwt_route_count++;
            if (jwt_secret == NULL || jwt_issuer == NULL || jwt_audience == NULL) {
                fprintf(stderr,
                        "yaza: route %s %s requires YAZA_JWT_SECRET, YAZA_JWT_ISSUER, and YAZA_JWT_AUDIENCE\n",
                        routes[index].method, routes[index].path);
                free(routes);
                yaza_http_resources_release(resources, resource_count);
                return 1;
            }
        }
        if (routes[index].auth_policy == 2 && api_token == NULL) {
            fprintf(stderr, "yaza: route %s %s requires YAZA_API_TOKEN\n",
                    routes[index].method, routes[index].path);
            free(routes);
            yaza_http_resources_release(resources, resource_count);
            return 1;
        }
    }
    const char *rate_limit_requests_text = getenv("YAZA_RATE_LIMIT_REQUESTS");
    const char *rate_limit_window_text = getenv("YAZA_RATE_LIMIT_WINDOW_MS");
    bool rate_limit_enabled = rate_limit_requests_text != NULL && *rate_limit_requests_text != '\0';
    bool rate_limit_window_supplied = rate_limit_window_text != NULL && *rate_limit_window_text != '\0';
    int64_t rate_limit_requests = 0;
    int64_t rate_limit_window_ms = 60000;
    if ((!rate_limit_enabled && rate_limit_window_supplied) ||
        (rate_limit_enabled && !yaza_http_parse_bounded_positive(
            rate_limit_requests_text, 1, 100000, &rate_limit_requests)) ||
        (rate_limit_window_supplied && !yaza_http_parse_bounded_positive(
            rate_limit_window_text, 1000, 3600000, &rate_limit_window_ms))) {
        fprintf(stderr,
                "yaza: YAZA_RATE_LIMIT_REQUESTS must be 1..100000; optional YAZA_RATE_LIMIT_WINDOW_MS must be 1000..3600000 and requires the request limit\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    const char *connection_capacity_text = getenv("YAZA_HTTP_MAX_CONNECTIONS");
    int64_t configured_connection_capacity = YAZA_HTTP_DEFAULT_CONNECTIONS;
    if (connection_capacity_text != NULL && *connection_capacity_text != '\0' &&
        !yaza_http_parse_bounded_positive(connection_capacity_text, 1,
                                          YAZA_HTTP_MAX_CONNECTIONS,
                                          &configured_connection_capacity)) {
        fprintf(stderr, "yaza: YAZA_HTTP_MAX_CONNECTIONS must be an integer from 1 to %u\n",
                (unsigned)YAZA_HTTP_MAX_CONNECTIONS);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    size_t connection_capacity = (size_t)configured_connection_capacity;
    const char *worker_count_text = getenv("YAZA_API_WORKERS");
    int64_t configured_worker_count = 4;
    if (worker_count_text != NULL && *worker_count_text != '\0' &&
        !yaza_http_parse_bounded_positive(worker_count_text, 1,
                                          YAZA_WORK_POOL_MAX_THREADS,
                                          &configured_worker_count)) {
        fprintf(stderr, "yaza: YAZA_API_WORKERS must be an integer from 1 to %u\n",
                (unsigned)YAZA_WORK_POOL_MAX_THREADS);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    const char *max_in_flight_text = getenv("YAZA_API_MAX_IN_FLIGHT");
    int64_t configured_max_in_flight = configured_connection_capacity;
    if (max_in_flight_text != NULL && *max_in_flight_text != '\0' &&
        !yaza_http_parse_bounded_positive(max_in_flight_text, 1,
                                          configured_connection_capacity,
                                          &configured_max_in_flight)) {
        fprintf(stderr,
                "yaza: YAZA_API_MAX_IN_FLIGHT must be an integer from 1 to %lld (the configured connection capacity)\n",
                (long long)configured_connection_capacity);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    const char *request_timeout_text = getenv("YAZA_HTTP_REQUEST_TIMEOUT_MS");
    const char *keep_alive_timeout_text = getenv("YAZA_HTTP_KEEP_ALIVE_TIMEOUT_MS");
    const char *shutdown_grace_text = getenv("YAZA_HTTP_SHUTDOWN_GRACE_MS");
    const char *response_write_timeout_text = getenv("YAZA_HTTP_RESPONSE_WRITE_TIMEOUT_MS");
    int64_t configured_request_timeout_ms = YAZA_HTTP_REQUEST_TIMEOUT_DEFAULT_MS;
    int64_t configured_keep_alive_timeout_ms = YAZA_HTTP_KEEP_ALIVE_TIMEOUT_DEFAULT_MS;
    int64_t configured_shutdown_grace_ms = YAZA_HTTP_SHUTDOWN_GRACE_DEFAULT_MS;
    int64_t configured_response_write_timeout_ms = YAZA_HTTP_RESPONSE_WRITE_TIMEOUT_DEFAULT_MS;
    if (request_timeout_text != NULL && *request_timeout_text != '\0' &&
        !yaza_http_parse_bounded_positive(request_timeout_text, 1000, 300000,
                                          &configured_request_timeout_ms)) {
        fprintf(stderr, "yaza: YAZA_HTTP_REQUEST_TIMEOUT_MS must be an integer from 1000 to 300000\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (keep_alive_timeout_text != NULL && *keep_alive_timeout_text != '\0' &&
        !yaza_http_parse_bounded_positive(keep_alive_timeout_text, 1000, 60000,
                                          &configured_keep_alive_timeout_ms)) {
        fprintf(stderr, "yaza: YAZA_HTTP_KEEP_ALIVE_TIMEOUT_MS must be an integer from 1000 to 60000\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (shutdown_grace_text != NULL && *shutdown_grace_text != '\0' &&
        !yaza_http_parse_bounded_positive(shutdown_grace_text, 1000, 120000,
                                          &configured_shutdown_grace_ms)) {
        fprintf(stderr, "yaza: YAZA_HTTP_SHUTDOWN_GRACE_MS must be an integer from 1000 to 120000\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (response_write_timeout_text != NULL && *response_write_timeout_text != '\0' &&
        !yaza_http_parse_bounded_positive(response_write_timeout_text, 1000, 300000,
                                          &configured_response_write_timeout_ms)) {
        fprintf(stderr, "yaza: YAZA_HTTP_RESPONSE_WRITE_TIMEOUT_MS must be an integer from 1000 to 300000\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    yaza_http_request_timeout_ms = configured_request_timeout_ms;
    yaza_http_keep_alive_timeout_ms = configured_keep_alive_timeout_ms;
    yaza_http_shutdown_grace_ms = configured_shutdown_grace_ms;
    yaza_http_response_write_timeout_ms = configured_response_write_timeout_ms;
    struct in_addr configured_address;
    if (inet_pton(AF_INET, configured_host, &configured_address) != 1) {
        fprintf(stderr, "yaza: API listen host must be an IPv4 address\n");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    bool loopback_bind = (ntohl(configured_address.s_addr) & 0xff000000U) == 0x7f000000U;
    if (!loopback_bind && api_token == NULL &&
        (jwt_route_count == 0 || !all_routes_have_explicit_auth)) {
        fprintf(stderr,
                "yaza: refusing to bind API to non-loopback address %s without YAZA_API_TOKEN; "
                "JWT-only mode requires at least one auth jwt route and explicit auth on every route\n",
                configured_host);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (!yaza_http_allowed_hosts_configure(configured_host, loopback_bind)) {
        fprintf(stderr,
                "yaza: YAZA_ALLOWED_HOSTS must contain 1..%u exact host names (no wildcard or port); "
                "it is required for non-loopback binds\n",
                (unsigned)YAZA_HTTP_MAX_ALLOWED_HOSTS);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    char cors_origin[512] = "";
    const char *cors_override = getenv("YAZA_CORS_ORIGIN");
    if (cors_override != NULL && *cors_override != '\0') {
        if (strlen(cors_override) >= sizeof(cors_origin) || !yaza_http_origin_is_valid(cors_override)) {
            fprintf(stderr, "yaza: YAZA_CORS_ORIGIN must be one exact http:// or https:// origin without a path\n");
            free(routes);
            yaza_http_resources_release(resources, resource_count);
            return 1;
        }
        snprintf(cors_origin, sizeof(cors_origin), "%s", cors_override);
    }

    const char *database_url = getenv("DATABASE_URL");
    if (database_url != NULL && *database_url != '\0') {
        if (yaza_http_startup_handler == NULL) {
            fprintf(stderr, "YAZA API startup rejected: DATABASE_URL is configured but no startup hook is declared\n");
            yaza_http_resources_release(resources, resource_count);
            free(routes);
            return 1;
        }
    }
    if (yaza_http_startup_handler != NULL) {
        int64_t startup_status = yaza_http_startup_handler();
        if (startup_status != 0) {
            fprintf(stderr, "YAZA API startup hook failed (code %lld; details redacted)\n",
                    (long long)startup_status);
            yaza_http_resources_release(resources, resource_count);
            free(routes);
            return 1;
        }
    }

    signal(SIGPIPE, SIG_IGN);
    int server_fd = -1;
    int64_t active_port = configured_port;
    int bind_error = 0;
    unsigned bind_attempt = 0;
    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_addr = configured_address;
    for (; bind_attempt < 100; bind_attempt++) {
        int64_t candidate_port = configured_port + (int64_t)bind_attempt;
        if (candidate_port > 65535)
            candidate_port = 1024 + (candidate_port - 65536);
        int candidate_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (candidate_fd < 0) {
            perror("yaza: socket");
            free(routes);
            yaza_http_resources_release(resources, resource_count);
            return 1;
        }
        int reuse_address = 1;
        (void)setsockopt(candidate_fd, SOL_SOCKET, SO_REUSEADDR, &reuse_address, sizeof(reuse_address));
        address.sin_port = htons((uint16_t)candidate_port);
        if (bind(candidate_fd, (struct sockaddr *)&address, sizeof(address)) == 0) {
            server_fd = candidate_fd;
            active_port = candidate_port;
            break;
        }
        bind_error = errno;
        close(candidate_fd);
        if (bind_error != EADDRINUSE) break;
    }
    if (server_fd < 0) {
        errno = bind_error;
        perror("yaza: bind");
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    if (active_port != configured_port)
        fprintf(stderr, "yaza: requested port %lld is occupied; selected the next available port %lld\n",
                (long long)configured_port, (long long)active_port);
    if (listen(server_fd, (int)connection_capacity) < 0) {
        perror("yaza: listen");
        close(server_fd);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    int server_flags = fcntl(server_fd, F_GETFL, 0);
    if (server_flags < 0 || fcntl(server_fd, F_SETFL, server_flags | O_NONBLOCK) < 0) {
        perror("yaza: nonblocking listen socket");
        close(server_fd);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    yaza_io_driver io_driver = {.fd = -1};
    if (!yaza_io_driver_open(&io_driver) || !yaza_io_watch_read(&io_driver, server_fd, 0)) {
        perror("yaza: initialize native I/O event backend");
        yaza_io_driver_close(&io_driver);
        close(server_fd);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    struct sigaction shutdown_action;
    memset(&shutdown_action, 0, sizeof(shutdown_action));
    shutdown_action.sa_handler = yaza_http_request_shutdown;
    sigemptyset(&shutdown_action.sa_mask);
    yaza_http_shutdown_requested = 0;
    yaza_http_requests_total = 0;
    yaza_http_connections_rejected_total = 0;
    yaza_http_accept_backoffs_total = 0;
    yaza_http_retry_after_seconds = 1;
    memset(yaza_http_rate_limit_buckets, 0, sizeof(yaza_http_rate_limit_buckets));
    memset(yaza_http_metric_status_counts, 0, sizeof(yaza_http_metric_status_counts));
    yaza_http_cors_response_origin[0] = '\0';
    yaza_http_cors_preflight_active = false;
    yaza_http_response_keep_alive = false;
    yaza_http_active_connection = NULL;
    yaza_http_pending_response_bytes = 0;
    if (sigaction(SIGINT, &shutdown_action, NULL) != 0 || sigaction(SIGTERM, &shutdown_action, NULL) != 0) {
        perror("yaza: signal handler");
        yaza_io_driver_close(&io_driver);
        close(server_fd);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    yaza_http_connection *connections = (yaza_http_connection *)calloc(
        connection_capacity, sizeof(yaza_http_connection));
    if (connections == NULL) {
        fprintf(stderr, "yaza: cannot allocate bounded HTTP connection table\n");
        yaza_io_driver_close(&io_driver);
        close(server_fd);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    for (size_t index = 0; index < connection_capacity; index++) connections[index].fd = -1;
    yaza_scheduler scheduler;
    yaza_scheduler_init(&scheduler);
    yaza_work_pool handler_pool;
    if (!yaza_work_pool_open(&handler_pool, (size_t)configured_worker_count,
                             (size_t)configured_max_in_flight)) {
        fprintf(stderr, "yaza: could not start the bounded API handler worker pool\n");
        free(connections);
        yaza_io_driver_close(&io_driver);
        close(server_fd);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    uint64_t handler_pool_wake_token = yaza_io_allocate_token(&io_driver);
    if (handler_pool_wake_token == 0 ||
        !yaza_io_watch_read(&io_driver, handler_pool.wake_read_fd, handler_pool_wake_token)) {
        perror("yaza: register API worker completion wakeup");
        (void)yaza_work_pool_stop(&handler_pool);
        (void)yaza_work_pool_collect(&handler_pool, connection_capacity);
        (void)yaza_work_pool_close(&handler_pool);
        free(connections);
        yaza_io_driver_close(&io_driver);
        close(server_fd);
        free(routes);
        yaza_http_resources_release(resources, resource_count);
        return 1;
    }
    fprintf(stderr, "\nYAZA API Runtime  |  development\n");
    fprintf(stderr, "  Status        : ready\n");
    fprintf(stderr, "  Listening     : http://%s:%lld\n", configured_host, (long long)active_port);
    fprintf(stderr, "  Host policy   : %zu exact host names (request port ignored)\n",
            yaza_http_allowed_host_count);
    fprintf(stderr, "  Health        : http://%s:%lld/healthz\n", configured_host, (long long)active_port);
    fprintf(stderr, "  Readiness     : http://%s:%lld/readyz\n", configured_host, (long long)active_port);
    fprintf(stderr, "  Metrics       : http://%s:%lld/metrics\n", configured_host, (long long)active_port);
    if (api_token != NULL && jwt_route_count > 0)
        fprintf(stderr, "  API auth      : shared Bearer token%s + JWT HS256 on %zu routes\n",
                api_token_secondary != NULL ? " overlap (2 active credentials)" : "", jwt_route_count);
    else if (api_token != NULL)
        fprintf(stderr, "  API auth      : shared Bearer token%s enabled\n",
                api_token_secondary != NULL ? " overlap (2 active credentials)" : "");
    else if (jwt_route_count > 0)
        fprintf(stderr, "  API auth      : JWT HS256 enabled for %zu routes (issuer and audience pinned)\n", jwt_route_count);
    else
        fprintf(stderr, "  API auth      : disabled (set YAZA_API_TOKEN or declare auth jwt)\n");
    if (rate_limit_enabled)
        fprintf(stderr, "  Rate limit    : %lld requests per %lld ms per client IPv4 (health and metrics excluded)\n",
                (long long)rate_limit_requests, (long long)rate_limit_window_ms);
    else
        fprintf(stderr, "  Rate limit    : disabled (set YAZA_RATE_LIMIT_REQUESTS to enable)\n");
    if (route_cors_count > 0 && cors_origin[0] != '\0')
        fprintf(stderr, "  CORS          : global %s + %zu route policies\n", cors_origin, route_cors_count);
    else if (route_cors_count > 0)
        fprintf(stderr, "  CORS          : %zu route-scoped origin policies\n", route_cors_count);
    else
        fprintf(stderr, "  CORS          : %s\n", cors_origin[0] == '\0' ? "disabled" : cors_origin);
    fprintf(stderr, "  Data store    : %s\n",
            database_url != NULL && *database_url != '\0'
                ? "PostgreSQL (YAZA protocol; DATABASE_URL)"
                : "in-memory (data resets on shutdown)");
    fprintf(stderr, "  Event loop    : %s + YAZA cooperative reader tasks\n", yaza_io_backend_name());
    fprintf(stderr, "  API handlers  : %lld bounded worker threads, %lld in-flight jobs max\n",
            (long long)configured_worker_count, (long long)configured_max_in_flight);
    fprintf(stderr, "  Socket writes : owned by the event-loop thread\n");
    fprintf(stderr, "  Capacity      : %zu open connections, %lld ms request deadline\n",
            connection_capacity, (long long)yaza_http_request_timeout_ms);
    fprintf(stderr, "  Keep-alive    : HTTP/1.1, %lld ms idle timeout, %d requests per connection\n",
            (long long)yaza_http_keep_alive_timeout_ms, YAZA_HTTP_MAX_REQUESTS_PER_CONNECTION);
    fprintf(stderr, "  Response I/O  : nonblocking, %u KiB write quantum, %d ms total deadline\n",
            (unsigned)(YAZA_HTTP_WRITE_QUANTUM_BYTES / 1024U),
            (int)yaza_http_response_write_timeout_ms);
    size_t displayed_route_count = route_count;
    if (displayed_route_count > YAZA_HTTP_STARTUP_ROUTE_DISPLAY_MAX)
        displayed_route_count = YAZA_HTTP_STARTUP_ROUTE_DISPLAY_MAX;
    fprintf(stderr, "  Routes        : %zu registered\n", route_count);
    for (size_t index = 0; index < displayed_route_count; index++)
        fprintf(stderr, "    %-7s %s\n", routes[index].method, routes[index].path);
    if (displayed_route_count < route_count)
        fprintf(stderr, "    ... %zu additional routes omitted from startup output\n",
                route_count - displayed_route_count);
    fprintf(stderr, "  Logs          : structured JSON access events on stderr\n");
    fprintf(stderr, "  Shutdown      : Ctrl+C or SIGTERM, %lld ms response-drain grace\n\n",
            (long long)yaza_http_shutdown_grace_ms);

    bool server_failed = false;
    bool shutdown_started = false;
    bool shutdown_readiness_collected = false;
    bool listener_paused = false;
    int64_t shutdown_deadline_ms = 0;
    int64_t listener_resume_at_ms = 0;
    for (;;) {
        if (yaza_http_shutdown_requested && !shutdown_started) {
            fprintf(stderr, "YAZA API shutdown requested; stopping accepts and flushing pending responses\n");
            if (server_fd >= 0) {
                (void)yaza_io_unwatch(&io_driver, server_fd);
                close(server_fd);
                server_fd = -1;
            }
            int64_t shutdown_now_ms = yaza_monotonic_milliseconds();
            if (shutdown_now_ms < 0 ||
                shutdown_now_ms > INT64_MAX - yaza_http_shutdown_grace_ms) {
                server_failed = true;
                break;
            }
            shutdown_started = true;
            shutdown_deadline_ms = shutdown_now_ms + yaza_http_shutdown_grace_ms;
            for (size_t index = 0; index < connection_capacity; index++) {
                if (connections[index].fd < 0) continue;
                if (connections[index].response_pending)
                    connections[index].response_keep_alive = false;
            }
        }
        if (shutdown_started) {
            bool pending_response = false;
            for (size_t index = 0; index < connection_capacity; index++) {
                if (connections[index].fd >= 0 && connections[index].response_pending) {
                    pending_response = true;
                    break;
                }
            }
            int64_t shutdown_now_ms = yaza_monotonic_milliseconds();
            if (shutdown_now_ms < 0 ||
                (!pending_response && shutdown_readiness_collected) ||
                shutdown_now_ms >= shutdown_deadline_ms) {
                if (pending_response)
                    fprintf(stderr, "YAZA API shutdown grace expired; closing remaining response connections\n");
                break;
            }
        }
        int64_t scheduler_now_ms = yaza_monotonic_milliseconds();
        if (scheduler_now_ms < 0) {
            fprintf(stderr, "yaza: monotonic clock failed before scheduler dispatch\n");
            server_failed = true;
            break;
        }
        if (listener_paused && !yaza_http_shutdown_requested &&
            scheduler_now_ms >= listener_resume_at_ms) {
            if (!yaza_io_watch_read(&io_driver, server_fd, 0)) {
                perror("yaza: resume accept after descriptor-limit backoff");
                server_failed = true;
                break;
            }
            listener_paused = false;
            listener_resume_at_ms = 0;
            fprintf(stderr, "YAZA API listener resumed after descriptor-limit backoff\n");
        }
        uint64_t scheduler_now_ns = (uint64_t)scheduler_now_ms * UINT64_C(1000000);
        (void)yaza_scheduler_run(&scheduler, scheduler_now_ns, connection_capacity);
        short listener_events = 0;
        int poll_timeout = YAZA_HTTP_POLL_INTERVAL_MS;
        if (shutdown_started && !shutdown_readiness_collected) poll_timeout = 0;
        for (size_t index = 0; index < connection_capacity; index++) {
            /* The scheduler may have already completed a reader task above. Do not
             * sleep for the fallback poll interval when there is parsed work ready
             * for dispatch on this event-loop turn. */
            if (connections[index].fd >= 0 && connections[index].request_ready) {
                poll_timeout = 0;
                break;
            }
            if (connections[index].fd >= 0 && connections[index].has_buffered_pipeline) {
                poll_timeout = 0;
                break;
            }
        }
        yaza_io_event ready_events[YAZA_IO_MAX_EVENTS];
        int ready_count = yaza_io_wait(&io_driver, ready_events,
                                       connection_capacity + 2, poll_timeout);
        if (ready_count < 0) {
            if (errno == EINTR && !yaza_http_shutdown_requested) continue;
            if (errno == EINTR && yaza_http_shutdown_requested) {
                /* Collect socket readiness that was already queued when SIGINT/SIGTERM arrived. */
                ready_count = yaza_io_wait(&io_driver, ready_events,
                    connection_capacity + 2, 0);
                if (ready_count < 0 && errno == EINTR) ready_count = 0;
            }
            if (ready_count < 0) {
                if (!yaza_http_shutdown_requested) {
                    perror("yaza: native I/O event wait");
                    server_failed = true;
                }
                break;
            }
        }
        for (int event_index = 0; event_index < ready_count; event_index++) {
            yaza_io_event *event = &ready_events[event_index];
            if (event->token == handler_pool_wake_token) {
                (void)yaza_work_pool_collect(&handler_pool, connection_capacity);
            } else if (event->token == 0) {
                if (event->fd == server_fd) {
                    if ((event->events & YAZA_IO_READABLE) != 0) listener_events |= POLLIN;
                    if ((event->events & YAZA_IO_ERROR) != 0) listener_events |= POLLERR;
                    if ((event->events & YAZA_IO_HANGUP) != 0) listener_events |= POLLHUP;
                }
            } else {
                for (size_t connection_index = 0; connection_index < connection_capacity;
                     connection_index++) {
                    yaza_http_connection *connection = &connections[connection_index];
                    if (connection->fd < 0 || !connection->response_pending ||
                        !connection->response_waiting ||
                        connection->response_write_token != event->token) continue;
                    (void)yaza_io_unwatch_write(&io_driver, connection->fd);
                    connection->response_waiting = false;
                    connection->response_write_token = 0;
                    break;
                }
            }
        }
        if (listener_events & (POLLERR | POLLHUP | POLLNVAL)) {
            fprintf(stderr, "yaza: listen socket failed during %s wait\n", yaza_io_backend_name());
            server_failed = true;
            break;
        }
        if (listener_events & POLLIN) {
            for (size_t accepted = 0; accepted < 32 && !yaza_http_shutdown_requested; accepted++) {
                struct sockaddr_in remote_address;
                socklen_t remote_address_length = sizeof(remote_address);
                memset(&remote_address, 0, sizeof(remote_address));
                int client_fd = accept(server_fd, (struct sockaddr *)&remote_address,
                                       &remote_address_length);
                if (client_fd < 0) {
                    int accept_error = errno;
                    if (yaza_http_shutdown_requested) break;
                    yaza_http_accept_error_action action =
                        yaza_http_classify_accept_error(accept_error);
                    if (action == YAZA_HTTP_ACCEPT_ERROR_DRAIN) break;
                    if (action == YAZA_HTTP_ACCEPT_ERROR_RETRY) continue;
                    if (action == YAZA_HTTP_ACCEPT_ERROR_BACKOFF) {
                        int64_t backoff_now_ms = yaza_monotonic_milliseconds();
                        if (backoff_now_ms < 0 ||
                            backoff_now_ms > INT64_MAX - YAZA_HTTP_ACCEPT_BACKOFF_MS) {
                            fprintf(stderr, "yaza: monotonic clock failed during accept backoff\n");
                            server_failed = true;
                            break;
                        }
                        if (!yaza_io_unwatch(&io_driver, server_fd)) {
                            perror("yaza: pause accept after descriptor limit");
                            server_failed = true;
                            break;
                        }
                        if (yaza_http_accept_backoffs_total < UINT64_MAX)
                            yaza_http_accept_backoffs_total++;
                        listener_paused = true;
                        listener_resume_at_ms = backoff_now_ms + YAZA_HTTP_ACCEPT_BACKOFF_MS;
                        fprintf(stderr,
                            "YAZA API listener paused: accept() reached the file-descriptor limit; retrying in %d ms\n",
                            YAZA_HTTP_ACCEPT_BACKOFF_MS);
                        break;
                    }
                    errno = accept_error;
                    perror("yaza: accept");
                    server_failed = true;
                    break;
                }
                if (yaza_http_shutdown_requested) {
                    close(client_fd);
                    break;
                }
                if (remote_address_length < sizeof(remote_address) ||
                    remote_address.sin_family != AF_INET) {
                    close(client_fd);
                    continue;
                }
                size_t slot = connection_capacity;
                for (size_t index = 0; index < connection_capacity; index++) {
                    if (connections[index].fd < 0) {
                        slot = index;
                        break;
                    }
                }
                if (slot == connection_capacity) {
                    if (yaza_http_connections_rejected_total < UINT64_MAX)
                        yaza_http_connections_rejected_total++;
                    close(client_fd);
                    continue;
                }
                if (connections[slot].generation == UINT64_MAX) {
                    close(client_fd);
                    continue;
                }
                connections[slot].generation++;
                int client_flags = fcntl(client_fd, F_GETFL, 0);
                if (client_flags < 0 || fcntl(client_fd, F_SETFL, client_flags | O_NONBLOCK) < 0) {
                    close(client_fd);
                    continue;
                }
                connections[slot].fd = client_fd;
                connections[slot].remote_ipv4 = remote_address.sin_addr.s_addr;
                connections[slot].io_driver = &io_driver;
                connections[slot].used = 0;
                int64_t accepted_at_ms = yaza_monotonic_milliseconds();
                connections[slot].last_activity_ms = accepted_at_ms;
                connections[slot].request_started_at_ms = accepted_at_ms;
                connections[slot].requests_served = 0;
                connections[slot].request_ready = false;
                connections[slot].has_overwritten_pipeline_byte = false;
                connections[slot].has_buffered_pipeline = false;
                connections[slot].request[0] = '\0';
                uint64_t reader_task_id = yaza_scheduler_spawn(&scheduler, 0,
                    yaza_http_connection_read_step, &connections[slot]);
                if (reader_task_id == 0) {
                    fprintf(stderr, "yaza: bounded scheduler rejected HTTP connection reader task\n");
                    yaza_http_connection_reset(&io_driver, &scheduler, connections, slot);
                } else {
                    connections[slot].reader_task_id = reader_task_id;
                }
            }
            if (server_failed) break;
        }
        (void)yaza_io_dispatch_task_waits(&io_driver, &scheduler, ready_events, (size_t)ready_count);
        int64_t dispatch_now_ms = yaza_monotonic_milliseconds();
        if (dispatch_now_ms < 0) {
            fprintf(stderr, "yaza: monotonic clock failed during scheduler dispatch\n");
            server_failed = true;
            break;
        }
        (void)yaza_scheduler_run(&scheduler,
            (uint64_t)dispatch_now_ms * UINT64_C(1000000), connection_capacity);
        int64_t now_ms = yaza_monotonic_milliseconds();
        if (now_ms < 0) {
            fprintf(stderr, "yaza: monotonic clock failed in HTTP event loop\n");
            server_failed = true;
            break;
        }
        for (size_t connection_index = 0; connection_index < connection_capacity; connection_index++) {
            if (connections[connection_index].fd < 0) continue;
            if (connections[connection_index].response_pending &&
                !connections[connection_index].response_waiting) {
                int flush_status = yaza_http_flush_response(&io_driver, &connections[connection_index]);
                if (flush_status < 0) {
                    yaza_http_connection_reset(&io_driver, &scheduler, connections, connection_index);
                    continue;
                }
                if (flush_status > 0)
                    yaza_http_finish_response(&io_driver, &scheduler, connections, connection_index);
                if (connections[connection_index].fd < 0) continue;
            }
            int64_t deadline_start = connections[connection_index].response_pending
                ? connections[connection_index].response_started_ms
                : (connections[connection_index].used == 0
                    ? connections[connection_index].last_activity_ms
                    : connections[connection_index].request_started_at_ms);
            int64_t deadline = connections[connection_index].response_pending
                ? yaza_http_response_write_timeout_ms
                : (connections[connection_index].used == 0
                    ? yaza_http_keep_alive_timeout_ms : yaza_http_request_timeout_ms);
            if (now_ms - deadline_start >= deadline) {
                if (connections[connection_index].worker_pending) {
                    (void)yaza_http_worker_timeout_response(&io_driver, &scheduler,
                        connections, connection_index);
                    continue;
                }
                yaza_http_connection_reset(&io_driver, &scheduler, connections, connection_index);
                continue;
            }
            if (connections[connection_index].response_pending) continue;
            if (!connections[connection_index].request_ready) continue;
        if (connections[connection_index].request_status == YAZA_HTTP_REQUEST_EOF) {
            yaza_http_connection_reset(&io_driver, &scheduler, connections, connection_index);
            continue;
        }
        int client_fd = connections[connection_index].fd;
        snprintf(yaza_http_current_method, sizeof(yaza_http_current_method), "unknown");
        snprintf(yaza_http_current_path, sizeof(yaza_http_current_path), "unknown");
        char *request = connections[connection_index].request;
        char *method = connections[connection_index].method;
        char *path = connections[connection_index].path;
        const char *request_body = connections[connection_index].request_body;
        size_t request_length = connections[connection_index].request_length;
        bool request_keep_alive = connections[connection_index].request_keep_alive;
        int request_status = connections[connection_index].request_status;
        yaza_http_head_request = request_status == 0 && strcmp(method, "HEAD") == 0;
        unsigned char verified_jwt_claims[YAZA_HTTP_JWT_MAX_SEGMENT_BYTES + 1U] = {0};
        bool jwt_authenticated = false;
        connections[connection_index].request_ready = false;
        yaza_http_response_keep_alive = request_status == 0 && request_keep_alive &&
            connections[connection_index].requests_served + 1 < YAZA_HTTP_MAX_REQUESTS_PER_CONNECTION;
        yaza_http_current_started_ms = connections[connection_index].request_started_at_ms;
        yaza_http_current_request_id[0] = '\0';
        yaza_http_assign_request_id();
        snprintf(connections[connection_index].request_id,
                 sizeof(connections[connection_index].request_id), "%s",
                 yaza_http_current_request_id);
        connections[connection_index].request_cors_origin[0] = '\0';
        yaza_memory_arena request_arena;
        yaza_memory_arena_init(&request_arena, YAZA_REQUEST_MEMORY_LIMIT);
        yaza_memory_arena *previous_arena = yaza_memory_arena_enter(&request_arena);
        yaza_http_active_connection = &connections[connection_index];
        if (request_status != 0) {
            if (request_status == -8)
                yaza_http_respond(client_fd, 503, "Service Unavailable", "{\"error\":\"Request scheduler unavailable\"}");
            else if (request_status == -2)
                yaza_http_respond(client_fd, 413, "Payload Too Large", "{\"error\":\"Payload Too Large\"}");
            else if (request_status == -3)
                yaza_http_respond(client_fd, 431, "Request Header Fields Too Large", "{\"error\":\"Request Headers Too Large\"}");
            else if (request_status == -4)
                yaza_http_respond(client_fd, 415, "Unsupported Media Type", "{\"error\":\"Content-Type must be application/json\"}");
            else
                yaza_http_respond(client_fd, 400, "Bad Request", "{\"error\":\"Bad Request\"}");
        } else {
            snprintf(yaza_http_current_method, sizeof(yaza_http_current_method), "%s", method);
            snprintf(yaza_http_current_path, sizeof(yaza_http_current_path), "%s", path);
            yaza_http_cors_response_origin[0] = '\0';
            snprintf(yaza_http_cors_allow_headers, sizeof(yaza_http_cors_allow_headers),
                     "Accept, Authorization, Content-Type");
            yaza_http_cors_preflight_active = false;
            char request_origin[512];
            bool has_request_origin = false;
            if (!yaza_http_header_parameter_value(request, "Origin", request_origin,
                                                  sizeof(request_origin), &has_request_origin)) {
                yaza_http_response_keep_alive = false;
                yaza_http_respond(client_fd, 400, "Bad Request", "{\"error\":\"Invalid Origin header\"}");
                goto yaza_http_dispatch_done;
            }
            const char *query_parameters = NULL;
            char *query = strchr(path, '?');
            if (query != NULL) {
                *query = '\0';
                query_parameters = query + 1;
            }
            const yaza_http_route *cors_route = NULL;
            const yaza_http_route *cors_path_route = NULL;
            char cors_requested_method[32];
            bool has_cors_requested_method = false;
            bool cors_requested_method_valid = true;
            if (strcmp(method, "OPTIONS") == 0) {
                cors_requested_method_valid = yaza_http_header_parameter_value(
                    request, "Access-Control-Request-Method", cors_requested_method,
                    sizeof(cors_requested_method), &has_cors_requested_method);
            }
            for (size_t index = 0; index < route_count; index++) {
                if (!yaza_http_path_matches(routes[index].path, path)) continue;
                if (cors_path_route == NULL) cors_path_route = &routes[index];
            }
            const char *candidate_method = strcmp(method, "OPTIONS") == 0
                ? cors_requested_method : method;
            bool candidate_method_present = strcmp(method, "OPTIONS") != 0 ||
                (cors_requested_method_valid && has_cors_requested_method);
            if (candidate_method_present)
                cors_route = yaza_http_route_for_method(routes, route_count, path, candidate_method);
            if (cors_route == NULL) cors_route = cors_path_route;
            const char *effective_cors_origin = cors_route != NULL && cors_route->cors_origin[0] != '\0'
                ? cors_route->cors_origin : cors_origin;
            if (effective_cors_origin[0] != '\0' && has_request_origin &&
                strcmp(request_origin, effective_cors_origin) == 0)
                snprintf(yaza_http_cors_response_origin, sizeof(yaza_http_cors_response_origin),
                         "%s", effective_cors_origin);
            snprintf(connections[connection_index].request_cors_origin,
                     sizeof(connections[connection_index].request_cors_origin), "%s",
                     yaza_http_cors_response_origin);
            if (yaza_http_requests_total < UINT64_MAX) yaza_http_requests_total++;
            if (strcmp(method, "OPTIONS") == 0 && yaza_http_cors_response_origin[0] != '\0') {
                if (!cors_requested_method_valid) {
                    yaza_http_response_keep_alive = false;
                    yaza_http_respond(client_fd, 400, "Bad Request", "{\"error\":\"Invalid CORS preflight\"}");
                    goto yaza_http_dispatch_done;
                }
                if (has_cors_requested_method) {
                    yaza_http_response_keep_alive = false;
                    const char *requested_method = cors_requested_method;
                    bool preflight_path_found = false;
                    for (size_t index = 0; index < route_count; index++) {
                        if (!yaza_http_path_matches(routes[index].path, path)) continue;
                        preflight_path_found = true;
                    }
                    const yaza_http_route *preflight_route = yaza_http_route_for_method(
                        routes, route_count, path, requested_method);
                    bool preflight_route_found = preflight_route != NULL;
                    if (!preflight_path_found && strcmp(path, "/healthz") == 0 &&
                        (strcmp(requested_method, "GET") == 0 || strcmp(requested_method, "HEAD") == 0)) {
                        preflight_path_found = true;
                        preflight_route_found = true;
                    }
                    if (!preflight_route_found) {
                        yaza_http_respond(client_fd, preflight_path_found ? 403 : 404,
                                          preflight_path_found ? "Forbidden" : "Not Found",
                                          preflight_path_found ? "{\"error\":\"CORS method is not allowed\"}" : "{\"error\":\"Not Found\"}");
                        goto yaza_http_dispatch_done;
                    }
                    if (!yaza_http_cors_requested_headers_valid(request, preflight_route,
                            yaza_http_cors_allow_headers, sizeof(yaza_http_cors_allow_headers))) {
                        yaza_http_respond(client_fd, 400, "Bad Request", "{\"error\":\"Invalid CORS preflight\"}");
                        goto yaza_http_dispatch_done;
                    }
                    yaza_http_cors_preflight_active = true;
                    yaza_http_respond_content(client_fd, 204, "No Content", "application/json; charset=utf-8", "");
                    goto yaza_http_dispatch_done;
                }
            }
            bool operational_path = strcmp(path, "/healthz") == 0 ||
                strcmp(path, "/readyz") == 0 || strcmp(path, "/metrics") == 0;
            if (rate_limit_enabled && !operational_path) {
                int64_t retry_after_seconds = 1;
                if (!yaza_http_rate_limit_allow(connections[connection_index].remote_ipv4, 0,
                                                now_ms, rate_limit_requests,
                                                rate_limit_window_ms, &retry_after_seconds)) {
                    yaza_http_response_keep_alive = false;
                    yaza_http_retry_after_seconds = retry_after_seconds;
                    yaza_http_respond(client_fd, 429, "Too Many Requests",
                                      "{\"error\":{\"type\":\"rate_limit_error\",\"code\":\"rate_limited\"}}");
                    yaza_http_retry_after_seconds = 1;
                    goto yaza_http_dispatch_done;
                }
            }
            bool public_health_route = (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0 ||
                                        strcmp(method, "OPTIONS") == 0) &&
                (strcmp(path, "/healthz") == 0 || strcmp(path, "/readyz") == 0);
            const yaza_http_route *authentication_route = yaza_http_route_for_method(
                routes, route_count, path, method);
            if (authentication_route == NULL && strcmp(method, "OPTIONS") == 0)
                authentication_route = yaza_http_route_for_path_policy(routes, route_count, path);
            if (authentication_route != NULL && authentication_route->rate_limit_requests > 0 &&
                !operational_path) {
                int64_t retry_after_seconds = 1;
                if (!yaza_http_rate_limit_allow(connections[connection_index].remote_ipv4,
                                                authentication_route->rate_limit_scope_id,
                                                now_ms, authentication_route->rate_limit_requests,
                                                authentication_route->rate_limit_window_ms,
                                                &retry_after_seconds)) {
                    yaza_http_response_keep_alive = false;
                    yaza_http_retry_after_seconds = retry_after_seconds;
                    yaza_http_respond(client_fd, 429, "Too Many Requests",
                                      "{\"error\":{\"type\":\"rate_limit_error\",\"code\":\"rate_limited\"}}");
                    yaza_http_retry_after_seconds = 1;
                    goto yaza_http_dispatch_done;
                }
            }
            if (authentication_route != NULL && authentication_route->auth_policy == 3) {
                int jwt_status = yaza_http_jwt_authenticated(request, jwt_secret, jwt_issuer, jwt_audience,
                    verified_jwt_claims, sizeof(verified_jwt_claims));
                if (jwt_status == 2) yaza_http_respond_token_expired(client_fd);
                else if (jwt_status != 1) yaza_http_respond_unauthorized(client_fd);
                if (jwt_status != 1) goto yaza_http_dispatch_done;
                jwt_authenticated = true;
            } else {
                bool authentication_required = api_token != NULL && !public_health_route;
                if (authentication_route != NULL && authentication_route->auth_policy == 1)
                    authentication_required = false;
                else if (authentication_route != NULL && authentication_route->auth_policy == 2)
                    authentication_required = true;
                if (authentication_required &&
                    (api_token == NULL || !yaza_http_bearer_authenticated(
                    request, api_tokens, api_token_lengths, api_token_count))) {
                    yaza_http_respond_unauthorized(client_fd);
                    goto yaza_http_dispatch_done;
                }
            }
            const char *response_body = NULL;
            const yaza_http_route *matched_route = NULL;
            bool server_options_target = strcmp(method, "OPTIONS") == 0 && strcmp(path, "*") == 0;
            bool path_found = server_options_target;
            bool route_found = false;
            bool allow_complete = true;
            char allow_methods[YAZA_HTTP_ALLOW_MAX_BYTES] = {0};
            bool health_path = strcmp(path, "/healthz") == 0 || strcmp(path, "/readyz") == 0;
            bool metrics_path = strcmp(path, "/metrics") == 0;
            for (size_t index = 0; index < route_count; index++) {
                if (!server_options_target && !yaza_http_path_matches(routes[index].path, path)) continue;
                path_found = true;
                if (!yaza_http_allow_add(allow_methods, sizeof(allow_methods), routes[index].method))
                    allow_complete = false;
                if (strcmp(routes[index].method, "GET") == 0 &&
                    !yaza_http_allow_add(allow_methods, sizeof(allow_methods), "HEAD"))
                    allow_complete = false;
            }
            matched_route = yaza_http_route_for_method(routes, route_count, path, method);
            if (matched_route != NULL) {
                route_found = true;
                response_body = matched_route->body;
            }
            if (!path_found && (health_path || metrics_path)) path_found = true;
            if (health_path || metrics_path) {
                if (!yaza_http_allow_add(allow_methods, sizeof(allow_methods), "GET"))
                    allow_complete = false;
                if (!yaza_http_allow_add(allow_methods, sizeof(allow_methods), "HEAD"))
                    allow_complete = false;
            }
            if (path_found && !yaza_http_allow_add(allow_methods, sizeof(allow_methods), "OPTIONS"))
                allow_complete = false;
            if (!route_found && strcmp(method, "OPTIONS") == 0) {
                if (!path_found) {
                    yaza_http_respond(client_fd, 404, "Not Found", not_found);
                } else if (allow_complete && allow_methods[0] != '\0') {
                    yaza_http_respond_content_with_allow(client_fd, 204, "No Content",
                        "application/json; charset=utf-8", "", allow_methods);
                } else {
                    yaza_http_respond(client_fd, 500, "Internal Server Error",
                                      "{\"error\":\"Route method list exceeds runtime limits\"}");
                }
                goto yaza_http_dispatch_done;
            }
            if (!route_found) {
                if ((health_path || metrics_path) &&
                    (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0)) {
                    if (health_path) {
                        if (strcmp(path, "/readyz") == 0 && yaza_http_readiness_handler != NULL) {
                            yaza_http_readiness_job *job = yaza_http_readiness_job_create(
                                &connections[connection_index], method, path,
                                yaza_http_cors_response_origin);
                            int64_t job_deadline_ms = connections[connection_index].request_started_at_ms;
                            if (job_deadline_ms < 0 ||
                                job_deadline_ms > INT64_MAX - yaza_http_request_timeout_ms) {
                                yaza_system_free(job);
                                yaza_http_respond(client_fd, 503, "Service Unavailable",
                                    "{\"error\":{\"type\":\"unavailable_error\",\"code\":\"readiness_queue_unavailable\"}}");
                            } else if (job == NULL) {
                                yaza_http_respond(client_fd, 503, "Service Unavailable",
                                    "{\"error\":{\"type\":\"unavailable_error\",\"code\":\"readiness_queue_unavailable\"}}");
                            } else {
                                job_deadline_ms += yaza_http_request_timeout_ms;
                                connections[connection_index].worker_pending = true;
                                connections[connection_index].worker_cancelled = &job->cancelled;
                                if (yaza_work_pool_submit(&handler_pool,
                                        yaza_http_readiness_worker_run,
                                        yaza_http_readiness_worker_complete, job,
                                        &job->cancelled, job_deadline_ms)) {
                                    goto yaza_http_dispatch_done;
                                }
                                connections[connection_index].worker_pending = false;
                                connections[connection_index].worker_cancelled = NULL;
                                yaza_system_free(job);
                                yaza_http_respond(client_fd, 503, "Service Unavailable",
                                    "{\"error\":{\"type\":\"unavailable_error\",\"code\":\"readiness_queue_full\"}}");
                            }
                        } else {
                            bool database_configured = getenv("DATABASE_URL") != NULL && *getenv("DATABASE_URL") != '\0';
                            bool database_ready = strcmp(path, "/readyz") != 0 || !database_configured;
                            yaza_http_respond(client_fd, database_ready ? 200 : 503,
                                              database_ready ? "OK" : "Service Unavailable",
                                              database_ready ? healthy : "{\"status\":\"not_ready\",\"dependency\":\"postgresql\"}");
                        }
                    } else {
                        char metrics[4096];
                        size_t active_connections = 0;
                        yaza_work_pool_stats worker_stats = {0};
                        (void)yaza_work_pool_get_stats(&handler_pool, &worker_stats);
                        for (size_t metric_connection_index = 0;
                             metric_connection_index < connection_capacity;
                             metric_connection_index++) {
                            if (connections[metric_connection_index].fd >= 0)
                                active_connections++;
                        }
                        int metrics_length = snprintf(metrics, sizeof(metrics),
                            "# HELP yaza_http_requests_total Total HTTP requests received.\n"
                            "# TYPE yaza_http_requests_total counter\n"
                            "yaza_http_requests_total %llu\n"
                            "# HELP yaza_http_responses_total HTTP responses returned by status code.\n"
                            "# TYPE yaza_http_responses_total counter\n"
                            "# HELP yaza_http_connections_active Active HTTP client connections.\n"
                            "# TYPE yaza_http_connections_active gauge\n"
                            "yaza_http_connections_active %zu\n"
                            "# HELP yaza_http_connections_limit Configured maximum active HTTP client connections.\n"
                            "# TYPE yaza_http_connections_limit gauge\n"
                            "yaza_http_connections_limit %zu\n"
                            "# HELP yaza_http_connections_rejected_total Accepted TCP connections closed because the active-connection table was full.\n"
                            "# TYPE yaza_http_connections_rejected_total counter\n"
                            "yaza_http_connections_rejected_total %llu\n"
                            "# HELP yaza_http_accept_backoffs_total Listener pauses after EMFILE or ENFILE accept failures.\n"
                            "# TYPE yaza_http_accept_backoffs_total counter\n"
                            "yaza_http_accept_backoffs_total %llu\n"
                            "# HELP yaza_api_workers Configured API handler worker threads.\n"
                            "# TYPE yaza_api_workers gauge\n"
                            "yaza_api_workers %zu\n"
                            "# HELP yaza_api_worker_queue_capacity Maximum in-flight handler jobs.\n"
                            "# TYPE yaza_api_worker_queue_capacity gauge\n"
                            "yaza_api_worker_queue_capacity %zu\n"
                            "# HELP yaza_api_worker_jobs_in_flight Handler jobs not yet delivered to the event loop.\n"
                            "# TYPE yaza_api_worker_jobs_in_flight gauge\n"
                            "yaza_api_worker_jobs_in_flight %zu\n"
                            "# HELP yaza_api_worker_jobs_queued Handler jobs waiting for a worker.\n"
                            "# TYPE yaza_api_worker_jobs_queued gauge\n"
                            "yaza_api_worker_jobs_queued %zu\n"
                            "# HELP yaza_api_worker_jobs_active Handler jobs currently executing.\n"
                            "# TYPE yaza_api_worker_jobs_active gauge\n"
                            "yaza_api_worker_jobs_active %zu\n"
                            "# HELP yaza_api_worker_jobs_completing Results waiting for event-loop delivery.\n"
                            "# TYPE yaza_api_worker_jobs_completing gauge\n"
                            "yaza_api_worker_jobs_completing %zu\n"
                            "# HELP yaza_api_worker_jobs_total Handler jobs accepted.\n"
                            "# TYPE yaza_api_worker_jobs_total counter\n"
                            "yaza_api_worker_jobs_total %llu\n"
                            "# HELP yaza_api_worker_jobs_rejected_total Handler jobs rejected by bounded admission.\n"
                            "# TYPE yaza_api_worker_jobs_rejected_total counter\n"
                            "yaza_api_worker_jobs_rejected_total %llu\n"
                            "# HELP yaza_api_worker_jobs_failed_total Handler jobs that failed or timed out.\n"
                            "# TYPE yaza_api_worker_jobs_failed_total counter\n"
                            "yaza_api_worker_jobs_failed_total %llu\n"
                            "# HELP yaza_api_worker_jobs_cancelled_total Handler jobs cancelled before or during execution.\n"
                            "# TYPE yaza_api_worker_jobs_cancelled_total counter\n"
                            "yaza_api_worker_jobs_cancelled_total %llu\n"
                            "# HELP yaza_api_worker_jobs_timed_out_total Handler jobs that reached or exceeded their deadline.\n"
                            "# TYPE yaza_api_worker_jobs_timed_out_total counter\n"
                            "yaza_api_worker_jobs_timed_out_total %llu\n",
                            (unsigned long long)yaza_http_requests_total,
                            active_connections, connection_capacity,
                            (unsigned long long)yaza_http_connections_rejected_total,
                            (unsigned long long)yaza_http_accept_backoffs_total,
                            worker_stats.threads, worker_stats.capacity, worker_stats.in_flight,
                            worker_stats.queued, worker_stats.active, worker_stats.completing,
                            (unsigned long long)worker_stats.submitted_total,
                            (unsigned long long)worker_stats.rejected_total,
                            (unsigned long long)worker_stats.failed_total,
                            (unsigned long long)worker_stats.cancelled_total,
                            (unsigned long long)worker_stats.timed_out_total);
                        size_t metrics_used = metrics_length > 0 && (size_t)metrics_length < sizeof(metrics)
                            ? (size_t)metrics_length : sizeof(metrics);
                        for (size_t metric_index = 0;
                             metrics_used < sizeof(metrics) &&
                             metric_index < sizeof(yaza_http_metric_status_codes) / sizeof(yaza_http_metric_status_codes[0]);
                             metric_index++) {
                            int metric_line_length = snprintf(metrics + metrics_used,
                                sizeof(metrics) - metrics_used,
                                "yaza_http_responses_total{status=\"%d\"} %llu\n",
                                yaza_http_metric_status_codes[metric_index],
                                (unsigned long long)yaza_http_metric_status_counts[metric_index]);
                            if (metric_line_length < 0 || (size_t)metric_line_length >= sizeof(metrics) - metrics_used) break;
                            metrics_used += (size_t)metric_line_length;
                        }
                        size_t pool_idle = 0, pool_leased = 0, pool_connecting = 0;
                        int64_t pool_maximum = 0;
                        const char *database_url = getenv("DATABASE_URL");
                        if (database_url != NULL && database_url[0] != '\0') {
                            yaza_bytes pool_identity = yaza_pg_pool_environment_identity();
                            yaza_pg_pool_counts pool_counts;
                            if (yaza_pg_pool_snapshot(pool_identity, &pool_counts)) {
                                pool_idle = pool_counts.idle;
                                pool_leased = pool_counts.leased;
                                pool_connecting = pool_counts.connecting;
                                (void)yaza_pg_pool_read_limit("YAZA_PG_POOL_SIZE", 8, 1,
                                                              YAZA_PG_POOL_MAX_PER_KEY, &pool_maximum);
                            }
                        }
                        if (metrics_used < sizeof(metrics)) {
                            int pool_metric_length = snprintf(metrics + metrics_used,
                                sizeof(metrics) - metrics_used,
                                "# HELP yaza_postgresql_pool_connections Current PostgreSQL pool connections by state.\n"
                                "# TYPE yaza_postgresql_pool_connections gauge\n"
                                "yaza_postgresql_pool_connections{state=\"idle\"} %zu\n"
                                "yaza_postgresql_pool_connections{state=\"leased\"} %zu\n"
                                "yaza_postgresql_pool_connections{state=\"connecting\"} %zu\n"
                                "# HELP yaza_postgresql_pool_max_connections Configured per-database PostgreSQL pool maximum.\n"
                                "# TYPE yaza_postgresql_pool_max_connections gauge\n"
                                "yaza_postgresql_pool_max_connections %lld\n",
                                pool_idle, pool_leased, pool_connecting, (long long)pool_maximum);
                            if (pool_metric_length > 0 &&
                                (size_t)pool_metric_length < sizeof(metrics) - metrics_used)
                                metrics_used += (size_t)pool_metric_length;
                            else
                                metrics[sizeof(metrics) - 1] = '\0';
                        }
                        yaza_http_respond_content(client_fd, 200, "OK", "text/plain; version=0.0.4; charset=utf-8", metrics);
                    }
                } else {
                    if (!path_found) {
                        yaza_http_respond(client_fd, 404, "Not Found", not_found);
                    } else if (allow_complete && allow_methods[0] != '\0') {
                        yaza_http_respond_method_not_allowed(client_fd, allow_methods);
                    } else {
                        yaza_http_respond(client_fd, 500, "Internal Server Error",
                                          "{\"error\":\"Route method list exceeds runtime limits\"}");
                    }
                }
            } else {
                yaza_http_parameter parameters[YAZA_HTTP_MAX_JSON_FIELDS];
                size_t parameter_count = 0;
                yaza_http_validation_error request_validation_error = {0};
                if (matched_route == NULL ||
                    !yaza_http_controller_parameters(matched_route->metadata, parameters,
                                                     YAZA_HTTP_MAX_JSON_FIELDS, &parameter_count)) {
                    yaza_http_respond(client_fd, 500, "Internal Server Error", "{\"error\":\"Invalid route metadata\"}");
                } else if (!yaza_http_bound_parameters_valid(parameters, parameter_count, matched_route->path,
                                                             path, query_parameters, request,
                                                             &request_validation_error)) {
                    yaza_http_respond_typed_error(client_fd, 400, "Bad Request", &request_validation_error);
                } else if (matched_route->handler_name != NULL && *matched_route->handler_name != '\0' &&
                           !yaza_http_body_parameters_valid(matched_route, request_body, parameters,
                                                            parameter_count, &request_validation_error)) {
                    yaza_http_respond_validation_error(client_fd, &request_validation_error);
                } else if (matched_route->handler_name != NULL && *matched_route->handler_name != '\0') {
                    yaza_http_resource *handler_resource = yaza_http_resource_for_path(resources, resource_count, path);
                    const yaza_http_request_context handler_context = {
                        matched_route, path, query_parameters, request, request_body,
                        client_fd, handler_resource, parameters, parameter_count,
                        jwt_authenticated && matched_route->auth_policy == 3
                            ? (const char *)verified_jwt_claims : NULL
                    };
                    yaza_http_handler_job *job = yaza_http_handler_job_create(
                        &connections[connection_index], matched_route, method, path,
                        query_parameters, request, request_body, client_fd, handler_resource,
                        parameters, parameter_count,
                        jwt_authenticated && matched_route->auth_policy == 3
                            ? verified_jwt_claims : NULL,
                        yaza_http_cors_response_origin);
                    int64_t job_deadline_ms = connections[connection_index].request_started_at_ms;
                    if (job_deadline_ms < 0 ||
                        job_deadline_ms > INT64_MAX - yaza_http_request_timeout_ms) {
                        yaza_system_free(job);
                        yaza_http_respond(client_fd, 503, "Service Unavailable",
                                          "{\"error\":{\"type\":\"unavailable_error\",\"code\":\"handler_queue_unavailable\"}}");
                    } else if (job == NULL) {
                        yaza_http_respond(client_fd, 503, "Service Unavailable",
                                          "{\"error\":{\"type\":\"unavailable_error\",\"code\":\"handler_queue_unavailable\"}}");
                    } else {
                        job_deadline_ms += yaza_http_request_timeout_ms;
                        connections[connection_index].worker_pending = true;
                        connections[connection_index].worker_cancelled = &job->cancelled;
                        if (yaza_work_pool_submit(&handler_pool, yaza_http_handler_worker_run,
                                yaza_http_handler_worker_complete, job, &job->cancelled,
                                job_deadline_ms)) {
                            goto yaza_http_dispatch_done;
                        }
                        connections[connection_index].worker_pending = false;
                        connections[connection_index].worker_cancelled = NULL;
                        yaza_system_free(job);
                        yaza_http_respond(client_fd, 503, "Service Unavailable",
                                          "{\"error\":{\"type\":\"unavailable_error\",\"code\":\"handler_queue_full\"}}");
                    }
                } else {
                    yaza_http_resource *resource = yaza_http_resource_for_path(resources, resource_count, path);
                    if (resource != NULL) {
#ifdef YAZA_WITH_POSTGRES
                        if (yaza_http_database != NULL)
                            yaza_http_pg_crud_respond(client_fd, resource, matched_route->method, path, query_parameters,
                                                      request_body, parameters, parameter_count,
                                                      matched_route->body_schema);
                        else
#endif
                        {
                            if (pthread_mutex_lock(&yaza_http_resources_mutex) != 0) {
                                yaza_http_respond(client_fd, 503, "Service Unavailable",
                                                  "{\"error\":\"Resource store unavailable\"}");
                            } else {
                                yaza_http_crud_respond(client_fd, resource, matched_route->method, path, query_parameters,
                                                   request_body, parameters, parameter_count,
                                                   matched_route->body_schema);
                                pthread_mutex_unlock(&yaza_http_resources_mutex);
                            }
                        }
                    } else yaza_http_respond(client_fd, 200, "OK", response_body == NULL ? not_found : response_body);
                }
            }
        }
        yaza_http_dispatch_done:
        yaza_http_head_request = false;
        yaza_http_active_connection = NULL;
        yaza_secure_wipe(verified_jwt_claims, sizeof(verified_jwt_claims));
        if (connections[connection_index].worker_pending) {
            yaza_memory_arena_leave(&request_arena, previous_arena);
            continue;
        }
        if (connections[connection_index].response_failed) {
            yaza_memory_arena_leave(&request_arena, previous_arena);
            yaza_http_connection_reset(&io_driver, &scheduler, connections, connection_index);
            continue;
        }
        if (connections[connection_index].response_pending) {
            int flush_status = yaza_http_flush_response(&io_driver, &connections[connection_index]);
            if (flush_status < 0) {
                yaza_memory_arena_leave(&request_arena, previous_arena);
                yaza_http_connection_reset(&io_driver, &scheduler, connections, connection_index);
                continue;
            }
            if (flush_status > 0)
                yaza_http_finish_response(&io_driver, &scheduler, connections, connection_index);
            yaza_memory_arena_leave(&request_arena, previous_arena);
            continue;
        }
        if (yaza_http_response_keep_alive && !yaza_http_shutdown_requested) {
            if (connections[connection_index].has_overwritten_pipeline_byte)
                request[request_length] = connections[connection_index].overwritten_pipeline_byte;
            size_t remaining = connections[connection_index].used > request_length
                ? connections[connection_index].used - request_length : 0;
            if (remaining > 0) memmove(request, request + request_length, remaining);
            connections[connection_index].used = remaining;
            request[remaining] = '\0';
            connections[connection_index].requests_served++;
            connections[connection_index].last_activity_ms = yaza_monotonic_milliseconds();
            connections[connection_index].request_started_at_ms = remaining > 0
                ? connections[connection_index].last_activity_ms : 0;
            connections[connection_index].has_overwritten_pipeline_byte = false;
            connections[connection_index].has_buffered_pipeline = remaining > 0;
            if (!yaza_scheduler_wake(&scheduler, connections[connection_index].reader_task_id)) {
                fprintf(stderr, "yaza: could not wake HTTP connection reader after response\n");
                yaza_http_connection_reset(&io_driver, &scheduler, connections, connection_index);
            }
        } else {
            yaza_http_connection_reset(&io_driver, &scheduler, connections, connection_index);
        }
        yaza_memory_arena_leave(&request_arena, previous_arena);
    }
        if (shutdown_started && !shutdown_readiness_collected) {
            shutdown_readiness_collected = true;
            for (size_t index = 0; index < connection_capacity; index++) {
                if (connections[index].fd >= 0 && !connections[index].response_pending)
                    yaza_http_connection_reset(&io_driver, &scheduler, connections, index);
            }
        }
    }
    for (size_t index = 0; index < connection_capacity; index++)
        yaza_http_connection_reset(&io_driver, &scheduler, connections, index);
    (void)yaza_io_unwatch(&io_driver, handler_pool.wake_read_fd);
    int64_t worker_stop_deadline_ms = shutdown_deadline_ms;
    if (!shutdown_started) {
        int64_t worker_stop_started_ms = yaza_monotonic_milliseconds();
        if (worker_stop_started_ms < 0 ||
            worker_stop_started_ms > INT64_MAX - yaza_http_shutdown_grace_ms) {
            fprintf(stderr, "YAZA API could not establish a bounded worker shutdown deadline\n");
            _exit(1);
        }
        worker_stop_deadline_ms = worker_stop_started_ms + yaza_http_shutdown_grace_ms;
    }
    if (!yaza_work_pool_stop_until(&handler_pool, worker_stop_deadline_ms)) {
        fprintf(stderr,
            "YAZA API worker pool could not stop before the shutdown deadline; terminating the process to avoid freeing state still in use\n");
        _exit(1);
    }
    (void)yaza_work_pool_collect(&handler_pool, connection_capacity);
    if (!yaza_work_pool_close(&handler_pool)) {
        fprintf(stderr, "yaza: API handler worker pool did not drain cleanly\n");
        server_failed = true;
    }
    yaza_io_driver_close(&io_driver);
    if (yaza_http_request_random_fd >= 0) {
        close(yaza_http_request_random_fd);
        yaza_http_request_random_fd = -1;
    }
    if (server_fd >= 0) close(server_fd);
    free(connections);
    free(routes);
    yaza_http_resources_release(resources, resource_count);
#ifdef YAZA_WITH_POSTGRES
    if (yaza_http_database != NULL) {
        PQfinish(yaza_http_database);
        yaza_http_database = NULL;
    }
#endif
    fprintf(stderr, "YAZA API stopped%s\n", server_failed ? " after a runtime error" : " gracefully");
    return server_failed ? 1 : 0;
}

int yaza_main(int argc, char **argv) {
    yaza_argc = argc - 1;
    yaza_argv = argv + 1;
