Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/src/runtime/rx_jspace.c # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / src / runtime / rx_jspace.c` 1978 lines ยท 78025 bytes Raw Blame History 1 /* SPDX-License-Identifier: Apache-2.0 2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 /* 18 * rx_jspace.c -- branch-native shared cognitive state (see rx_jspace.h). 19 * 20 * Semantics are those of the original host reference. Production mechanics 21 * (M20): slab-allocated realizations with {slot, gen} identity, reusable 22 * branch slots with generations, a bounded extent allocator for the spill / 23 * data file with quarantine of extents a checkpoint may still name, hard 24 * limits that fail before any change, one recursive space mutex, and a 25 * crash-safe metadata checkpoint (temporary file + fsync + rename) that 26 * records recipes and extents, never pointers. Content checks use a 64-bit 27 * word hash so the store does not pay SHA-256 on every unit; tests compare 28 * full SHA-256 digests outside the store. 29 */ 30 #include "rx_jspace.h" 31 #include "sha256.h" 32 #include "aien_machine_id.h" 33 34 /* JsHome.machine carries AienMachineId bytes (aien_mid_to_slot / aien_mid_from_slot). */ 35 _Static_assert(JS_MACHINE_ID_BYTES == AIEN_MID_ID_BYTES, "JsHome.machine must match AienMachineId width"); 36 37 #include 38 #include 39 #include 40 #include 41 #include 42 #include 43 #include 44 #include 45 #include 46 47 #define LOCK(s) pthread_mutex_lock((pthread_mutex_t *)&(s)->mu) 48 #define UNLOCK(s) pthread_mutex_unlock((pthread_mutex_t *)&(s)->mu) 49 50 static int restore_u(JsSpace *s, JsReal *r); 51 static int release_u(JsSpace *s, uint32_t bid); 52 53 static uint64_t now_ns(void) { 54 struct timespec ts; 55 clock_gettime(CLOCK_MONOTONIC, &ts); 56 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; 57 } 58 59 /* ---- content check ------------------------------------------------------- */ 60 61 static uint64_t mix64(uint64_t x) { 62 x ^= x >> 30; x *= 0xbf58476d1ce4e5b9ull; 63 x ^= x >> 27; x *= 0x94d049bb133111ebull; 64 return x ^ (x >> 31); 65 } 66 67 static void content_check(const uint8_t *p, size_t n, uint8_t out[32]) { 68 uint64_t h[4] = { 0x243f6a8885a308d3ull, 0x13198a2e03707344ull, 69 0xa4093822299f31d0ull, 0x082efa98ec4e6c89ull }; 70 size_t words = n / 8; 71 for (size_t i = 0; i < words; i++) { 72 uint64_t v; 73 memcpy(&v, p + i * 8, 8); 74 h[i & 3] = mix64(h[i & 3] ^ v) + i; 75 } 76 for (size_t i = words * 8; i < n; i++) h[0] = mix64(h[0] ^ p[i]); 77 for (int i = 0; i < 4; i++) { 78 uint64_t v = mix64(h[i] ^ h[(i + 1) & 3] ^ n); 79 memcpy(out + i * 8, &v, 8); 80 } 81 } 82 83 /* ---- semantic identity --------------------------------------------------- */ 84 85 static JsSemId sem_hash(const uint8_t *tag, size_t tag_len, const uint8_t *a, size_t an, 86 const uint8_t *b, size_t bn) { 87 sha256_ctx c; 88 JsSemId id; 89 sha256_init(&c); 90 sha256_update(&c, tag, tag_len); 91 if (an) sha256_update(&c, a, an); 92 if (bn) sha256_update(&c, b, bn); 93 sha256_final(&c, id.b); 94 return id; 95 } 96 97 JsSemId js_sem_root(uint64_t seed) { 98 return sem_hash((const uint8_t *)"js.root", 7, (const uint8_t *)&seed, 8, NULL, 0); 99 } 100 101 JsSemId js_sem_derive(const JsSemId *prev, uint64_t token) { 102 return sem_hash((const uint8_t *)"js.derive", 9, prev->b, 32, (const uint8_t *)&token, 8); 103 } 104 105 JsSemId js_sem_edit(const JsSemId *prev, uint32_t off, const uint8_t *patch, uint32_t len) { 106 uint8_t hdr[40]; 107 uint8_t ph[32]; 108 sha256_hash(patch, len, ph); 109 memcpy(hdr, prev->b, 32); 110 memcpy(hdr + 32, &off, 4); 111 memcpy(hdr + 36, &len, 4); 112 return sem_hash((const uint8_t *)"js.edit", 7, hdr, sizeof hdr, ph, 32); 113 } 114 115 JsSemId js_branch_semantic_id(const JsBranch *b) { 116 sha256_ctx c; 117 JsSemId id; 118 uint32_t n = b->n_units; 119 sha256_init(&c); 120 sha256_update(&c, (const uint8_t *)"js.branch", 9); 121 sha256_update(&c, (const uint8_t *)&n, 4); 122 for (uint32_t i = 0; i < n; i++) sha256_update(&c, b->units[i]->semantic_state_id.b, 32); 123 sha256_final(&c, id.b); 124 return id; 125 } 126 127 /* ---- extents in the spill / data file -------------------------------------- */ 128 129 static int ext_push(JsExtent **v, uint32_t *n, uint32_t *cap, uint32_t at, JsExtent e) { 130 if (*n == *cap) { 131 uint32_t nc = *cap ? *cap * 2 : 64; 132 JsExtent *nv = realloc(*v, nc * sizeof *nv); 133 if (!nv) return JS_ERR_NOMEM; 134 *v = nv; *cap = nc; 135 } 136 memmove(*v + at + 1, *v + at, (*n - at) * sizeof **v); 137 (*v)[at] = e; 138 (*n)++; 139 return JS_OK; 140 } 141 142 /* Return an extent to the free list now: sorted insert, coalesce, and give the 143 * tail back to the end of the file. */ 144 static void ext_free_now(JsSpace *s, uint64_t off, uint64_t len) { 145 if (!len) return; 146 uint32_t i = 0; 147 while (i < s->n_ext_free && s->ext_free[i].off < off) i++; 148 JsExtent *f = s->ext_free; 149 bool left = i > 0 && f[i - 1].off + f[i - 1].len == off; 150 bool right = i < s->n_ext_free && off + len == f[i].off; 151 if (left && right) { 152 f[i - 1].len += len + f[i].len; 153 memmove(f + i, f + i + 1, (s->n_ext_free - i - 1) * sizeof *f); 154 s->n_ext_free--; 155 i--; 156 } else if (left) { 157 f[i - 1].len += len; i--; 158 } else if (right) { 159 f[i].off = off; f[i].len += len; 160 } else if (ext_push(&s->ext_free, &s->n_ext_free, &s->cap_ext_free, i, 161 (JsExtent){ off, len }) != JS_OK) { 162 return; /* out of memory: the extent leaks until the next reopen */ 163 } 164 f = s->ext_free; 165 if (f[i].off + f[i].len == s->spill_end) { 166 s->spill_end = f[i].off; 167 memmove(f + i, f + i + 1, (s->n_ext_free - i - 1) * sizeof *f); 168 s->n_ext_free--; 169 } 170 } 171 172 /* Freed extent. A durable checkpoint may still name it, so it waits for the 173 * next commit before it can be written again. */ 174 static void ext_release(JsSpace *s, uint64_t off, uint64_t len) { 175 if (!len) return; 176 if (!s->durable) { ext_free_now(s, off, len); return; } 177 if (ext_push(&s->ext_pending, &s->n_ext_pending, &s->cap_ext_pending, s->n_ext_pending, 178 (JsExtent){ off, len }) != JS_OK) { 179 /* cannot quarantine: leak it rather than risk overwriting named bytes */ 180 } 181 } 182 183 /* First fit, else grow the file within max_spill_bytes. */ 184 static int ext_alloc(JsSpace *s, uint64_t len, uint64_t *off) { 185 for (uint32_t i = 0; i < s->n_ext_free; i++) { 186 JsExtent *e = &s->ext_free[i]; 187 if (e->len < len) continue; 188 *off = e->off; 189 e->off += len; e->len -= len; 190 if (!e->len) { 191 memmove(e, e + 1, (s->n_ext_free - i - 1) * sizeof *e); 192 s->n_ext_free--; 193 } 194 return JS_OK; 195 } 196 if (s->limits.max_spill_bytes && s->spill_end + len > s->limits.max_spill_bytes) 197 return JS_ERR_FULL; 198 *off = s->spill_end; 199 s->spill_end += len; 200 return JS_OK; 201 } 202 203 204 /* ---- realization slab ------------------------------------------------------ */ 205 206 static JsReal *slab_at(const JsSpace *s, uint32_t slot) { 207 if (slot >= s->real_hw) return NULL; 208 JsReal *c = s->slab[slot / JS_SLAB_CHUNK]; 209 return c ? &c[slot % JS_SLAB_CHUNK] : NULL; 210 } 211 212 /* Make sure the chunk holding `slot` exists. */ 213 static int slab_chunk(JsSpace *s, uint32_t slot) { 214 uint32_t k = slot / JS_SLAB_CHUNK; 215 if (k >= s->slab_chunks) return JS_ERR_FULL; 216 if (!s->slab[k]) { 217 JsReal *c = calloc(JS_SLAB_CHUNK, sizeof *c); 218 if (!c) return JS_ERR_NOMEM; 219 for (uint32_t i = 0; i < JS_SLAB_CHUNK; i++) { 220 c[i].slot = k * JS_SLAB_CHUNK + i; 221 c[i].gen = s->real_gen_floor; 222 } 223 s->slab[k] = c; 224 } 225 return JS_OK; 226 } 227 228 /* The generation after g, saturating at the retired marker: never wraps. */ 229 static uint64_t real_gen_next(uint64_t g) { 230 return g < JS_REAL_GEN_RETIRED ? g + 1 : JS_REAL_GEN_RETIRED; 231 } 232 233 /* A never-used slot can be handed out: below max_reals and its starting 234 * generation (the chunk's, or the floor for a chunk not yet made) is live. */ 235 static bool slab_fresh_ok(const JsSpace *s) { 236 if (s->real_hw >= s->limits.max_reals) return false; 237 const JsReal *c = s->real_hw / JS_SLAB_CHUNK < s->slab_chunks ? s->slab[s->real_hw / JS_SLAB_CHUNK] : NULL; 238 uint64_t g = c ? c[s->real_hw % JS_SLAB_CHUNK].gen : s->real_gen_floor; 239 return g != JS_REAL_GEN_RETIRED; 240 } 241 242 static JsReal *slab_take(JsSpace *s) { 243 JsReal *r = s->real_free; 244 if (r) { 245 s->real_free = r->free_next; 246 } else { 247 if (!slab_fresh_ok(s)) return NULL; 248 if (slab_chunk(s, s->real_hw) != JS_OK) return NULL; 249 r = &s->slab[s->real_hw / JS_SLAB_CHUNK][s->real_hw % JS_SLAB_CHUNK]; 250 s->real_hw++; 251 } 252 uint32_t slot = r->slot; 253 uint64_t gen = r->gen; 254 memset(r, 0, sizeof *r); 255 r->slot = slot; r->gen = gen; 256 r->patch_off = UINT64_MAX; 257 return r; 258 } 259 260 /* Release a slot: its generation moves on so every old JsRealId is stale. A 261 * slot whose next generation would be JS_REAL_GEN_RETIRED retires: it keeps 262 * that marker and never returns to the free list. */ 263 static void slab_give(JsSpace *s, JsReal *r) { 264 uint32_t slot = r->slot; 265 uint64_t gen = real_gen_next(r->gen); 266 memset(r, 0, sizeof *r); 267 r->slot = slot; r->gen = gen; 268 if (real_gen_next(gen) > s->real_gen_floor) s->real_gen_floor = real_gen_next(gen); 269 if (gen == JS_REAL_GEN_RETIRED) return; 270 r->free_next = s->real_free; 271 s->real_free = r; 272 } 273 274 /* ---- limits ------------------------------------------------------------------ */ 275 276 static int room(const JsSpace *s, uint32_t reals, uint64_t resident) { 277 if (reals && s->stats.live_reals + reals > s->limits.max_reals) return JS_ERR_FULL; 278 /* Retired slots count toward no live total but are never handed out. */ 279 if (reals && !s->real_free && !slab_fresh_ok(s)) return JS_ERR_FULL; 280 if (resident && s->limits.max_resident_bytes && 281 s->stats.resident_bytes + resident > s->limits.max_resident_bytes) return JS_ERR_FULL; 282 return JS_OK; 283 } 284 285 /* ---- residency accounting ------------------------------------------------ */ 286 287 static uint64_t resident_of(const JsReal *r) { 288 switch (r->placement) { 289 case JS_PLACE_HOT: case JS_PLACE_COLD: return r->realizer->unit_bytes; 290 case JS_PLACE_COMPRESSED: return r->packed_len; 291 default: return 0; 292 } 293 } 294 295 static void charge(JsSpace *s, const JsReal *r, int sign) { 296 uint64_t b = resident_of(r); 297 if (sign > 0) { 298 s->stats.resident_bytes += b; 299 if (s->stats.resident_bytes > s->stats.peak_resident_bytes) 300 s->stats.peak_resident_bytes = s->stats.resident_bytes; 301 if (r->placement == JS_PLACE_SPILLED) s->stats.spilled_bytes += r->realizer->unit_bytes; 302 } else { 303 s->stats.resident_bytes -= b; 304 if (r->placement == JS_PLACE_SPILLED) s->stats.spilled_bytes -= r->realizer->unit_bytes; 305 } 306 } 307 308 /* Drop whatever physical form r has; placement becomes EVICTED. */ 309 static void drop_physical(JsSpace *s, JsReal *r) { 310 charge(s, r, -1); 311 if (r->placement == JS_PLACE_SPILLED) ext_release(s, r->spill_off, r->realizer->unit_bytes); 312 free(r->bytes); r->bytes = NULL; 313 free(r->packed); r->packed = NULL; r->packed_len = 0; 314 r->placement = JS_PLACE_EVICTED; 315 } 316 317 static void set_hot(JsSpace *s, JsReal *r, uint8_t *bytes) { 318 r->bytes = bytes; 319 r->placement = JS_PLACE_HOT; 320 charge(s, r, +1); 321 } 322 323 /* ---- semantic reuse index ------------------------------------------------- */ 324 325 static uint32_t bucket_of(const JsSemId *id, JsRealType t) { 326 uint32_t v; 327 memcpy(&v, id->b, 4); 328 return (v ^ (uint32_t)t * 0x9e3779b1u) & (JS_INDEX_BUCKETS - 1u); 329 } 330 331 static JsReal *index_find(JsSpace *s, const JsSemId *id, JsRealType t) { 332 for (JsReal *r = s->index[bucket_of(id, t)]; r; r = r->index_next) 333 if (r->realization_type == t && !memcmp(r->semantic_state_id.b, id->b, 32)) return r; 334 return NULL; 335 } 336 337 static void index_insert(JsSpace *s, JsReal *r) { 338 uint32_t k = bucket_of(&r->semantic_state_id, r->realization_type); 339 r->index_next = s->index[k]; 340 s->index[k] = r; 341 } 342 343 static void index_remove(JsSpace *s, JsReal *r) { 344 JsReal **p = &s->index[bucket_of(&r->semantic_state_id, r->realization_type)]; 345 while (*p && *p != r) p = &(*p)->index_next; 346 if (*p) *p = r->index_next; 347 } 348 349 /* ---- realization lifetime ------------------------------------------------ */ 350 351 static void real_unref(JsSpace *s, JsReal *r) { 352 while (r && --r->refs == 0) { 353 JsReal *parent = r->parent_realization; 354 if (s->cache_r == r) s->cache_r = NULL; 355 index_remove(s, r); 356 drop_physical(s, r); 357 free(r->edit_bytes); 358 if (r->patch_off != UINT64_MAX) ext_release(s, r->patch_off, r->edit_len); 359 slab_give(s, r); 360 s->stats.live_reals--; 361 r = parent; 362 } 363 } 364 365 /* Callers check room() first, so NULL here means out of memory. */ 366 static JsReal *real_new(JsSpace *s, const JsRealizer *rz, JsSemId id, JsReal *parent, 367 JsRecipeKind kind) { 368 JsReal *r = slab_take(s); 369 if (!r) return NULL; 370 r->semantic_state_id = id; 371 r->realization_type = rz->type; 372 r->realizer = rz; 373 r->parent_realization = parent; 374 if (parent) parent->refs++; 375 r->recipe = kind; 376 r->placement = JS_PLACE_EVICTED; 377 s->stats.live_reals++; 378 return r; 379 } 380 381 /* ---- materialization ----------------------------------------------------- */ 382 383 /* Codec for COMPRESSED: bytes XOR parent bytes (zeros for a root), then 384 * 8-byte words as [u32 zero words][u32 literal words][literals]... */ 385 static size_t pack_delta(const uint8_t *cur, const uint8_t *base, size_t n, uint8_t *out) { 386 size_t words = n / 8, i = 0, o = 0; 387 while (i < words) { 388 uint32_t z = 0, l = 0; 389 while (i + z < words) { 390 uint64_t a, b = 0; 391 memcpy(&a, cur + (i + z) * 8, 8); 392 if (base) memcpy(&b, base + (i + z) * 8, 8); 393 if (a != b) break; 394 z++; 395 } 396 size_t lit_start = i + z; 397 while (lit_start + l < words) { 398 uint64_t a, b = 0; 399 memcpy(&a, cur + (lit_start + l) * 8, 8); 400 if (base) memcpy(&b, base + (lit_start + l) * 8, 8); 401 if (a == b) break; 402 l++; 403 } 404 memcpy(out + o, &z, 4); memcpy(out + o + 4, &l, 4); o += 8; 405 for (uint32_t k = 0; k < l; k++) { 406 uint64_t a, b = 0; 407 memcpy(&a, cur + (lit_start + k) * 8, 8); 408 if (base) memcpy(&b, base + (lit_start + k) * 8, 8); 409 a ^= b; 410 memcpy(out + o, &a, 8); o += 8; 411 } 412 i = lit_start + l; 413 } 414 return o; 415 } 416 417 static void unpack_delta(const uint8_t *in, size_t in_len, const uint8_t *base, size_t n, 418 uint8_t *out) { 419 size_t i = 0, o = 0; 420 if (base) memcpy(out, base, n); else memset(out, 0, n); 421 while (i < in_len) { 422 uint32_t z, l; 423 memcpy(&z, in + i, 4); memcpy(&l, in + i + 4, 4); i += 8; 424 o += z; 425 for (uint32_t k = 0; k < l; k++, o++, i += 8) { 426 uint64_t a, d; 427 memcpy(&a, out + o * 8, 8); 428 memcpy(&d, in + i, 8); 429 a ^= d; 430 memcpy(out + o * 8, &a, 8); 431 } 432 } 433 } 434 435 /* A node whose bytes can be produced without its parent's bytes. */ 436 static bool is_stop(const JsReal *r) { 437 return r->placement == JS_PLACE_HOT || r->placement == JS_PLACE_COLD || 438 r->placement == JS_PLACE_SPILLED || !r->parent_realization; 439 } 440 441 static int stop_bytes(JsSpace *s, JsReal *r, uint8_t *out) { 442 size_t n = r->realizer->unit_bytes; 443 switch (r->placement) { 444 case JS_PLACE_HOT: case JS_PLACE_COLD: 445 memcpy(out, r->bytes, n); return JS_OK; 446 case JS_PLACE_SPILLED: { 447 ssize_t got = pread(s->spill_fd, out, n, (off_t)r->spill_off); 448 return got == (ssize_t)n ? JS_OK : JS_ERR_IO; 449 } 450 case JS_PLACE_COMPRESSED: /* no parent: coded against zeros */ 451 unpack_delta(r->packed, r->packed_len, NULL, n, out); 452 return JS_OK; 453 default: /* evicted root */ 454 r->realizer->derive(NULL, r->token, out, n); 455 s->stats.derives++; 456 s->stats.actions[JS_ACT_RECOMPUTE]++; 457 return JS_OK; 458 } 459 } 460 461 /* Produce r's bytes from its parent's bytes (`pb`, NULL for a root). */ 462 static void step_bytes(JsSpace *s, JsReal *r, const uint8_t *pb, uint8_t *out) { 463 size_t n = r->realizer->unit_bytes; 464 if (r->placement == JS_PLACE_COMPRESSED) { 465 unpack_delta(r->packed, r->packed_len, pb, n, out); 466 return; 467 } 468 /* EVICTED: follow the recipe. */ 469 s->stats.actions[JS_ACT_RECOMPUTE]++; 470 if (r->recipe == JS_RECIPE_DERIVE) { 471 r->realizer->derive(pb, r->token, out, n); 472 s->stats.derives++; 473 } else { 474 memcpy(out, pb, n); 475 memcpy(out + r->edit_off, r->edit_bytes, r->edit_len); 476 } 477 } 478 479 /* Write r's bytes into out without changing any placement. Walks back to the 480 * nearest node that needs no parent, then replays forward. */ 481 static int materialize(JsSpace *s, JsReal *r, uint8_t *out) { 482 size_t n = r->realizer->unit_bytes; 483 uint32_t depth = 0, cap = 64; 484 JsReal **chain = malloc(cap * sizeof *chain); 485 if (!chain) return JS_ERR_NOMEM; 486 JsReal *c = r; 487 bool cached = false; 488 while (!is_stop(c)) { 489 if (c == s->cache_r && s->cache_len == n) { cached = true; break; } 490 if (depth == cap) { 491 JsReal **nc = realloc(chain, (cap *= 2) * sizeof *chain); 492 if (!nc) { free(chain); return JS_ERR_NOMEM; } 493 chain = nc; 494 } 495 chain[depth++] = c; 496 c = c->parent_realization; 497 } 498 uint8_t *a = depth ? malloc(n) : out; 499 uint8_t *b = depth ? malloc(n) : NULL; 500 if (depth && (!a || !b)) { free(a); free(b); free(chain); return JS_ERR_NOMEM; } 501 int rc = JS_OK; 502 if (cached) memcpy(a, s->cache_bytes, n); 503 else rc = stop_bytes(s, c, a); 504 for (uint32_t k = depth; rc == JS_OK && k-- > 0;) { 505 uint8_t *dst = k == 0 ? out : b; 506 step_bytes(s, chain[k], a, dst); 507 if (k) { uint8_t *t = a; a = b; b = t; } 508 } 509 if (depth) { free(a); free(b); } 510 free(chain); 511 if (rc != JS_OK) return rc; 512 uint8_t chk[32]; 513 content_check(out, n, chk); 514 if (memcmp(chk, r->content, 32)) { s->stats.corrupt_restores++; return JS_ERR_CORRUPT; } 515 if (depth && r->placement != JS_PLACE_HOT && r->placement != JS_PLACE_COLD) { 516 if (s->cache_len != n) { 517 uint8_t *nb = realloc(s->cache_bytes, n); 518 if (!nb) return JS_OK; 519 s->cache_bytes = nb; 520 s->cache_len = n; 521 } 522 memcpy(s->cache_bytes, out, n); 523 s->cache_r = r; 524 } 525 return JS_OK; 526 } 527 528 static int restore_u(JsSpace *s, JsReal *r) { 529 if (r->placement == JS_PLACE_HOT || r->placement == JS_PLACE_COLD) return JS_OK; 530 int rc = room(s, 0, r->realizer->unit_bytes - resident_of(r)); 531 if (rc) return rc; 532 uint8_t *buf = malloc(r->realizer->unit_bytes); 533 if (!buf) return JS_ERR_NOMEM; 534 rc = materialize(s, r, buf); 535 if (rc != JS_OK) { free(buf); return rc; } 536 drop_physical(s, r); 537 set_hot(s, r, buf); 538 return JS_OK; 539 } 540 541 /* ---- physical operations -------------------------------------------------- */ 542 543 static int move_u(JsSpace *s, JsReal *r) { 544 if (r->placement != JS_PLACE_HOT && r->placement != JS_PLACE_COLD) return JS_ERR_ARG; 545 size_t n = r->realizer->unit_bytes; 546 uint8_t *dst = malloc(n); 547 if (!dst) return JS_ERR_NOMEM; 548 memcpy(dst, r->bytes, n); 549 free(r->bytes); 550 r->bytes = dst; 551 r->placement = r->placement == JS_PLACE_HOT ? JS_PLACE_COLD : JS_PLACE_HOT; 552 s->stats.actions[JS_ACT_MOVE]++; 553 return JS_OK; 554 } 555 556 static int compress_u(JsSpace *s, JsReal *r) { 557 size_t n = r->realizer->unit_bytes; 558 uint8_t *cur = malloc(n), *base = NULL; 559 uint8_t *tmp = malloc(n + (n / 8) * 8 + 16); 560 int rc = JS_ERR_NOMEM; 561 if (!cur || !tmp) goto out; 562 if ((rc = materialize(s, r, cur)) != JS_OK) goto out; 563 if (r->parent_realization) { 564 base = malloc(n); 565 if (!base) { rc = JS_ERR_NOMEM; goto out; } 566 if ((rc = materialize(s, r->parent_realization, base)) != JS_OK) goto out; 567 } 568 size_t len = pack_delta(cur, base, n, tmp); 569 uint8_t *packed = malloc(len ? len : 1); 570 if (!packed) { rc = JS_ERR_NOMEM; goto out; } 571 memcpy(packed, tmp, len); 572 drop_physical(s, r); 573 r->packed = packed; 574 r->packed_len = len; 575 r->placement = JS_PLACE_COMPRESSED; 576 charge(s, r, +1); 577 s->stats.actions[JS_ACT_COMPRESS]++; 578 out: 579 free(cur); free(base); free(tmp); 580 return rc; 581 } 582 583 static int spill_u(JsSpace *s, JsReal *r) { 584 size_t n = r->realizer->unit_bytes; 585 uint8_t *cur = malloc(n); 586 if (!cur) return JS_ERR_NOMEM; 587 uint64_t off = 0; 588 int rc = materialize(s, r, cur); 589 if (rc == JS_OK) rc = ext_alloc(s, n, &off); 590 if (rc == JS_OK) { 591 ssize_t put = pwrite(s->spill_fd, cur, n, (off_t)off); 592 if (put != (ssize_t)n) { rc = JS_ERR_IO; ext_free_now(s, off, n); } 593 } 594 free(cur); 595 if (rc != JS_OK) return rc; 596 drop_physical(s, r); 597 r->spill_off = off; 598 r->placement = JS_PLACE_SPILLED; 599 charge(s, r, +1); 600 s->stats.actions[JS_ACT_SPILL]++; 601 return JS_OK; 602 } 603 604 static int evict_u(JsSpace *s, JsReal *r) { 605 if (r->placement == JS_PLACE_EVICTED) return JS_OK; 606 drop_physical(s, r); 607 s->stats.actions[JS_ACT_EVICT]++; 608 return JS_OK; 609 } 610 611 /* ---- space ---------------------------------------------------------------- */ 612 613 void js_limits_default(JsLimits *lim) { 614 lim->max_reals = 1u << 24; 615 lim->max_branches = JS_MAX_BRANCHES; 616 lim->max_spill_bytes = 0; 617 lim->max_resident_bytes = 0; 618 } 619 620 /* Everything but the files. */ 621 static int space_setup(JsSpace *s, const JsLimits *lim) { 622 memset(s, 0, sizeof *s); 623 s->spill_fd = -1; 624 if (lim) s->limits = *lim; else js_limits_default(&s->limits); 625 if (!s->limits.max_reals || !s->limits.max_branches || 626 s->limits.max_branches > JS_MAX_BRANCHES) return JS_ERR_ARG; 627 s->slab_chunks = (s->limits.max_reals + JS_SLAB_CHUNK - 1) / JS_SLAB_CHUNK; 628 s->slab = calloc(s->slab_chunks, sizeof *s->slab); 629 if (!s->slab) return JS_ERR_NOMEM; 630 pthread_mutexattr_t a; 631 pthread_mutexattr_init(&a); 632 pthread_mutexattr_settype(&a, PTHREAD_MUTEX_RECURSIVE); 633 int prc = pthread_mutex_init(&s->mu, &a); 634 pthread_mutexattr_destroy(&a); 635 if (prc) { free(s->slab); s->slab = NULL; return JS_ERR_NOMEM; } 636 s->mu_ready = true; 637 s->reuse_enabled = true; 638 return JS_OK; 639 } 640 641 int js_space_init_limits(JsSpace *s, const char *spill_path, const JsLimits *lim) { 642 int rc = space_setup(s, lim); 643 if (rc) return rc; 644 s->spill_fd = open(spill_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); 645 if (s->spill_fd < 0) { js_space_destroy(s); return JS_ERR_IO; } 646 unlink(spill_path); /* anonymous from here on */ 647 return JS_OK; 648 } 649 650 int js_space_init(JsSpace *s, const char *spill_path) { 651 return js_space_init_limits(s, spill_path, NULL); 652 } 653 654 void js_space_destroy(JsSpace *s) { 655 if (s->mu_ready) LOCK(s); 656 for (uint32_t i = 0; i < s->n_branches; i++) 657 if (s->branches[i]) release_u(s, i); 658 if (s->spill_fd >= 0) close(s->spill_fd); 659 s->spill_fd = -1; 660 free(s->cache_bytes); 661 s->cache_bytes = NULL; 662 s->cache_r = NULL; 663 s->cache_len = 0; 664 for (uint32_t k = 0; s->slab && k < s->slab_chunks; k++) { 665 JsReal *c = s->slab[k]; 666 /* Realizations no branch holds (none after the releases above, unless 667 * a load failed half way) still own heap buffers. */ 668 for (uint32_t i = 0; c && i < JS_SLAB_CHUNK; i++) { 669 free(c[i].bytes); free(c[i].packed); free(c[i].edit_bytes); 670 } 671 free(c); 672 } 673 free(s->slab); s->slab = NULL; 674 free(s->ext_free); s->ext_free = NULL; 675 free(s->ext_pending); s->ext_pending = NULL; 676 free(s->dir); s->dir = NULL; 677 if (s->mu_ready) { 678 UNLOCK(s); 679 pthread_mutex_destroy(&s->mu); 680 s->mu_ready = false; 681 } 682 } 683 684 static JsBranch *branch_at(JsSpace *s, uint32_t id) { 685 return id < s->n_branches ? s->branches[id] : NULL; 686 } 687 688 static JsBranch *branch_ref_at(JsSpace *s, JsBranchRef ref) { 689 JsBranch *b = branch_at(s, ref.id); 690 return b && b->gen == ref.gen ? b : NULL; 691 } 692 693 static int branch_push(JsBranch *b, JsReal *r) { 694 if (b->n_units == b->cap_units) { 695 uint32_t cap = b->cap_units ? b->cap_units * 2 : 64; 696 JsReal **u = realloc(b->units, cap * sizeof *u); 697 if (!u) return JS_ERR_NOMEM; 698 b->units = u; 699 b->cap_units = cap; 700 } 701 b->units[b->n_units++] = r; 702 r->refs++; 703 r->holders++; 704 return JS_OK; 705 } 706 707 /* A released slot is reused before a new one is taken; its generation moved 708 * on at release, so old references to it are stale. */ 709 static int branch_room(const JsSpace *s) { 710 return s->n_free_branch || s->n_branches < s->limits.max_branches ? JS_OK : JS_ERR_FULL; 711 } 712 713 static int branch_alloc(JsSpace *s, const JsRealizer *rz, uint32_t *out) { 714 if (branch_room(s)) return JS_ERR_FULL; 715 JsBranch *b = calloc(1, sizeof *b); 716 if (!b) return JS_ERR_NOMEM; 717 uint32_t id = s->n_free_branch ? s->free_branch[--s->n_free_branch] : s->n_branches++; 718 b->branch_id = id; 719 b->realizer = rz; 720 b->gen = s->branch_gen[id]; 721 b->home = s->local_home; 722 b->home.locality = JS_HOME_LOCAL; 723 s->branches[id] = b; 724 *out = id; 725 return JS_OK; 726 } 727 728 /* A new realization's bytes are ready in `bytes`: fix its content check, 729 * make it HOT and file it in the reuse index. */ 730 static void real_publish(JsSpace *s, JsReal *r, uint8_t *bytes) { 731 content_check(bytes, r->realizer->unit_bytes, r->content); 732 set_hot(s, r, bytes); 733 index_insert(s, r); 734 } 735 736 static int root_u(JsSpace *s, const JsRealizer *rz, uint64_t seed, uint32_t *out) { 737 if (!rz || !rz->derive || !rz->unit_bytes) return JS_ERR_ARG; 738 JsSemId sid = js_sem_root(seed); 739 JsReal *r = s->reuse_enabled ? index_find(s, &sid, rz->type) : NULL; 740 int rc = branch_room(s); 741 if (!rc && !r) rc = room(s, 1, rz->unit_bytes); 742 if (rc) return rc; 743 uint32_t id; 744 if ((rc = branch_alloc(s, rz, &id))) return rc; 745 JsBranch *b = s->branches[id]; 746 b->parent_branch = UINT32_MAX; 747 b->common_ancestor = id; 748 if (r) { 749 s->stats.actions[JS_ACT_REUSE]++; 750 } else { 751 uint8_t *bytes = malloc(rz->unit_bytes); 752 if (!bytes || !(r = real_new(s, rz, sid, NULL, JS_RECIPE_ROOT))) { 753 free(bytes); release_u(s, id); return JS_ERR_NOMEM; 754 } 755 r->token = seed; 756 rz->derive(NULL, seed, bytes, rz->unit_bytes); 757 s->stats.derives++; 758 real_publish(s, r, bytes); 759 } 760 rc = branch_push(b, r); 761 if (rc) { if (!r->refs) { r->refs = 1; real_unref(s, r); } release_u(s, id); return rc; } 762 *out = id; 763 return rc; 764 } 765 766 static int fork_u(JsSpace *s, uint32_t parent, uint32_t *out) { 767 JsBranch *p = branch_at(s, parent); 768 if (!p) return JS_ERR_ARG; 769 if (p->home.locality != JS_HOME_LOCAL) return JS_ERR_REMOTE; 770 uint32_t id; 771 int rc = branch_alloc(s, p->realizer, &id); 772 if (rc) return rc; 773 JsBranch *b = s->branches[id]; 774 b->parent_branch = parent; 775 b->common_ancestor = p->common_ancestor; 776 b->divergence_point = p->n_units; 777 b->units = malloc((p->n_units + 64) * sizeof *b->units); 778 if (!b->units) { release_u(s, id); return JS_ERR_NOMEM; } 779 b->cap_units = p->n_units + 64; 780 memcpy(b->units, p->units, p->n_units * sizeof *b->units); 781 b->n_units = p->n_units; 782 for (uint32_t i = 0; i < p->n_units; i++) { p->units[i]->refs++; p->units[i]->holders++; } 783 s->stats.actions[JS_ACT_REFERENCE] += p->n_units; 784 p->frozen = true; 785 *out = id; 786 return JS_OK; 787 } 788 789 static int ensure_hot(JsSpace *s, JsReal *r) { 790 if (r->placement == JS_PLACE_HOT || r->placement == JS_PLACE_COLD) return JS_OK; 791 return restore_u(s, r); 792 } 793 794 static bool is_resident_raw(const JsReal *r) { 795 return r->placement == JS_PLACE_HOT || r->placement == JS_PLACE_COLD; 796 } 797 798 static int derive_u(JsSpace *s, uint32_t bid, uint64_t token) { 799 JsBranch *b = branch_at(s, bid); 800 if (!b || !b->n_units) return JS_ERR_ARG; 801 if (b->home.locality != JS_HOME_LOCAL) return JS_ERR_REMOTE; 802 if (b->frozen) return JS_ERR_FROZEN; 803 JsReal *prev = b->units[b->n_units - 1]; 804 JsSemId sid = js_sem_derive(&prev->semantic_state_id, token); 805 JsReal *r = s->reuse_enabled ? index_find(s, &sid, b->realizer->type) : NULL; 806 if (r) { 807 s->stats.actions[JS_ACT_REUSE]++; 808 return branch_push(b, r); 809 } 810 size_t n = b->realizer->unit_bytes; 811 int rc = room(s, 1, n + (is_resident_raw(prev) ? 0 : n - resident_of(prev))); 812 if (rc) return rc; 813 rc = ensure_hot(s, prev); 814 if (rc) return rc; 815 uint8_t *bytes = malloc(n); 816 if (!bytes || !(r = real_new(s, b->realizer, sid, prev, JS_RECIPE_DERIVE))) { 817 free(bytes); return JS_ERR_NOMEM; 818 } 819 r->token = token; 820 b->realizer->derive(prev->bytes, token, bytes, n); 821 s->stats.derives++; 822 real_publish(s, r, bytes); 823 return branch_push(b, r); 824 } 825 826 static int edit_u(JsSpace *s, uint32_t bid, uint32_t idx, uint32_t off, 827 const uint8_t *patch, uint32_t len) { 828 JsBranch *b = branch_at(s, bid); 829 if (!b || idx >= b->n_units || !len || off + (uint64_t)len > b->realizer->unit_bytes) 830 return JS_ERR_ARG; 831 if (b->home.locality != JS_HOME_LOCAL) return JS_ERR_REMOTE; 832 if (b->frozen) return JS_ERR_FROZEN; 833 JsReal *old = b->units[idx]; 834 JsSemId sid = js_sem_edit(&old->semantic_state_id, off, patch, len); 835 JsReal *r = s->reuse_enabled ? index_find(s, &sid, b->realizer->type) : NULL; 836 if (!r) { 837 bool take = old->refs == 1 && is_resident_raw(old); 838 int rc = room(s, 1, take ? 0 : b->realizer->unit_bytes); 839 if (rc) return rc; 840 } 841 if (r) { 842 s->stats.actions[JS_ACT_REUSE]++; 843 r->refs++; r->holders++; 844 } else { 845 size_t n = b->realizer->unit_bytes; 846 uint8_t *edit = malloc(len), *bytes = NULL; 847 if (!edit || !(r = real_new(s, b->realizer, sid, old, JS_RECIPE_EDIT))) { 848 free(edit); return JS_ERR_NOMEM; 849 } 850 memcpy(edit, patch, len); 851 r->edit_off = off; r->edit_len = len; r->edit_bytes = edit; 852 /* Exclusively held and resident: take the buffer instead of copying. The 853 * old realization keeps its recipe and becomes EVICTED; the new one holds 854 * it as its parent, so it can still be rebuilt. */ 855 if (old->refs == 1 && (old->placement == JS_PLACE_HOT || old->placement == JS_PLACE_COLD)) { 856 charge(s, old, -1); 857 bytes = old->bytes; 858 old->bytes = NULL; 859 old->placement = JS_PLACE_EVICTED; 860 } else { 861 bytes = malloc(n); 862 if (!bytes) { r->refs = 1; real_unref(s, r); return JS_ERR_NOMEM; } 863 if (old->placement == JS_PLACE_HOT || old->placement == JS_PLACE_COLD) { 864 memcpy(bytes, old->bytes, n); 865 s->stats.actions[JS_ACT_COPY]++; 866 s->stats.bytes_copied += n; 867 } else { 868 int rc = materialize(s, old, bytes); /* counts RECOMPUTE where it rebuilds */ 869 if (rc) { free(bytes); r->refs = 1; real_unref(s, r); return rc; } 870 } 871 } 872 memcpy(bytes + off, patch, len); 873 real_publish(s, r, bytes); 874 r->refs++; r->holders++; 875 } 876 b->units[idx] = r; 877 old->holders--; 878 real_unref(s, old); 879 return JS_OK; 880 } 881 882 static int read_u(JsSpace *s, uint32_t bid, uint32_t idx, uint8_t *out) { 883 JsBranch *b = branch_at(s, bid); 884 if (!b || idx >= b->n_units) return JS_ERR_ARG; 885 JsReal *r = b->units[idx]; 886 r->last_use = ++s->clock; 887 r->reads++; 888 if (r->placement == JS_PLACE_HOT || r->placement == JS_PLACE_COLD) { 889 memcpy(out, r->bytes, b->realizer->unit_bytes); 890 return JS_OK; 891 } 892 /* The authoritative bytes live on another machine: fetching them is 893 * Fabric's job, and Fabric does not exist in this build. */ 894 if (b->home.locality == JS_HOME_REMOTE_OWNED) return JS_ERR_REMOTE; 895 return materialize(s, r, out); 896 } 897 898 static int digest_u(JsSpace *s, uint32_t bid, uint8_t out[32]) { 899 JsBranch *b = branch_at(s, bid); 900 if (!b) return JS_ERR_ARG; 901 size_t n = b->realizer->unit_bytes; 902 uint8_t *buf = malloc(n); 903 if (!buf) return JS_ERR_NOMEM; 904 sha256_ctx c; 905 sha256_init(&c); 906 int rc = JS_OK; 907 for (uint32_t i = 0; i < b->n_units && rc == JS_OK; i++) { 908 rc = read_u(s, bid, i, buf); 909 if (rc == JS_OK) sha256_update(&c, buf, n); 910 } 911 sha256_final(&c, out); 912 free(buf); 913 return rc; 914 } 915 916 static int release_u(JsSpace *s, uint32_t bid) { 917 JsBranch *b = branch_at(s, bid); 918 if (!b) return JS_ERR_ARG; 919 for (uint32_t i = 0; i < b->n_units; i++) { 920 b->units[i]->holders--; 921 real_unref(s, b->units[i]); 922 } 923 free(b->units); 924 free(b); 925 s->branches[bid] = NULL; 926 /* Every old reference is now stale. A slot whose next generation would be 927 * JS_BRANCH_GEN_RETIRED retires: the marker stays and the slot is never 928 * handed out again (32-bit generations: the ref packs into a World field). */ 929 if (s->branch_gen[bid] < JS_BRANCH_GEN_RETIRED) s->branch_gen[bid]++; 930 if (s->branch_gen[bid] != JS_BRANCH_GEN_RETIRED) s->free_branch[s->n_free_branch++] = bid; 931 return JS_OK; 932 } 933 934 /* ---- costs ----------------------------------------------------------------- */ 935 936 /* Expected cost of producing r's bytes from its current physical state. */ 937 static double restore_cost(const JsSpace *s, const JsReal *r) { 938 const JsCosts *c = &s->costs; 939 double n = (double)r->realizer->unit_bytes, cost = 0; 940 uint32_t guard = 0; 941 for (const JsReal *x = r; x && guard < 1u << 20; x = x->parent_realization, guard++) { 942 switch (x->placement) { 943 case JS_PLACE_HOT: case JS_PLACE_COLD: return cost + (x == r ? 0 : n * c->copy_ns_per_byte); 944 case JS_PLACE_SPILLED: return cost + n * c->spill_read_ns_per_byte; 945 case JS_PLACE_COMPRESSED: cost += n * c->decompress_ns_per_byte; break; 946 default: 947 cost += x->recipe == JS_RECIPE_EDIT ? n * c->copy_ns_per_byte : c->derive_ns; 948 if (x->recipe == JS_RECIPE_ROOT) return cost; 949 } 950 } 951 return cost; 952 } 953 954 static double predicted_packed(const JsSpace *s, const JsReal *r) { 955 double n = (double)r->realizer->unit_bytes; 956 if (r->recipe == JS_RECIPE_EDIT) return (double)r->edit_len + 16.0; 957 return n * s->costs.compress_ratio; 958 } 959 960 /* Expected cost if r were rebuilt by recipe from its parent's current state. */ 961 static double recompute_cost(const JsSpace *s, const JsReal *r) { 962 double n = (double)r->realizer->unit_bytes; 963 double own = r->recipe == JS_RECIPE_EDIT ? n * s->costs.copy_ns_per_byte : s->costs.derive_ns; 964 if (!r->parent_realization) return own; 965 return own + restore_cost(s, r->parent_realization); 966 } 967 968 /* Expected future reads: every branch holding r may read it again. */ 969 static double expected_reads(const JsReal *r) { 970 return (double)(r->holders ? r->holders : 1); 971 } 972 973 /* One alternative the residency chooser builds: its cost inputs. Its score 974 * (nanoseconds of expected work per byte given back) goes to score[] below. */ 975 typedef struct { JsAction a; double now, later, freed; } Alt; 976 977 /* The residency decision for one candidate, with its working set exposed: 978 * opt[0..*k_out) are the alternatives in build order (MOVE, COMPRESS, SPILL, 979 * EVICT), score[i] the score of opt[i] when it frees bytes (untouched when it 980 * does not); *best_out is the cheapest score (0 when none). choose() is this 981 * decision with the working set dropped. 982 * DUAL-3a observation reads the working set; nothing else does. */ 983 static JsAction decide(const JsSpace *s, const JsReal *r, double pressure, bool allow_move, 984 Alt opt[4], double score[4], int *k_out, double *best_out) { 985 const JsCosts *c = &s->costs; 986 double n = (double)r->realizer->unit_bytes; 987 double e = expected_reads(r); 988 double best = 0; 989 JsAction act = JS_ACT_COUNT; /* keep */ 990 *k_out = 0; 991 *best_out = 0; 992 if (r->placement != JS_PLACE_HOT && r->placement != JS_PLACE_COLD && 993 r->placement != JS_PLACE_COMPRESSED) return JS_ACT_COUNT; 994 double held = r->placement == JS_PLACE_COMPRESSED ? (double)r->packed_len : n; 995 int k = 0; 996 if (r->placement == JS_PLACE_HOT && allow_move) { 997 /* MOVE frees hot-arena bytes, not total residency. */ 998 opt[k++] = (typeof(opt[0])){ JS_ACT_MOVE, n * c->move_ns_per_byte, 0, n * 0.5 }; 999 } 1000 if (r->placement != JS_PLACE_COMPRESSED) { 1001 double p = predicted_packed(s, r); 1002 if (p < n) 1003 /* A delta is decoded against its parent's bytes, so restoring it 1004 * also pays for producing those. */ 1005 opt[k++] = (typeof(opt[0])){ JS_ACT_COMPRESS, n * c->compress_ns_per_byte, 1006 n * c->decompress_ns_per_byte + 1007 (r->parent_realization ? restore_cost(s, r->parent_realization) : 0), 1008 n - p }; 1009 } 1010 opt[k++] = (typeof(opt[0])){ JS_ACT_SPILL, n * c->spill_write_ns_per_byte, 1011 n * c->spill_read_ns_per_byte, held }; 1012 opt[k++] = (typeof(opt[0])){ JS_ACT_EVICT, 0, recompute_cost(s, r), held }; 1013 for (int i = 0; i < k; i++) { 1014 if (opt[i].freed <= 0) continue; 1015 /* nanoseconds of expected work per byte of residency given back */ 1016 double cost = (opt[i].now + e * opt[i].later) / opt[i].freed; 1017 score[i] = cost; 1018 if (act == JS_ACT_COUNT || cost < best) { best = cost; act = opt[i].a; } 1019 } 1020 *k_out = k; 1021 *best_out = best; 1022 /* Keep when holding the bytes is cheaper than the best way to give them up. */ 1023 if (act != JS_ACT_COUNT && best >= pressure * c->retain_ns_per_byte) return JS_ACT_COUNT; 1024 return act; 1025 } 1026 1027 static JsAction choose(const JsSpace *s, const JsReal *r, double pressure, bool allow_move) { 1028 Alt opt[4]; 1029 double score[4]; 1030 int k; 1031 double best; 1032 return decide(s, r, pressure, allow_move, opt, score, &k, &best); 1033 } 1034 1035 /* ---- DUAL-3a decision-site observation ("jspace.residency", rx_jspace.h) -- */ 1036 1037 static uint8_t *put_u8(uint8_t *p, uint64_t v) { *p = (uint8_t)v; return p + 1; } 1038 static uint8_t *put_u32(uint8_t *p, uint32_t v) { 1039 for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); 1040 return p + 4; 1041 } 1042 static uint8_t *put_u64(uint8_t *p, uint64_t v) { 1043 for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); 1044 return p + 8; 1045 } 1046 static uint8_t *put_f64(uint8_t *p, double d) { 1047 uint64_t v; 1048 memcpy(&v, &d, 8); 1049 return put_u64(p, v); 1050 } 1051 1052 size_t js_dual_observation_encode(const JsDualObservation *o, uint8_t out[JS_DUAL_OBS_BYTES]) { 1053 uint8_t *p = out; 1054 p = put_u8(p, o->kind); 1055 p = put_u8(p, o->version); 1056 p = put_u8(p, JS_DUAL_SITE_ID_LEN); 1057 memcpy(p, JS_DUAL_SITE_ID, JS_DUAL_SITE_ID_LEN); p += JS_DUAL_SITE_ID_LEN; 1058 p = put_u64(p, o->seq); 1059 p = put_f64(p, o->pressure); 1060 p = put_u8(p, o->pressure_case); 1061 p = put_u8(p, o->allow_move); 1062 p = put_u8(p, o->chosen); 1063 p = put_u8(p, o->n_priced); 1064 for (unsigned i = 0; i < JS_DUAL_OBS_N_ALT; i++) { 1065 p = put_u8(p, o->alt[i].action); 1066 p = put_u8(p, o->alt[i].status); 1067 p = put_f64(p, o->alt[i].now_ns); 1068 p = put_f64(p, o->alt[i].later_ns); 1069 p = put_f64(p, o->alt[i].freed_bytes); 1070 p = put_f64(p, o->alt[i].score); 1071 } 1072 p = put_f64(p, o->best_score); 1073 p = put_f64(p, o->keep_threshold); 1074 p = put_f64(p, o->expected_reads); 1075 p = put_u32(p, o->real_slot); 1076 p = put_u64(p, o->real_gen); 1077 p = put_u8(p, o->real_type); 1078 p = put_u8(p, o->placement); 1079 p = put_u8(p, o->recipe); 1080 p = put_u64(p, o->unit_bytes); 1081 p = put_u64(p, o->held_bytes); 1082 p = put_u32(p, o->holders); 1083 p = put_u32(p, o->refs); 1084 p = put_u64(p, o->last_use); 1085 memcpy(p, o->semantic_state_id, 32); p += 32; 1086 p = put_u64(p, o->budget_bytes); 1087 p = put_u64(p, o->resident_bytes); 1088 p = put_u64(p, o->hot_bytes); 1089 return (size_t)(p - out); 1090 } 1091 1092 void js_dual_set_observer(JsSpace *s, JsDualObserver fn, const void *ctx) { 1093 LOCK(s); 1094 s->dual_observer = fn; 1095 s->dual_ctx = fn ? ctx : NULL; 1096 UNLOCK(s); 1097 } 1098 1099 /* The same decision as choose(), followed by one observation record handed to 1100 * the observer. The returned action is the chooser's own local result; the 1101 * record is a copy the observer cannot act through. */ 1102 static JsAction observed_u(JsSpace *s, const JsReal *r, double pressure, bool over_total, 1103 uint64_t budget_bytes, uint64_t hot) { 1104 Alt opt[4]; 1105 double score[4] = { 0, 0, 0, 0 }; 1106 int k; 1107 double best; 1108 JsAction a = decide(s, r, pressure, !over_total, opt, score, &k, &best); 1109 JsDualObservation o; 1110 memset(&o, 0, sizeof o); 1111 o.kind = JS_DUAL_OBS_KIND; 1112 o.version = JS_DUAL_OBS_VERSION; 1113 o.seq = ++s->dual_seq; 1114 o.pressure = pressure; 1115 o.pressure_case = over_total ? JS_DUAL_PRESSURE_CAPACITY : JS_DUAL_PRESSURE_SOFT; 1116 o.allow_move = !over_total; 1117 o.chosen = (uint8_t)a; 1118 for (unsigned i = 0; i < JS_DUAL_OBS_N_ALT; i++) { 1119 o.alt[i].action = (uint8_t)(JS_ACT_MOVE + i); 1120 o.alt[i].status = JS_DUAL_ALT_INADMISSIBLE; 1121 } 1122 for (int i = 0; i < k; i++) { 1123 JsDualAlternative *d = &o.alt[opt[i].a - JS_ACT_MOVE]; 1124 d->status = opt[i].freed > 0 ? JS_DUAL_ALT_PRICED : JS_DUAL_ALT_UNPRICED; 1125 d->now_ns = opt[i].now; 1126 d->later_ns = opt[i].later; 1127 d->freed_bytes = opt[i].freed; 1128 d->score = score[i]; 1129 if (opt[i].freed > 0) o.n_priced++; 1130 } 1131 o.best_score = best; 1132 o.keep_threshold = pressure * s->costs.retain_ns_per_byte; 1133 o.expected_reads = expected_reads(r); 1134 o.real_slot = r->slot; 1135 o.real_gen = r->gen; 1136 o.real_type = (uint8_t)r->realization_type; 1137 o.placement = (uint8_t)r->placement; 1138 o.recipe = (uint8_t)r->recipe; 1139 o.unit_bytes = r->realizer->unit_bytes; 1140 o.held_bytes = resident_of(r); 1141 o.holders = r->holders; 1142 o.refs = r->refs; 1143 o.last_use = r->last_use; 1144 memcpy(o.semantic_state_id, r->semantic_state_id.b, 32); 1145 o.budget_bytes = budget_bytes; 1146 o.resident_bytes = s->stats.resident_bytes; 1147 o.hot_bytes = hot; 1148 uint8_t enc[JS_DUAL_OBS_BYTES]; 1149 size_t len = js_dual_observation_encode(&o, enc); 1150 sha256_ctx h; 1151 sha256_init(&h); 1152 /* domain string including its terminating zero byte */ 1153 sha256_update(&h, (const uint8_t *)JS_DUAL_OBS_DOMAIN, sizeof JS_DUAL_OBS_DOMAIN); 1154 sha256_update(&h, enc, len); 1155 sha256_final(&h, o.digest); 1156 s->dual_observer(&o, s->dual_ctx); 1157 return a; 1158 } 1159 1160 JsAction js_forge_choose(const JsSpace *s, const JsReal *r, double pressure) { 1161 return choose(s, r, pressure, true); 1162 } 1163 1164 typedef struct { JsReal *r; double score; } Cand; 1165 1166 static int cand_cmp(const void *a, const void *b) { 1167 const Cand *x = a, *y = b; 1168 return (x->score > y->score) - (x->score < y->score); 1169 } 1170 1171 static uint64_t hot_bytes(const JsSpace *s, Cand *cs, uint32_t n) { 1172 uint64_t h = 0; 1173 (void)s; 1174 for (uint32_t i = 0; i < n; i++) 1175 if (cs[i].r->placement == JS_PLACE_HOT) h += cs[i].r->realizer->unit_bytes; 1176 return h; 1177 } 1178 1179 /* Collect every live realization once (through the branches that hold them). */ 1180 static uint32_t collect(JsSpace *s, Cand **out) { 1181 uint32_t cap = 1024, n = 0; 1182 Cand *cs = malloc(cap * sizeof *cs); 1183 for (uint32_t k = 0; k < JS_INDEX_BUCKETS && cs; k++) 1184 for (JsReal *r = s->index[k]; r; r = r->index_next) { 1185 if (n == cap) { 1186 Cand *nc = realloc(cs, (cap *= 2) * sizeof *cs); 1187 if (!nc) { free(cs); cs = NULL; break; } 1188 cs = nc; 1189 } 1190 cs[n].r = r; cs[n].score = 0; n++; 1191 } 1192 *out = cs; 1193 return cs ? n : 0; 1194 } 1195 1196 /* Bring resident bytes (HOT + COLD + COMPRESSED) under budget_bytes and hot 1197 * bytes under half of it. Candidates are ranked by the expected nanoseconds of 1198 * future work per byte given back, least-used first on ties. */ 1199 static int enforce_u(JsSpace *s, uint64_t budget_bytes, JsPolicyReport *rep) { 1200 Cand *cs; 1201 uint32_t n = collect(s, &cs); 1202 if (!cs) return JS_ERR_NOMEM; 1203 uint64_t hot = hot_bytes(s, cs, n); 1204 for (uint32_t i = 0; i < n; i++) { 1205 JsReal *r = cs[i].r; 1206 cs[i].score = expected_reads(r) * recompute_cost(s, r) / (double)r->realizer->unit_bytes 1207 + (double)r->last_use * 1e-6; 1208 } 1209 qsort(cs, n, sizeof *cs, cand_cmp); 1210 int rc = JS_OK; 1211 for (uint32_t i = 0; i < n && rc == JS_OK; i++) { 1212 bool over_total = s->stats.resident_bytes > budget_bytes; 1213 bool over_hot = hot > budget_bytes / 2; 1214 if (!over_total && !over_hot) break; 1215 JsReal *r = cs[i].r; 1216 double pressure = over_total ? 1e9 : 1e3; 1217 /* A move lowers hot-arena bytes, not total residency. */ 1218 JsAction a = s->dual_observer ? observed_u(s, r, pressure, over_total, budget_bytes, hot) 1219 : choose(s, r, pressure, !over_total); 1220 if (rep) rep->considered++; 1221 if (a == JS_ACT_COUNT) { if (rep) rep->kept++; continue; } 1222 uint64_t before_hot = r->placement == JS_PLACE_HOT ? r->realizer->unit_bytes : 0; 1223 switch (a) { 1224 case JS_ACT_MOVE: rc = move_u(s, r); break; 1225 case JS_ACT_COMPRESS: rc = compress_u(s, r); break; 1226 case JS_ACT_SPILL: rc = spill_u(s, r); break; 1227 case JS_ACT_EVICT: rc = evict_u(s, r); break; 1228 default: break; 1229 } 1230 if (rc == JS_OK) { 1231 hot -= before_hot; 1232 if (rep) rep->chosen[a]++; 1233 } 1234 } 1235 free(cs); 1236 return rc; 1237 } 1238 1239 /* ---- calibration ------------------------------------------------------------ */ 1240 1241 static int calibrate_u(JsSpace *s, const JsRealizer *rz) { 1242 if (!rz || !rz->derive || rz->unit_bytes == 0) return JS_ERR_ARG; 1243 size_t n = rz->unit_bytes; 1244 const int reps = 32; 1245 uint8_t *a = malloc(n), *b = malloc(n), *p = malloc(n + (n / 8) * 8 + 16); 1246 if (!a || !b || !p) { free(a); free(b); free(p); return JS_ERR_NOMEM; } 1247 JsCosts *c = &s->costs; 1248 rz->derive(NULL, 7, a, n); 1249 uint64_t t0 = now_ns(); 1250 for (int i = 0; i < reps; i++) { rz->derive(a, (uint64_t)i, b, n); memcpy(a, b, n); } 1251 uint64_t t1 = now_ns(); 1252 for (int i = 0; i < reps; i++) memcpy(b, a, n), a[(size_t)i % n] ^= 1; 1253 uint64_t t2 = now_ns(); 1254 c->derive_ns = (double)(t1 - t0) / reps - (double)(t2 - t1) / reps; 1255 if (c->derive_ns < 1) c->derive_ns = 1; 1256 c->copy_ns_per_byte = (double)(t2 - t1) / reps / (double)n; 1257 c->move_ns_per_byte = c->copy_ns_per_byte; 1258 1259 /* Compression of a derive step's delta: what a DERIVE realization packs to. */ 1260 rz->derive(a, 99, b, n); 1261 size_t len = 0; 1262 t0 = now_ns(); 1263 for (int i = 0; i < reps; i++) len = pack_delta(b, a, n, p); 1264 t1 = now_ns(); 1265 for (int i = 0; i < reps; i++) unpack_delta(p, len, a, n, b); 1266 t2 = now_ns(); 1267 c->compress_ratio = (double)len / (double)n; 1268 c->compress_ns_per_byte = (double)(t1 - t0) / reps / (double)n; 1269 c->decompress_ns_per_byte = (double)(t2 - t1) / reps / (double)n; 1270 1271 t0 = now_ns(); 1272 for (int i = 0; i < reps; i++) 1273 if (pwrite(s->spill_fd, a, n, (off_t)(s->spill_end + (uint64_t)i * n)) != (ssize_t)n) break; 1274 fdatasync(s->spill_fd); 1275 t1 = now_ns(); 1276 for (int i = 0; i < reps; i++) 1277 if (pread(s->spill_fd, b, n, (off_t)(s->spill_end + (uint64_t)i * n)) != (ssize_t)n) break; 1278 t2 = now_ns(); 1279 /* Scratch past every named extent: give the space back. */ 1280 if (ftruncate(s->spill_fd, (off_t)s->spill_end)) { /* keep the measurement */ } 1281 c->spill_write_ns_per_byte = (double)(t1 - t0) / reps / (double)n; 1282 c->spill_read_ns_per_byte = (double)(t2 - t1) / reps / (double)n; 1283 1284 /* Price of residency: faulting in fresh memory for someone else. */ 1285 size_t m = n * 64; 1286 t0 = now_ns(); 1287 uint8_t *f = mmap(NULL, m, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 1288 if (f != MAP_FAILED) { 1289 for (size_t i = 0; i < m; i += 4096) f[i] = 1; 1290 munmap(f, m); 1291 } 1292 t1 = now_ns(); 1293 c->retain_ns_per_byte = (double)(t1 - t0) / (double)m; 1294 free(a); free(b); free(p); 1295 return JS_OK; 1296 } 1297 1298 /* ---- inspection ------------------------------------------------------------- */ 1299 1300 static void realization_u(JsSpace *s, uint32_t bid, JsSharedStateRealization *out) { 1301 memset(out, 0, sizeof *out); 1302 JsBranch *b = branch_at(s, bid); 1303 if (!b) return; 1304 out->semantic_state_id = js_branch_semantic_id(b); 1305 out->realization_type = b->realizer->type; 1306 out->parent_realization = b->parent_branch; 1307 for (uint32_t i = 0; i < b->n_units; i++) { 1308 JsReal *r = b->units[i]; 1309 if (r->holders > 1) out->n_shared++; else out->n_private++; 1310 out->resident_bytes += resident_of(r); 1311 if (r->placement < 6) out->placement_count[r->placement]++; 1312 out->recompute_cost_ns += recompute_cost(s, r); 1313 out->transfer_cost_ns += (double)r->realizer->unit_bytes * s->costs.copy_ns_per_byte; 1314 out->retain_cost_ns += (double)resident_of(r) * s->costs.retain_ns_per_byte; 1315 out->eviction_cost_ns += expected_reads(r) * recompute_cost(s, r); 1316 } 1317 } 1318 1319 const char *js_action_name(JsAction a) { 1320 static const char *n[] = { "reuse", "copy", "reference", "recompute", "move", 1321 "compress", "spill", "evict" }; 1322 return a < JS_ACT_COUNT ? n[a] : "keep"; 1323 } 1324 1325 const char *js_placement_name(JsPlacement p) { 1326 static const char *n[] = { "?", "hot", "cold", "compressed", "spilled", "evicted" }; 1327 return p <= JS_PLACE_EVICTED ? n[p] : "?"; 1328 } 1329 1330 const char *js_real_type_name(JsRealType t) { 1331 static const char *n[] = { "?", "latent_checkpoint", "activation_checkpoint", "kv_state", 1332 "compiled_features", "world_projection", "cortex_projection", 1333 "physical_tensor" }; 1334 return t <= JS_REAL_PHYSICAL_TENSOR ? n[t] : "?"; 1335 } 1336 1337 /* ---- public entry points: one recursive space mutex ------------------------ */ 1338 1339 #define LOCKED_INT(call) do { LOCK(s); int rc_ = (call); UNLOCK(s); return rc_; } while (0) 1340 1341 int js_real_restore(JsSpace *s, JsReal *r) { LOCKED_INT(restore_u(s, r)); } 1342 int js_real_move(JsSpace *s, JsReal *r) { LOCKED_INT(move_u(s, r)); } 1343 int js_real_compress(JsSpace *s, JsReal *r) { LOCKED_INT(compress_u(s, r)); } 1344 int js_real_spill(JsSpace *s, JsReal *r) { LOCKED_INT(spill_u(s, r)); } 1345 int js_real_evict(JsSpace *s, JsReal *r) { LOCKED_INT(evict_u(s, r)); } 1346 1347 int js_branch_root(JsSpace *s, const JsRealizer *rz, uint64_t seed, uint32_t *out) { 1348 LOCKED_INT(root_u(s, rz, seed, out)); 1349 } 1350 int js_branch_fork(JsSpace *s, uint32_t parent, uint32_t *out) { LOCKED_INT(fork_u(s, parent, out)); } 1351 int js_branch_derive(JsSpace *s, uint32_t b, uint64_t token) { LOCKED_INT(derive_u(s, b, token)); } 1352 int js_branch_edit(JsSpace *s, uint32_t b, uint32_t idx, uint32_t off, 1353 const uint8_t *patch, uint32_t len) { 1354 LOCKED_INT(edit_u(s, b, idx, off, patch, len)); 1355 } 1356 int js_branch_read(JsSpace *s, uint32_t b, uint32_t idx, uint8_t *out) { 1357 LOCKED_INT(read_u(s, b, idx, out)); 1358 } 1359 int js_branch_content_digest(JsSpace *s, uint32_t b, uint8_t out[32]) { 1360 LOCKED_INT(digest_u(s, b, out)); 1361 } 1362 int js_branch_release(JsSpace *s, uint32_t b) { LOCKED_INT(release_u(s, b)); } 1363 int js_forge_enforce(JsSpace *s, uint64_t budget_bytes, JsPolicyReport *rep) { 1364 LOCKED_INT(enforce_u(s, budget_bytes, rep)); 1365 } 1366 1367 void js_branch_realization(JsSpace *s, uint32_t b, JsSharedStateRealization *out) { 1368 LOCK(s); realization_u(s, b, out); UNLOCK(s); 1369 } 1370 1371 int js_calibrate(JsSpace *s, const JsRealizer *r) { 1372 LOCK(s); int rc = calibrate_u(s, r); UNLOCK(s); 1373 return rc; 1374 } 1375 1376 /* ---- stable references, ownership, staging, placement ---------------------- */ 1377 1378 int js_branch_ref(JsSpace *s, uint32_t id, JsBranchRef *out) { 1379 LOCK(s); 1380 JsBranch *b = branch_at(s, id); 1381 if (b) *out = (JsBranchRef){ id, b->gen }; 1382 UNLOCK(s); 1383 return b ? JS_OK : JS_ERR_ARG; 1384 } 1385 1386 int js_branch_check(JsSpace *s, JsBranchRef ref) { 1387 LOCK(s); 1388 int rc = branch_ref_at(s, ref) ? JS_OK : JS_ERR_STALE; 1389 UNLOCK(s); 1390 return rc; 1391 } 1392 1393 int js_real_id(JsSpace *s, uint32_t bid, uint32_t idx, JsRealId *out) { 1394 LOCK(s); 1395 JsBranch *b = branch_at(s, bid); 1396 int rc = b && idx < b->n_units ? JS_OK : JS_ERR_ARG; 1397 if (!rc) *out = (JsRealId){ b->units[idx]->slot, b->units[idx]->gen }; 1398 UNLOCK(s); 1399 return rc; 1400 } 1401 1402 JsReal *js_real_lookup(JsSpace *s, JsRealId id) { 1403 LOCK(s); 1404 JsReal *r = slab_at(s, id.slot); 1405 if (r && (r->gen != id.gen || !r->realizer)) r = NULL; 1406 UNLOCK(s); 1407 return r; 1408 } 1409 1410 int js_branch_fork_staged(JsSpace *s, JsBranchRef parent, uint32_t owner, JsBranchRef *out) { 1411 LOCK(s); 1412 uint32_t id = 0; 1413 int rc = branch_ref_at(s, parent) ? fork_u(s, parent.id, &id) : JS_ERR_STALE; 1414 if (!rc) { 1415 JsBranch *b = s->branches[id]; 1416 b->staged = true; 1417 b->owner = owner; 1418 *out = (JsBranchRef){ id, b->gen }; 1419 } 1420 UNLOCK(s); 1421 return rc; 1422 } 1423 1424 int js_branch_seal(JsSpace *s, JsBranchRef ref) { 1425 LOCK(s); 1426 JsBranch *b = branch_ref_at(s, ref); 1427 if (b) b->staged = false; 1428 UNLOCK(s); 1429 return b ? JS_OK : JS_ERR_STALE; 1430 } 1431 1432 int js_branch_release_ref(JsSpace *s, JsBranchRef ref, uint32_t subject) { 1433 LOCK(s); 1434 JsBranch *b = branch_ref_at(s, ref); 1435 int rc = !b ? JS_ERR_STALE 1436 : (b->owner && b->owner != subject) ? JS_ERR_OWNER 1437 : release_u(s, ref.id); 1438 UNLOCK(s); 1439 return rc; 1440 } 1441 1442 uint32_t js_space_reclaim_staged(JsSpace *s) { 1443 LOCK(s); 1444 uint32_t n = 0; 1445 for (uint32_t i = 0; i < s->n_branches; i++) 1446 if (s->branches[i] && s->branches[i]->staged) { release_u(s, i); n++; } 1447 UNLOCK(s); 1448 return n; 1449 } 1450 1451 int js_branch_set_owner(JsSpace *s, JsBranchRef ref, uint32_t owner) { 1452 LOCK(s); 1453 JsBranch *b = branch_ref_at(s, ref); 1454 if (b) b->owner = owner; 1455 UNLOCK(s); 1456 return b ? JS_OK : JS_ERR_STALE; 1457 } 1458 1459 int js_branch_set_home(JsSpace *s, JsBranchRef ref, const JsHome *home) { 1460 if (!home || home->locality > JS_HOME_REPLICA) return JS_ERR_ARG; 1461 LOCK(s); 1462 JsBranch *b = branch_ref_at(s, ref); 1463 if (b) b->home = *home; 1464 UNLOCK(s); 1465 return b ? JS_OK : JS_ERR_STALE; 1466 } 1467 1468 int js_branch_home(JsSpace *s, JsBranchRef ref, JsHome *out) { 1469 LOCK(s); 1470 JsBranch *b = branch_ref_at(s, ref); 1471 if (b) *out = b->home; 1472 UNLOCK(s); 1473 return b ? JS_OK : JS_ERR_STALE; 1474 } 1475 1476 /* ---- durable checkpoint ------------------------------------------------------ 1477 * 1478 * jspace.meta, little-endian, all fixed-width fields: 1479 * header (128 B): "OMJSPC01" | u32 version=3 | u32 header_bytes=128 | 1480 * u64 commit_seq | u64 body_len | u32 n_types | u32 n_reals | 1481 * u32 n_branch_slots | u32 n_branches | u64 spill_end | 1482 * u64 real_gen_floor | sha256(body) | sha256(header[0..96)) 1483 * body: 1484 * n_types x { u32 type | u32 0 | u64 unit_bytes } 1485 * n_branch_slots x u32 slot generation (JS_BRANCH_GEN_RETIRED = retired) 1486 * n_reals x 136 B { u32 slot | u32 parent_slot | u64 gen | u64 parent_gen | 1487 * u32 type | u32 recipe | u64 token | u32 edit_off | 1488 * u32 edit_len | u64 patch_off | u32 placement | u32 0 | 1489 * u64 spill_off | semid[32] | content[32] } 1490 * n_branches x { u32 id | u32 gen | u32 parent | u32 common_ancestor | 1491 * u32 divergence | u32 frozen | u32 owner | u32 locality | 1492 * u32 type | u32 n_units | machine[32] | 1493 * n_units x { u32 slot | u64 gen } } 1494 * Version 3 appends a fixed 48-byte opaque client anchor (u64 count | digest[32] | 1495 * u64 reserved, little-endian) as the last bytes of the body, after the branches, 1496 * covered by the body digest. A version-2 checkpoint (no anchor section) still 1497 * loads with the anchor absent; the next commit writes version 3. 1498 * Version 2 widened realization generations to 64 bits (Lane 32). Version 1 1499 * (32-bit realization generations) is refused with JS_ERR_VERSION, never 1500 * reinterpreted. No pointer is stored. Placement is SPILLED (bytes at spill_off in 1501 * jspace.data) or EVICTED (rebuild from the recipe). EDIT patches live in 1502 * jspace.data at patch_off. Staged branches and realizations only they reach 1503 * are left out. */ 1504 1505 #define JS_META_MAGIC "OMJSPC01" 1506 #define JS_META_VERSION 3u 1507 #define JS_META_VERSION_V2 2u 1508 #define JS_META_ANCHOR 48u 1509 #define JS_META_VERSION_V1 1u 1510 #define JS_META_HDR 128u 1511 #define JS_META_REAL 136u 1512 #define JS_META_UNIT 12u 1513 #define JS_META_BRANCH 72u 1514 1515 typedef struct { uint8_t *p; size_t n, cap; bool oom; } Buf; 1516 1517 static void buf_put(Buf *b, const void *v, size_t n) { 1518 if (b->oom) return; 1519 if (b->n + n > b->cap) { 1520 size_t c = b->cap ? b->cap : 4096; 1521 while (c < b->n + n) c *= 2; 1522 uint8_t *np = realloc(b->p, c); 1523 if (!np) { b->oom = true; return; } 1524 b->p = np; b->cap = c; 1525 } 1526 memcpy(b->p + b->n, v, n); 1527 b->n += n; 1528 } 1529 static void le32(uint8_t *o, uint32_t v) { for (int i = 0; i < 4; i++) o[i] = (uint8_t)(v >> (8 * i)); } 1530 static void le64(uint8_t *o, uint64_t v) { for (int i = 0; i < 8; i++) o[i] = (uint8_t)(v >> (8 * i)); } 1531 static uint32_t rd32(const uint8_t *p) { uint32_t v = 0; for (int i = 3; i >= 0; i--) v = v << 8 | p[i]; return v; } 1532 static uint64_t rd64(const uint8_t *p) { uint64_t v = 0; for (int i = 7; i >= 0; i--) v = v << 8 | p[i]; return v; } 1533 static void put32(Buf *b, uint32_t v) { uint8_t o[4]; le32(o, v); buf_put(b, o, 4); } 1534 static void put64(Buf *b, uint64_t v) { uint8_t o[8]; le64(o, v); buf_put(b, o, 8); } 1535 1536 static char *path_in(const char *dir, const char *name) { 1537 size_t n = strlen(dir) + strlen(name) + 2; 1538 char *p = malloc(n); 1539 if (p) snprintf(p, n, "%s/%s", dir, name); 1540 return p; 1541 } 1542 1543 static int write_all(int fd, const uint8_t *p, size_t n) { 1544 while (n) { 1545 ssize_t w = write(fd, p, n); 1546 if (w < 0) { if (errno == EINTR) continue; return JS_ERR_IO; } 1547 p += w; n -= (size_t)w; 1548 } 1549 return JS_OK; 1550 } 1551 1552 /* Mark every realization a persisted (non-staged) branch reaches. */ 1553 static uint8_t *mark_persisted(JsSpace *s) { 1554 uint8_t *m = calloc(s->real_hw ? s->real_hw : 1, 1); 1555 if (!m) return NULL; 1556 for (uint32_t i = 0; i < s->n_branches; i++) { 1557 JsBranch *b = s->branches[i]; 1558 if (!b || b->staged) continue; 1559 for (uint32_t u = 0; u < b->n_units; u++) 1560 for (JsReal *r = b->units[u]; r && !m[r->slot]; r = r->parent_realization) 1561 m[r->slot] = 1; 1562 } 1563 return m; 1564 } 1565 1566 static int commit_u(JsSpace *s) { 1567 if (!s->durable) return JS_ERR_ARG; 1568 uint8_t *mark = mark_persisted(s); 1569 if (!mark) return JS_ERR_NOMEM; 1570 int rc = JS_OK; 1571 /* 1. Data: every persisted EDIT patch gets an extent. */ 1572 for (uint32_t k = 0; k < s->real_hw && rc == JS_OK; k++) { 1573 JsReal *r = slab_at(s, k); 1574 if (!mark[k] || r->recipe != JS_RECIPE_EDIT || r->patch_off != UINT64_MAX) continue; 1575 uint64_t off; 1576 if ((rc = ext_alloc(s, r->edit_len, &off)) != JS_OK) break; 1577 if (pwrite(s->spill_fd, r->edit_bytes, r->edit_len, (off_t)off) != (ssize_t)r->edit_len) { 1578 ext_free_now(s, off, r->edit_len); 1579 rc = JS_ERR_IO; 1580 break; 1581 } 1582 r->patch_off = off; 1583 } 1584 if (rc == JS_OK && fdatasync(s->spill_fd)) rc = JS_ERR_IO; 1585 if (rc != JS_OK) { free(mark); return rc; } 1586 1587 /* 2. Metadata body. Types are the distinct realizers in use. */ 1588 const JsRealizer *types[64]; 1589 uint32_t n_types = 0, n_reals = 0, n_br = 0; 1590 Buf body = { 0 }; 1591 for (uint32_t i = 0; i < s->n_branches; i++) { 1592 JsBranch *b = s->branches[i]; 1593 if (!b || b->staged) continue; 1594 n_br++; 1595 bool seen = false; 1596 for (uint32_t t = 0; t < n_types; t++) if (types[t] == b->realizer) seen = true; 1597 if (!seen) { 1598 if (n_types == 64) { free(mark); return JS_ERR_FULL; } 1599 types[n_types++] = b->realizer; 1600 } 1601 } 1602 for (uint32_t t = 0; t < n_types; t++) { 1603 put32(&body, (uint32_t)types[t]->type); put32(&body, 0); 1604 put64(&body, (uint64_t)types[t]->unit_bytes); 1605 } 1606 for (uint32_t i = 0; i < s->n_branches; i++) { 1607 JsBranch *b = s->branches[i]; 1608 /* A staged occupant is not persisted: its slot reopens free, one 1609 * generation on, so a reference to it stays stale. */ 1610 put32(&body, b && b->staged ? s->branch_gen[i] + 1 : s->branch_gen[i]); 1611 } 1612 for (uint32_t k = 0; k < s->real_hw; k++) { 1613 if (!mark[k]) continue; 1614 JsReal *r = slab_at(s, k); 1615 n_reals++; 1616 JsReal *p = r->parent_realization; 1617 put32(&body, r->slot); put32(&body, p ? p->slot : UINT32_MAX); 1618 put64(&body, r->gen); put64(&body, p ? p->gen : 0); 1619 put32(&body, (uint32_t)r->realization_type); put32(&body, (uint32_t)r->recipe); 1620 put64(&body, r->token); 1621 put32(&body, r->edit_off); put32(&body, r->edit_len); 1622 put64(&body, r->patch_off); 1623 bool sp = r->placement == JS_PLACE_SPILLED; 1624 put32(&body, sp ? JS_PLACE_SPILLED : JS_PLACE_EVICTED); put32(&body, 0); 1625 put64(&body, sp ? r->spill_off : 0); 1626 buf_put(&body, r->semantic_state_id.b, 32); 1627 buf_put(&body, r->content, 32); 1628 } 1629 free(mark); 1630 for (uint32_t i = 0; i < s->n_branches; i++) { 1631 JsBranch *b = s->branches[i]; 1632 if (!b || b->staged) continue; 1633 JsBranch *pb = branch_at(s, b->parent_branch); 1634 put32(&body, i); put32(&body, b->gen); 1635 put32(&body, pb && !pb->staged ? b->parent_branch : UINT32_MAX); 1636 put32(&body, b->common_ancestor); put32(&body, b->divergence_point); 1637 put32(&body, b->frozen); put32(&body, b->owner); put32(&body, b->home.locality); 1638 put32(&body, (uint32_t)b->realizer->type); put32(&body, b->n_units); 1639 buf_put(&body, b->home.machine, JS_MACHINE_ID_BYTES); 1640 for (uint32_t u = 0; u < b->n_units; u++) { 1641 put32(&body, b->units[u]->slot); put64(&body, b->units[u]->gen); 1642 } 1643 } 1644 buf_put(&body, s->anchor_set ? s->anchor : (const uint8_t[JS_META_ANCHOR]){ 0 }, JS_META_ANCHOR); 1645 if (body.oom) { free(body.p); return JS_ERR_NOMEM; } 1646 1647 /* 3. Header. */ 1648 uint8_t h[JS_META_HDR]; 1649 memset(h, 0, sizeof h); 1650 memcpy(h, JS_META_MAGIC, 8); 1651 le32(h + 8, JS_META_VERSION); le32(h + 12, JS_META_HDR); 1652 le64(h + 16, s->commit_seq + 1); le64(h + 24, body.n); 1653 le32(h + 32, n_types); le32(h + 36, n_reals); 1654 le32(h + 40, s->n_branches); le32(h + 44, n_br); 1655 le64(h + 48, s->spill_end); 1656 uint64_t floor = s->real_gen_floor; 1657 for (uint32_t k = 0; k < s->real_hw; k++) { 1658 JsReal *r = slab_at(s, k); 1659 if (real_gen_next(r->gen) > floor) floor = real_gen_next(r->gen); 1660 } 1661 le64(h + 56, floor); 1662 sha256_hash(body.p ? body.p : (const uint8_t *)"", body.n, h + 64); 1663 sha256_hash(h, 96, h + 96); 1664 1665 /* 4. Temporary file, fsync, atomic rename, directory fsync. */ 1666 char *tmp = path_in(s->dir, "jspace.meta.tmp"), *fin = path_in(s->dir, "jspace.meta"); 1667 int fd = tmp && fin ? open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600) : -1; 1668 rc = fd < 0 ? JS_ERR_IO : JS_OK; 1669 if (rc == JS_OK) rc = write_all(fd, h, sizeof h); 1670 if (rc == JS_OK && body.n) rc = write_all(fd, body.p, body.n); 1671 if (rc == JS_OK && fsync(fd)) rc = JS_ERR_IO; 1672 if (fd >= 0) close(fd); 1673 if (rc == JS_OK && rename(tmp, fin)) rc = JS_ERR_IO; 1674 if (rc == JS_OK) { 1675 int dfd = open(s->dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC); 1676 if (dfd < 0 || fsync(dfd)) rc = JS_ERR_IO; 1677 if (dfd >= 0) close(dfd); 1678 } 1679 if (rc != JS_OK && tmp) unlink(tmp); 1680 free(tmp); free(fin); free(body.p); 1681 if (rc != JS_OK) return rc; 1682 1683 /* 5. The new checkpoint names none of the quarantined extents. */ 1684 s->commit_seq++; 1685 s->real_gen_floor = floor; 1686 for (uint32_t i = 0; i < s->n_ext_pending; i++) 1687 ext_free_now(s, s->ext_pending[i].off, s->ext_pending[i].len); 1688 s->n_ext_pending = 0; 1689 return JS_OK; 1690 } 1691 1692 int js_space_commit(JsSpace *s) { LOCKED_INT(commit_u(s)); } 1693 1694 void js_space_set_anchor(JsSpace *s, const uint8_t anchor[48]) { 1695 LOCK(s); 1696 memcpy(s->anchor, anchor, JS_META_ANCHOR); 1697 s->anchor_set = true; 1698 UNLOCK(s); 1699 } 1700 1701 int js_space_anchor(const JsSpace *s, uint8_t out[48]) { 1702 LOCK(s); 1703 int set = s->anchor_set ? 1 : 0; 1704 if (set) memcpy(out, s->anchor, JS_META_ANCHOR); 1705 UNLOCK(s); 1706 return set; 1707 } 1708 1709 static int ext_cmp(const void *a, const void *b) { 1710 const JsExtent *x = a, *y = b; 1711 return (x->off > y->off) - (x->off < y->off); 1712 } 1713 1714 /* Validate and load a checkpoint into a freshly set-up space. Any 1715 * inconsistency is JS_ERR_CORRUPT; the caller tears the space down. */ 1716 static int load_u(JsSpace *s, const uint8_t *f, size_t fn, 1717 const JsRealizer *const *rzs, uint32_t n_rz) { 1718 if (fn < JS_META_HDR || memcmp(f, JS_META_MAGIC, 8)) return JS_ERR_CORRUPT; 1719 uint8_t d[32]; 1720 sha256_hash(f, 96, d); 1721 if (memcmp(d, f + 96, 32)) return JS_ERR_CORRUPT; 1722 /* Version 1 had 32-bit realization generations: refused, never reinterpreted. */ 1723 if (rd32(f + 8) == JS_META_VERSION_V1) return JS_ERR_VERSION; 1724 uint32_t ver = rd32(f + 8); 1725 if ((ver != JS_META_VERSION && ver != JS_META_VERSION_V2) || rd32(f + 12) != JS_META_HDR) 1726 return JS_ERR_CORRUPT; 1727 uint64_t body_len = rd64(f + 24); 1728 if (body_len != fn - JS_META_HDR) return JS_ERR_CORRUPT; 1729 const uint8_t *p = f + JS_META_HDR, *end = p + body_len; 1730 sha256_hash(p, body_len, d); 1731 if (memcmp(d, f + 64, 32)) return JS_ERR_CORRUPT; 1732 uint32_t n_types = rd32(f + 32), n_reals = rd32(f + 36); 1733 uint32_t n_slots = rd32(f + 40), n_br = rd32(f + 44); 1734 uint64_t spill_end = rd64(f + 48); 1735 s->commit_seq = rd64(f + 16); 1736 s->real_gen_floor = rd64(f + 56); 1737 if (n_types > 64 || n_slots > s->limits.max_branches || n_br > n_slots || 1738 n_reals > s->limits.max_reals) return JS_ERR_CORRUPT; 1739 if (s->limits.max_spill_bytes && spill_end > s->limits.max_spill_bytes) return JS_ERR_FULL; 1740 struct stat st; 1741 if (fstat(s->spill_fd, &st) || (uint64_t)st.st_size < spill_end) return JS_ERR_CORRUPT; 1742 s->spill_end = spill_end; 1743 1744 /* Types bind to the realizers the caller supplied. */ 1745 const JsRealizer *types[64]; 1746 if ((size_t)(end - p) < (size_t)n_types * 16) return JS_ERR_CORRUPT; 1747 for (uint32_t t = 0; t < n_types; t++, p += 16) { 1748 uint32_t ty = rd32(p); 1749 uint64_t ub = rd64(p + 8); 1750 types[t] = NULL; 1751 for (uint32_t i = 0; i < n_rz; i++) 1752 if (rzs[i] && (uint32_t)rzs[i]->type == ty && rzs[i]->unit_bytes == ub) types[t] = rzs[i]; 1753 if (!types[t]) return JS_ERR_ARG; /* caller did not supply this representation */ 1754 } 1755 if ((size_t)(end - p) < (size_t)n_slots * 4) return JS_ERR_CORRUPT; 1756 for (uint32_t i = 0; i < n_slots; i++, p += 4) s->branch_gen[i] = rd32(p); 1757 s->n_branches = n_slots; 1758 1759 /* Realizations: place each at its own slot, link parents in a second pass. */ 1760 if ((size_t)(end - p) < (size_t)n_reals * JS_META_REAL) return JS_ERR_CORRUPT; 1761 uint32_t *parent_slot = malloc((n_reals ? n_reals : 1) * sizeof *parent_slot); 1762 uint64_t *parent_gen = malloc((n_reals ? n_reals : 1) * sizeof *parent_gen); 1763 JsReal **loaded = malloc((n_reals ? n_reals : 1) * sizeof *loaded); 1764 JsExtent *ext = malloc((2 * (size_t)n_reals + 1) * sizeof *ext); 1765 uint32_t n_ext = 0; 1766 int rc = parent_slot && parent_gen && loaded && ext ? JS_OK : JS_ERR_NOMEM; 1767 for (uint32_t i = 0; i < n_reals && rc == JS_OK; i++, p += JS_META_REAL) { 1768 uint32_t slot = rd32(p), ty = rd32(p + 24), rec = rd32(p + 28); 1769 uint64_t gen = rd64(p + 8); 1770 const JsRealizer *rz = NULL; 1771 for (uint32_t t = 0; t < n_types; t++) if ((uint32_t)types[t]->type == ty) rz = types[t]; 1772 if (!rz || slot >= s->limits.max_reals || gen >= s->real_gen_floor || 1773 rec < JS_RECIPE_ROOT || rec > JS_RECIPE_EDIT) { rc = JS_ERR_CORRUPT; break; } 1774 if ((rc = slab_chunk(s, slot)) != JS_OK) { rc = rc == JS_ERR_FULL ? JS_ERR_CORRUPT : rc; break; } 1775 JsReal *r = &s->slab[slot / JS_SLAB_CHUNK][slot % JS_SLAB_CHUNK]; 1776 if (r->realizer) { rc = JS_ERR_CORRUPT; break; } /* duplicate slot */ 1777 if (slot >= s->real_hw) s->real_hw = slot + 1; 1778 r->gen = gen; 1779 r->realizer = rz; 1780 r->realization_type = rz->type; 1781 r->recipe = (JsRecipeKind)rec; 1782 r->token = rd64(p + 32); 1783 r->edit_off = rd32(p + 40); r->edit_len = rd32(p + 44); 1784 r->patch_off = rd64(p + 48); 1785 uint32_t place = rd32(p + 56); 1786 memcpy(r->semantic_state_id.b, p + 72, 32); 1787 memcpy(r->content, p + 104, 32); 1788 r->placement = JS_PLACE_EVICTED; 1789 parent_slot[i] = rd32(p + 4); parent_gen[i] = rd64(p + 16); 1790 loaded[i] = r; 1791 s->stats.live_reals++; 1792 if (place == JS_PLACE_SPILLED) { 1793 r->spill_off = rd64(p + 64); 1794 r->placement = JS_PLACE_SPILLED; 1795 ext[n_ext++] = (JsExtent){ r->spill_off, rz->unit_bytes }; 1796 charge(s, r, +1); 1797 } else if (place != JS_PLACE_EVICTED) { 1798 rc = JS_ERR_CORRUPT; 1799 } 1800 if (rec == JS_RECIPE_EDIT) { 1801 if (!r->edit_len || (uint64_t)r->edit_off + r->edit_len > rz->unit_bytes || 1802 r->patch_off == UINT64_MAX) { rc = JS_ERR_CORRUPT; break; } 1803 ext[n_ext++] = (JsExtent){ r->patch_off, r->edit_len }; 1804 } else if (r->patch_off != UINT64_MAX) { 1805 rc = JS_ERR_CORRUPT; 1806 } 1807 } 1808 /* Extents: inside the file, never overlapping. The gaps below the last 1809 * live extent are the free list; the file's logical end is that extent. */ 1810 if (rc == JS_OK) { 1811 qsort(ext, n_ext, sizeof *ext, ext_cmp); 1812 uint64_t at = 0; 1813 for (uint32_t i = 0; i < n_ext && rc == JS_OK; i++) { 1814 uint64_t e = ext[i].off + ext[i].len; 1815 if (ext[i].off < at || e < ext[i].off || e > spill_end) { rc = JS_ERR_CORRUPT; break; } 1816 if (ext[i].off > at && 1817 ext_push(&s->ext_free, &s->n_ext_free, &s->cap_ext_free, s->n_ext_free, 1818 (JsExtent){ at, ext[i].off - at }) != JS_OK) { rc = JS_ERR_NOMEM; break; } 1819 at = e; 1820 } 1821 s->spill_end = at; 1822 } 1823 /* Parents, recipe shape, and semantic identity recomputed from the recipe. */ 1824 for (uint32_t i = 0; i < n_reals && rc == JS_OK; i++) { 1825 JsReal *r = loaded[i]; 1826 JsReal *par = NULL; 1827 if (parent_slot[i] != UINT32_MAX) { 1828 par = slab_at(s, parent_slot[i]); 1829 if (!par || !par->realizer || par->gen != parent_gen[i] || 1830 par->realizer != r->realizer) { rc = JS_ERR_CORRUPT; break; } 1831 } 1832 if ((r->recipe == JS_RECIPE_ROOT) != (par == NULL)) { rc = JS_ERR_CORRUPT; break; } 1833 r->parent_realization = par; 1834 if (par) par->refs++; 1835 JsSemId want; 1836 if (r->recipe == JS_RECIPE_ROOT) { 1837 want = js_sem_root(r->token); 1838 } else if (r->recipe == JS_RECIPE_DERIVE) { 1839 want = js_sem_derive(&par->semantic_state_id, r->token); 1840 } else { 1841 r->edit_bytes = malloc(r->edit_len); 1842 if (!r->edit_bytes) { rc = JS_ERR_NOMEM; break; } 1843 if (pread(s->spill_fd, r->edit_bytes, r->edit_len, (off_t)r->patch_off) != 1844 (ssize_t)r->edit_len) { rc = JS_ERR_CORRUPT; break; } 1845 want = js_sem_edit(&par->semantic_state_id, r->edit_off, r->edit_bytes, r->edit_len); 1846 } 1847 /* Identities are a hash chain, so a parent cycle cannot satisfy this 1848 * for every member; with it, every chain ends at a root. */ 1849 if (memcmp(want.b, r->semantic_state_id.b, 32)) { rc = JS_ERR_CORRUPT; break; } 1850 } 1851 /* Branches. */ 1852 for (uint32_t i = 0; i < n_br && rc == JS_OK; i++) { 1853 if ((size_t)(end - p) < JS_META_BRANCH) { rc = JS_ERR_CORRUPT; break; } 1854 uint32_t id = rd32(p), gen = rd32(p + 4), ty = rd32(p + 32), nu = rd32(p + 36); 1855 uint32_t loc = rd32(p + 28); 1856 const JsRealizer *rz = NULL; 1857 for (uint32_t t = 0; t < n_types; t++) if ((uint32_t)types[t]->type == ty) rz = types[t]; 1858 if (!rz || id >= n_slots || s->branches[id] || gen != s->branch_gen[id] || 1859 gen == JS_BRANCH_GEN_RETIRED || !nu || 1860 loc > JS_HOME_REPLICA || (size_t)(end - p) < JS_META_BRANCH + (size_t)nu * JS_META_UNIT) { 1861 rc = JS_ERR_CORRUPT; break; 1862 } 1863 JsBranch *b = calloc(1, sizeof *b); 1864 JsReal **units = malloc((size_t)(nu + 64) * sizeof *units); 1865 if (!b || !units) { free(b); free(units); rc = JS_ERR_NOMEM; break; } 1866 b->branch_id = id; b->gen = gen; b->realizer = rz; 1867 b->parent_branch = rd32(p + 8); b->common_ancestor = rd32(p + 12); 1868 b->divergence_point = rd32(p + 16); b->frozen = rd32(p + 20) != 0; 1869 b->owner = rd32(p + 24); b->home.locality = loc; 1870 memcpy(b->home.machine, p + 40, JS_MACHINE_ID_BYTES); 1871 b->units = units; b->cap_units = nu + 64; 1872 s->branches[id] = b; 1873 const uint8_t *u = p + JS_META_BRANCH; 1874 for (uint32_t k = 0; k < nu; k++, u += JS_META_UNIT) { 1875 JsReal *r = slab_at(s, rd32(u)); 1876 if (!r || !r->realizer || r->gen != rd64(u + 4) || r->realizer != rz) { 1877 rc = JS_ERR_CORRUPT; break; 1878 } 1879 b->units[b->n_units++] = r; 1880 r->refs++; r->holders++; 1881 } 1882 p = u; 1883 } 1884 if (rc == JS_OK && ver == JS_META_VERSION) { 1885 if ((size_t)(end - p) != JS_META_ANCHOR) rc = JS_ERR_CORRUPT; 1886 else { 1887 /* An all-zero section is "never set": absent, like version 2. */ 1888 static const uint8_t zero[JS_META_ANCHOR]; 1889 memcpy(s->anchor, p, JS_META_ANCHOR); 1890 s->anchor_set = memcmp(p, zero, JS_META_ANCHOR) != 0; 1891 p = end; 1892 } 1893 } 1894 if (rc == JS_OK && p != end) rc = JS_ERR_CORRUPT; 1895 /* Every persisted realization is held by something; nothing dangles. */ 1896 for (uint32_t i = 0; i < n_reals && rc == JS_OK; i++) 1897 if (!loaded[i]->refs) rc = JS_ERR_CORRUPT; 1898 if (rc == JS_OK) { 1899 for (uint32_t i = 0; i < n_reals; i++) index_insert(s, loaded[i]); 1900 /* Unused slots below the high-water mark go on the free list. */ 1901 for (uint32_t k = s->real_hw; k-- > 0;) { 1902 if (slab_chunk(s, k) != JS_OK) { rc = JS_ERR_NOMEM; break; } 1903 JsReal *r = &s->slab[k / JS_SLAB_CHUNK][k % JS_SLAB_CHUNK]; 1904 if (r->realizer) continue; 1905 r->gen = s->real_gen_floor; 1906 if (r->gen == JS_REAL_GEN_RETIRED) continue; /* exhausted: never reused */ 1907 r->free_next = s->real_free; 1908 s->real_free = r; 1909 } 1910 for (uint32_t i = n_slots; i-- > 0;) 1911 if (!s->branches[i] && s->branch_gen[i] != JS_BRANCH_GEN_RETIRED) 1912 s->free_branch[s->n_free_branch++] = i; /* a retired slot stays retired */ 1913 } 1914 free(parent_slot); free(parent_gen); free(loaded); free(ext); 1915 return rc; 1916 } 1917 1918 int js_space_open(JsSpace *s, const char *dir, const JsRealizer *const *realizers, 1919 uint32_t n_realizers, const JsLimits *lim, const JsHome *local_home) { 1920 if (!dir) return JS_ERR_ARG; 1921 int rc = space_setup(s, lim); 1922 if (rc) return rc; 1923 if (local_home) s->local_home = *local_home; 1924 s->local_home.locality = JS_HOME_LOCAL; 1925 s->durable = true; 1926 if (mkdir(dir, 0700) && errno != EEXIST) { js_space_destroy(s); return JS_ERR_IO; } 1927 s->dir = strdup(dir); 1928 char *data = path_in(dir, "jspace.data"), *meta = path_in(dir, "jspace.meta"); 1929 char *tmp = path_in(dir, "jspace.meta.tmp"); 1930 if (!s->dir || !data || !meta || !tmp) { rc = JS_ERR_NOMEM; goto out; } 1931 unlink(tmp); /* a torn temporary checkpoint is never authoritative */ 1932 s->spill_fd = open(data, O_RDWR | O_CREAT | O_CLOEXEC, 0600); 1933 if (s->spill_fd < 0) { rc = JS_ERR_IO; goto out; } 1934 int mfd = open(meta, O_RDONLY | O_CLOEXEC); 1935 if (mfd < 0) { 1936 if (errno != ENOENT) { rc = JS_ERR_IO; goto out; } 1937 /* No checkpoint yet: nothing in the data file is named. */ 1938 if (ftruncate(s->spill_fd, 0)) { rc = JS_ERR_IO; goto out; } 1939 goto out; 1940 } 1941 struct stat st; 1942 uint8_t *f = NULL; 1943 if (fstat(mfd, &st)) rc = JS_ERR_IO; 1944 else if (!(f = malloc(st.st_size ? (size_t)st.st_size : 1))) rc = JS_ERR_NOMEM; 1945 else { 1946 size_t got = 0; 1947 while (got < (size_t)st.st_size) { 1948 ssize_t k = read(mfd, f + got, (size_t)st.st_size - got); 1949 if (k < 0 && errno == EINTR) continue; 1950 if (k <= 0) break; 1951 got += (size_t)k; 1952 } 1953 rc = got == (size_t)st.st_size ? load_u(s, f, got, realizers, n_realizers) : JS_ERR_IO; 1954 } 1955 free(f); 1956 close(mfd); 1957 out: 1958 free(data); free(meta); free(tmp); 1959 if (rc) js_space_destroy(s); 1960 return rc; 1961 } 1962 1963 int js_branch_info(JsSpace *s, JsBranchRef ref, JsBranchInfo *out) { 1964 if (!out) return JS_ERR_ARG; 1965 LOCK(s); 1966 JsBranch *b = branch_ref_at(s, ref); 1967 if (b) { 1968 memset(out, 0, sizeof *out); 1969 out->owner = b->owner; 1970 out->staged = b->staged; 1971 out->locality = b->home.locality; 1972 out->parent = b->parent_branch; 1973 JsBranch *p = b->parent_branch != UINT32_MAX ? branch_at(s, b->parent_branch) : NULL; 1974 out->parent_gen = p ? p->gen : 0; 1975 } 1976 UNLOCK(s); 1977 return b ? JS_OK : JS_ERR_STALE; 1978 }