diff --git a/src/fabric/fabric.c b/src/fabric/fabric.c index 369aa27e0..a598f9c41 100644 --- a/src/fabric/fabric.c +++ b/src/fabric/fabric.c @@ -68,20 +68,119 @@ static void withdraw_all(FabNode *n, FabMember *m) { for (uint32_t i = 0; i < m->n_keys; i++) (void)cq_withdraw(n->cfg.catalog, &m->keys[i]); } +/* ---- replay window store (see fabric.h, Restart) ---- */ + +static uint32_t r32(const uint8_t *p) { + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} + +/* Save the window as it will be once `who` holds (gen, seq): every member as + * held, with who's entry replaced, or appended when who is not yet a member. + * FAB_OK without a store (memory only). */ +static int window_save(FabNode *n, const AienMachineId *who, uint64_t gen, uint64_t seq) { + const FabStore *st = n->cfg.store; + if (!st) return FAB_OK; + uint8_t rec[FAB_STATE_MAX]; + uint32_t cnt = 0; + int found = 0; + uint8_t *p = rec + 12 + AIEN_MID_RECORD_BYTES; + for (uint32_t i = 0; i <= n->n_members; i++) { + const AienMachineId *mid; + uint64_t g, s; + if (i < n->n_members) { + const FabMember *m = &n->members[i]; + if (m->state == FAB_ST_NONE) continue; + mid = &m->machine; + g = m->generation; + s = m->last_seq; + if (who && aien_mid_equal(mid, who)) { g = gen; s = seq; found = 1; } + } else { + if (!who || found) break; + mid = who; g = gen; s = seq; + } + if (cnt == FAB_MAX_MEMBERS || aien_mid_encode(mid, p) != AIEN_MID_OK) return FAB_E_STATE; + w64(p + AIEN_MID_RECORD_BYTES, g); + w64(p + AIEN_MID_RECORD_BYTES + 8, s); + p += FAB_STATE_ENTRY; + cnt++; + } + memcpy(rec, "AFST", 4); + w32(rec + 4, FAB_STATE_VERSION); + if (aien_mid_encode(&n->cfg.self, rec + 8) != AIEN_MID_OK) return FAB_E_STATE; + w32(rec + 8 + AIEN_MID_RECORD_BYTES, cnt); + size_t len = (size_t)(p - rec); + sha256_hash(rec, len, p); + return st->save(st->ctx, rec, len + 32) == 0 ? FAB_OK : FAB_E_STATE; +} + +/* Restore a saved window: every peer comes back LOST with its generation and + * last seq. Any damage is FAB_E_STATE and restores nothing. */ +static int window_restore(FabNode *n, const uint8_t *rec, size_t len) { + const size_t head = 12 + AIEN_MID_RECORD_BYTES; + if (len < head + 32 || len > FAB_STATE_MAX || memcmp(rec, "AFST", 4) != 0 || + r32(rec + 4) != FAB_STATE_VERSION) + return FAB_E_STATE; + uint32_t cnt = r32(rec + 8 + AIEN_MID_RECORD_BYTES); + if (cnt > FAB_MAX_MEMBERS || len != head + (size_t)cnt * FAB_STATE_ENTRY + 32) return FAB_E_STATE; + uint8_t dg[32]; + sha256_hash(rec, len - 32, dg); + if (memcmp(dg, rec + len - 32, 32) != 0) return FAB_E_STATE; + AienMachineId self; + if (aien_mid_decode(rec + 8, AIEN_MID_RECORD_BYTES, &self) != AIEN_MID_OK || + !aien_mid_equal(&self, &n->cfg.self)) + return FAB_E_STATE; /* another machine's window */ + FabMember got[FAB_MAX_MEMBERS]; + const uint8_t *p = rec + head; + for (uint32_t i = 0; i < cnt; i++, p += FAB_STATE_ENTRY) { + FabMember *m = &got[i]; + memset(m, 0, sizeof *m); + if (aien_mid_decode(p, AIEN_MID_RECORD_BYTES, &m->machine) != AIEN_MID_OK || + aien_mid_equal(&m->machine, &n->cfg.self)) + return FAB_E_STATE; + for (uint32_t j = 0; j < i; j++) + if (aien_mid_equal(&got[j].machine, &m->machine)) return FAB_E_STATE; + m->generation = r64(p + AIEN_MID_RECORD_BYTES); + m->last_seq = r64(p + AIEN_MID_RECORD_BYTES + 8); + if (m->generation == 0 || m->generation > FAB_GEN_MAX) return FAB_E_STATE; + m->state = FAB_ST_LOST; /* back only by a JOIN of a higher generation */ + } + memcpy(n->members, got, cnt * sizeof got[0]); + n->n_members = cnt; + return FAB_OK; +} + +static int window_open(FabNode *n) { + const FabStore *st = n->cfg.store; + if (!st) return FAB_OK; + uint8_t rec[FAB_STATE_MAX]; + size_t len = 0; + int got = st->load(st->ctx, rec, sizeof rec, &len); + if (got == 0) return n->cfg.store_fresh ? window_save(n, NULL, 0, 0) : FAB_E_STATE; + if (got != 1 || n->cfg.store_fresh || len > sizeof rec) return FAB_E_STATE; + return window_restore(n, rec, len); +} + int fab_node_init(FabNode *n, const FabConfig *cfg) { if (!n || !cfg || !cfg->roster || !cfg->catalog || !cfg->transport || !cfg->auth || !cfg->transport->send || !cfg->transport->recv || !cfg->auth->sign || !cfg->auth->verify || cfg->generation == 0 || cfg->max_lease_us == 0) return FAB_E_ARG; + if (cfg->store ? !cfg->store->save || !cfg->store->load || cfg->store_fresh > 1 + : cfg->store_fresh != 0) + return FAB_E_ARG; + if (cfg->generation > FAB_GEN_MAX) return FAB_E_GENERATION; if (aien_mid_is_zero_(cfg->self.id) || !cfg->catalog->machines) return FAB_E_ARG; if (cq_machine_index(cfg->catalog, &cfg->self) != cfg->catalog->self_machine) return FAB_E_ARG; memset(n, 0, sizeof *n); n->cfg = *cfg; sha256_init(&n->event_hash); - return FAB_OK; + int rc = window_open(n); + if (rc != FAB_OK) memset(n, 0, sizeof *n); + return rc; } int fab_node_set_generation(FabNode *n, uint64_t generation) { + if (n && generation > FAB_GEN_MAX) return FAB_E_GENERATION; if (!n || generation <= n->cfg.generation) return FAB_E_STALE_GEN; n->cfg.generation = generation; n->seq = 0; @@ -96,6 +195,7 @@ int fab_seal(FabNode *n, const AienMachineId *dest, uint32_t kind, const uint8_t size_t body_len, uint64_t now_us, uint8_t *out, size_t *out_len) { if (!n || !dest || !out || !out_len || body_size(kind) != body_len || (body_len && !body)) return FAB_E_ARG; + if (n->cfg.generation == 0 || n->cfg.generation > FAB_GEN_MAX) return FAB_E_GENERATION; memcpy(out, "AFAB", 4); out[4] = FAB_VERSION; out[5] = (uint8_t)kind; @@ -221,6 +321,7 @@ int fab_receive(FabNode *n, const uint8_t *msg, size_t len, uint64_t now_us, Fab v->sender = sender; uint64_t gen = r64(msg + 96), seq = r64(msg + 104); if (gen == 0 || seq == 0) return refuse(n, v, FAB_E_FORMAT, 0, &sender, gen, seq, now_us); + if (gen > FAB_GEN_MAX) return refuse(n, v, FAB_E_GENERATION, 0, &sender, gen, seq, now_us); /* addressing and identity */ if (!aien_mid_equal(&dest, &n->cfg.self) || aien_mid_equal(&sender, &n->cfg.self)) @@ -241,7 +342,12 @@ int fab_receive(FabNode *n, const uint8_t *msg, size_t len, uint64_t now_us, Fab * sequence number whatever the outcome, so a refused message (for * example a RENEW refused for catalog capacity) cannot succeed if it * is replayed later. */ - if (gen == m->generation) m->last_seq = seq; + if (gen == m->generation) { + /* Saved before it is consumed: a restart never forgets it. */ + if (window_save(n, &sender, gen, seq) != FAB_OK) + return refuse(n, v, FAB_E_STATE, 0, &sender, gen, seq, now_us); + m->last_seq = seq; + } } const uint8_t *body = msg + FAB_HDR_BYTES; if (kind == FAB_MSG_JOIN) { @@ -255,6 +361,11 @@ int fab_receive(FabNode *n, const uint8_t *msg, size_t len, uint64_t now_us, Fab if (!m) { if (n->n_members == FAB_MAX_MEMBERS) return refuse(n, v, FAB_E_FULL, 0, &sender, gen, seq, now_us); + } + /* Saved before admission: after a restart this JOIN is stale. */ + if (window_save(n, &sender, gen, seq) != FAB_OK) + return refuse(n, v, FAB_E_STATE, 0, &sender, gen, seq, now_us); + if (!m) { m = &n->members[n->n_members++]; memset(m, 0, sizeof *m); m->machine = sender; @@ -408,6 +519,8 @@ const char *fab_strerror(int code) { case FAB_E_CAPQ: return "capability graph refused the record"; case FAB_E_FULL: return "table full"; case FAB_E_TRANSPORT: return "transport error"; + case FAB_E_GENERATION: return "membership generation out of range (1 .. 2^32-1)"; + case FAB_E_STATE: return "replay window store missing, corrupt or not saved"; default: return "unknown"; } } diff --git a/src/fabric/fabric.h b/src/fabric/fabric.h index 5778d5323..bd56498bf 100644 --- a/src/fabric/fabric.h +++ b/src/fabric/fabric.h @@ -55,11 +55,13 @@ * REPLAY check consumes its seq even when refused later, so a refused message * can never succeed on replay): * form FAB_E_FORMAT + * generation > FAB_GEN_MAX FAB_E_GENERATION (never truncated) * dest != self, sender = self FAB_E_MISMATCH * sender not on the roster FAB_E_NOT_ENROLLED * sig does not verify FAB_E_AUTH (forged identity, altered bytes) * generation < held FAB_E_STALE_GEN * same generation, seq <= last FAB_E_REPLAY + * window not saved (store) FAB_E_STATE (see Restart; nothing applied) * JOIN with generation <= held FAB_E_STALE_GEN * non-JOIN, not a member, or a * generation it never joined with FAB_E_NOT_MEMBER @@ -78,15 +80,32 @@ * Generations never move back: a JOIN is accepted only with a generation * above the one held, and anything older is FAB_E_STALE_GEN, so old traffic * still in flight after a restart cannot roll membership back. - * Limits (F5-0): the held generation and seq live in memory only, so a - * receiver restart forgets them (persistence comes with the TRUST-1 / M6 - * identity work), and a JOIN of a new generation refused before admission - * (ontology, capacity) is not remembered. + * + * Restart. With a FabStore the replay window (each peer's generation and + * last seq) is saved before it changes: a message of the held generation is + * saved before its seq is consumed, and a JOIN before it is admitted. A save + * that fails refuses the message with FAB_E_STATE and changes nothing in + * memory. On restart fab_node_init restores every peer as LOST with its + * generation and last seq, so a captured message replayed after the restart + * is FAB_E_STALE_GEN or FAB_E_REPLAY exactly as before it, and a peer comes + * back only by a JOIN with a higher generation. A missing (without + * store_fresh), unreadable or corrupt record is FAB_E_STATE: the node fails + * closed instead of starting with an empty window. + * Limits: the store must resist rollback; the record's sha256 detects damage, + * not an attacker who restores an older record (that needs the TRUST-1 + * sealed / owner-key storage, not done here). A node with no store keeps the + * window in memory only and forgets it on restart. The node's own sending + * generation is not saved: after a restart the caller must give a higher one + * (fab_node_set_generation). Every authenticated fresh message costs one + * save. A JOIN refused before admission (ontology, capacity) is not reliably + * remembered: a refusal after its save only makes the record stricter until + * the next save rewrites it from memory. * Capability generations. rx_capq accepts a record only when its generation * is newer than the one held. Advertisers number entries with * fab_entry_generation(node, rev) = generation << 32 | rev, so a rejoin with a - * new generation always outranks anything from before. + * new generation always outranks anything from before. Generations above + * FAB_GEN_MAX are refused, so the shift never drops a high bit. */ #ifndef FABRIC_H #define FABRIC_H @@ -110,6 +129,19 @@ #define FAB_MAX_KEYS 64u /* capability entries one peer may advertise */ #define FAB_EVENT_RING 256u +/* Membership generations are 1 .. FAB_GEN_MAX: entry generations pack + * generation << 32 | rev into 64 bits, so a wider one would lose its high + * bits. Anything above is FAB_E_GENERATION everywhere (init, set, seal, + * receive), never truncated. */ +#define FAB_GEN_MAX UINT32_MAX + +/* Replay-window record (see FabStore): "AFST" | u32 version | self record | + * u32 n | n x { machine record | u64 generation | u64 last_seq } | sha256 of + * everything before it. */ +#define FAB_STATE_VERSION 1u +#define FAB_STATE_ENTRY (AIEN_MID_RECORD_BYTES + 16u) +#define FAB_STATE_MAX (12u + AIEN_MID_RECORD_BYTES + FAB_MAX_MEMBERS * FAB_STATE_ENTRY + 32u) + enum { FAB_MSG_JOIN = 1, FAB_MSG_RENEW = 2, FAB_MSG_ADVERTISE = 3, FAB_MSG_LEAVE = 4 }; /* Member states in this node's view. */ @@ -129,6 +161,8 @@ enum { FAB_ST_NONE = 0, FAB_ST_JOINED = 1, FAB_ST_LOST = 2, FAB_ST_LEFT = 3 }; #define FAB_E_CAPQ -11 #define FAB_E_FULL -12 #define FAB_E_TRANSPORT -13 +#define FAB_E_GENERATION -14 /* membership generation outside 1 .. FAB_GEN_MAX */ +#define FAB_E_STATE -15 /* replay-window store missing, corrupt or not durable */ /* ---- what a real transport and a real signer must provide ---- */ @@ -152,6 +186,16 @@ typedef struct { const uint8_t sig[FAB_SIG_BYTES]); } FabAuth; +/* Where the replay window survives a restart. Supplied by the caller (the + * Fabric itself touches no file, socket or process). save: 0 only once the + * record is durable, anything else is a failure. load: 1 with a record in buf + * (len bytes), 0 when nothing was ever saved, <0 on error. */ +typedef struct { + void *ctx; + int (*save)(void *ctx, const uint8_t *rec, size_t len); + int (*load)(void *ctx, uint8_t *buf, size_t cap, size_t *len); +} FabStore; + /* Enrolled machines (from the AEGIS / owner-key boundary). Read-only here. */ typedef struct { uint32_t n; @@ -165,7 +209,14 @@ typedef struct { const FabTransport *transport; const FabAuth *auth; uint64_t max_lease_us; /* longest lease this node grants */ - uint64_t generation; /* this node's membership generation, >= 1 */ + uint64_t generation; /* this node's membership generation, 1 .. FAB_GEN_MAX */ + /* Replay window store. NULL keeps the window in memory only (loopback + * tests); a node that can restart must have one. store_fresh = 1 is the + * caller saying this is the node's first start: the store must then be + * empty. With store_fresh = 0 an empty, unreadable or corrupt store is + * FAB_E_STATE: the node does not start rather than forget. */ + const FabStore *store; + uint32_t store_fresh; } FabConfig; /* ---- typed records ---- */ @@ -213,8 +264,13 @@ typedef struct { /* ---- node ---- */ +/* FAB_E_ARG for a bad config (generation 0 included), FAB_E_GENERATION for a + * generation above FAB_GEN_MAX, FAB_E_STATE when cfg->store cannot be read, + * holds a damaged record or one for another machine, is empty without + * store_fresh, or is not empty with it. On any error n holds no usable node. */ int fab_node_init(FabNode *n, const FabConfig *cfg); -/* Start a new membership generation (after a restart): must be higher. */ +/* Start a new membership generation (after a restart): must be higher + * (FAB_E_STALE_GEN) and at most FAB_GEN_MAX (FAB_E_GENERATION). */ int fab_node_set_generation(FabNode *n, uint64_t generation); uint64_t fab_entry_generation(const FabNode *n, uint32_t rev); diff --git a/src/runtime/rx_jspace.c b/src/runtime/rx_jspace.c index 202d9a8f4..ebacd4f23 100644 --- a/src/runtime/rx_jspace.c +++ b/src/runtime/rx_jspace.c @@ -209,28 +209,48 @@ static int slab_chunk(JsSpace *s, uint32_t slot) { return JS_OK; } +/* The generation after g, saturating at the retired marker: never wraps. */ +static uint64_t real_gen_next(uint64_t g) { + return g < JS_REAL_GEN_RETIRED ? g + 1 : JS_REAL_GEN_RETIRED; +} + +/* A never-used slot can be handed out: below max_reals and its starting + * generation (the chunk's, or the floor for a chunk not yet made) is live. */ +static bool slab_fresh_ok(const JsSpace *s) { + if (s->real_hw >= s->limits.max_reals) return false; + const JsReal *c = s->real_hw / JS_SLAB_CHUNK < s->slab_chunks ? s->slab[s->real_hw / JS_SLAB_CHUNK] : NULL; + uint64_t g = c ? c[s->real_hw % JS_SLAB_CHUNK].gen : s->real_gen_floor; + return g != JS_REAL_GEN_RETIRED; +} + static JsReal *slab_take(JsSpace *s) { JsReal *r = s->real_free; if (r) { s->real_free = r->free_next; } else { - if (s->real_hw >= s->limits.max_reals) return NULL; + if (!slab_fresh_ok(s)) return NULL; if (slab_chunk(s, s->real_hw) != JS_OK) return NULL; r = &s->slab[s->real_hw / JS_SLAB_CHUNK][s->real_hw % JS_SLAB_CHUNK]; s->real_hw++; } - uint32_t slot = r->slot, gen = r->gen; + uint32_t slot = r->slot; + uint64_t gen = r->gen; memset(r, 0, sizeof *r); r->slot = slot; r->gen = gen; r->patch_off = UINT64_MAX; return r; } +/* Release a slot: its generation moves on so every old JsRealId is stale. A + * slot whose next generation would be JS_REAL_GEN_RETIRED retires: it keeps + * that marker and never returns to the free list. */ static void slab_give(JsSpace *s, JsReal *r) { - uint32_t slot = r->slot, gen = r->gen + 1; + uint32_t slot = r->slot; + uint64_t gen = real_gen_next(r->gen); memset(r, 0, sizeof *r); r->slot = slot; r->gen = gen; - if (gen + 1 > s->real_gen_floor) s->real_gen_floor = gen + 1; + if (real_gen_next(gen) > s->real_gen_floor) s->real_gen_floor = real_gen_next(gen); + if (gen == JS_REAL_GEN_RETIRED) return; r->free_next = s->real_free; s->real_free = r; } @@ -239,6 +259,8 @@ static void slab_give(JsSpace *s, JsReal *r) { static int room(const JsSpace *s, uint32_t reals, uint64_t resident) { if (reals && s->stats.live_reals + reals > s->limits.max_reals) return JS_ERR_FULL; + /* Retired slots count toward no live total but are never handed out. */ + if (reals && !s->real_free && !slab_fresh_ok(s)) return JS_ERR_FULL; if (resident && s->limits.max_resident_bytes && s->stats.resident_bytes + resident > s->limits.max_resident_bytes) return JS_ERR_FULL; return JS_OK; @@ -885,8 +907,11 @@ static int release_u(JsSpace *s, uint32_t bid) { free(b->units); free(b); s->branches[bid] = NULL; - s->branch_gen[bid]++; /* every old reference is now stale */ - s->free_branch[s->n_free_branch++] = bid; + /* Every old reference is now stale. A slot whose next generation would be + * JS_BRANCH_GEN_RETIRED retires: the marker stays and the slot is never + * handed out again (32-bit generations: the ref packs into a World field). */ + if (s->branch_gen[bid] < JS_BRANCH_GEN_RETIRED) s->branch_gen[bid]++; + if (s->branch_gen[bid] != JS_BRANCH_GEN_RETIRED) s->free_branch[s->n_free_branch++] = bid; return JS_OK; } @@ -1282,30 +1307,34 @@ int js_branch_home(JsSpace *s, JsBranchRef ref, JsHome *out) { /* ---- durable checkpoint ------------------------------------------------------ * * jspace.meta, little-endian, all fixed-width fields: - * header (128 B): "OMJSPC01" | u32 version=1 | u32 header_bytes=128 | + * header (128 B): "OMJSPC01" | u32 version=2 | u32 header_bytes=128 | * u64 commit_seq | u64 body_len | u32 n_types | u32 n_reals | * u32 n_branch_slots | u32 n_branches | u64 spill_end | - * u32 real_gen_floor | u32 reserved | sha256(body) | sha256(header[0..96)) + * u64 real_gen_floor | sha256(body) | sha256(header[0..96)) * body: * n_types x { u32 type | u32 0 | u64 unit_bytes } - * n_branch_slots x u32 slot generation - * n_reals x 128 B { u32 slot | u32 gen | u32 parent_slot | u32 parent_gen | + * n_branch_slots x u32 slot generation (JS_BRANCH_GEN_RETIRED = retired) + * n_reals x 136 B { u32 slot | u32 parent_slot | u64 gen | u64 parent_gen | * u32 type | u32 recipe | u64 token | u32 edit_off | * u32 edit_len | u64 patch_off | u32 placement | u32 0 | * u64 spill_off | semid[32] | content[32] } * n_branches x { u32 id | u32 gen | u32 parent | u32 common_ancestor | * u32 divergence | u32 frozen | u32 owner | u32 locality | * u32 type | u32 n_units | machine[32] | - * n_units x { u32 slot | u32 gen } } - * No pointer is stored. Placement is SPILLED (bytes at spill_off in + * n_units x { u32 slot | u64 gen } } + * Version 2 widened realization generations to 64 bits (Lane 32). Version 1 + * (32-bit realization generations) is refused with JS_ERR_VERSION, never + * reinterpreted. No pointer is stored. Placement is SPILLED (bytes at spill_off in * jspace.data) or EVICTED (rebuild from the recipe). EDIT patches live in * jspace.data at patch_off. Staged branches and realizations only they reach * are left out. */ #define JS_META_MAGIC "OMJSPC01" -#define JS_META_VERSION 1u +#define JS_META_VERSION 2u +#define JS_META_VERSION_V1 1u #define JS_META_HDR 128u -#define JS_META_REAL 128u +#define JS_META_REAL 136u +#define JS_META_UNIT 12u #define JS_META_BRANCH 72u typedef struct { uint8_t *p; size_t n, cap; bool oom; } Buf; @@ -1410,8 +1439,8 @@ static int commit_u(JsSpace *s) { JsReal *r = slab_at(s, k); n_reals++; JsReal *p = r->parent_realization; - put32(&body, r->slot); put32(&body, r->gen); - put32(&body, p ? p->slot : UINT32_MAX); put32(&body, p ? p->gen : 0); + put32(&body, r->slot); put32(&body, p ? p->slot : UINT32_MAX); + put64(&body, r->gen); put64(&body, p ? p->gen : 0); put32(&body, (uint32_t)r->realization_type); put32(&body, (uint32_t)r->recipe); put64(&body, r->token); put32(&body, r->edit_off); put32(&body, r->edit_len); @@ -1434,7 +1463,7 @@ static int commit_u(JsSpace *s) { put32(&body, (uint32_t)b->realizer->type); put32(&body, b->n_units); buf_put(&body, b->home.machine, JS_MACHINE_ID_BYTES); for (uint32_t u = 0; u < b->n_units; u++) { - put32(&body, b->units[u]->slot); put32(&body, b->units[u]->gen); + put32(&body, b->units[u]->slot); put64(&body, b->units[u]->gen); } } if (body.oom) { free(body.p); return JS_ERR_NOMEM; } @@ -1448,12 +1477,12 @@ static int commit_u(JsSpace *s) { le32(h + 32, n_types); le32(h + 36, n_reals); le32(h + 40, s->n_branches); le32(h + 44, n_br); le64(h + 48, s->spill_end); - uint32_t floor = s->real_gen_floor; + uint64_t floor = s->real_gen_floor; for (uint32_t k = 0; k < s->real_hw; k++) { JsReal *r = slab_at(s, k); - if (r->gen + 1 > floor) floor = r->gen + 1; + if (real_gen_next(r->gen) > floor) floor = real_gen_next(r->gen); } - le32(h + 56, floor); + le64(h + 56, floor); sha256_hash(body.p ? body.p : (const uint8_t *)"", body.n, h + 64); sha256_hash(h, 96, h + 96); @@ -1499,6 +1528,8 @@ static int load_u(JsSpace *s, const uint8_t *f, size_t fn, uint8_t d[32]; sha256_hash(f, 96, d); if (memcmp(d, f + 96, 32)) return JS_ERR_CORRUPT; + /* Version 1 had 32-bit realization generations: refused, never reinterpreted. */ + if (rd32(f + 8) == JS_META_VERSION_V1) return JS_ERR_VERSION; if (rd32(f + 8) != JS_META_VERSION || rd32(f + 12) != JS_META_HDR) return JS_ERR_CORRUPT; uint64_t body_len = rd64(f + 24); if (body_len != fn - JS_META_HDR) return JS_ERR_CORRUPT; @@ -1509,7 +1540,7 @@ static int load_u(JsSpace *s, const uint8_t *f, size_t fn, uint32_t n_slots = rd32(f + 40), n_br = rd32(f + 44); uint64_t spill_end = rd64(f + 48); s->commit_seq = rd64(f + 16); - s->real_gen_floor = rd32(f + 56); + s->real_gen_floor = rd64(f + 56); if (n_types > 64 || n_slots > s->limits.max_branches || n_br > n_slots || n_reals > s->limits.max_reals) return JS_ERR_CORRUPT; if (s->limits.max_spill_bytes && spill_end > s->limits.max_spill_bytes) return JS_ERR_FULL; @@ -1535,13 +1566,14 @@ static int load_u(JsSpace *s, const uint8_t *f, size_t fn, /* Realizations: place each at its own slot, link parents in a second pass. */ if ((size_t)(end - p) < (size_t)n_reals * JS_META_REAL) return JS_ERR_CORRUPT; uint32_t *parent_slot = malloc((n_reals ? n_reals : 1) * sizeof *parent_slot); - uint32_t *parent_gen = malloc((n_reals ? n_reals : 1) * sizeof *parent_gen); + uint64_t *parent_gen = malloc((n_reals ? n_reals : 1) * sizeof *parent_gen); JsReal **loaded = malloc((n_reals ? n_reals : 1) * sizeof *loaded); JsExtent *ext = malloc((2 * (size_t)n_reals + 1) * sizeof *ext); uint32_t n_ext = 0; int rc = parent_slot && parent_gen && loaded && ext ? JS_OK : JS_ERR_NOMEM; for (uint32_t i = 0; i < n_reals && rc == JS_OK; i++, p += JS_META_REAL) { - uint32_t slot = rd32(p), gen = rd32(p + 4), ty = rd32(p + 16), rec = rd32(p + 20); + uint32_t slot = rd32(p), ty = rd32(p + 24), rec = rd32(p + 28); + uint64_t gen = rd64(p + 8); const JsRealizer *rz = NULL; for (uint32_t t = 0; t < n_types; t++) if ((uint32_t)types[t]->type == ty) rz = types[t]; if (!rz || slot >= s->limits.max_reals || gen >= s->real_gen_floor || @@ -1554,18 +1586,18 @@ static int load_u(JsSpace *s, const uint8_t *f, size_t fn, r->realizer = rz; r->realization_type = rz->type; r->recipe = (JsRecipeKind)rec; - r->token = rd64(p + 24); - r->edit_off = rd32(p + 32); r->edit_len = rd32(p + 36); - r->patch_off = rd64(p + 40); - uint32_t place = rd32(p + 48); - memcpy(r->semantic_state_id.b, p + 64, 32); - memcpy(r->content, p + 96, 32); + r->token = rd64(p + 32); + r->edit_off = rd32(p + 40); r->edit_len = rd32(p + 44); + r->patch_off = rd64(p + 48); + uint32_t place = rd32(p + 56); + memcpy(r->semantic_state_id.b, p + 72, 32); + memcpy(r->content, p + 104, 32); r->placement = JS_PLACE_EVICTED; - parent_slot[i] = rd32(p + 8); parent_gen[i] = rd32(p + 12); + parent_slot[i] = rd32(p + 4); parent_gen[i] = rd64(p + 16); loaded[i] = r; s->stats.live_reals++; if (place == JS_PLACE_SPILLED) { - r->spill_off = rd64(p + 56); + r->spill_off = rd64(p + 64); r->placement = JS_PLACE_SPILLED; ext[n_ext++] = (JsExtent){ r->spill_off, rz->unit_bytes }; charge(s, r, +1); @@ -1630,8 +1662,9 @@ static int load_u(JsSpace *s, const uint8_t *f, size_t fn, uint32_t loc = rd32(p + 28); const JsRealizer *rz = NULL; for (uint32_t t = 0; t < n_types; t++) if ((uint32_t)types[t]->type == ty) rz = types[t]; - if (!rz || id >= n_slots || s->branches[id] || gen != s->branch_gen[id] || !nu || - loc > JS_HOME_REPLICA || (size_t)(end - p) < JS_META_BRANCH + (size_t)nu * 8) { + if (!rz || id >= n_slots || s->branches[id] || gen != s->branch_gen[id] || + gen == JS_BRANCH_GEN_RETIRED || !nu || + loc > JS_HOME_REPLICA || (size_t)(end - p) < JS_META_BRANCH + (size_t)nu * JS_META_UNIT) { rc = JS_ERR_CORRUPT; break; } JsBranch *b = calloc(1, sizeof *b); @@ -1645,9 +1678,9 @@ static int load_u(JsSpace *s, const uint8_t *f, size_t fn, b->units = units; b->cap_units = nu + 64; s->branches[id] = b; const uint8_t *u = p + JS_META_BRANCH; - for (uint32_t k = 0; k < nu; k++, u += 8) { + for (uint32_t k = 0; k < nu; k++, u += JS_META_UNIT) { JsReal *r = slab_at(s, rd32(u)); - if (!r || !r->realizer || r->gen != rd32(u + 4) || r->realizer != rz) { + if (!r || !r->realizer || r->gen != rd64(u + 4) || r->realizer != rz) { rc = JS_ERR_CORRUPT; break; } b->units[b->n_units++] = r; @@ -1667,11 +1700,13 @@ static int load_u(JsSpace *s, const uint8_t *f, size_t fn, JsReal *r = &s->slab[k / JS_SLAB_CHUNK][k % JS_SLAB_CHUNK]; if (r->realizer) continue; r->gen = s->real_gen_floor; + if (r->gen == JS_REAL_GEN_RETIRED) continue; /* exhausted: never reused */ r->free_next = s->real_free; s->real_free = r; } for (uint32_t i = n_slots; i-- > 0;) - if (!s->branches[i]) s->free_branch[s->n_free_branch++] = i; + if (!s->branches[i] && s->branch_gen[i] != JS_BRANCH_GEN_RETIRED) + s->free_branch[s->n_free_branch++] = i; /* a retired slot stays retired */ } free(parent_slot); free(parent_gen); free(loaded); free(ext); return rc; diff --git a/src/runtime/rx_jspace.h b/src/runtime/rx_jspace.h index b2eac5f03..d0ddfeebb 100644 --- a/src/runtime/rx_jspace.h +++ b/src/runtime/rx_jspace.h @@ -43,6 +43,7 @@ #define JS_ERR_STALE -7 /* handle generation is not current: the object was reclaimed */ #define JS_ERR_REMOTE -8 /* not locally owned; this build has no remote transport */ #define JS_ERR_OWNER -9 /* caller is not the recorded owner */ +#define JS_ERR_VERSION -10 /* durable checkpoint in a refused older format (v1: 32-bit realization generations) */ #include @@ -77,6 +78,17 @@ typedef struct { uint8_t b[32]; } JsSemId; * place: once forked it is frozen, so older World generations keep reading * the bytes they named. * + * Generations never wrap. A realization generation is 64 bits: one slot + * reused once per nanosecond needs about 584 years to exhaust it, and if it + * ever were, the slot retires (JS_REAL_GEN_RETIRED) instead of wrapping. A + * branch generation stays 32 bits because a JsBranchRef packs into one 64-bit + * World field ({id, gen}); a branch slot whose next generation would be + * JS_BRANCH_GEN_RETIRED (UINT32_MAX) retires instead: it is never handed out + * again, in memory or after js_space_open, the rule World objects follow + * (rx_world_retire). A retired branch slot costs one of max_branches; when no + * slot is left, a new branch fails JS_ERR_FULL. Either way a reference to a + * reclaimed object never validates again. + * * Concurrency: one space mutex (recursive) serializes every public call, * matching the World reference's single world mutex. Realized bytes never * change after publication, so a read returns the bytes of the generation @@ -102,9 +114,13 @@ typedef struct { uint32_t locality; /* JsLocality */ } JsHome; -typedef struct { uint32_t slot; uint32_t gen; } JsRealId; +typedef struct { uint32_t slot; uint64_t gen; } JsRealId; typedef struct { uint32_t id; uint32_t gen; } JsBranchRef; +/* Generation values that are never live (see "Generations never wrap"). */ +#define JS_REAL_GEN_RETIRED UINT64_MAX +#define JS_BRANCH_GEN_RETIRED UINT32_MAX + /* A branch reference fits one 64-bit World field. */ static inline uint64_t js_branch_ref_pack(JsBranchRef r) { return ((uint64_t)r.gen << 32) | r.id; @@ -192,7 +208,8 @@ struct JsReal { uint64_t reads; JsReal *index_next; /* semantic reuse index chain */ /* M20: stable identity and durable recipe input. */ - uint32_t slot, gen; /* JsRealId; the slab never moves a JsReal */ + uint32_t slot; /* JsRealId slot; the slab never moves a JsReal */ + uint64_t gen; /* JsRealId generation, never JS_REAL_GEN_RETIRED while live */ uint64_t patch_off; /* EDIT patch extent in the data file, UINT64_MAX if none */ JsReal *free_next; /* slab free list */ }; @@ -274,13 +291,13 @@ typedef struct { JsLimits limits; pthread_mutex_t mu; /* recursive; serializes every public call */ bool mu_ready; - uint32_t branch_gen[JS_MAX_BRANCHES]; + uint32_t branch_gen[JS_MAX_BRANCHES]; /* JS_BRANCH_GEN_RETIRED = slot retired */ uint32_t free_branch[JS_MAX_BRANCHES]; uint32_t n_free_branch; JsReal **slab; /* chunks of JS_SLAB_CHUNK realizations */ uint32_t slab_chunks; uint32_t real_hw; /* slots ever handed out */ - uint32_t real_gen_floor; /* first generation of a never-used slot */ + uint64_t real_gen_floor; /* first generation of a never-used slot (saturates) */ JsReal *real_free; JsExtent *ext_free; /* free extents, sorted by offset, coalesced */ uint32_t n_ext_free, cap_ext_free; @@ -308,7 +325,9 @@ void js_limits_default(JsLimits *lim); * SPILLED (if their extent was checkpointed) or EVICTED and rebuild from their * recipe. `realizers` must name every realization type the checkpoint uses * (matched by type and unit_bytes). A torn or corrupt checkpoint fails with - * JS_ERR_CORRUPT and leaves no state; a leftover temporary file is ignored. */ + * JS_ERR_CORRUPT and leaves no state; a leftover temporary file is ignored. + * A version-1 checkpoint (32-bit realization generations) fails with + * JS_ERR_VERSION and leaves no state: it is refused, never reinterpreted. */ int js_space_open(JsSpace *s, const char *dir, const JsRealizer *const *realizers, uint32_t n_realizers, const JsLimits *lim, const JsHome *local_home); /* Make the current non-staged state the durable checkpoint: data first diff --git a/tests/fabric/fab_living_phase.h b/tests/fabric/fab_living_phase.h index caa94ac04..24041e89e 100644 --- a/tests/fabric/fab_living_phase.h +++ b/tests/fabric/fab_living_phase.h @@ -299,8 +299,8 @@ static int fl_setup(FlRig *r, const AienMachineId *self) { fab_hmac_auth_init(&r->auth_b, &r->b, r->key_b, 2, r->roster_ids, (const uint8_t (*)[32])r->roster_keys) != FAB_OK) return -5; - FabConfig ca = { r->a, &r->roster, &r->cat_a, &r->loop.transport, &r->auth_a.auth, FL_LEASE, 1 }; - FabConfig cb = { r->b, &r->roster, &r->cat_b, &r->loop.transport, &r->auth_b.auth, FL_LEASE, 1 }; + FabConfig ca = { r->a, &r->roster, &r->cat_a, &r->loop.transport, &r->auth_a.auth, FL_LEASE, 1, NULL, 0 }; + FabConfig cb = { r->b, &r->roster, &r->cat_b, &r->loop.transport, &r->auth_b.auth, FL_LEASE, 1, NULL, 0 }; if (fab_node_init(&r->node_a, &ca) != FAB_OK || fab_node_init(&r->node_b, &cb) != FAB_OK) return -6; if (fl_own_skill(&r->cat_b, &r->skills_b.skill[0], FX_OP_SCALE, 2, RX_RIGHT_READ, 5, diff --git a/tests/fabric/fabric_test.c b/tests/fabric/fabric_test.c index 1e7ddaa78..701cb69a7 100644 --- a/tests/fabric/fabric_test.c +++ b/tests/fabric/fabric_test.c @@ -99,7 +99,7 @@ static void house_init(House *h) { (const uint8_t (*)[32])h->key) == FAB_E_ARG, "oversized verifier roster refused"); CHECK(fab_hmac_auth_init(&h->auth[i], &h->id[i], h->key[i], 3, h->roster_ids, (const uint8_t (*)[32])h->key) == FAB_OK, "verifier roster"); - FabConfig cfg = { h->id[i], &h->roster, c, &h->loop.transport, &h->auth[i].auth, LEASE, 1 }; + FabConfig cfg = { h->id[i], &h->roster, c, &h->loop.transport, &h->auth[i].auth, LEASE, 1, NULL, 0 }; CHECK(fab_node_init(&h->node[i], &cfg) == FAB_OK, "node init"); } } @@ -450,9 +450,206 @@ static void test_sig64(void) { house_free(h); } +/* ---- Lane 32: generation width ---- + * Entry generations are generation << 32 | rev, so a membership generation of + * 2^32 or more would lose its high bits (2^32 would rank as 0). Every way in + * refuses it with FAB_E_GENERATION and changes nothing. Outside scenario() so + * the replay digest is unchanged. */ +static void test_gen_width(void) { + static House hh; + static FabNode tmp; + House *h = &hh; + house_init(h); + const uint64_t wide[2] = { 1ull << 32, (1ull << 32) + 1 }; + for (int w = 0; w < 2; w++) { + CHECK(fab_node_set_generation(&h->node[A], wide[w]) == FAB_E_GENERATION, + "set_generation(%llu) not refused", (unsigned long long)wide[w]); + CHECK(h->node[A].cfg.generation == 1, "refused set_generation changed the generation"); + FabConfig cfg = { h->id[A], &h->roster, &h->cat[A], &h->loop.transport, &h->auth[A].auth, + LEASE, wide[w], NULL, 0 }; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_GENERATION, "init with generation %llu not refused", + (unsigned long long)wide[w]); + } + CHECK(fab_entry_generation(&h->node[A], 7) == (1ull << 32 | 7), "entry generation at 1"); + + /* A peer's JOIN claiming generation 2^32 or 2^32+1 (validly signed). */ + for (int i = 0; i < 3; i++) CHECK(fab_join(&h->node[i], LEASE, 0) == FAB_OK, "join %d", i); + uint8_t m[FAB_MSG_MAX]; + size_t len = peek(h, A, C, FAB_MSG_JOIN, m); + CHECK(len == FAB_HDR_BYTES + FAB_JOIN_BODY + FAB_SIG_BYTES, "captured C join"); + CHECK(pump(h, 0) == 0, "joins accepted"); + for (int w = 0; w < 2; w++) { + put64(m + 96, wide[w]); + put64(m + 104, 100 + (uint64_t)w); + reseal(m, len, h->key[C]); + FabVerdict v = deliver(h, A, m, len, MS); + CHECK(v.code == FAB_E_GENERATION, "JOIN at generation %llu: %s", + (unsigned long long)wide[w], fab_strerror(v.code)); + const FabMember *c = fab_member(&h->node[A], &h->id[C]); + CHECK(c && c->generation == 1 && c->state == FAB_ST_JOINED, + "JOIN at generation %llu changed C's membership", (unsigned long long)wide[w]); + } + /* The top of the range still works and keeps every bit. */ + CHECK(fab_node_set_generation(&h->node[A], FAB_GEN_MAX) == FAB_OK, "set_generation(FAB_GEN_MAX)"); + CHECK(fab_entry_generation(&h->node[A], 7) == ((uint64_t)FAB_GEN_MAX << 32 | 7), "entry generation at max"); + house_free(h); +} + +/* ---- Lane 32: replay window survives a receiver restart ---- */ + +typedef struct { + uint8_t rec[FAB_STATE_MAX + 64]; + size_t len; + int has, fail_save, fail_load; + unsigned saves; +} MemStore; + +static int mem_save(void *ctx, const uint8_t *rec, size_t len) { + MemStore *s = ctx; + if (s->fail_save || len > sizeof s->rec) return -1; + memcpy(s->rec, rec, len); + s->len = len; + s->has = 1; + s->saves++; + return 0; +} + +static int mem_load(void *ctx, uint8_t *buf, size_t cap, size_t *len) { + MemStore *s = ctx; + if (s->fail_load) return -1; + if (!s->has) return 0; + if (s->len > cap) return -1; + memcpy(buf, s->rec, s->len); + *len = s->len; + return 1; +} + +/* Node i starts over: new catalog (memory is gone), window from the store. */ +static int restart(House *h, int i, const FabStore *st, uint32_t fresh) { + cq_catalog_free(&h->cat[i]); + aien_mid_index_init(&h->index[i], h->slots[i], 8); + CqCatalog *c = &h->cat[i]; + CHECK(cq_catalog_init_canonical(c, &h->index[i], &h->id[i], 8, 16) == CQ_OK, "catalog"); + uint32_t dom = CQ_SRC(CQ_SRC_GRAPH) | CQ_SRC(CQ_SRC_FABRIC); + CHECK(cq_op_define(c, 1, 0, dom) == CQ_OK && cq_op_define(c, 2, 1, dom) == CQ_OK, "ops"); + FabConfig cfg = { h->id[i], &h->roster, c, &h->loop.transport, &h->auth[i].auth, LEASE, 1, st, fresh }; + return fab_node_init(&h->node[i], &cfg); +} + +static uint64_t seq_of(House *h, int i, int peer) { + const FabMember *m = fab_member(&h->node[i], &h->id[peer]); + return m ? m->last_seq : UINT64_MAX; +} + +static void test_restart_replay(void) { + static House hh; + static MemStore ms; + static FabNode tmp; + House *h = &hh; + memset(&ms, 0, sizeof ms); + FabStore st = { &ms, mem_save, mem_load }; + house_init(h); + CHECK(restart(h, A, &st, 1) == FAB_OK, "A first start with an empty store"); + CHECK(ms.has, "first start saved an empty window"); + + /* t=0 joins; t=100ms C renews. Capture C's JOIN and RENEW to A. */ + uint8_t join_c[FAB_MSG_MAX], renew_c[FAB_MSG_MAX], renew_c2[FAB_MSG_MAX]; + for (int i = 0; i < 3; i++) CHECK(fab_join(&h->node[i], LEASE, 0) == FAB_OK, "join %d", i); + size_t join_len = peek(h, A, C, FAB_MSG_JOIN, join_c); + CHECK(pump(h, 0) == 0, "joins accepted"); + CHECK(fab_renew(&h->node[C], LEASE, 100 * MS) == FAB_OK, "renew C"); + size_t renew_len = peek(h, A, C, FAB_MSG_RENEW, renew_c); + CHECK(join_len && renew_len, "captured C's JOIN and RENEW"); + CHECK(pump(h, 100 * MS) == 0, "renewal accepted"); + const FabMember *c = fab_member(&h->node[A], &h->id[C]); + uint64_t c_seq = c ? c->last_seq : 0; + CHECK(c && c->state == FAB_ST_JOINED && c->generation == 1 && c_seq >= 2, "A holds C"); + + /* Receiver A restarts from its store. */ + CHECK(restart(h, A, &st, 0) == FAB_OK, "A restarts from the saved window"); + CHECK(fab_node_set_generation(&h->node[A], 2) == FAB_OK, "A sends in a new generation"); + c = fab_member(&h->node[A], &h->id[C]); + CHECK(c && c->state == FAB_ST_LOST && c->generation == 1 && c->last_seq == c_seq, + "restored C: LOST, generation 1, last seq %llu", (unsigned long long)c_seq); + FabVerdict v = deliver(h, A, join_c, join_len, 200 * MS); + CHECK(v.code == FAB_E_REPLAY, "captured JOIN replayed after restart: %s", fab_strerror(v.code)); + v = deliver(h, A, renew_c, renew_len, 200 * MS); + CHECK(v.code == FAB_E_REPLAY, "captured RENEW replayed after restart: %s", fab_strerror(v.code)); + CHECK(!fab_member_live(&h->node[A], &h->id[C], 200 * MS), "replay made C live"); + + /* A fresh legitimate message after the restart: C rejoins at generation 2. */ + CHECK(fab_node_set_generation(&h->node[C], 2) == FAB_OK, "C new generation"); + CHECK(fab_join(&h->node[C], LEASE, 300 * MS) == FAB_OK, "C rejoins"); + CHECK(pump(h, 300 * MS) == 0, "fresh JOIN after restart accepted"); + c = fab_member(&h->node[A], &h->id[C]); + CHECK(c && c->state == FAB_ST_JOINED && c->generation == 2, "A holds C at generation 2"); + CHECK(fab_member_live(&h->node[A], &h->id[C], 300 * MS), "C live on A after rejoin"); + v = deliver(h, A, join_c, join_len, 300 * MS); + CHECK(v.code == FAB_E_STALE_GEN, "old JOIN after rejoin: %s", fab_strerror(v.code)); + + /* A save that fails refuses the message and consumes nothing. */ + CHECK(fab_renew(&h->node[C], LEASE, 400 * MS) == FAB_OK, "renew C"); + size_t renew2_len = peek(h, A, C, FAB_MSG_RENEW, renew_c2); + CHECK(renew2_len > 0, "captured second RENEW"); + uint64_t before = seq_of(h, A, C); + ms.fail_save = 1; + CHECK(pump(h, 400 * MS) == 1, "unsaved RENEW refused (B accepts its copy)"); + CHECK(seq_of(h, A, C) == before, "unsaved RENEW consumed its seq"); + ms.fail_save = 0; + v = deliver(h, A, renew_c2, renew2_len, 400 * MS); + CHECK(v.code == FAB_OK, "same RENEW once the store works: %s", fab_strerror(v.code)); + v = deliver(h, A, renew_c2, renew2_len, 400 * MS); + CHECK(v.code == FAB_E_REPLAY, "second delivery: %s", fab_strerror(v.code)); + + /* Second restart: the generation-2 window came back too. */ + CHECK(restart(h, A, &st, 0) == FAB_OK, "A restarts again"); + c = fab_member(&h->node[A], &h->id[C]); + CHECK(c && c->generation == 2 && c->state == FAB_ST_LOST, "generation 2 restored"); + v = deliver(h, A, renew_c2, renew2_len, 500 * MS); + CHECK(v.code == FAB_E_REPLAY, "RENEW replayed after second restart: %s", fab_strerror(v.code)); + + /* Fail closed. Each refused start leaves the store as it was. */ + FabConfig cfg = { h->id[A], &h->roster, &h->cat[A], &h->loop.transport, &h->auth[A].auth, + LEASE, 3, &st, 0 }; + MemStore keep = ms; + CHECK(fab_node_init(&tmp, &cfg) == FAB_OK, "intact window starts"); + cfg.store_fresh = 1; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_STATE, "first start over a saved window"); + cfg.store_fresh = 0; + ms.has = 0; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_STATE, "missing window started (would forget)"); + ms = keep; + ms.fail_load = 1; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_STATE, "unreadable window started"); + ms = keep; + for (size_t at = 0; at < keep.len; at += 13) { + ms.rec[at] ^= 0x01; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_STATE, "window with byte %zu flipped started", at); + ms.rec[at] ^= 0x01; + } + ms.len = keep.len - 1; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_STATE, "truncated window started"); + ms.len = keep.len + 1; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_STATE, "padded window started"); + ms = keep; + FabConfig other = { h->id[B], &h->roster, &h->cat[B], &h->loop.transport, &h->auth[B].auth, + LEASE, 3, &st, 0 }; + CHECK(fab_node_init(&tmp, &other) == FAB_E_STATE, "another machine's window accepted"); + FabStore half = { &ms, mem_save, NULL }; + cfg.store = ½ + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_ARG, "store without load accepted"); + cfg.store = NULL; + cfg.store_fresh = 1; + CHECK(fab_node_init(&tmp, &cfg) == FAB_E_ARG, "store_fresh without a store accepted"); + CHECK(ms.len == keep.len && memcmp(ms.rec, keep.rec, keep.len) == 0, "refused starts changed the store"); + house_free(h); +} + int main(void) { test_hmac(); test_sig64(); + test_gen_width(); + test_restart_replay(); uint8_t r1[4][32], r2[4][32]; scenario(r1); unsigned first_checks = checks; diff --git a/tests/runtime/rx_jspace_prod.c b/tests/runtime/rx_jspace_prod.c index 47dad4368..e2a57b11f 100644 --- a/tests/runtime/rx_jspace_prod.c +++ b/tests/runtime/rx_jspace_prod.c @@ -13,6 +13,7 @@ #include "runtime/rx_caproot.h" #include "runtime/rx_world.h" #include "runtime/rx_jspace.h" +#include "sha256.h" #include #include @@ -670,6 +671,154 @@ static void test_world(void) { printf(" world: %u writer activations, %u committed steps\n", u.ran, n); } +/* ---- Lane 32: generations never wrap (no ABA) ------------------------------ + * + * A slot is driven to the last live generation its type can hold (standing in + * for ~2^64 realization reuses or ~2^32 branch reuses) by writing the public + * struct field, then released and reused. The exhausted slot must never be + * handed out again and no older reference may validate. The top is computed + * from the field's own type so this test also compiles against 32-bit + * realization generations, where it fails (the slot wraps to generation 0 and + * the first occupant's reference validates again). */ +#define GEN_TOP(T) ((T)~(T)0) +typedef __typeof__(((JsReal *)0)->gen) RealGen; +typedef __typeof__(((JsBranchRef *)0)->gen) BranchGen; + +static void test_gen_exhaustion(void) { + static JsSpace s; + /* Realization slot. */ + CHECK(js_space_init(&s, "/tmp/jspace_prod_spill") == JS_OK, "init"); + uint32_t root; + js_branch_root(&s, &RZ, 77, &root); + JsBranchRef rr, c; + js_branch_ref(&s, root, &rr); + CHECK(js_branch_fork_staged(&s, rr, 0, &c) == JS_OK, "fork"); + CHECK(js_branch_derive(&s, c.id, 700) == JS_OK, "derive"); + uint32_t last = s.branches[c.id]->n_units - 1; + JsRealId first, top; + js_real_id(&s, c.id, last, &first); + CHECK(first.gen == 0, "first occupant generation %llu", (unsigned long long)first.gen); + JsReal *r = unit_of(&s, c.id, last); + r->gen = GEN_TOP(RealGen) - 1; /* the last live generation */ + js_real_id(&s, c.id, last, &top); + CHECK(js_real_lookup(&s, top) == r, "top-generation reference resolves while live"); + CHECK(js_branch_release_ref(&s, c, 0) == JS_OK, "release at top generation"); + CHECK(js_real_lookup(&s, top) == NULL, "released top-generation reference resolves"); + for (int k = 0; k < 4; k++) { + CHECK(js_branch_fork_staged(&s, rr, 0, &c) == JS_OK, "refork %d", k); + CHECK(js_branch_derive(&s, c.id, 701 + (uint64_t)k) == JS_OK, "rederive %d", k); + JsRealId now; + js_real_id(&s, c.id, s.branches[c.id]->n_units - 1, &now); + CHECK(now.slot != first.slot, "cycle %d: exhausted realization slot %u handed out again (gen %llu)", + k, now.slot, (unsigned long long)now.gen); + CHECK(js_real_lookup(&s, first) == NULL, "cycle %d: first occupant's reference validates (ABA)", k); + CHECK(js_real_lookup(&s, top) == NULL, "cycle %d: top-generation reference validates", k); + CHECK(js_branch_release_ref(&s, c, 0) == JS_OK, "release %d", k); + } + js_space_destroy(&s); + + /* Branch slot: 32-bit generations (a JsBranchRef packs into a World field). */ + CHECK(js_space_init(&s, "/tmp/jspace_prod_spill") == JS_OK, "init"); + js_branch_root(&s, &RZ, 78, &root); + js_branch_ref(&s, root, &rr); + JsBranchRef b0, btop; + CHECK(js_branch_fork_staged(&s, rr, 0, &b0) == JS_OK, "fork b0"); + CHECK(b0.gen == 0, "first branch occupant generation %u", b0.gen); + s.branch_gen[b0.id] = GEN_TOP(BranchGen) - 1; + s.branches[b0.id]->gen = GEN_TOP(BranchGen) - 1; + btop = (JsBranchRef){ b0.id, GEN_TOP(BranchGen) - 1 }; + CHECK(js_branch_check(&s, btop) == JS_OK, "top-generation branch ref valid while live"); + CHECK(js_branch_check(&s, b0) == JS_ERR_STALE, "older branch ref valid"); + CHECK(js_branch_release_ref(&s, btop, 0) == JS_OK, "release branch at top generation"); + for (int k = 0; k < 4; k++) { + JsBranchRef nb; + CHECK(js_branch_fork_staged(&s, rr, 0, &nb) == JS_OK, "branch refork %d", k); + CHECK(nb.id != b0.id, "cycle %d: exhausted branch slot %u handed out again (gen %u)", k, nb.id, nb.gen); + CHECK(js_branch_check(&s, b0) == JS_ERR_STALE, "cycle %d: first branch reference validates (ABA)", k); + CHECK(js_branch_check(&s, btop) == JS_ERR_STALE, "cycle %d: top branch reference validates", k); + CHECK(js_branch_release_ref(&s, nb, 0) == JS_OK, "branch release %d", k); + } + /* A full space whose only free slot retired refuses a new branch. */ + js_space_destroy(&s); + JsLimits l = lim(64, 2, 0, 0); + CHECK(js_space_init_limits(&s, "/tmp/jspace_prod_spill", &l) == JS_OK, "init 2 branches"); + js_branch_root(&s, &RZ, 79, &root); + js_branch_ref(&s, root, &rr); + CHECK(js_branch_fork_staged(&s, rr, 0, &b0) == JS_OK, "fork into the last slot"); + s.branch_gen[b0.id] = GEN_TOP(BranchGen) - 1; + s.branches[b0.id]->gen = GEN_TOP(BranchGen) - 1; + btop = (JsBranchRef){ b0.id, GEN_TOP(BranchGen) - 1 }; + CHECK(js_branch_release_ref(&s, btop, 0) == JS_OK, "release last slot at top generation"); + JsBranchRef nb; + CHECK(js_branch_fork_staged(&s, rr, 0, &nb) == JS_ERR_FULL, "retired slot reused instead of JS_ERR_FULL"); + js_space_destroy(&s); +} + +/* Durable: a retired branch slot stays retired after reopen, a realization + * generation above 2^32 comes back whole, and a version-1 checkpoint (32-bit + * realization generations) is refused with JS_ERR_VERSION. */ +static void test_gen_durable(void) { + char dir[64], meta[128], data[128]; + snprintf(dir, sizeof dir, "/tmp/jspace_gen_XXXXXX"); + if (!mkdtemp(dir)) { CHECK(0, "mkdtemp"); return; } + snprintf(meta, sizeof meta, "%s/jspace.meta", dir); + snprintf(data, sizeof data, "%s/jspace.data", dir); + static JsSpace s; + JsHome me = { .locality = JS_HOME_LOCAL }; + memset(me.machine, 0x11, sizeof me.machine); + CHECK(js_space_open(&s, dir, RZS, 2, NULL, &me) == JS_OK, "fresh open"); + uint32_t a, b, c; + js_branch_root(&s, &RZ, 90, &a); + for (unsigned i = 0; i < 3; i++) js_branch_derive(&s, a, 900 + i); + CHECK(js_branch_fork(&s, a, &b) == JS_OK, "fork b"); + CHECK(js_branch_derive(&s, b, 950) == JS_OK, "derive b"); + uint32_t bl = s.branches[b]->n_units - 1; + const RealGen wide = sizeof(RealGen) == 8 ? (RealGen)((1ull << 32) + 5) : (RealGen)5; + CHECK(sizeof(RealGen) == 8, "realization generations are %zu bytes, not 8", sizeof(RealGen)); + unit_of(&s, b, bl)->gen = wide; + JsRealId wid; + js_real_id(&s, b, bl, &wid); + CHECK(js_branch_fork(&s, a, &c) == JS_OK, "fork c"); + s.branch_gen[c] = GEN_TOP(BranchGen) - 1; + s.branches[c]->gen = GEN_TOP(BranchGen) - 1; + CHECK(js_branch_release(&s, c) == JS_OK, "release c at top generation"); + CHECK(js_space_commit(&s) == JS_OK, "commit"); + js_space_destroy(&s); + + CHECK(js_space_open(&s, dir, RZS, 2, NULL, &me) == JS_OK, "reopen"); + JsRealId got; + CHECK(js_real_id(&s, b, bl, &got) == JS_OK && got.gen == wid.gen && got.slot == wid.slot, + "wide realization generation did not survive reopen (%llu vs %llu)", + (unsigned long long)got.gen, (unsigned long long)wid.gen); + JsRealId low = { wid.slot, (RealGen)(uint32_t)wid.gen }; + CHECK(js_real_lookup(&s, low) == NULL, "truncated generation resolves"); + CHECK(s.branch_gen[c] == GEN_TOP(BranchGen), "retired branch slot generation %u after reopen", s.branch_gen[c]); + JsBranchRef ar; + js_branch_ref(&s, a, &ar); + for (int k = 0; k < 3; k++) { + JsBranchRef nb; + CHECK(js_branch_fork_staged(&s, ar, 0, &nb) == JS_OK, "fork after reopen %d", k); + CHECK(nb.id != c, "retired branch slot %u handed out after reopen", c); + CHECK(js_branch_check(&s, (JsBranchRef){ c, 0 }) == JS_ERR_STALE, "first ref of retired slot valid"); + js_branch_release_ref(&s, nb, 0); + } + js_space_destroy(&s); + + /* Rewrite the header as version 1 (header hash recomputed): refused. */ + int fd = open(meta, O_RDWR); + uint8_t h[128]; + CHECK(fd >= 0 && pread(fd, h, sizeof h, 0) == (ssize_t)sizeof h, "read header"); + h[8] = 1; h[9] = h[10] = h[11] = 0; + sha256_hash(h, 96, h + 96); + CHECK(fd >= 0 && pwrite(fd, h, sizeof h, 0) == (ssize_t)sizeof h, "write v1 header"); + if (fd >= 0) close(fd); + int rc = js_space_open(&s, dir, RZS, 2, NULL, &me); + CHECK(rc == JS_ERR_VERSION, "version-1 checkpoint: open rc %d, want JS_ERR_VERSION", rc); + if (rc == JS_OK) js_space_destroy(&s); + unlink(meta); unlink(data); + rmdir(dir); +} + int main(void) { struct { const char *name; void (*fn)(void); } t[] = { { "alloc_reclaim", test_alloc_reclaim }, @@ -679,6 +828,8 @@ int main(void) { { "remote", test_remote }, { "durable", test_durable }, { "world_commit", test_world }, + { "gen_exhaustion", test_gen_exhaustion }, + { "gen_durable", test_gen_durable }, }; for (size_t i = 0; i < sizeof t / sizeof *t; i++) { int before = g_fail;