Instructions to use NoesisLab/LITOperator with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LeRobot
How to use NoesisLab/LITOperator with LeRobot:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download lit_operator/lit_operator.c from NoesisLab/LITOperator: direct link, hf CLI and curl.
- Browser
- Download file 81.7 kB
-
https://huggingface.co/NoesisLab/LITOperator/resolve/main/lit_operator/lit_operator.c
- Command line
-
hf download hf://NoesisLab/LITOperator/lit_operator/lit_operator.c
-
curl -L -o lit_operator.c https://huggingface.co/NoesisLab/LITOperator/resolve/main/lit_operator/lit_operator.c
81.7 kB
/* lit_operator.c — the LIT DO search operator: the DO node arena and
* the frontier scan. The tree stores interventions, not machine
* states: a node's state is replayed from its DO chain. This is the
* mainline for synthesis: the search path, flattened, is the program.
* The Coder only mines macros. No game, no ARC, no Python: the caller
* supplies the machine/state, the actions, and the oracle. */
#include "lit_operator.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lit_do_apply(lit_machine *m, const lit_do *d)
{
if (!m || !d || !m->V || m->pending || d->slot >= m->n) {
return -1;
}
switch (d->kind) {
case LIT_DO_LOAD: {
uint64_t value = d->value & m->mask;
for (uint32_t c = 0; c < m->k; c++) {
m->V[(size_t)c * m->n + d->slot] = value;
}
return 0;
}
case LIT_DO_WIRE:
if (d->src >= m->n) {
return -1;
}
return lit_machine_connect(m, d->slot, d->src, d->gain,
&d->weight, -1);
default:
return -1;
}
}
int lit_do_restore(const lit_donode *node, lit_machine *m)
{
const lit_donode *nd;
lit_do *ops;
size_t depth = 0;
size_t i;
if (!node || !m) {
return -1;
}
for (nd = node; nd->parent; nd = nd->parent) {
depth++;
}
if (depth == 0) {
return 0;
}
ops = malloc(depth * sizeof(*ops));
if (!ops) {
return -1;
}
depth = 0;
for (nd = node; nd->parent; nd = nd->parent) {
ops[depth++] = nd->op;
}
for (i = depth; i > 0; i--) {
if (lit_do_apply(m, &ops[i - 1]) != 0) {
free(ops);
return -1;
}
}
free(ops);
return 0;
}
/* ---------------------------------------------------------------- */
/* DO node arena */
/* ---------------------------------------------------------------- */
lit_donode *lit_do_alloc(lit_do_arena *a, lit_donode *parent,
const lit_do *op, uint32_t depth)
{
lit_donode *n;
if (a->used == a->cap) {
lit_donode **chunk = realloc(a->chunk,
(a->nchunk + 1) * sizeof(*chunk));
if (!chunk) {
return NULL;
}
a->chunk = chunk;
a->chunk[a->nchunk] = malloc(LIT_DO_CHUNK * sizeof(lit_donode));
if (!a->chunk[a->nchunk]) {
return NULL;
}
a->nchunk++;
a->cap += LIT_DO_CHUNK;
}
n = &a->chunk[a->used / LIT_DO_CHUNK][a->used % LIT_DO_CHUNK];
a->used++;
memset(n, 0, sizeof(*n));
n->parent = parent;
if (op) {
n->op = *op;
}
n->depth = depth;
n->state = LIT_DO_OPEN;
if (parent) {
n->next_sibling = parent->first_child;
parent->first_child = n;
}
return n;
}
void lit_do_arena_free(lit_do_arena *a)
{
for (size_t i = 0; i < a->nchunk; i++) {
free(a->chunk[i]);
}
free(a->chunk);
memset(a, 0, sizeof(*a));
}
/* ---------------------------------------------------------------- */
/* Flat DO tree + full machine state */
/* ---------------------------------------------------------------- */
/* Find the arena index of a node; chunk pointers stay stable. */
static int node_index(const lit_do_arena *a, const lit_donode *node,
uint32_t *out)
{
uintptr_t addr = (uintptr_t)node;
size_t bytes = LIT_DO_CHUNK * sizeof(lit_donode);
for (size_t c = 0; c < a->nchunk; c++) {
uintptr_t base = (uintptr_t)a->chunk[c];
if (addr >= base && addr < base + bytes) {
size_t off = (addr - base) / sizeof(lit_donode);
size_t idx = c * LIT_DO_CHUNK + off;
if (idx > UINT32_MAX) {
return -1;
}
*out = (uint32_t)idx;
return 0;
}
}
return -1;
}
static int tree_alloc(lit_tree *t, uint32_t n, uint32_t words,
uint32_t slots, uint32_t clusters, uint32_t bits)
{
size_t nsz = n;
size_t wsz = words;
size_t ksz = clusters;
if (n == 0 || words == 0 || slots == 0 || clusters == 0 ||
bits < 1 || bits > 64 ||
(uint64_t)slots * clusters != words) {
return -1;
}
if (nsz > SIZE_MAX / sizeof(uint32_t) ||
nsz > SIZE_MAX / sizeof(uint64_t) ||
wsz > SIZE_MAX / sizeof(uint32_t) ||
wsz > SIZE_MAX / sizeof(uint64_t) ||
ksz > SIZE_MAX / sizeof(uint64_t)) {
return -1;
}
memset(t, 0, sizeof(*t));
t->n = n;
t->words = words;
t->slots = slots;
t->clusters = clusters;
t->bits = bits;
t->parent = malloc(nsz * sizeof(uint32_t));
t->kind = malloc(nsz * sizeof(uint32_t));
t->slot = malloc(nsz * sizeof(uint32_t));
t->do_src = malloc(nsz * sizeof(uint32_t));
t->gain = malloc(nsz * sizeof(uint64_t));
t->weight = malloc(nsz * sizeof(uint64_t));
t->value = malloc(nsz * sizeof(uint64_t));
t->depth = malloc(nsz * sizeof(uint32_t));
t->root_v = malloc(wsz * sizeof(uint64_t));
t->root_src = malloc(wsz * sizeof(uint32_t));
t->root_gain = malloc(wsz * sizeof(uint64_t));
t->root_weight = malloc(wsz * sizeof(uint64_t));
t->root_dist = malloc(ksz * sizeof(uint64_t));
t->root_diff = malloc(wsz * sizeof(uint64_t));
if (!t->parent || !t->kind || !t->slot || !t->do_src ||
!t->gain || !t->weight || !t->value || !t->depth ||
!t->root_v || !t->root_src || !t->root_gain ||
!t->root_weight || !t->root_dist || !t->root_diff) {
lit_tree_free(t);
return -1;
}
return 0;
}
static int tree_valid(const lit_tree *t)
{
if (!t || t->n == 0 || t->words == 0 || t->slots == 0 ||
t->clusters == 0 || t->bits < 1 || t->bits > 64 ||
(uint64_t)t->slots * t->clusters != t->words) {
return 0;
}
return t->parent && t->kind && t->slot && t->do_src &&
t->gain && t->weight && t->value && t->depth &&
t->root_v && t->root_src && t->root_gain &&
t->root_weight && t->root_dist && t->root_diff;
}
int lit_tree_flatten(lit_tree *t, const lit_do_arena *a,
const lit_machine *root)
{
size_t n;
size_t words;
size_t clusters;
if (!t || !a || !root || !root->V || !root->src || !root->gain ||
!root->weight || !root->dist || !root->diff || root->n == 0 ||
root->k == 0 || root->bits < 1 || root->bits > 64 ||
root->pending) {
return -1;
}
if ((uint64_t)root->n * root->k > UINT32_MAX) {
return -1;
}
n = a->used;
if (n == 0 || n > UINT32_MAX) {
return -1;
}
memset(t, 0, sizeof(*t));
if (tree_alloc(t, (uint32_t)n,
(uint32_t)((uint64_t)root->n * root->k),
root->n, root->k, root->bits) != 0) {
return -1;
}
words = t->words;
clusters = t->clusters;
memcpy(t->root_v, root->V, words * sizeof(uint64_t));
memcpy(t->root_src, root->src, words * sizeof(uint32_t));
memcpy(t->root_gain, root->gain, words * sizeof(uint64_t));
memcpy(t->root_weight, root->weight, words * sizeof(uint64_t));
memcpy(t->root_diff, root->diff, words * sizeof(uint64_t));
memcpy(t->root_dist, root->dist, clusters * sizeof(uint64_t));
for (size_t i = 0; i < n; i++) {
const lit_donode *node =
&a->chunk[i / LIT_DO_CHUNK][i % LIT_DO_CHUNK];
t->parent[i] = UINT32_MAX;
if (node->parent &&
node_index(a, node->parent, &t->parent[i]) != 0) {
lit_tree_free(t);
return -1;
}
if (t->parent[i] != UINT32_MAX && t->parent[i] >= (uint32_t)n) {
lit_tree_free(t);
return -1;
}
t->kind[i] = (uint32_t)node->op.kind;
t->slot[i] = node->op.slot;
t->do_src[i] = node->op.src;
t->gain[i] = node->op.gain;
t->weight[i] = node->op.weight;
t->value[i] = node->op.value;
t->depth[i] = node->depth;
}
return 0;
}
int lit_tree_restore(const lit_tree *t, uint32_t i,
lit_machine *m)
{
uint32_t *chain;
size_t depth = 0;
uint32_t cur;
if (!t || !m || !tree_valid(t) || i >= t->n || !m->V || !m->src ||
!m->gain || !m->weight || !m->dist || !m->diff ||
m->n != t->slots || m->k != t->clusters || m->bits != t->bits ||
m->pending) {
return -1;
}
memcpy(m->V, t->root_v, (size_t)t->words * sizeof(uint64_t));
memcpy(m->src, t->root_src, (size_t)t->words * sizeof(uint32_t));
memcpy(m->gain, t->root_gain, (size_t)t->words * sizeof(uint64_t));
memcpy(m->weight, t->root_weight, (size_t)t->words * sizeof(uint64_t));
memcpy(m->diff, t->root_diff, (size_t)t->words * sizeof(uint64_t));
memcpy(m->dist, t->root_dist,
(size_t)t->clusters * sizeof(uint64_t));
m->pending = 0;
m->flat_dirty = 1;
for (cur = i; cur != UINT32_MAX; cur = t->parent[cur]) {
depth++;
}
if (depth <= 1) {
return 0; /* the root: nothing to replay */
}
chain = malloc((depth - 1) * sizeof(*chain));
if (!chain) {
return -1;
}
depth = 0;
for (cur = i; t->parent[cur] != UINT32_MAX; cur = t->parent[cur]) {
chain[depth++] = cur;
}
while (depth > 0) {
lit_do d;
uint32_t at = chain[--depth];
d.kind = (lit_do_kind)t->kind[at];
d.slot = t->slot[at];
d.src = t->do_src[at];
d.gain = t->gain[at];
d.weight = t->weight[at];
d.value = t->value[at];
if (lit_do_apply(m, &d) != 0) {
free(chain);
return -1;
}
}
free(chain);
return 0;
}
void lit_tree_free(lit_tree *t)
{
if (!t) {
return;
}
free(t->parent);
free(t->kind);
free(t->slot);
free(t->do_src);
free(t->gain);
free(t->weight);
free(t->value);
free(t->depth);
free(t->root_v);
free(t->root_src);
free(t->root_gain);
free(t->root_weight);
free(t->root_dist);
free(t->root_diff);
memset(t, 0, sizeof(*t));
}
#define LIT_TREE_MAGIC 0x4c495434u /* LIT4: no per-node states */
int lit_tree_save(const lit_tree *t, const char *path)
{
FILE *f;
uint32_t magic = LIT_TREE_MAGIC;
uint32_t n, words, slots, clusters, bits;
int bad = 0;
if (!tree_valid(t) || !path) {
return -1;
}
f = fopen(path, "wb");
if (!f) {
return -1;
}
n = t->n;
words = t->words;
slots = t->slots;
clusters = t->clusters;
bits = t->bits;
if (fwrite(&magic, sizeof(magic), 1, f) != 1 ||
fwrite(&n, sizeof(n), 1, f) != 1 ||
fwrite(&words, sizeof(words), 1, f) != 1 ||
fwrite(&slots, sizeof(slots), 1, f) != 1 ||
fwrite(&clusters, sizeof(clusters), 1, f) != 1 ||
fwrite(&bits, sizeof(bits), 1, f) != 1 ||
fwrite(t->parent, sizeof(uint32_t), n, f) != n ||
fwrite(t->kind, sizeof(uint32_t), n, f) != n ||
fwrite(t->slot, sizeof(uint32_t), n, f) != n ||
fwrite(t->do_src, sizeof(uint32_t), n, f) != n ||
fwrite(t->gain, sizeof(uint64_t), n, f) != n ||
fwrite(t->weight, sizeof(uint64_t), n, f) != n ||
fwrite(t->value, sizeof(uint64_t), n, f) != n ||
fwrite(t->depth, sizeof(uint32_t), n, f) != n ||
fwrite(t->root_v, sizeof(uint64_t), words, f) != words ||
fwrite(t->root_src, sizeof(uint32_t), words, f) != words ||
fwrite(t->root_gain, sizeof(uint64_t), words, f) != words ||
fwrite(t->root_weight, sizeof(uint64_t), words, f) != words ||
fwrite(t->root_diff, sizeof(uint64_t), words, f) != words ||
fwrite(t->root_dist, sizeof(uint64_t), clusters, f) != clusters) {
bad = 1;
}
if (fclose(f) != 0) {
bad = 1;
}
return bad ? -1 : 0;
}
int lit_tree_load(lit_tree *t, const char *path)
{
FILE *f;
uint32_t magic;
uint32_t n, words, slots, clusters, bits;
int bad = 0;
if (!t || !path) {
return -1;
}
memset(t, 0, sizeof(*t));
f = fopen(path, "rb");
if (!f) {
return -1;
}
if (fread(&magic, sizeof(magic), 1, f) != 1 ||
fread(&n, sizeof(n), 1, f) != 1 ||
fread(&words, sizeof(words), 1, f) != 1 ||
fread(&slots, sizeof(slots), 1, f) != 1 ||
fread(&clusters, sizeof(clusters), 1, f) != 1 ||
fread(&bits, sizeof(bits), 1, f) != 1 ||
magic != LIT_TREE_MAGIC) {
fclose(f);
return -1;
}
if (tree_alloc(t, n, words, slots, clusters, bits) != 0) {
fclose(f);
return -1;
}
if (fread(t->parent, sizeof(uint32_t), n, f) != n ||
fread(t->kind, sizeof(uint32_t), n, f) != n ||
fread(t->slot, sizeof(uint32_t), n, f) != n ||
fread(t->do_src, sizeof(uint32_t), n, f) != n ||
fread(t->gain, sizeof(uint64_t), n, f) != n ||
fread(t->weight, sizeof(uint64_t), n, f) != n ||
fread(t->value, sizeof(uint64_t), n, f) != n ||
fread(t->depth, sizeof(uint32_t), n, f) != n ||
fread(t->root_v, sizeof(uint64_t), words, f) != words ||
fread(t->root_src, sizeof(uint32_t), words, f) != words ||
fread(t->root_gain, sizeof(uint64_t), words, f) != words ||
fread(t->root_weight, sizeof(uint64_t), words, f) != words ||
fread(t->root_diff, sizeof(uint64_t), words, f) != words ||
fread(t->root_dist, sizeof(uint64_t), clusters, f) != clusters) {
bad = 1;
}
if (fclose(f) != 0) {
bad = 1;
}
if (!bad) {
for (uint32_t i = 0; i < n; i++) {
if (t->parent[i] != UINT32_MAX && t->parent[i] >= n) {
bad = 1;
break;
}
}
}
if (bad) {
lit_tree_free(t);
return -1;
}
return 0;
}
static void put_u32(FILE *f, const char *name, const char *field,
const uint32_t *v, size_t n)
{
fprintf(f, "static const uint32_t %s_%s[%zu] = {", name, field, n);
for (size_t i = 0; i < n; i++) {
fprintf(f, "%s%u", i ? "," : "", v[i]);
}
fprintf(f, "};\n");
}
static void put_u64(FILE *f, const char *name, const char *field,
const uint64_t *v, size_t n)
{
fprintf(f, "static const uint64_t %s_%s[%zu] = {", name, field, n);
for (size_t i = 0; i < n; i++) {
fprintf(f, "%s%llu", i ? "," : "",
(unsigned long long)v[i]);
}
fprintf(f, "};\n");
}
int lit_tree_write_c(const lit_tree *t, const char *path,
const char *name)
{
FILE *f;
int bad;
if (!tree_valid(t) || !path || !name) {
return -1;
}
f = fopen(path, "w");
if (!f) {
return -1;
}
fprintf(f, "/* generated by the LIT operator: DO tree C array */\n");
fprintf(f, "#include <stdint.h>\n\n");
fprintf(f, "#define %s_N %u\n", name, t->n);
fprintf(f, "#define %s_WORDS %u\n", name, t->words);
fprintf(f, "#define %s_SLOTS %u\n", name, t->slots);
fprintf(f, "#define %s_CLUSTERS %u\n", name, t->clusters);
fprintf(f, "#define %s_BITS %u\n\n", name, t->bits);
put_u32(f, name, "parent", t->parent, t->n);
put_u32(f, name, "kind", t->kind, t->n);
put_u32(f, name, "slot", t->slot, t->n);
put_u32(f, name, "do_src", t->do_src, t->n);
put_u64(f, name, "gain", t->gain, t->n);
put_u64(f, name, "weight", t->weight, t->n);
put_u64(f, name, "value", t->value, t->n);
put_u32(f, name, "depth", t->depth, t->n);
put_u64(f, name, "root_v", t->root_v, t->words);
put_u32(f, name, "root_src", t->root_src, t->words);
put_u64(f, name, "root_gain", t->root_gain, t->words);
put_u64(f, name, "root_weight", t->root_weight, t->words);
put_u64(f, name, "root_diff", t->root_diff, t->words);
put_u64(f, name, "root_dist", t->root_dist, t->clusters);
bad = ferror(f);
if (fclose(f) != 0) {
bad = 1;
}
return bad ? -1 : 0;
}
/* ---------------------------------------------------------------- */
/* Generic program-search driver. The operator owns the tree (every */
/* node carries its dynamic score), the path nodes, and the seen */
/* set; the host owns the game. Nothing else is trusted: every */
/* counterfactual branch is expanded, and a bounded world is walked */
/* to exhaustion. The goal is only the stopping condition. */
/* ---------------------------------------------------------------- */
typedef struct {
uint32_t parent; /* UINT32_MAX = root */
lit_action act;
lit_key key;
uint64_t g; /* the DO score accumulated along the path */
uint32_t depth;
uint32_t first_child; /* UINT32_MAX = none */
uint32_t next_sibling; /* UINT32_MAX = none */
uint8_t goal;
uint8_t dead;
uint8_t expanded;
} lit_snode;
typedef struct {
lit_snode *v;
size_t n;
size_t cap;
} lit_sarena;
static void sarena_free(lit_sarena *a)
{
free(a->v);
a->v = NULL;
a->n = 0;
a->cap = 0;
}
static int sarena_add(lit_sarena *a, const lit_snode *node,
uint32_t *idx)
{
if (a->n >= UINT32_MAX) {
return -1;
}
if (a->n == a->cap) {
size_t cap = a->cap ? a->cap * 2 : 1024;
lit_snode *v;
if (cap < a->cap || cap > SIZE_MAX / sizeof(*v)) {
return -1;
}
v = realloc(a->v, cap * sizeof(*v));
if (!v) {
return -1;
}
a->v = v;
a->cap = cap;
}
a->v[a->n] = *node;
a->v[a->n].first_child = UINT32_MAX;
a->v[a->n].next_sibling = UINT32_MAX;
*idx = (uint32_t)a->n;
a->n++;
return 0;
}
typedef struct {
lit_key key;
uint32_t node;
uint8_t used;
} lit_kslot;
typedef struct {
lit_kslot *v;
size_t cap; /* power of two, or zero */
size_t n;
} lit_ktab;
static uint64_t key_mix(uint64_t x)
{
x ^= x >> 30;
x *= 0xbf58476d1ce4e5b9ULL;
x ^= x >> 27;
x *= 0x94d049bb133111ebULL;
x ^= x >> 31;
return x;
}
static int key_eq(lit_key a, lit_key b)
{
return a.hi == b.hi && a.lo == b.lo;
}
static size_t ktab_slot(const lit_ktab *t, lit_key k)
{
size_t mask = t->cap - 1;
size_t i = (size_t)key_mix(k.hi ^ (k.lo +
0x9e3779b97f4a7c15ULL + (k.hi << 6) + (k.hi >> 2))) & mask;
while (t->v[i].used && !key_eq(t->v[i].key, k)) {
i = (i + 1) & mask;
}
return i;
}
static void lit_ktab_free(lit_ktab *t)
{
free(t->v);
t->v = NULL;
t->cap = 0;
t->n = 0;
}
static int ktab_resize(lit_ktab *t, size_t cap)
{
lit_kslot *v;
size_t i;
if (cap < 1024) {
cap = 1024;
}
v = calloc(cap, sizeof(*v));
if (!v) {
return -1;
}
for (i = 0; i < t->cap; i++) {
if (t->v[i].used) {
size_t j = (size_t)key_mix(t->v[i].key.hi ^
(t->v[i].key.lo + 0x9e3779b97f4a7c15ULL +
(t->v[i].key.hi << 6) + (t->v[i].key.hi >> 2))) &
(cap - 1);
while (v[j].used) {
j = (j + 1) & (cap - 1);
}
v[j] = t->v[i];
}
}
free(t->v);
t->v = v;
t->cap = cap;
return 0;
}
static int ktab_insert(lit_ktab *t, lit_key key, uint32_t node)
{
size_t i;
if (t->cap == 0) {
if (ktab_resize(t, 1024) != 0) {
return -1;
}
} else if ((t->n + 1) * 10 >= t->cap * 7) {
if (t->cap > SIZE_MAX / 2 ||
ktab_resize(t, t->cap * 2) != 0) {
return -1;
}
}
i = ktab_slot(t, key);
if (t->v[i].used) {
return 0;
}
t->v[i].key = key;
t->v[i].node = node;
t->v[i].used = 1;
t->n++;
return 1;
}
static int build_path(const lit_sarena *a, uint32_t idx,
lit_action *buf, size_t cap, size_t *len)
{
size_t d = a->v[idx].depth;
size_t pos = d;
uint32_t cur = idx;
if (d > cap) {
return -1;
}
while (cur != UINT32_MAX && a->v[cur].depth > 0) {
if (pos == 0) {
return -1;
}
buf[--pos] = a->v[cur].act;
cur = a->v[cur].parent;
}
if (pos != 0) {
return -1;
}
*len = d;
return 0;
}
static int fill_out_path(const lit_sarena *a, uint32_t idx,
lit_path *out)
{
size_t d = a->v[idx].depth;
lit_action *p;
out->acts = NULL;
out->n = 0;
if (d == 0) {
return 0;
}
if (d > SIZE_MAX / sizeof(*p)) {
return -1;
}
p = malloc(d * sizeof(*p));
if (!p) {
return -1;
}
if (build_path(a, idx, p, d, &out->n) != 0) {
free(p);
return -1;
}
out->acts = p;
return 0;
}
struct lit_search {
lit_host host;
lit_sarena nodes;
lit_ktab seen;
uint32_t *heap; /* max-heap of frontier node indices */
size_t heap_n;
size_t heap_cap;
lit_action *pathbuf;
size_t pathcap;
lit_action *actbuf;
size_t actcap;
lit_key *kbuf;
int *gbuf;
int *dbuf;
uint64_t *cgbuf;
size_t rescap;
lit_node_view *views;
size_t views_cap;
uint64_t *sbuf;
size_t scorecap;
uint32_t anchor;
int anchor_valid;
};
/* Max-heap of flat node indices: the top is the unexpanded, non-dead
* node with the largest g; ties take the smaller index. The frontier
* is this heap, not a linear scan. The comparison is the same direct
* comparison the operator always used, only now in O(log n). */
static int heap_better(const lit_sarena *a, uint32_t x, uint32_t y)
{
const lit_snode *nx = &a->v[x];
const lit_snode *ny = &a->v[y];
if (nx->g != ny->g) {
return nx->g > ny->g;
}
return x < y;
}
static int heap_push(lit_search *s, uint32_t idx)
{
size_t i;
if (s->heap_n == s->heap_cap) {
size_t cap = s->heap_cap ? s->heap_cap * 2 : 1024;
uint32_t *h;
if (cap < s->heap_cap || cap > SIZE_MAX / sizeof(*h)) {
return -1;
}
h = realloc(s->heap, cap * sizeof(*h));
if (!h) {
return -1;
}
s->heap = h;
s->heap_cap = cap;
}
i = s->heap_n++;
s->heap[i] = idx;
while (i > 0) {
size_t p = (i - 1) / 2;
uint32_t t;
if (heap_better(&s->nodes, s->heap[p], s->heap[i])) {
break;
}
t = s->heap[p];
s->heap[p] = s->heap[i];
s->heap[i] = t;
i = p;
}
return 0;
}
static uint32_t heap_pop(lit_search *s)
{
uint32_t top;
size_t i = 0;
if (s->heap_n == 0) {
return UINT32_MAX;
}
top = s->heap[0];
s->heap[0] = s->heap[--s->heap_n];
for (;;) {
size_t l = i * 2 + 1;
size_t r = l + 1;
size_t best = i;
uint32_t t;
if (l < s->heap_n &&
heap_better(&s->nodes, s->heap[l], s->heap[best])) {
best = l;
}
if (r < s->heap_n &&
heap_better(&s->nodes, s->heap[r], s->heap[best])) {
best = r;
}
if (best == i) {
break;
}
t = s->heap[best];
s->heap[best] = s->heap[i];
s->heap[i] = t;
i = best;
}
return top;
}
static void link_child(lit_search *s, uint32_t parent, uint32_t child)
{
s->nodes.v[child].next_sibling = s->nodes.v[parent].first_child;
s->nodes.v[parent].first_child = child;
}
/* Append a child, link it into the parent's child list, and push it on
* the open heap unless it is dead. This is the one place a node enters
* the tree, so the child links and the heap can never disagree. */
static int add_child(lit_search *s, uint32_t parent,
const lit_snode *child, uint32_t *idx)
{
if (sarena_add(&s->nodes, child, idx) != 0) {
return -1;
}
link_child(s, parent, *idx);
if (!child->dead && heap_push(s, *idx) != 0) {
return -1;
}
return 0;
}
static lit_search *search_alloc(const lit_host *host)
{
lit_search *s;
if (!host || !host->root || !host->actions ||
(!host->eval && !host->expand)) {
return NULL;
}
if (host->score && !host->expand) {
return NULL;
}
s = calloc(1, sizeof(*s));
if (!s) {
return NULL;
}
s->host = *host;
s->anchor = UINT32_MAX;
s->anchor_valid = 0;
return s;
}
lit_search *lit_search_new(const lit_host *host)
{
lit_search *s;
lit_key root_key = {0, 0};
int root_goal = 0;
int root_dead = 0;
lit_snode root;
uint32_t root_idx;
s = search_alloc(host);
if (!s) {
return NULL;
}
if (host->root(host->ctx, &root_key, &root_goal,
&root_dead) != 0) {
lit_search_free(s);
return NULL;
}
memset(&root, 0, sizeof(root));
root.parent = UINT32_MAX;
root.key = root_key;
root.goal = (uint8_t)(root_goal != 0);
root.dead = (uint8_t)(root_dead != 0);
if (sarena_add(&s->nodes, &root, &root_idx) != 0 ||
ktab_insert(&s->seen, root_key, root_idx) != 1 ||
heap_push(s, root_idx) != 0) {
lit_search_free(s);
return NULL;
}
return s;
}
/* Bulk ingest one causal edge. The node is just another flat-tree
* node: parent index, opaque action, host key, accumulated g, judge
* flags. It starts unexpanded, so a later continue can grow from it;
* the seen set records the key so the search keeps its dedupe. The
* operator never interprets the action or the key. */
uint32_t lit_search_ingest(lit_search *s, uint32_t parent,
const lit_action *act, lit_key key,
uint64_t g, int goal, int dead)
{
lit_snode node;
uint32_t idx;
if (!s || !act || parent >= s->nodes.n) {
return UINT32_MAX;
}
memset(&node, 0, sizeof(node));
node.parent = parent;
node.act = *act;
node.key = key;
node.g = g;
node.depth = s->nodes.v[parent].depth + 1;
node.goal = (uint8_t)(goal != 0);
node.dead = (uint8_t)(dead != 0);
node.expanded = 0;
if (add_child(s, parent, &node, &idx) != 0) {
return UINT32_MAX;
}
if (ktab_insert(&s->seen, key, idx) < 0) {
return UINT32_MAX;
}
return idx;
}
/* Extend the read-only node views by the delta [views_n, nodes.n). Nodes
* are append-only, so an index always means the same node and the host
* only has to look at the new tail. */
static void view_fill(const lit_snode *nd, lit_node_view *v)
{
v->parent = nd->parent;
v->depth = nd->depth;
v->g = nd->g;
v->key = nd->key;
v->act = nd->act;
v->first_child = nd->first_child;
v->next_sibling = nd->next_sibling;
v->goal = nd->goal;
v->dead = nd->dead;
v->expanded = nd->expanded;
}
static int views_ensure(lit_search *s)
{
size_t n = s->nodes.n;
size_t i;
if (s->views_cap < n) {
lit_node_view *v = realloc(s->views, n * sizeof(*v));
if (!v) {
return -1;
}
s->views = v;
s->views_cap = n;
}
/* Refresh every view: goal, dead, and expanded are node state that
changes after the view was first built. Indices stay stable. */
for (i = 0; i < n; i++) {
view_fill(&s->nodes.v[i], &s->views[i]);
}
return 0;
}
uint32_t lit_search_follow(const lit_search *s, const lit_action *path,
size_t path_len, lit_key *key)
{
uint32_t node = 0;
size_t i;
if (!s || !path || s->nodes.n == 0) {
return UINT32_MAX;
}
for (i = 0; i < path_len; i++) {
uint32_t c = s->nodes.v[node].first_child;
while (c != UINT32_MAX) {
if (memcmp(&s->nodes.v[c].act, &path[i],
sizeof(lit_action)) == 0) {
break;
}
c = s->nodes.v[c].next_sibling;
}
if (c == UINT32_MAX) {
return UINT32_MAX;
}
node = c;
}
if (key) {
*key = s->nodes.v[node].key;
}
return node;
}
int lit_search_node(const lit_search *s, uint32_t i, lit_node_view *out)
{
if (!s || !out || i >= s->nodes.n) {
return -1;
}
view_fill(&s->nodes.v[i], out);
return 0;
}
void lit_search_stats(const lit_search *s, uint64_t *nodes,
uint64_t *unique, uint64_t *open)
{
if (!s) {
return;
}
if (nodes) {
*nodes = (uint64_t)s->nodes.n;
}
if (unique) {
*unique = (uint64_t)s->seen.n;
}
if (open) {
*open = (uint64_t)s->heap_n;
}
}
/* Host-chosen interventions: the operator exposes the whole tree and the
* host picks any node to expand next (jump/backtrack). No open list and
* no seen set: every intervention creates a new branch. */
static int search_choose(lit_search *s, const lit_search_opts *opts,
lit_path *out)
{
uint64_t pops = 0;
uint64_t max_nodes = opts ? opts->max_nodes : 0;
int rc = LIT_SEARCH_ERROR;
if (!s->host.expand) {
return -1;
}
for (;;) {
uint32_t idx;
lit_snode parent;
const lit_action *acts = NULL;
size_t nact = 0;
size_t plen;
size_t i;
if (max_nodes && pops >= max_nodes) {
rc = LIT_SEARCH_BUDGET;
break;
}
if (views_ensure(s) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
if (s->host.choose(s->host.ctx, s->views, s->nodes.n, &idx) != 0 ||
idx >= s->nodes.n) {
rc = LIT_SEARCH_EMPTY;
break;
}
parent = s->nodes.v[idx];
pops++;
if (s->host.seek) {
(void)s->host.seek(s->host.ctx, &parent.key);
}
plen = parent.depth;
if (plen > s->pathcap) {
lit_action *p;
if (plen > SIZE_MAX / sizeof(*p)) {
rc = LIT_SEARCH_ERROR;
break;
}
p = realloc(s->pathbuf, plen * sizeof(*p));
if (!p) {
rc = LIT_SEARCH_ERROR;
break;
}
s->pathbuf = p;
s->pathcap = plen;
}
if (build_path(&s->nodes, idx, s->pathbuf, s->pathcap,
&plen) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
if (s->host.actions(s->host.ctx, s->pathbuf, plen, &acts,
&nact) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
if (nact != 0 && !acts) {
rc = LIT_SEARCH_ERROR;
break;
}
if (nact > s->actcap) {
lit_action *p;
if (nact > SIZE_MAX / sizeof(*p)) {
rc = LIT_SEARCH_ERROR;
break;
}
p = realloc(s->actbuf, nact * sizeof(*p));
if (!p) {
rc = LIT_SEARCH_ERROR;
break;
}
s->actbuf = p;
s->actcap = nact;
}
if (nact != 0) {
memcpy(s->actbuf, acts, nact * sizeof(*s->actbuf));
}
if (nact > s->rescap) {
lit_key *nk = realloc(s->kbuf, nact * sizeof(*nk));
int *ng;
int *nd;
uint64_t *ncg;
if (!nk) {
rc = LIT_SEARCH_ERROR;
break;
}
s->kbuf = nk;
ng = realloc(s->gbuf, nact * sizeof(*ng));
if (!ng) {
rc = LIT_SEARCH_ERROR;
break;
}
s->gbuf = ng;
nd = realloc(s->dbuf, nact * sizeof(*nd));
if (!nd) {
rc = LIT_SEARCH_ERROR;
break;
}
s->dbuf = nd;
ncg = realloc(s->cgbuf, nact * sizeof(*ncg));
if (!ncg) {
rc = LIT_SEARCH_ERROR;
break;
}
s->cgbuf = ncg;
s->rescap = nact;
}
for (i = 0; i < nact; i++) {
uint64_t cost = s->actbuf[i].cost;
s->cgbuf[i] = (UINT64_MAX - parent.g < cost)
? UINT64_MAX : parent.g + cost;
}
if (s->host.expand(s->host.ctx, s->pathbuf, plen,
s->actbuf, s->cgbuf, nact,
s->kbuf, s->gbuf, s->dbuf) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
for (i = 0; i < nact; i++) {
lit_snode child;
uint32_t cidx;
if (s->cgbuf[i] == UINT64_MAX) {
continue;
}
memset(&child, 0, sizeof(child));
child.parent = idx;
child.act = s->actbuf[i];
child.key = s->kbuf[i];
child.g = s->cgbuf[i];
child.depth = parent.depth + 1;
child.goal = (uint8_t)(s->gbuf[i] != 0);
child.dead = (uint8_t)(s->dbuf[i] != 0);
if (add_child(s, idx, &child, &cidx) != 0) {
rc = LIT_SEARCH_ERROR;
goto done;
}
}
if (s->host.event) {
s->host.event(s->host.ctx, s->pathbuf, plen, pops,
s->nodes.n, 0, parent.g, 0.0, parent.goal);
}
}
done:
out->acts = NULL;
out->n = 0;
out->pops = pops;
if (s->nodes.n != 0) {
out->nodes = s->nodes.n;
}
return rc == LIT_SEARCH_ERROR ? -1 : rc;
}
/* Global attention: the host scores every node of the whole tree with
* integer scores; the operator expands the largest by a direct
* comparison (ties take the earlier node). Expanded nodes may be
* chosen again (backtracking) and the seen set is bypassed: every
* intervention creates a new branch. Dead nodes are skipped; a chosen
* goal returns its path. No float, no heuristic: only the host's
* numbers and the operator's compare. */
static int search_score(lit_search *s, const lit_search_opts *opts,
lit_path *out, uint64_t base_g)
{
uint64_t pops = 0;
uint64_t max_steps = opts ? opts->max_steps : 0;
uint64_t max_nodes = opts ? opts->max_nodes : 0;
int rc = LIT_SEARCH_ERROR;
for (;;) {
uint32_t sel = UINT32_MAX;
lit_snode parent;
const lit_action *acts = NULL;
size_t nact = 0;
size_t plen;
size_t i;
if (max_nodes && pops >= max_nodes) {
rc = LIT_SEARCH_BUDGET;
break;
}
if (views_ensure(s) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
if (s->nodes.n > s->scorecap) {
uint64_t *p = realloc(s->sbuf,
s->nodes.n * sizeof(*s->sbuf));
if (!p) {
rc = LIT_SEARCH_ERROR;
break;
}
s->sbuf = p;
s->scorecap = s->nodes.n;
}
if (s->host.score(s->host.ctx, s->views, s->nodes.n,
s->sbuf) != 0) {
rc = LIT_SEARCH_EMPTY;
break;
}
for (i = 0; i < s->nodes.n; i++) {
if (s->nodes.v[i].dead) {
continue;
}
if (sel == UINT32_MAX || s->sbuf[i] > s->sbuf[sel]) {
sel = (uint32_t)i;
}
}
if (sel == UINT32_MAX) {
rc = LIT_SEARCH_EMPTY;
break;
}
s->nodes.v[sel].expanded = 1;
parent = s->nodes.v[sel];
if (max_steps && parent.g - base_g > max_steps) {
rc = LIT_SEARCH_BUDGET;
break;
}
pops++;
if (parent.goal) {
if (fill_out_path(&s->nodes, sel, out) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
s->anchor = sel;
s->anchor_valid = 1;
rc = LIT_SEARCH_FOUND;
break;
}
if (s->host.seek) {
(void)s->host.seek(s->host.ctx, &parent.key);
}
plen = parent.depth;
if (plen > s->pathcap) {
lit_action *p;
if (plen > SIZE_MAX / sizeof(*p)) {
rc = LIT_SEARCH_ERROR;
break;
}
p = realloc(s->pathbuf, plen * sizeof(*p));
if (!p) {
rc = LIT_SEARCH_ERROR;
break;
}
s->pathbuf = p;
s->pathcap = plen;
}
if (build_path(&s->nodes, sel, s->pathbuf, s->pathcap,
&plen) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
if (s->host.actions(s->host.ctx, s->pathbuf, plen, &acts,
&nact) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
if (nact != 0 && !acts) {
rc = LIT_SEARCH_ERROR;
break;
}
if (nact > s->actcap) {
lit_action *p;
if (nact > SIZE_MAX / sizeof(*p)) {
rc = LIT_SEARCH_ERROR;
break;
}
p = realloc(s->actbuf, nact * sizeof(*p));
if (!p) {
rc = LIT_SEARCH_ERROR;
break;
}
s->actbuf = p;
s->actcap = nact;
}
if (nact != 0) {
memcpy(s->actbuf, acts, nact * sizeof(*s->actbuf));
}
if (nact > s->rescap) {
lit_key *nk = realloc(s->kbuf, nact * sizeof(*nk));
int *ng;
int *nd;
uint64_t *ncg;
if (!nk) {
rc = LIT_SEARCH_ERROR;
break;
}
s->kbuf = nk;
ng = realloc(s->gbuf, nact * sizeof(*ng));
if (!ng) {
rc = LIT_SEARCH_ERROR;
break;
}
s->gbuf = ng;
nd = realloc(s->dbuf, nact * sizeof(*nd));
if (!nd) {
rc = LIT_SEARCH_ERROR;
break;
}
s->dbuf = nd;
ncg = realloc(s->cgbuf, nact * sizeof(*ncg));
if (!ncg) {
rc = LIT_SEARCH_ERROR;
break;
}
s->cgbuf = ncg;
s->rescap = nact;
}
for (i = 0; i < nact; i++) {
uint64_t cost = s->actbuf[i].cost;
s->cgbuf[i] = (UINT64_MAX - parent.g < cost)
? UINT64_MAX : parent.g + cost;
}
if (s->host.expand(s->host.ctx, s->pathbuf, plen,
s->actbuf, s->cgbuf, nact,
s->kbuf, s->gbuf, s->dbuf) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
for (i = 0; i < nact; i++) {
lit_snode child;
uint32_t cidx;
if (s->cgbuf[i] == UINT64_MAX) {
continue;
}
memset(&child, 0, sizeof(child));
child.parent = sel;
child.act = s->actbuf[i];
child.key = s->kbuf[i];
child.g = s->cgbuf[i];
child.depth = parent.depth + 1;
child.goal = (uint8_t)(s->gbuf[i] != 0);
child.dead = (uint8_t)(s->dbuf[i] != 0);
if (add_child(s, sel, &child, &cidx) != 0) {
rc = LIT_SEARCH_ERROR;
goto done;
}
}
if (s->host.event) {
s->host.event(s->host.ctx, s->pathbuf, plen, pops,
s->nodes.n, 0, parent.g, 0.0, parent.goal);
}
}
done:
out->pops = pops;
if (s->nodes.n != 0) {
out->nodes = s->nodes.n;
}
if (rc != LIT_SEARCH_FOUND) {
free(out->acts);
out->acts = NULL;
out->n = 0;
}
return rc == LIT_SEARCH_ERROR ? -1 : rc;
}
static int search_continue(lit_search *s, const lit_search_opts *opts,
lit_path *out)
{
uint64_t pops = 0;
uint64_t max_steps = opts ? opts->max_steps : 0;
uint64_t max_nodes = opts ? opts->max_nodes : 0;
uint64_t base_g = 0;
int rc = LIT_SEARCH_ERROR;
if (s->host.choose) {
return search_choose(s, opts, out);
}
if (s->anchor_valid) {
size_t i;
s->nodes.v[s->anchor].goal = 0;
s->nodes.v[s->anchor].dead = 0;
base_g = s->nodes.v[s->anchor].g;
/* A new level starts from the anchor alone: every other node is
closed. The tree stays; the seen set belongs to the level. */
for (i = 0; i < s->nodes.n; i++) {
s->nodes.v[i].expanded = 1;
}
s->nodes.v[s->anchor].expanded = 0;
s->heap_n = 0;
if (heap_push(s, s->anchor) != 0) {
return -1;
}
lit_ktab_free(&s->seen);
if (ktab_insert(&s->seen, s->nodes.v[s->anchor].key,
s->anchor) != 1) {
return -1;
}
s->anchor_valid = 0;
}
if (s->host.score) {
return search_score(s, opts, out, base_g);
}
for (;;) {
uint32_t sel;
size_t frontier;
lit_snode parent;
const lit_action *acts = NULL;
size_t nact = 0;
size_t plen;
size_t i;
/* The frontier is the max-heap. Its top is the unexpanded,
non-dead node with the largest score; ties take the earlier
node. The open pool grows and shrinks with the tree. */
frontier = s->heap_n;
sel = heap_pop(s);
if (sel == UINT32_MAX) {
rc = LIT_SEARCH_EMPTY;
break;
}
s->nodes.v[sel].expanded = 1;
parent = s->nodes.v[sel];
if (max_steps && parent.g - base_g > max_steps) {
rc = LIT_SEARCH_BUDGET;
break;
}
pops++;
if (parent.goal) {
if (fill_out_path(&s->nodes, sel, out) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
s->anchor = sel;
s->anchor_valid = 1;
rc = LIT_SEARCH_FOUND;
break;
}
if (parent.dead) {
continue;
}
/* O(1) restore: the host may move the world by the node key
instead of replaying the whole action path. When it does,
the path is not built at all: the host promised not to read
it for a restored node. */
plen = parent.depth;
if (s->host.seek &&
s->host.seek(s->host.ctx, &parent.key) == 0) {
plen = 0;
} else {
if (plen > s->pathcap) {
lit_action *p;
if (plen > SIZE_MAX / sizeof(*p)) {
rc = LIT_SEARCH_ERROR;
break;
}
p = realloc(s->pathbuf, plen * sizeof(*p));
if (!p) {
rc = LIT_SEARCH_ERROR;
break;
}
s->pathbuf = p;
s->pathcap = plen;
}
if (build_path(&s->nodes, sel, s->pathbuf, s->pathcap,
&plen) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
}
if (s->host.actions(s->host.ctx, s->pathbuf, plen, &acts,
&nact) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
if (nact != 0 && !acts) {
rc = LIT_SEARCH_ERROR;
break;
}
if (nact > s->actcap) {
lit_action *p;
if (nact > SIZE_MAX / sizeof(*p)) {
rc = LIT_SEARCH_ERROR;
break;
}
p = realloc(s->actbuf, nact * sizeof(*p));
if (!p) {
rc = LIT_SEARCH_ERROR;
break;
}
s->actbuf = p;
s->actcap = nact;
}
if (nact != 0) {
memcpy(s->actbuf, acts, nact * sizeof(*s->actbuf));
}
if (s->host.expand) {
if (nact > s->rescap) {
lit_key *nk = realloc(s->kbuf, nact * sizeof(*nk));
int *ng;
int *nd;
uint64_t *ncg;
if (!nk) {
rc = LIT_SEARCH_ERROR;
break;
}
s->kbuf = nk;
ng = realloc(s->gbuf, nact * sizeof(*ng));
if (!ng) {
rc = LIT_SEARCH_ERROR;
break;
}
s->gbuf = ng;
nd = realloc(s->dbuf, nact * sizeof(*nd));
if (!nd) {
rc = LIT_SEARCH_ERROR;
break;
}
s->dbuf = nd;
ncg = realloc(s->cgbuf, nact * sizeof(*ncg));
if (!ncg) {
rc = LIT_SEARCH_ERROR;
break;
}
s->cgbuf = ncg;
s->rescap = nact;
}
for (i = 0; i < nact; i++) {
uint64_t cost = s->actbuf[i].cost
? s->actbuf[i].cost : 1;
s->cgbuf[i] = (UINT64_MAX - parent.g < cost)
? UINT64_MAX : parent.g + cost;
}
if (s->host.expand(s->host.ctx, s->pathbuf, plen,
s->actbuf, s->cgbuf, nact,
s->kbuf, s->gbuf, s->dbuf) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
for (i = 0; i < nact; i++) {
lit_action act = s->actbuf[i];
uint64_t child_g = s->cgbuf[i];
lit_key ck;
int goal;
int dead;
int fresh;
lit_snode child;
uint32_t idx;
if (child_g == UINT64_MAX) {
continue;
}
if (max_steps && child_g - base_g > max_steps) {
continue;
}
ck = s->kbuf[i];
goal = s->gbuf[i];
dead = s->dbuf[i];
if (dead) {
continue;
}
fresh = ktab_insert(&s->seen, ck,
(uint32_t)s->nodes.n);
if (fresh < 0) {
rc = LIT_SEARCH_ERROR;
goto done;
}
if (fresh == 0) {
continue;
}
memset(&child, 0, sizeof(child));
child.parent = sel;
child.act = act;
child.key = ck;
child.g = child_g;
child.depth = parent.depth + 1;
child.goal = (uint8_t)(goal != 0);
if (add_child(s, sel, &child, &idx) != 0) {
rc = LIT_SEARCH_ERROR;
goto done;
}
}
} else {
for (i = 0; i < nact; i++) {
lit_action act = s->actbuf[i];
uint64_t cost = act.cost;
uint64_t child_g;
lit_key ck = {0, 0};
int goal = 0;
int dead = 0;
int fresh;
lit_snode child;
uint32_t idx;
if (UINT64_MAX - parent.g < cost) {
continue;
}
child_g = parent.g + cost;
if (max_steps && child_g - base_g > max_steps) {
continue;
}
if (s->host.eval(s->host.ctx, s->pathbuf, plen, &act,
child_g, &ck, &goal, &dead) != 0) {
continue;
}
if (dead) {
continue;
}
fresh = ktab_insert(&s->seen, ck,
(uint32_t)s->nodes.n);
if (fresh < 0) {
rc = LIT_SEARCH_ERROR;
goto done;
}
if (fresh == 0) {
continue;
}
memset(&child, 0, sizeof(child));
child.parent = sel;
child.act = act;
child.key = ck;
child.g = child_g;
child.depth = parent.depth + 1;
child.goal = (uint8_t)(goal != 0);
if (add_child(s, sel, &child, &idx) != 0) {
rc = LIT_SEARCH_ERROR;
goto done;
}
}
}
if (s->host.event) {
s->host.event(s->host.ctx, s->pathbuf, plen, pops,
s->nodes.n, frontier,
parent.g, (double)parent.act.cost,
parent.goal);
}
if (max_nodes && pops >= max_nodes) {
rc = LIT_SEARCH_BUDGET;
break;
}
}
done:
out->pops = pops;
if (s->nodes.n != 0) {
out->nodes = s->nodes.n;
}
if (rc != LIT_SEARCH_FOUND) {
free(out->acts);
out->acts = NULL;
out->n = 0;
}
return rc == LIT_SEARCH_ERROR ? -1 : rc;
}
int lit_search_continue(lit_search *s, const lit_search_opts *opts,
lit_path *out)
{
if (!s || !out) {
return -1;
}
memset(out, 0, sizeof(*out));
return search_continue(s, opts, out);
}
int lit_search_run(const lit_host *host, const lit_search_opts *opts,
lit_path *out)
{
lit_search *s;
int rc;
if (!out) {
return -1;
}
s = lit_search_new(host);
if (!s) {
return -1;
}
rc = lit_search_continue(s, opts, out);
lit_search_free(s);
return rc;
}
int lit_memory_search(const lit_host *host, const lit_search_opts *opts,
lit_path *out)
{
lit_action *path = NULL;
size_t n = 0, cap = 0;
uint64_t cursor = 0, step = 0;
int rc = LIT_SEARCH_BUDGET;
if (!host || !host->root || !host->actions || !host->eval || !out) {
return -1;
}
out->acts = NULL;
out->n = 0;
out->pops = 0;
out->nodes = 0;
{
lit_key rk;
int rg = 0, rd = 0;
if (host->root(host->ctx, &rk, &rg, &rd) != 0) {
return -1;
}
if (rg) {
return LIT_SEARCH_FOUND;
}
}
for (;;) {
const lit_action *acts = NULL;
size_t na = 0, k;
int chosen = -1, goal = 0;
lit_key ck;
if (opts && ((opts->max_steps && step >= opts->max_steps) ||
(opts->max_nodes && step >= opts->max_nodes))) {
rc = LIT_SEARCH_BUDGET;
break;
}
if (host->actions(host->ctx, path, n, &acts, &na) != 0) {
rc = LIT_SEARCH_ERROR;
break;
}
out->pops++;
if (na == 0 || !acts) {
rc = LIT_SEARCH_EMPTY;
break;
}
{
size_t start = (size_t)(cursor % na);
uint32_t best = 0;
/* Every candidate is hard-wired to the current path; the DO
score is its cost. Compare directly, take the largest;
there is no open list. */
for (k = 0; k < na; k++) {
size_t idx = (start + k) % na;
int g2 = 0, d2 = 0;
uint32_t score = acts[idx].cost;
if (host->eval(host->ctx, path, n, &acts[idx], step + 1,
&ck, &g2, &d2) != 0 || d2) {
continue;
}
if (chosen < 0 || score > best) {
chosen = (int)idx;
best = score;
goal = g2;
}
}
}
if (chosen < 0) {
rc = LIT_SEARCH_EMPTY;
break;
}
if (n == cap) {
size_t nc = cap ? cap * 2 : 64;
lit_action *np = realloc(path, nc * sizeof(*np));
if (!np) {
free(path);
return -1;
}
path = np;
cap = nc;
}
path[n++] = acts[chosen];
cursor++;
step++;
out->nodes++;
if (goal) {
out->acts = malloc(n * sizeof(*out->acts));
if (!out->acts) {
free(path);
return -1;
}
memcpy(out->acts, path, n * sizeof(*out->acts));
out->n = n;
rc = LIT_SEARCH_FOUND;
break;
}
}
free(path);
return rc;
}
void lit_search_free(lit_search *s)
{
if (!s) {
return;
}
free(s->pathbuf);
free(s->actbuf);
free(s->kbuf);
free(s->gbuf);
free(s->dbuf);
free(s->cgbuf);
free(s->views);
free(s->sbuf);
free(s->heap);
lit_ktab_free(&s->seen);
sarena_free(&s->nodes);
free(s);
}
void lit_path_free(lit_path *p)
{
if (!p) {
return;
}
free(p->acts);
p->acts = NULL;
p->n = 0;
p->pops = 0;
p->nodes = 0;
}
/* ---------------------------------------------------------------- */
/* Search-tree persistence: JSON and safetensors */
/* ---------------------------------------------------------------- */
/* Every number in the two formats is a non-negative integer, so the
* minimal JSON reader below carries numbers as u64 and never loses a
* 64-bit key. Standard short escapes are handled; \u is rejected. */
typedef enum {
JV_NUM,
JV_STR,
JV_ARR,
JV_OBJ
} jv_type;
typedef struct jv {
jv_type type;
uint64_t num; /* JV_NUM */
char *str; /* JV_STR */
char *key; /* object member name */
struct jv *child; /* first array element / object member */
struct jv *next; /* sibling */
struct jv *alloc; /* allocation list */
} jv;
typedef struct {
jv *arena;
} jv_parser;
static jv *jv_new(jv_parser *jp, jv_type type)
{
jv *v = calloc(1, sizeof(*v));
if (!v) {
return NULL;
}
v->type = type;
v->alloc = jp->arena;
jp->arena = v;
return v;
}
static void jv_free(jv_parser *jp)
{
jv *v = jp->arena;
while (v) {
jv *next = v->alloc;
free(v->str);
free(v->key);
free(v);
v = next;
}
jp->arena = NULL;
}
static void jv_ws(const char **pp, const char *end)
{
const char *p = *pp;
while (p < end && (*p == ' ' || *p == '\t' ||
*p == '\n' || *p == '\r')) {
p++;
}
*pp = p;
}
static char *jv_str(const char **pp, const char *end)
{
const char *p = *pp;
const char *q;
char *s;
char *d;
if (p >= end || *p != '"') {
return NULL;
}
p++;
for (q = p; q < end; q++) {
if (*q == '"') {
break;
}
if (*q == '\\') {
if (q + 1 >= end || q[1] == 'u') {
return NULL;
}
q++;
}
}
if (q >= end) {
return NULL;
}
s = malloc((size_t)(q - p) + 1);
if (!s) {
return NULL;
}
d = s;
while (p < q) {
char c = *p++;
if (c == '\\') {
c = *p++;
switch (c) {
case '"':
case '\\':
case '/':
break;
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
default:
free(s);
return NULL;
}
}
*d++ = c;
}
*d = '\0';
*pp = q + 1;
return s;
}
static int jv_num(const char **pp, const char *end, uint64_t *out)
{
const char *p = *pp;
uint64_t v = 0;
if (p >= end || *p < '0' || *p > '9') {
return -1;
}
while (p < end && *p >= '0' && *p <= '9') {
unsigned d = (unsigned)(*p - '0');
if (v > (UINT64_MAX - d) / 10) {
return -1;
}
v = v * 10 + d;
p++;
}
*pp = p;
*out = v;
return 0;
}
static jv *jv_value(jv_parser *jp, const char **pp, const char *end,
int depth)
{
const char *p = *pp;
jv *v;
jv *tail;
if (depth > 64) {
return NULL;
}
jv_ws(&p, end);
if (p >= end) {
return NULL;
}
if (*p == '{') {
p++;
v = jv_new(jp, JV_OBJ);
if (!v) {
return NULL;
}
tail = NULL;
jv_ws(&p, end);
if (p < end && *p == '}') {
*pp = p + 1;
return v;
}
for (;;) {
char *key;
jv *m;
jv_ws(&p, end);
key = jv_str(&p, end);
if (!key) {
return NULL;
}
jv_ws(&p, end);
if (p >= end || *p != ':') {
free(key);
return NULL;
}
p++;
m = jv_value(jp, &p, end, depth + 1);
if (!m) {
free(key);
return NULL;
}
m->key = key;
if (tail) {
tail->next = m;
} else {
v->child = m;
}
tail = m;
jv_ws(&p, end);
if (p < end && *p == ',') {
p++;
continue;
}
if (p < end && *p == '}') {
*pp = p + 1;
return v;
}
return NULL;
}
}
if (*p == '[') {
p++;
v = jv_new(jp, JV_ARR);
if (!v) {
return NULL;
}
tail = NULL;
jv_ws(&p, end);
if (p < end && *p == ']') {
*pp = p + 1;
return v;
}
for (;;) {
jv *e = jv_value(jp, &p, end, depth + 1);
if (!e) {
return NULL;
}
if (tail) {
tail->next = e;
} else {
v->child = e;
}
tail = e;
jv_ws(&p, end);
if (p < end && *p == ',') {
p++;
continue;
}
if (p < end && *p == ']') {
*pp = p + 1;
return v;
}
return NULL;
}
}
if (*p == '"') {
v = jv_new(jp, JV_STR);
if (!v) {
return NULL;
}
v->str = jv_str(&p, end);
if (!v->str) {
return NULL;
}
*pp = p;
return v;
}
{
uint64_t num;
if (jv_num(&p, end, &num) != 0) {
return NULL;
}
v = jv_new(jp, JV_NUM);
if (!v) {
return NULL;
}
v->num = num;
*pp = p;
return v;
}
}
static const jv *jv_get(const jv *obj, const char *key)
{
const jv *m;
if (!obj || obj->type != JV_OBJ) {
return NULL;
}
for (m = obj->child; m; m = m->next) {
if (m->key && strcmp(m->key, key) == 0) {
return m;
}
}
return NULL;
}
static const jv *jv_at(const jv *arr, size_t i)
{
const jv *e;
if (!arr || arr->type != JV_ARR) {
return NULL;
}
for (e = arr->child; e && i > 0; e = e->next) {
i--;
}
return e;
}
static size_t jv_len(const jv *arr)
{
size_t n = 0;
const jv *e;
if (!arr || arr->type != JV_ARR) {
return 0;
}
for (e = arr->child; e; e = e->next) {
n++;
}
return n;
}
static int jv_obj_u32(const jv *obj, const char *key, uint32_t *out)
{
const jv *v = jv_get(obj, key);
if (!v || v->type != JV_NUM || v->num > UINT32_MAX) {
return -1;
}
*out = (uint32_t)v->num;
return 0;
}
static int jv_obj_u64(const jv *obj, const char *key, uint64_t *out)
{
const jv *v = jv_get(obj, key);
if (!v || v->type != JV_NUM) {
return -1;
}
*out = v->num;
return 0;
}
static int jv_arr_u64(const jv *arr, size_t i, uint64_t *out)
{
const jv *e = jv_at(arr, i);
if (!e || e->type != JV_NUM) {
return -1;
}
*out = e->num;
return 0;
}
static int jv_str_is(const jv *v, const char *s)
{
return v && v->type == JV_STR && v->str && strcmp(v->str, s) == 0;
}
/* Snapshot of the search tree in flat arrays, one array per field. */
typedef struct {
uint32_t n;
uint32_t *parent;
uint32_t *kind;
uint32_t *id;
uint32_t *x;
uint32_t *y;
uint32_t *cost;
uint64_t *key_hi;
uint64_t *key_lo;
uint64_t *g;
uint32_t *depth;
uint8_t *goal;
uint8_t *dead;
uint32_t *open;
size_t open_n;
uint32_t anchor;
int anchor_valid;
} lit_search_snap;
static void snap_free(lit_search_snap *sn)
{
free(sn->parent);
free(sn->kind);
free(sn->id);
free(sn->x);
free(sn->y);
free(sn->cost);
free(sn->key_hi);
free(sn->key_lo);
free(sn->g);
free(sn->depth);
free(sn->goal);
free(sn->dead);
free(sn->open);
memset(sn, 0, sizeof(*sn));
}
static int snap_alloc(lit_search_snap *sn, uint32_t n, size_t open_n)
{
memset(sn, 0, sizeof(*sn));
if (n == 0 || (uint64_t)n > SIZE_MAX / sizeof(uint32_t) ||
open_n > SIZE_MAX / sizeof(uint32_t)) {
return -1;
}
sn->n = n;
sn->open_n = open_n;
sn->parent = malloc((size_t)n * sizeof(*sn->parent));
sn->kind = malloc((size_t)n * sizeof(*sn->kind));
sn->id = malloc((size_t)n * sizeof(*sn->id));
sn->x = malloc((size_t)n * sizeof(*sn->x));
sn->y = malloc((size_t)n * sizeof(*sn->y));
sn->cost = malloc((size_t)n * sizeof(*sn->cost));
sn->key_hi = malloc((size_t)n * sizeof(*sn->key_hi));
sn->key_lo = malloc((size_t)n * sizeof(*sn->key_lo));
sn->g = malloc((size_t)n * sizeof(*sn->g));
sn->depth = malloc((size_t)n * sizeof(*sn->depth));
sn->goal = malloc((size_t)n * sizeof(*sn->goal));
sn->dead = malloc((size_t)n * sizeof(*sn->dead));
sn->open = open_n ? malloc(open_n * sizeof(*sn->open)) : NULL;
if (!sn->parent || !sn->kind || !sn->id || !sn->x || !sn->y ||
!sn->cost || !sn->key_hi || !sn->key_lo || !sn->g ||
!sn->depth || !sn->goal || !sn->dead ||
(open_n && !sn->open)) {
snap_free(sn);
return -1;
}
return 0;
}
static int snap_from_search(const lit_search *s, lit_search_snap *sn)
{
size_t frontier = 0;
size_t f = 0;
if (!s || s->nodes.n == 0 || s->nodes.n > UINT32_MAX) {
return -1;
}
for (uint32_t i = 0; i < s->nodes.n; i++) {
if (!s->nodes.v[i].expanded && !s->nodes.v[i].dead) {
frontier++;
}
}
if (snap_alloc(sn, (uint32_t)s->nodes.n, frontier) != 0) {
return -1;
}
for (uint32_t i = 0; i < sn->n; i++) {
const lit_snode *node = &s->nodes.v[i];
sn->parent[i] = node->parent;
sn->kind[i] = node->act.kind;
sn->id[i] = node->act.id;
sn->x[i] = node->act.x;
sn->y[i] = node->act.y;
sn->cost[i] = node->act.cost;
sn->key_hi[i] = node->key.hi;
sn->key_lo[i] = node->key.lo;
sn->g[i] = node->g;
sn->depth[i] = node->depth;
sn->goal[i] = node->goal;
sn->dead[i] = node->dead;
if (!node->expanded && !node->dead) {
sn->open[f++] = i;
}
}
sn->anchor = s->anchor;
sn->anchor_valid = s->anchor_valid;
return 0;
}
static int read_whole(const char *path, char **out, size_t *outlen)
{
FILE *f;
long sz;
char *buf;
size_t got;
f = fopen(path, "rb");
if (!f) {
return -1;
}
if (fseek(f, 0, SEEK_END) != 0) {
fclose(f);
return -1;
}
sz = ftell(f);
if (sz < 0) {
fclose(f);
return -1;
}
if (fseek(f, 0, SEEK_SET) != 0) {
fclose(f);
return -1;
}
buf = malloc((size_t)sz + 1);
if (!buf) {
fclose(f);
return -1;
}
got = fread(buf, 1, (size_t)sz, f);
if (got != (size_t)sz || fclose(f) != 0) {
free(buf);
return -1;
}
buf[sz] = '\0';
*out = buf;
*outlen = (size_t)sz;
return 0;
}
static int json_write_snap(const lit_search_snap *sn, const char *path)
{
FILE *f;
char *vbuf;
int bad = 0;
f = fopen(path, "wb");
if (!f) {
return -1;
}
vbuf = malloc(1 << 20);
if (vbuf) {
setvbuf(f, vbuf, _IOFBF, 1 << 20);
}
fprintf(f, "{\"format\":\"lit-search-tree\",\"version\":1,");
fprintf(f, "\"n\":%u,\"anchor\":%u,\"anchor_valid\":%d,\"nodes\":[\n",
(unsigned)sn->n, (unsigned)sn->anchor,
sn->anchor_valid ? 1 : 0);
for (uint32_t i = 0; i < sn->n; i++) {
fprintf(f, "%s{\"parent\":%u,\"kind\":%u,\"id\":%u,\"x\":%u,"
"\"y\":%u,\"cost\":%u,\"key_hi\":%llu,\"key_lo\":%llu,"
"\"g\":%llu,\"depth\":%u,\"goal\":%u,\"dead\":%u}",
i ? ",\n" : "", (unsigned)sn->parent[i],
(unsigned)sn->kind[i], (unsigned)sn->id[i],
(unsigned)sn->x[i], (unsigned)sn->y[i],
(unsigned)sn->cost[i],
(unsigned long long)sn->key_hi[i],
(unsigned long long)sn->key_lo[i],
(unsigned long long)sn->g[i], (unsigned)sn->depth[i],
(unsigned)sn->goal[i], (unsigned)sn->dead[i]);
}
fprintf(f, "\n],\"open\":[");
for (size_t i = 0; i < sn->open_n; i++) {
fprintf(f, "%s%u", i ? "," : "", (unsigned)sn->open[i]);
}
fprintf(f, "]}\n");
if (ferror(f)) {
bad = 1;
}
if (fclose(f) != 0) {
bad = 1;
}
free(vbuf);
return bad ? -1 : 0;
}
static int json_read_snap(const jv *root, lit_search_snap *sn)
{
const jv *nodes;
const jv *open;
size_t nopen;
uint64_t v64;
uint64_t n;
if (!root || root->type != JV_OBJ ||
!jv_str_is(jv_get(root, "format"), "lit-search-tree") ||
jv_obj_u64(root, "version", &v64) != 0 || v64 != 1) {
return -1;
}
nodes = jv_get(root, "nodes");
open = jv_get(root, "open");
if (!nodes || nodes->type != JV_ARR) {
return -1;
}
n = jv_len(nodes);
if (n == 0 || n > UINT32_MAX ||
jv_obj_u64(root, "n", &v64) != 0 || v64 != n) {
return -1;
}
if (open && open->type != JV_ARR) {
return -1;
}
nopen = jv_len(open);
if (snap_alloc(sn, (uint32_t)n, nopen) != 0) {
return -1;
}
if (jv_obj_u32(root, "anchor", &sn->anchor) != 0 ||
jv_obj_u64(root, "anchor_valid", &v64) != 0 || v64 > 1) {
goto fail;
}
sn->anchor_valid = (int)v64;
if (sn->anchor_valid && sn->anchor >= sn->n) {
goto fail;
}
for (uint32_t i = 0; i < sn->n; i++) {
const jv *node = jv_at(nodes, i);
uint32_t bit;
if (!node || node->type != JV_OBJ) {
goto fail;
}
if (jv_obj_u32(node, "parent", &sn->parent[i]) != 0) {
goto fail;
}
if (sn->parent[i] != UINT32_MAX && sn->parent[i] >= sn->n) {
goto fail;
}
if (jv_obj_u32(node, "kind", &sn->kind[i]) != 0 ||
jv_obj_u32(node, "id", &sn->id[i]) != 0 ||
jv_obj_u32(node, "x", &sn->x[i]) != 0 ||
jv_obj_u32(node, "y", &sn->y[i]) != 0 ||
jv_obj_u32(node, "cost", &sn->cost[i]) != 0 ||
jv_obj_u64(node, "key_hi", &sn->key_hi[i]) != 0 ||
jv_obj_u64(node, "key_lo", &sn->key_lo[i]) != 0 ||
jv_obj_u64(node, "g", &sn->g[i]) != 0 ||
jv_obj_u32(node, "depth", &sn->depth[i]) != 0 ||
jv_obj_u32(node, "goal", &bit) != 0 || bit > 1) {
goto fail;
}
sn->goal[i] = (uint8_t)bit;
if (jv_obj_u32(node, "dead", &bit) != 0 || bit > 1) {
goto fail;
}
sn->dead[i] = (uint8_t)bit;
}
for (size_t i = 0; i < sn->open_n; i++) {
const jv *e = jv_at(open, i);
uint64_t idx;
if (!e || e->type != JV_NUM) {
goto fail;
}
idx = e->num;
if (idx >= sn->n) {
goto fail;
}
sn->open[i] = (uint32_t)idx;
}
return 0;
fail:
snap_free(sn);
return -1;
}
typedef struct {
const char *name;
const char *dtype;
uint64_t count;
size_t esize;
const void *data;
} st_tensor;
static int st_append(char *buf, size_t cap, size_t *len, const char *fmt,
...)
{
va_list ap;
int w;
va_start(ap, fmt);
w = vsnprintf(buf + *len, cap - *len, fmt, ap);
va_end(ap);
if (w < 0 || (size_t)w >= cap - *len) {
return -1;
}
*len += (size_t)w;
return 0;
}
static int st_write_snap(const lit_search_snap *sn, const char *path)
{
st_tensor t[13];
size_t nt = 0;
char hdr[8192];
size_t len = 0;
uint64_t off = 0;
FILE *f;
int bad = 0;
t[nt++] = (st_tensor){"parent", "U32", sn->n, 4, sn->parent};
t[nt++] = (st_tensor){"act_kind", "U32", sn->n, 4, sn->kind};
t[nt++] = (st_tensor){"act_id", "U32", sn->n, 4, sn->id};
t[nt++] = (st_tensor){"act_x", "U32", sn->n, 4, sn->x};
t[nt++] = (st_tensor){"act_y", "U32", sn->n, 4, sn->y};
t[nt++] = (st_tensor){"act_cost", "U32", sn->n, 4, sn->cost};
t[nt++] = (st_tensor){"key_hi", "U64", sn->n, 8, sn->key_hi};
t[nt++] = (st_tensor){"key_lo", "U64", sn->n, 8, sn->key_lo};
t[nt++] = (st_tensor){"g", "U64", sn->n, 8, sn->g};
t[nt++] = (st_tensor){"depth", "U32", sn->n, 4, sn->depth};
t[nt++] = (st_tensor){"goal", "U8", sn->n, 1, sn->goal};
t[nt++] = (st_tensor){"dead", "U8", sn->n, 1, sn->dead};
t[nt++] = (st_tensor){"open", "U32", sn->open_n, 4, sn->open};
if (st_append(hdr, sizeof(hdr), &len, "{") != 0) {
return -1;
}
for (size_t i = 0; i < nt; i++) {
uint64_t bytes = t[i].count * t[i].esize;
if (st_append(hdr, sizeof(hdr), &len,
"%s\"%s\":{\"dtype\":\"%s\",\"shape\":[%llu],"
"\"data_offsets\":[%llu,%llu]}",
i ? "," : "", t[i].name, t[i].dtype,
(unsigned long long)t[i].count,
(unsigned long long)off,
(unsigned long long)(off + bytes)) != 0) {
return -1;
}
off += bytes;
}
if (st_append(hdr, sizeof(hdr), &len,
",\"__metadata__\":{\"format\":\"lit-search-tree\","
"\"version\":\"1\",\"anchor\":\"%u\","
"\"anchor_valid\":\"%d\",\"n\":\"%u\"}}",
(unsigned)sn->anchor, sn->anchor_valid ? 1 : 0,
(unsigned)sn->n) != 0) {
return -1;
}
while (len % 8 != 0) {
if (len + 1 >= sizeof(hdr)) {
return -1;
}
hdr[len++] = ' ';
}
f = fopen(path, "wb");
if (!f) {
return -1;
}
{
unsigned char sz[8];
uint64_t hlen = (uint64_t)len;
for (int i = 0; i < 8; i++) {
sz[i] = (unsigned char)(hlen >> (8 * i));
}
if (fwrite(sz, 1, 8, f) != 8) {
bad = 1;
}
}
if (!bad && fwrite(hdr, 1, len, f) != len) {
bad = 1;
}
for (size_t i = 0; i < nt && !bad; i++) {
if (t[i].count != 0 &&
fwrite(t[i].data, t[i].esize, t[i].count, f) != t[i].count) {
bad = 1;
}
}
if (fclose(f) != 0) {
bad = 1;
}
return bad ? -1 : 0;
}
static int st_shape1(const jv *root, const char *name, uint64_t *out)
{
const jv *t = jv_get(root, name);
const jv *shape;
if (!t || t->type != JV_OBJ) {
return -1;
}
shape = jv_get(t, "shape");
if (!shape || shape->type != JV_ARR || jv_len(shape) != 1) {
return -1;
}
return jv_arr_u64(shape, 0, out);
}
static int st_tensor_get(const jv *root, const char *name,
const char *dtype, uint64_t count,
size_t esize, const char *data, size_t dlen,
void *out)
{
const jv *t = jv_get(root, name);
const jv *shape;
const jv *offs;
uint64_t dim;
uint64_t begin;
uint64_t end;
if (!t || t->type != JV_OBJ) {
return -1;
}
if (!jv_str_is(jv_get(t, "dtype"), dtype)) {
return -1;
}
shape = jv_get(t, "shape");
offs = jv_get(t, "data_offsets");
if (!shape || shape->type != JV_ARR || jv_len(shape) != 1 ||
jv_arr_u64(shape, 0, &dim) != 0 || dim != count) {
return -1;
}
if (!offs || offs->type != JV_ARR || jv_len(offs) != 2 ||
jv_arr_u64(offs, 0, &begin) != 0 ||
jv_arr_u64(offs, 1, &end) != 0) {
return -1;
}
if (end < begin || end > dlen || end - begin != count * esize) {
return -1;
}
if (count != 0) {
memcpy(out, data + begin, (size_t)(end - begin));
}
return 0;
}
static int jv_meta_u64(const jv *meta, const char *key, uint64_t *out)
{
const jv *v = jv_get(meta, key);
char *endp;
unsigned long long x;
if (!v) {
return 1;
}
if (v->type != JV_STR || !v->str) {
return -1;
}
x = strtoull(v->str, &endp, 10);
if (endp == v->str || *endp != '\0') {
return -1;
}
*out = (uint64_t)x;
return 0;
}
static int st_read_snap(const jv *root, const char *data, size_t dlen,
lit_search_snap *sn)
{
const jv *meta;
uint64_t n;
uint64_t open_n;
uint64_t v;
int rc;
if (!root || root->type != JV_OBJ) {
return -1;
}
if (st_shape1(root, "parent", &n) != 0 || n == 0 ||
n > UINT32_MAX) {
return -1;
}
if (st_shape1(root, "open", &open_n) != 0 ||
open_n > (uint64_t)(SIZE_MAX / sizeof(uint32_t))) {
return -1;
}
if (snap_alloc(sn, (uint32_t)n, (size_t)open_n) != 0) {
return -1;
}
if (st_tensor_get(root, "parent", "U32", n, 4, data, dlen,
sn->parent) != 0 ||
st_tensor_get(root, "act_kind", "U32", n, 4, data, dlen,
sn->kind) != 0 ||
st_tensor_get(root, "act_id", "U32", n, 4, data, dlen,
sn->id) != 0 ||
st_tensor_get(root, "act_x", "U32", n, 4, data, dlen,
sn->x) != 0 ||
st_tensor_get(root, "act_y", "U32", n, 4, data, dlen,
sn->y) != 0 ||
st_tensor_get(root, "act_cost", "U32", n, 4, data, dlen,
sn->cost) != 0 ||
st_tensor_get(root, "key_hi", "U64", n, 8, data, dlen,
sn->key_hi) != 0 ||
st_tensor_get(root, "key_lo", "U64", n, 8, data, dlen,
sn->key_lo) != 0 ||
st_tensor_get(root, "g", "U64", n, 8, data, dlen,
sn->g) != 0 ||
st_tensor_get(root, "depth", "U32", n, 4, data, dlen,
sn->depth) != 0 ||
st_tensor_get(root, "goal", "U8", n, 1, data, dlen,
sn->goal) != 0 ||
st_tensor_get(root, "dead", "U8", n, 1, data, dlen,
sn->dead) != 0 ||
st_tensor_get(root, "open", "U32", open_n, 4, data, dlen,
sn->open) != 0) {
goto fail;
}
sn->anchor = UINT32_MAX;
sn->anchor_valid = 0;
meta = jv_get(root, "__metadata__");
if (meta) {
rc = jv_meta_u64(meta, "anchor", &v);
if (rc < 0 || (rc == 0 && v > UINT32_MAX)) {
goto fail;
}
if (rc == 0) {
sn->anchor = (uint32_t)v;
}
rc = jv_meta_u64(meta, "anchor_valid", &v);
if (rc < 0 || (rc == 0 && v > 1)) {
goto fail;
}
if (rc == 0) {
sn->anchor_valid = (int)v;
}
}
if (sn->anchor_valid && sn->anchor >= sn->n) {
goto fail;
}
for (uint32_t i = 0; i < sn->n; i++) {
if (sn->parent[i] != UINT32_MAX && sn->parent[i] >= sn->n) {
goto fail;
}
if (sn->goal[i] > 1 || sn->dead[i] > 1) {
goto fail;
}
}
for (size_t i = 0; i < sn->open_n; i++) {
if (sn->open[i] >= sn->n) {
goto fail;
}
}
return 0;
fail:
snap_free(sn);
return -1;
}
static lit_search *search_from_snap(const lit_host *host,
const lit_search_snap *sn)
{
lit_search *s;
uint32_t idx;
if (!sn || sn->n == 0) {
return NULL;
}
s = search_alloc(host);
if (!s) {
return NULL;
}
for (uint32_t i = 0; i < sn->n; i++) {
lit_snode node;
lit_key key;
memset(&node, 0, sizeof(node));
node.parent = sn->parent[i];
node.act.kind = sn->kind[i];
node.act.id = sn->id[i];
node.act.x = sn->x[i];
node.act.y = sn->y[i];
node.act.cost = sn->cost[i];
key.hi = sn->key_hi[i];
key.lo = sn->key_lo[i];
node.key = key;
node.g = sn->g[i];
node.depth = sn->depth[i];
node.goal = sn->goal[i];
node.dead = sn->dead[i];
node.expanded = 1;
if (sarena_add(&s->nodes, &node, &idx) != 0 || idx != i) {
goto fail;
}
}
for (uint32_t i = 1; i < sn->n; i++) {
uint32_t p = s->nodes.v[i].parent;
if (p != UINT32_MAX && p < i) {
link_child(s, p, i);
}
}
for (uint32_t i = 0; i < sn->n; i++) {
lit_key key;
key.hi = sn->key_hi[i];
key.lo = sn->key_lo[i];
/* Open-set trees deliberately contain duplicate keys (a sampled
* counterfactual can land on a seen state). The seen table keeps
* the first node; a duplicate is not a load error. */
if (ktab_insert(&s->seen, key, i) < 0) {
goto fail;
}
}
for (size_t i = 0; i < sn->open_n; i++) {
uint32_t node = sn->open[i];
if (node >= sn->n) {
goto fail;
}
s->nodes.v[node].expanded = 0;
}
for (size_t i = 0; i < sn->open_n; i++) {
if (heap_push(s, sn->open[i]) != 0) {
goto fail;
}
}
s->anchor = sn->anchor;
s->anchor_valid = sn->anchor_valid;
if (s->anchor_valid && s->anchor >= sn->n) {
goto fail;
}
if (!s->anchor_valid) {
s->anchor = UINT32_MAX;
}
return s;
fail:
lit_search_free(s);
return NULL;
}
int lit_search_save_json(const lit_search *s, const char *path)
{
lit_search_snap sn;
int rc;
if (!s || !path || snap_from_search(s, &sn) != 0) {
return -1;
}
rc = json_write_snap(&sn, path);
snap_free(&sn);
return rc;
}
int lit_search_save_safetensors(const lit_search *s, const char *path)
{
lit_search_snap sn;
int rc;
if (!s || !path || snap_from_search(s, &sn) != 0) {
return -1;
}
rc = st_write_snap(&sn, path);
snap_free(&sn);
return rc;
}
lit_search *lit_search_load_json(const lit_host *host, const char *path)
{
jv_parser jp;
char *file = NULL;
size_t len = 0;
const char *p;
const char *end;
const jv *root;
lit_search_snap sn;
lit_search *s = NULL;
if (!host || !path || read_whole(path, &file, &len) != 0) {
return NULL;
}
memset(&jp, 0, sizeof(jp));
p = file;
end = file + len;
jv_ws(&p, end);
root = jv_value(&jp, &p, end, 0);
if (root) {
jv_ws(&p, end);
if (p != end) {
root = NULL;
}
}
memset(&sn, 0, sizeof(sn));
if (root && json_read_snap(root, &sn) == 0) {
s = search_from_snap(host, &sn);
}
snap_free(&sn);
jv_free(&jp);
free(file);
return s;
}
lit_search *lit_search_load_safetensors(const lit_host *host,
const char *path)
{
jv_parser jp;
char *file = NULL;
size_t len = 0;
uint64_t hlen = 0;
const char *p;
const char *end;
const jv *root;
const char *data;
size_t dlen;
lit_search_snap sn;
lit_search *s = NULL;
if (!host || !path || read_whole(path, &file, &len) != 0 ||
len < 8) {
free(file);
return NULL;
}
for (int i = 0; i < 8; i++) {
hlen |= (uint64_t)(unsigned char)file[i] << (8 * i);
}
if (hlen < 2 || hlen > len - 8 || hlen % 8 != 0) {
free(file);
return NULL;
}
memset(&jp, 0, sizeof(jp));
p = file + 8;
end = p + hlen;
jv_ws(&p, end);
root = jv_value(&jp, &p, end, 0);
if (root) {
jv_ws(&p, end);
if (p != end) {
root = NULL;
}
}
data = file + 8 + hlen;
dlen = len - 8 - (size_t)hlen;
memset(&sn, 0, sizeof(sn));
if (root && st_read_snap(root, data, dlen, &sn) == 0) {
s = search_from_snap(host, &sn);
}
snap_free(&sn);
jv_free(&jp);
free(file);
return s;
}
/* lit_operator.c — the LIT DO search operator: the DO node arena and
* the frontier scan. The tree stores interventions, not machine
* states: a node's state is replayed from its DO chain. This is the
* mainline for synthesis: the search path, flattened, is the program.
* The Coder only mines macros. No game, no ARC, no Python: the caller
* supplies the machine/state, the actions, and the oracle. */
int lit_do_apply(lit_machine *m, const lit_do *d)
{
if (!m || !d || !m->V || m->pending || d->slot >= m->n) {
return -1;
}
switch (d->kind) {
case LIT_DO_LOAD: {
uint64_t value = d->value & m->mask;
for (uint32_t c = 0; c < m->k; c++) {
m->V[(size_t)c * m->n + d->slot] = value;
}
return 0;
}
case LIT_DO_WIRE:
if (d->src >= m->n) {
return -1;
}
return lit_machine_connect(m, d->slot, d->src, d->gain,
&d->weight, -1);
default:
return -1;
}
}
int lit_do_restore(const lit_donode *node, lit_machine *m)
{
const lit_donode *nd;
lit_do *ops;
size_t depth = 0;
size_t i;
if (!node || !m) {
return -1;
}
for (nd = node; nd->parent; nd = nd->parent) {
depth++;
}
if (depth == 0) {
return 0;
}
ops = malloc(depth * sizeof(*ops));
if (!ops) {
return -1;
}
depth = 0;
for (nd = node; nd->parent; nd = nd->parent) {
ops[depth++] = nd->op;
}
for (i = depth; i > 0; i--) {
if (lit_do_apply(m, &ops[i - 1]) != 0) {
free(ops);
return -1;
}
}
free(ops);
return 0;
}
/* ---------------------------------------------------------------- */
/* DO node arena */
/* ---------------------------------------------------------------- */
lit_donode *lit_do_alloc(lit_do_arena *a, lit_donode *parent,
const lit_do *op, uint32_t depth)
{
lit_donode *n;
if (a->used == a->cap) {
lit_donode **chunk = realloc(a->chunk,
(a->nchunk + 1) * sizeof(*chunk));
if (!chunk) {
return NULL;
}
a->chunk = chunk;
a->chunk[a->nchunk] = malloc(LIT_DO_CHUNK * sizeof(lit_donode));
if (!a->chunk[a->nchunk]) {
return NULL;
}
a->nchunk++;
a->cap += LIT_DO_CHUNK;
}
n = &a->chunk[a->used / LIT_DO_CHUNK][a->used % LIT_DO_CHUNK];
a->used++;
memset(n, 0, sizeof(*n));
n->parent = parent;