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
omega-mv / src / physics0 / ladder / pd0_ladder.c
| 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 | #include "pd0_ladder.h" |
| 18 | #include "pd0_rng.h" |
| 19 | #include "sha256.h" |
| 20 | #include <math.h> |
| 21 | #include <stdio.h> |
| 22 | #include <stdlib.h> |
| 23 | #include <string.h> |
| 24 | |
| 25 | #define MAX_REC 65536u |
| 26 | #define MAX_EP 2048u |
| 27 | #define MAX_RELS 64u |
| 28 | #define MAX_PREREG 64u |
| 29 | #define MAX_BATCH 32u |
| 30 | #define EXP_BYTES 8192u |
| 31 | |
| 32 | const char *pd0_ladder_state_name(int s) |
| 33 | { |
| 34 | static const char *n[] = { "START", "OBSERVATION", "CORRELATION", "CANDIDATE", "HYPOTHESIS", "PREDICTED", "INTERVENED", "REPLICATED" }; |
| 35 | return (s >= 0 && s <= LS_REPLICATED) ? n[s] : "?"; |
| 36 | } |
| 37 | |
| 38 | void pd0_ladder_params_default(pd0_ladder_params *P, uint8_t n_obs, uint8_t n_channels) |
| 39 | { |
| 40 | memset(P, 0, sizeof *P); |
| 41 | P->n_obs = n_obs; P->n_channels = n_channels; |
| 42 | for (int c = 0; c < n_channels; c++) { P->chan_min[c] = -2 * PD0_MICRO; P->chan_max[c] = 2 * PD0_MICRO; } |
| 43 | P->reset_min = -2 * PD0_MICRO; P->reset_max = 2 * PD0_MICRO; P->episode_len = 100; P->dt_micro = 50000; |
| 44 | P->size_bound = 6; P->eps_bound_micro = 20000; |
| 45 | P->min_t1_records = 100; P->min_t1_episodes = 5; P->min_prereg = 5; P->min_batches = 3; P->min_batch_episodes = 10; P->rollout_steps = 20; |
| 46 | } |
| 47 | |
| 48 | /* ---------- statistics ---------- */ |
| 49 | double pd0_pearson(const double *x, const double *y, uint32_t n) |
| 50 | { |
| 51 | double sx = 0, sy = 0; for (uint32_t i = 0; i < n; i++) { sx += x[i]; sy += y[i]; } |
| 52 | double mx = sx / n, my = sy / n, sxy = 0, sxx = 0, syy = 0; |
| 53 | for (uint32_t i = 0; i < n; i++) { double a = x[i] - mx, b = y[i] - my; sxy += a * b; sxx += a * a; syy += b * b; } |
| 54 | if (sxx <= 0 || syy <= 0) return 0; |
| 55 | return sxy / sqrt(sxx * syy); |
| 56 | } |
| 57 | double pd0_perm_p(const double *x, const double *y, uint32_t n, uint32_t n_shuffles, uint64_t seed) |
| 58 | { |
| 59 | double r0 = fabs(pd0_pearson(x, y, n)); uint32_t hits = 0; |
| 60 | double *yp = malloc(sizeof(double) * n); if (!yp) return 1.0; |
| 61 | memcpy(yp, y, sizeof(double) * n); |
| 62 | pd0_rng g; pd0_rng_stream(&g, seed, "perm"); |
| 63 | for (uint32_t s = 0; s < n_shuffles; s++) { |
| 64 | for (uint32_t i = n - 1; i > 0; i--) { uint32_t j = (uint32_t)(pd0_rng_next(&g) % (i + 1)); double t = yp[i]; yp[i] = yp[j]; yp[j] = t; } |
| 65 | if (fabs(pd0_pearson(x, yp, n)) >= r0) hits++; |
| 66 | } |
| 67 | free(yp); |
| 68 | return (double)(hits + 1) / (double)(n_shuffles + 1); |
| 69 | } |
| 70 | typedef struct { double se[PD0_MAX_OBS], s[PD0_MAX_OBS], ss[PD0_MAX_OBS]; uint32_t n; } nrmse_acc; |
| 71 | static void acc_add(nrmse_acc *a, const int64_t *pred, const int64_t *obs, uint8_t n_obs) |
| 72 | { |
| 73 | for (int j = 0; j < n_obs; j++) { double e = (double)(pred[j] - obs[j]) / 1e6, v = (double)obs[j] / 1e6; a->se[j] += e * e; a->s[j] += v; a->ss[j] += v * v; } |
| 74 | a->n++; |
| 75 | } |
| 76 | static int64_t acc_nrmse(const nrmse_acc *a, uint8_t n_obs) |
| 77 | { |
| 78 | if (a->n == 0) return INT64_MAX; double worst = 0; |
| 79 | for (int j = 0; j < n_obs; j++) { |
| 80 | double rmse = sqrt(a->se[j] / a->n), m = a->s[j] / a->n, var = a->ss[j] / a->n - m * m, sd = var > 0 ? sqrt(var) : 0; |
| 81 | double v = sd > 1e-9 ? rmse / sd : rmse; if (v > worst) worst = v; |
| 82 | } |
| 83 | return worst > 9e12 ? INT64_MAX : (int64_t)(worst * 1e6); |
| 84 | } |
| 85 | int64_t pd0_nrmse_micro(const int64_t *pred, const int64_t *obs, uint32_t n, uint8_t n_obs) |
| 86 | { |
| 87 | nrmse_acc a; memset(&a, 0, sizeof a); |
| 88 | for (uint32_t i = 0; i < n; i++) acc_add(&a, pred + (size_t)i * n_obs, obs + (size_t)i * n_obs, n_obs); |
| 89 | return acc_nrmse(&a, n_obs); |
| 90 | } |
| 91 | /* spec rev 6 (b): a step record carries an outcome (valid vars_after) when it is OK or EPISODE_END; |
| 92 | * only REFUSED_RANGE, OUT_OF_BOUNDS and BUDGET_EXHAUSTED carry none. */ |
| 93 | static int rec_has_outcome(const pd0_rec *r) { return r->status == PD0_ST_OK || r->status == PD0_ST_EPISODE_END; } |
| 94 | /* spec rev 6 (a): rollout error per variable = RMSE / pooled sd of that variable over the FIT records, |
| 95 | * never the within-trial spread (sd_micro[j] == 0 falls back to the plain RMSE) */ |
| 96 | static int64_t acc_nrmse_sd(const nrmse_acc *a, uint8_t n_obs, const int64_t *sd_micro) |
| 97 | { |
| 98 | if (a->n == 0) return INT64_MAX; double worst = 0; |
| 99 | for (int j = 0; j < n_obs; j++) { double rmse = sqrt(a->se[j] / a->n), sd = (double)sd_micro[j] / 1e6; double v = sd > 1e-9 ? rmse / sd : rmse; if (v > worst) worst = v; } |
| 100 | return worst > 9e12 ? INT64_MAX : (int64_t)(worst * 1e6); |
| 101 | } |
| 102 | int64_t pd0_nrmse_pooled_micro(const int64_t *pred, const int64_t *obs, uint32_t n, uint8_t n_obs, const int64_t *sd_micro) |
| 103 | { |
| 104 | nrmse_acc a; memset(&a, 0, sizeof a); |
| 105 | for (uint32_t i = 0; i < n; i++) acc_add(&a, pred + (size_t)i * n_obs, obs + (size_t)i * n_obs, n_obs); |
| 106 | return acc_nrmse_sd(&a, n_obs, sd_micro); |
| 107 | } |
| 108 | uint32_t pd0_confidence_ppm(uint32_t p, uint32_t f) { return (uint32_t)((1000000ull * (p + 1)) / (p + f + 2)); } |
| 109 | |
| 110 | /* ---------- internal model ---------- */ |
| 111 | typedef struct { uint32_t first, n; uint8_t tag, origin, has_tag; uint32_t batch_id, tag_entry, first_entry, episode_no; int complete; } episode; |
| 112 | typedef struct { uint8_t hash[PD0_HASH]; uint8_t role; pd0_rel rel; } relent; |
| 113 | typedef struct { pd0_exp e; uint8_t hash[PD0_HASH]; uint32_t entry; int matched_ep; } prereg; |
| 114 | typedef struct { pd0_batch b; uint8_t hash[PD0_HASH]; uint32_t entry; } batchent; |
| 115 | |
| 116 | typedef struct { |
| 117 | const pd0_ladder_params *P; pd0_ladder_report *R; |
| 118 | pd0_rec *rec; uint32_t nrec; uint8_t last_rec_hash[PD0_HASH]; int have_rec; |
| 119 | episode ep[MAX_EP]; uint32_t nep; |
| 120 | relent rels[MAX_RELS]; uint32_t nrels; |
| 121 | int have_fals; pd0_falsifier fals; uint8_t fals_hash[PD0_HASH]; |
| 122 | prereg pre[MAX_PREREG]; uint32_t npre; |
| 123 | batchent bat[MAX_BATCH]; uint32_t nbat; |
| 124 | uint32_t entry_idx; |
| 125 | } ctx; |
| 126 | |
| 127 | static episode *find_ep(ctx *c, uint32_t no, int create) |
| 128 | { |
| 129 | for (uint32_t i = 0; i < c->nep; i++) if (c->ep[i].episode_no == no) return &c->ep[i]; |
| 130 | if (!create || c->nep >= MAX_EP) return NULL; |
| 131 | episode *e = &c->ep[c->nep++]; memset(e, 0, sizeof *e); e->episode_no = no; e->first = UINT32_MAX; return e; |
| 132 | } |
| 133 | static int ep_visible(const episode *e) { return e->has_tag && (e->tag == TAG_FIT || e->tag == TAG_SELECT); } |
| 134 | static int ep_fit(const episode *e) { return e->has_tag && e->tag == TAG_FIT; } |
| 135 | static uint32_t ep_ok_steps(const ctx *c, const episode *e) |
| 136 | { |
| 137 | uint32_t k = 0; for (uint32_t i = 0; i < e->n; i++) { const pd0_rec *r = &c->rec[e->first + i]; if (r->kind == PD0_KIND_STEP && rec_has_outcome(r)) k++; } |
| 138 | return k; |
| 139 | } |
| 140 | /* schedule hash over the reset record and the first n_steps OK steps */ |
| 141 | static int ep_schedule_hash(const ctx *c, const episode *e, uint8_t n_steps, uint8_t out[PD0_HASH]) |
| 142 | { |
| 143 | const pd0_rec *r0 = &c->rec[e->first]; if (r0->kind != PD0_KIND_RESET) return 0; |
| 144 | pd0_step st[PD0_MAX_STEPS]; uint8_t k = 0; |
| 145 | for (uint32_t i = 1; i < e->n && k < n_steps; i++) { const pd0_rec *r = &c->rec[e->first + i]; if (r->kind == PD0_KIND_STEP && rec_has_outcome(r)) { st[k].channel = r->channel; st[k].value = r->applied; k++; } } |
| 146 | if (k < n_steps) return 0; |
| 147 | pd0_schedule_hash(r0->n_obs, r0->after, n_steps, st, out); |
| 148 | return 1; |
| 149 | } |
| 150 | /* spec rev 5: a preregistered schedule binds the REQUESTED reset values and the applied (channel, value) |
| 151 | * steps, never the observed reset (which carries noise on noisy levels). The requested reset is the one |
| 152 | * in the PD0EXP1 entry; the episode matches when the hash of that reset with the episode's applied steps |
| 153 | * equals the preregistered hash and, on noise-free levels, the observed reset equals the requested one. |
| 154 | * On noisy levels the observed reset is not compared (limit: the trial error bound covers it). */ |
| 155 | static int ep_matches_prereg(const ctx *c, const episode *ep, const pd0_exp *e) |
| 156 | { |
| 157 | const pd0_rec *r0 = &c->rec[ep->first]; if (r0->kind != PD0_KIND_RESET || r0->n_obs != e->n_obs) return 0; |
| 158 | pd0_step st[PD0_MAX_STEPS]; uint8_t k = 0; |
| 159 | for (uint32_t i = 1; i < ep->n && k < e->n_steps; i++) { const pd0_rec *r = &c->rec[ep->first + i]; if (r->kind == PD0_KIND_STEP && rec_has_outcome(r)) { st[k].channel = r->channel; st[k].value = r->applied; k++; } } |
| 160 | if (k < e->n_steps) return 0; |
| 161 | uint8_t h[PD0_HASH]; pd0_schedule_hash(e->n_obs, e->reset, e->n_steps, st, h); if (memcmp(h, e->schedule_hash, PD0_HASH)) return 0; |
| 162 | if (!c->P->noisy) for (int j = 0; j < e->n_obs; j++) if (r0->after[j] != e->reset[j]) return 0; |
| 163 | return 1; |
| 164 | } |
| 165 | static void set_code(ctx *c, int t, int code) { c->R->transition = t; c->R->code = code; if (code == PD0V_OK) c->R->stall_code = 0; else if (!c->R->stall_code) c->R->stall_code = code; } |
| 166 | static void refute(ctx *c, const pd0_rec *bad, int64_t predicted, int64_t observed) |
| 167 | { |
| 168 | pd0_ladder_report *R = c->R; |
| 169 | if (R->n_exceptions < PD0_MAX_EXC) { |
| 170 | pd0_exception *x = &R->exc[R->n_exceptions++]; x->record_seq = bad->seq; memcpy(x->record_hash, bad->record_hash, PD0_HASH); |
| 171 | x->predicted = predicted; x->observed = observed; x->error_micro = predicted - observed; |
| 172 | } |
| 173 | R->n_refutations++; |
| 174 | R->have_candidate = 0; c->have_fals = 0; c->npre = 0; c->nbat = 0; |
| 175 | for (uint32_t i = 0; i < c->nep; i++) if (c->ep[i].has_tag) { c->ep[i].tag = TAG_FIT; } |
| 176 | R->state = LS_CANDIDATE; |
| 177 | } |
| 178 | static void add_experiment(ctx *c, const uint8_t *id, uint8_t kind, const uint8_t *prereg_hash, const uint8_t *outcome, uint8_t result, uint64_t first, uint64_t last) |
| 179 | { |
| 180 | pd0_ladder_report *R = c->R; if (R->n_experiments >= PD0_MAX_EXP) return; |
| 181 | pd0_experiment *x = &R->exp[R->n_experiments++]; memcpy(x->experiment_id, id, PD0_HASH); x->kind = kind; |
| 182 | memcpy(x->prereg_hash, prereg_hash, PD0_HASH); memcpy(x->outcome_hash, outcome, PD0_HASH); x->result = result; x->first_seq = first; x->last_seq = last; |
| 183 | } |
| 184 | |
| 185 | /* pooled sd per observed variable over the outcomes of FIT records (spec rev 6 a) */ |
| 186 | static void fit_sd(const ctx *c, int64_t *sd_micro) |
| 187 | { |
| 188 | uint8_t no = c->P->n_obs; double s[PD0_MAX_OBS] = { 0 }, ss[PD0_MAX_OBS] = { 0 }; uint32_t n = 0; |
| 189 | for (uint32_t i = 0; i < c->nep; i++) { const episode *e = &c->ep[i]; if (!ep_fit(e)) continue; |
| 190 | for (uint32_t j = 0; j < e->n; j++) { const pd0_rec *r = &c->rec[e->first + j]; if (r->kind != PD0_KIND_STEP || !rec_has_outcome(r)) continue; |
| 191 | for (int v = 0; v < no; v++) { double x = (double)r->after[v] / 1e6; s[v] += x; ss[v] += x * x; } n++; } } |
| 192 | for (int v = 0; v < no; v++) { double m = n ? s[v] / n : 0, var = n ? ss[v] / n - m * m : 0; sd_micro[v] = var > 0 ? (int64_t)(sqrt(var) * 1e6) : 0; } |
| 193 | } |
| 194 | static int64_t nrmse_pooled(const ctx *c, const int64_t *pred, const int64_t *obs, uint32_t m, uint8_t no) { int64_t sd[PD0_MAX_OBS]; fit_sd(c, sd); return pd0_nrmse_pooled_micro(pred, obs, m, no, sd); } |
| 195 | /* rollout of relation along an episode's recorded applied schedule; fills pred[n][n_obs] for the first n OK steps */ |
| 196 | static uint32_t rollout_episode(const ctx *c, const pd0_rel *rel, const episode *e, uint32_t n, int64_t *pred, int64_t *obs, const pd0_rec **last) |
| 197 | { |
| 198 | const pd0_rec *r0 = &c->rec[e->first]; int64_t st[PD0_MAX_VARS], nx[PD0_MAX_VARS]; uint32_t k = 0; uint8_t no = c->P->n_obs; |
| 199 | memset(st, 0, sizeof st); for (int j = 0; j < no; j++) st[j] = r0->after[j]; |
| 200 | for (uint32_t i = 1; i < e->n && k < n; i++) { |
| 201 | const pd0_rec *r = &c->rec[e->first + i]; if (r->kind != PD0_KIND_STEP || !rec_has_outcome(r)) continue; |
| 202 | pd0_rel_step(rel, st, r->channel, r->applied, nx); |
| 203 | for (int j = 0; j < no; j++) { pred[k * no + j] = nx[j]; obs[k * no + j] = r->after[j]; } |
| 204 | memcpy(st, nx, sizeof st); k++; if (last) *last = r; |
| 205 | } |
| 206 | return k; |
| 207 | } |
| 208 | |
| 209 | /* ---------- T1 ---------- */ |
| 210 | static void try_t1(ctx *c) |
| 211 | { |
| 212 | uint32_t ok = 0, eps = 0; |
| 213 | for (uint32_t i = 0; i < c->nep; i++) { const episode *e = &c->ep[i]; if (!ep_visible(e)) continue; uint32_t k = ep_ok_steps(c, e); if (k) { ok += k; eps++; } } |
| 214 | if (ok < c->P->min_t1_records) { set_code(c, 1, PD0V_T1_TOO_FEW_RECORDS); return; } |
| 215 | if (eps < c->P->min_t1_episodes) { set_code(c, 1, PD0V_T1_TOO_FEW_EPISODES); return; } |
| 216 | c->R->state = LS_OBSERVATION; set_code(c, 1, PD0V_OK); |
| 217 | } |
| 218 | /* ---------- T2 ---------- */ |
| 219 | static int try_t2(ctx *c, const pd0_corr *k) |
| 220 | { |
| 221 | uint8_t no = c->P->n_obs; if (k->var_b >= no || (k->var_a >= no && k->var_a != PD0_CHAN_NONE)) return PD0V_BAD_FIELD; |
| 222 | if (k->var_a == k->var_b) { set_code(c, 2, PD0V_T2_NO_EVIDENCE); return 0; } /* spec rev 5: a variable against its own one-step change is regression to the mean, not evidence */ |
| 223 | if (k->n_shuffles < 2000) { set_code(c, 2, PD0V_T2_TOO_FEW_SHUFFLES); return 0; } |
| 224 | double *x = malloc(sizeof(double) * MAX_REC), *y = malloc(sizeof(double) * MAX_REC); uint32_t n = 0; |
| 225 | if (!x || !y) { free(x); free(y); return PD0V_TOO_LARGE; } |
| 226 | for (uint32_t i = 0; i < c->nep; i++) { const episode *e = &c->ep[i]; if (!ep_visible(e)) continue; |
| 227 | for (uint32_t j = 0; j < e->n; j++) { const pd0_rec *r = &c->rec[e->first + j]; if (r->kind != PD0_KIND_STEP || !rec_has_outcome(r)) continue; |
| 228 | x[n] = (k->var_a == PD0_CHAN_NONE) ? (double)r->applied : (double)r->before[k->var_a]; y[n] = (double)(r->after[k->var_b] - r->before[k->var_b]); n++; } } |
| 229 | int rc = 0; |
| 230 | if (n < 100 || n != k->n) { set_code(c, 2, PD0V_T2_TOO_FEW_RECORDS); } |
| 231 | else { |
| 232 | double r = pd0_pearson(x, y, n); c->R->last_r = r; |
| 233 | if (llabs((int64_t)(r * 1e6) - k->r_micro) > 1000) { set_code(c, 2, PD0V_T2_CORR_MISMATCH); rc = PD0V_T2_CORR_MISMATCH; } |
| 234 | else if (fabs(r) < 0.3) set_code(c, 2, PD0V_T2_CORR_TOO_WEAK); |
| 235 | else { |
| 236 | double p = pd0_perm_p(x, y, n, k->n_shuffles, k->shuffle_seed) * (k->n_pairs ? k->n_pairs : 1); c->R->last_p = p; |
| 237 | if (p > 0.01 || k->p_micro > 10000) set_code(c, 2, PD0V_T2_P_TOO_HIGH); |
| 238 | else { c->R->state = LS_CORRELATION; set_code(c, 2, PD0V_OK); } |
| 239 | } |
| 240 | } |
| 241 | free(x); free(y); return rc; |
| 242 | } |
| 243 | /* ---------- T3 ---------- */ |
| 244 | static int rep_exists(const ctx *c) { for (uint32_t i = 0; i < c->nep; i++) if (c->ep[i].has_tag && c->ep[i].tag == TAG_REP) return 1; return 0; } |
| 245 | static void try_t3(ctx *c, const relent *re) |
| 246 | { |
| 247 | const pd0_ladder_params *P = c->P; const pd0_rel *rel = &re->rel; uint8_t no = P->n_obs; |
| 248 | if (rel->n_vars != no + rel->n_latent || rel->n_channels != P->n_channels) { set_code(c, 3, PD0V_T3_BAD_RELATION); return; } |
| 249 | if (pd0_rel_max_degree(rel) > 3) { set_code(c, 3, PD0V_T3_DEGREE_EXCEEDED); return; } |
| 250 | if (pd0_rel_size(rel) > P->size_bound) { set_code(c, 3, PD0V_T3_SIZE_EXCEEDED); return; } |
| 251 | /* one-step error on FIT with teacher forcing on observed variables */ |
| 252 | nrmse_acc a; memset(&a, 0, sizeof a); double lag_num[PD0_MAX_OBS] = { 0 }, lag_den[PD0_MAX_OBS] = { 0 }; |
| 253 | for (uint32_t i = 0; i < c->nep; i++) { const episode *e = &c->ep[i]; if (!ep_fit(e)) continue; |
| 254 | int64_t st[PD0_MAX_VARS], nx[PD0_MAX_VARS]; memset(st, 0, sizeof st); double prev_res[PD0_MAX_OBS] = { 0 }; int have_prev = 0; |
| 255 | for (uint32_t j = 0; j < e->n; j++) { const pd0_rec *r = &c->rec[e->first + j]; |
| 256 | if (r->kind == PD0_KIND_RESET) { memset(st, 0, sizeof st); for (int v = 0; v < no; v++) st[v] = r->after[v]; have_prev = 0; continue; } |
| 257 | if (!rec_has_outcome(r)) continue; |
| 258 | for (int v = 0; v < no; v++) st[v] = r->before[v]; |
| 259 | pd0_rel_step(rel, st, r->channel, r->applied, nx); |
| 260 | acc_add(&a, nx, r->after, no); |
| 261 | for (int v = 0; v < no; v++) { double res = (double)(r->after[v] - nx[v]) / 1e6; if (have_prev) { lag_num[v] += res * prev_res[v]; } lag_den[v] += res * res; prev_res[v] = res; } |
| 262 | have_prev = 1; memcpy(st, nx, sizeof st); } } |
| 263 | int64_t one = acc_nrmse(&a, no); c->R->last_nrmse_micro = one; |
| 264 | if (!P->noisy && one > 50000) { set_code(c, 3, PD0V_T3_FIT_ERROR_TOO_HIGH); return; } |
| 265 | if (P->noisy) { for (int v = 0; v < no; v++) { double ac = lag_den[v] > 0 ? lag_num[v] / lag_den[v] : 0; if (fabs(ac) > 0.1) { set_code(c, 3, PD0V_T3_RESIDUALS_NOT_WHITE); return; } } } |
| 266 | c->R->have_candidate = 1; c->R->candidate = *rel; memcpy(c->R->candidate_hash, re->hash, PD0_HASH); |
| 267 | c->R->state = LS_CANDIDATE; set_code(c, 3, PD0V_OK); |
| 268 | } |
| 269 | /* ---------- T4 ---------- */ |
| 270 | static const relent *find_rel(const ctx *c, const uint8_t *h) { for (uint32_t i = 0; i < c->nrels; i++) if (!memcmp(c->rels[i].hash, h, PD0_HASH)) return &c->rels[i]; return NULL; } |
| 271 | static int try_t4(ctx *c, const pd0_falsifier *f, const uint8_t *entry_hash) |
| 272 | { |
| 273 | if (memcmp(f->candidate, c->R->candidate_hash, PD0_HASH) != 0) { set_code(c, 4, PD0V_T4_UNKNOWN_CANDIDATE); return PD0V_T4_UNKNOWN_CANDIDATE; } |
| 274 | if (f->n_rivals == 0) { set_code(c, 4, PD0V_T4_NO_RIVAL); return 0; } |
| 275 | for (int k = 0; k < f->n_rivals; k++) { const relent *r = find_rel(c, f->rival[k]); if (!r || r->role == REL_CANDIDATE || !memcmp(f->rival[k], f->candidate, PD0_HASH)) { set_code(c, 4, PD0V_T4_UNKNOWN_RIVAL); return PD0V_T4_UNKNOWN_RIVAL; } } |
| 276 | if (f->eps_micro <= 0 || f->eps_micro > c->P->eps_bound_micro) { set_code(c, 4, PD0V_T4_EPS_ABOVE_BOUND); return 0; } |
| 277 | for (uint32_t i = 0; i < c->nep; i++) if (c->ep[i].has_tag && c->ep[i].tag == TAG_TRIAL) { set_code(c, 4, PD0V_T4_FALSIFIER_AFTER_TRIAL); return PD0V_T4_FALSIFIER_AFTER_TRIAL; } |
| 278 | c->have_fals = 1; c->fals = *f; memcpy(c->fals_hash, entry_hash, PD0_HASH); c->R->eps_micro = f->eps_micro; |
| 279 | c->R->state = LS_HYPOTHESIS; set_code(c, 4, PD0V_OK); return 0; |
| 280 | } |
| 281 | /* spec rev 7: a TRIAL or REP episode the world ends with OUT_OF_BOUNDS before the rollout horizon is void: |
| 282 | * not a failed prediction, never counted toward p or f, replaced from the same fresh stream. */ |
| 283 | static int ep_void(const ctx *c, const episode *e) |
| 284 | { |
| 285 | if (!e->has_tag || (e->tag != TAG_TRIAL && e->tag != TAG_REP) || ep_ok_steps(c, e) >= c->P->rollout_steps) return 0; |
| 286 | for (uint32_t i = 0; i < e->n; i++) if (c->rec[e->first + i].kind == PD0_KIND_STEP && c->rec[e->first + i].status == PD0_ST_OUT_OF_BOUNDS) return 1; |
| 287 | return 0; |
| 288 | } |
| 289 | /* a void episode matches a preregistration on the requested reset and the applied steps it did run */ |
| 290 | static int ep_matches_prereg_prefix(const ctx *c, const episode *ep, const pd0_exp *e) |
| 291 | { |
| 292 | const pd0_rec *r0 = &c->rec[ep->first]; if (r0->kind != PD0_KIND_RESET || r0->n_obs != e->n_obs) return 0; |
| 293 | if (!c->P->noisy) for (int j = 0; j < e->n_obs; j++) if (r0->after[j] != e->reset[j]) return 0; |
| 294 | uint8_t k = 0; |
| 295 | for (uint32_t i = 1; i < ep->n && k < e->n_steps; i++) { const pd0_rec *r = &c->rec[ep->first + i]; if (r->kind != PD0_KIND_STEP || r->status == PD0_ST_REFUSED_RANGE) continue; |
| 296 | if (r->channel != e->steps[k].channel || r->applied != e->steps[k].value) return 0; k++; } |
| 297 | return k > 0; |
| 298 | } |
| 299 | /* voids in a replication batch; more than 3 void the batch itself (spec rev 7) */ |
| 300 | static uint32_t batch_voids(const ctx *c, uint32_t b) |
| 301 | { |
| 302 | uint32_t v = 0; for (uint32_t i = 0; i < c->nep; i++) { const episode *ep = &c->ep[i]; if (ep->has_tag && ep->tag == TAG_REP && ep->batch_id == c->bat[b].b.batch_id && ep_void(c, ep)) v++; } |
| 303 | return v; |
| 304 | } |
| 305 | /* ---------- T5 ---------- */ |
| 306 | static int try_t5(ctx *c, const pd0_exp *e, const uint8_t *entry_hash) |
| 307 | { |
| 308 | const pd0_ladder_params *P = c->P; |
| 309 | if (e->n_obs != P->n_obs || e->n_steps != P->rollout_steps) return PD0V_BAD_FIELD; |
| 310 | if (e->n_hyp != 1u + c->fals.n_rivals) { set_code(c, 5, PD0V_T5_MISSING_RIVAL_PREDICTION); return PD0V_T5_MISSING_RIVAL_PREDICTION; } |
| 311 | for (int j = 0; j < e->n_obs; j++) if (e->reset[j] < P->reset_min || e->reset[j] > P->reset_max) { set_code(c, 5, PD0V_T5_OUT_OF_BOUNDS); return PD0V_T5_OUT_OF_BOUNDS; } |
| 312 | for (int s = 0; s < e->n_steps; s++) { uint8_t ch = e->steps[s].channel; if (ch != PD0_CHAN_NONE && (ch >= P->n_channels || e->steps[s].value < P->chan_min[ch] || e->steps[s].value > P->chan_max[ch])) { set_code(c, 5, PD0V_T5_OUT_OF_BOUNDS); return PD0V_T5_OUT_OF_BOUNDS; } } |
| 313 | for (uint32_t i = 0; i < c->nep; i++) { const episode *ep = &c->ep[i]; if (!ep->has_tag || ep->tag > TAG_HOLDOUT || ep->n == 0) continue; |
| 314 | if (ep_matches_prereg(c, ep, e)) { set_code(c, 5, PD0V_T5_SCHEDULE_REUSED); return PD0V_T5_SCHEDULE_REUSED; } } |
| 315 | for (uint32_t i = 0; i < c->npre; i++) if (!memcmp(c->pre[i].e.schedule_hash, e->schedule_hash, PD0_HASH)) { set_code(c, 5, PD0V_T5_SCHEDULE_REUSED); return PD0V_T5_SCHEDULE_REUSED; } |
| 316 | if (c->npre >= MAX_PREREG) return PD0V_TOO_LARGE; |
| 317 | prereg *p = &c->pre[c->npre++]; p->e = *e; memcpy(p->hash, entry_hash, PD0_HASH); p->entry = c->entry_idx; p->matched_ep = -1; |
| 318 | uint32_t need = c->fals.min_trials > P->min_prereg ? c->fals.min_trials : P->min_prereg; |
| 319 | if (c->npre >= need) { c->R->state = LS_PREDICTED; set_code(c, 5, PD0V_OK); } else set_code(c, 5, PD0V_T5_TOO_FEW_PREREG); |
| 320 | return 0; |
| 321 | } |
| 322 | /* ---------- T6 ---------- */ |
| 323 | static int try_t6(ctx *c) |
| 324 | { |
| 325 | const pd0_ladder_params *P = c->P; uint8_t no = P->n_obs; uint32_t n = P->rollout_steps; |
| 326 | /* match complete TRIAL episodes to preregistrations */ |
| 327 | uint32_t voided = 0; |
| 328 | for (uint32_t i = 0; i < c->nep; i++) { episode *ep = &c->ep[i]; if (!ep->has_tag || ep->tag != TAG_TRIAL || ep->n == 0) continue; |
| 329 | if (ep_void(c, ep)) { for (uint32_t k = 0; k < c->npre; k++) if (c->pre[k].matched_ep == -1 && c->pre[k].entry < ep->first_entry && ep_matches_prereg_prefix(c, ep, &c->pre[k].e)) { c->pre[k].matched_ep = -2; break; } continue; } |
| 330 | if (ep_ok_steps(c, ep) < n) continue; |
| 331 | int found = 0; |
| 332 | for (uint32_t k = 0; k < c->npre; k++) if (c->pre[k].entry < ep->first_entry && ep_matches_prereg(c, ep, &c->pre[k].e)) { c->pre[k].matched_ep = (int)i; found = 1; break; } |
| 333 | if (!found) { set_code(c, 6, PD0V_T6_TRIAL_NOT_PREREGISTERED); return PD0V_T6_TRIAL_NOT_PREREGISTERED; } } |
| 334 | for (uint32_t k = 0; k < c->npre; k++) if (c->pre[k].matched_ep == -2) voided++; /* void marks persist across passes */ |
| 335 | { uint32_t need = c->fals.min_trials > P->min_prereg ? c->fals.min_trials : P->min_prereg; |
| 336 | for (uint32_t k = 0; k < c->npre; k++) if (c->pre[k].matched_ep == -1) { set_code(c, 6, PD0V_T6_TRIAL_MISSING); return 0; } |
| 337 | if (c->npre - voided < need) { set_code(c, 6, PD0V_T6_TRIAL_MISSING); return 0; } } |
| 338 | /* evaluate every trial against the committed prediction (hypothesis index 0) */ |
| 339 | int64_t obs[PD0_MAX_STEPS * PD0_MAX_OBS], pk[PD0_MAX_STEPS * PD0_MAX_OBS]; |
| 340 | for (uint32_t k = 0; k < c->npre; k++) { prereg *p = &c->pre[k]; if (p->matched_ep < 0) continue; const episode *ep = &c->ep[p->matched_ep]; uint32_t m = 0; const pd0_rec *last = NULL, *worst_rec = NULL; int64_t wp = 0, wo = 0, wd = -1; |
| 341 | for (uint32_t i = 1; i < ep->n && m < n; i++) { const pd0_rec *r = &c->rec[ep->first + i]; if (r->kind != PD0_KIND_STEP || !rec_has_outcome(r)) continue; |
| 342 | for (int j = 0; j < no; j++) { obs[m * no + j] = r->after[j]; int64_t d = llabs(p->e.expected[0][m][j] - r->after[j]); if (d > wd) { wd = d; worst_rec = r; wp = p->e.expected[0][m][j]; wo = r->after[j]; } } |
| 343 | m++; last = r; } |
| 344 | for (uint32_t s = 0; s < m; s++) for (int j = 0; j < no; j++) pk[s * no + j] = p->e.expected[0][s][j]; |
| 345 | int64_t err = nrmse_pooled(c, pk, obs, m, no); c->R->last_nrmse_micro = err; |
| 346 | uint8_t id[PD0_HASH]; sha256_hash(p->hash, PD0_HASH, id); |
| 347 | if (err > c->R->eps_micro) { c->R->f++; add_experiment(c, id, 0, p->hash, last->record_hash, 1, c->rec[ep->first].seq, last->seq); refute(c, worst_rec, wp, wo); set_code(c, 6, PD0V_T6_TRIAL_FAILED); return 0; } |
| 348 | c->R->p++; add_experiment(c, id, 0, p->hash, last->record_hash, 0, c->rec[ep->first].seq, last->seq); } |
| 349 | c->R->state = LS_INTERVENED; set_code(c, 6, PD0V_OK); return 0; |
| 350 | } |
| 351 | /* ---------- T7 ---------- */ |
| 352 | static int try_t7(ctx *c) |
| 353 | { |
| 354 | const pd0_ladder_params *P = c->P; uint8_t no = P->n_obs; uint32_t n = P->rollout_steps; uint32_t ready = 0; |
| 355 | int64_t pred[PD0_MAX_STEPS * PD0_MAX_OBS], obs[PD0_MAX_STEPS * PD0_MAX_OBS]; |
| 356 | for (uint32_t b = 0; b < c->nbat; b++) { uint32_t cnt = 0, planner = 0, random = 0; if (batch_voids(c, b) > 3) continue; for (uint32_t i = 0; i < c->nep; i++) { const episode *ep = &c->ep[i]; if (ep->has_tag && ep->tag == TAG_REP && ep->batch_id == c->bat[b].b.batch_id && ep_ok_steps(c, ep) >= n) { cnt++; if (ep->origin == ORIGIN_PLANNER) planner++; else random++; } } |
| 357 | if (cnt < P->min_batch_episodes || cnt < c->bat[b].b.n_episodes) continue; |
| 358 | if (planner + 1 < random || random + 1 < planner) { set_code(c, 7, PD0V_T7_ORIGIN_IMBALANCE); return PD0V_T7_ORIGIN_IMBALANCE; } |
| 359 | ready++; } |
| 360 | if (ready < P->min_batches) { set_code(c, 7, ready || c->nbat ? PD0V_T7_BATCH_TOO_SMALL : PD0V_T7_TOO_FEW_BATCHES); return 0; } |
| 361 | for (uint32_t b = 0; b < c->nbat; b++) { nrmse_acc a; memset(&a, 0, sizeof a); const pd0_rec *first = NULL, *last = NULL; if (batch_voids(c, b) > 3) continue; |
| 362 | for (uint32_t i = 0; i < c->nep; i++) { const episode *ep = &c->ep[i]; if (!(ep->has_tag && ep->tag == TAG_REP && ep->batch_id == c->bat[b].b.batch_id && ep_ok_steps(c, ep) >= n)) continue; |
| 363 | /* freshness: schedule must not equal any other episode's schedule */ |
| 364 | uint8_t h1[PD0_HASH], h2[PD0_HASH]; ep_schedule_hash(c, ep, (uint8_t)n, h1); |
| 365 | for (uint32_t j = 0; j < c->nep; j++) if (j != i && c->ep[j].n && ep_schedule_hash(c, &c->ep[j], (uint8_t)n, h2) && !memcmp(h1, h2, PD0_HASH)) { set_code(c, 7, PD0V_T7_STREAM_REUSED); return PD0V_T7_STREAM_REUSED; } |
| 366 | const pd0_rec *l = NULL; uint32_t m = rollout_episode(c, &c->R->candidate, ep, n, pred, obs, &l); if (!first) first = &c->rec[ep->first]; last = l; |
| 367 | int64_t e1 = nrmse_pooled(c, pred, obs, m, no); |
| 368 | if (e1 > 3 * c->R->eps_micro) { c->R->f++; uint8_t id[PD0_HASH]; sha256_hash(c->bat[b].hash, PD0_HASH, id); add_experiment(c, id, 1, c->bat[b].hash, l->record_hash, 1, first->seq, l->seq); refute(c, l, pred[(m - 1) * no], obs[(m - 1) * no]); set_code(c, 7, PD0V_T7_EPISODE_ABOVE_3EPS); return 0; } |
| 369 | for (uint32_t s = 0; s < m; s++) acc_add(&a, pred + s * no, obs + s * no, no); c->R->p++; } |
| 370 | int64_t sdv[PD0_MAX_OBS]; fit_sd(c, sdv); int64_t eb = acc_nrmse_sd(&a, no, sdv); c->R->last_nrmse_micro = eb; uint8_t id[PD0_HASH]; sha256_hash(c->bat[b].hash, PD0_HASH, id); |
| 371 | if (eb > c->R->eps_micro) { c->R->f++; add_experiment(c, id, 1, c->bat[b].hash, last->record_hash, 1, first->seq, last->seq); refute(c, last, pred[(n - 1) * no], obs[(n - 1) * no]); set_code(c, 7, PD0V_T7_BATCH_FAILED); return 0; } |
| 372 | add_experiment(c, id, 1, c->bat[b].hash, last->record_hash, 0, first->seq, last->seq); } |
| 373 | c->R->state = LS_REPLICATED; set_code(c, 7, PD0V_OK); return 0; |
| 374 | } |
| 375 | /* ---------- post-law contradiction (demotion) ---------- */ |
| 376 | static void check_demotion(ctx *c, episode *ep) |
| 377 | { |
| 378 | if (c->R->state != LS_REPLICATED || !(ep->has_tag && (ep->tag == TAG_TRIAL || ep->tag == TAG_REP)) || ep->complete) return; |
| 379 | uint32_t n = c->P->rollout_steps; if (ep_ok_steps(c, ep) < n) return; ep->complete = 1; |
| 380 | int64_t pred[PD0_MAX_STEPS * PD0_MAX_OBS], obs[PD0_MAX_STEPS * PD0_MAX_OBS]; const pd0_rec *l = NULL; |
| 381 | uint32_t m = rollout_episode(c, &c->R->candidate, ep, n, pred, obs, &l); |
| 382 | if (nrmse_pooled(c, pred, obs, m, c->P->n_obs) > c->R->eps_micro) { c->R->f++; refute(c, l, pred[(m - 1) * c->P->n_obs], obs[(m - 1) * c->P->n_obs]); c->R->state = LS_HYPOTHESIS; c->R->demoted = 1; c->R->have_candidate = 1; set_code(c, 8, PD0V_LAW_DEMOTED); } |
| 383 | else c->R->p++; |
| 384 | } |
| 385 | |
| 386 | static void compute_domain(ctx *c) |
| 387 | { |
| 388 | pd0_domain *d = &c->R->dom; const pd0_ladder_params *P = c->P; memset(d, 0, sizeof *d); |
| 389 | d->n_obs = P->n_obs; d->n_channels = P->n_channels; d->dt_micro = P->dt_micro; d->reset_min = P->reset_min; d->reset_max = P->reset_max; d->episode_len = P->episode_len; |
| 390 | d->latent_reset = 0; int first = 1; |
| 391 | for (uint32_t i = 0; i < c->nep; i++) { const episode *e = &c->ep[i]; if (!e->has_tag || e->tag == TAG_HOLDOUT || e->tag == TAG_REP || e->n == 0) continue; int used = 0; |
| 392 | for (uint32_t j = 0; j < e->n; j++) { const pd0_rec *r = &c->rec[e->first + j]; if (!rec_has_outcome(r)) continue; used = 1; d->n_observations++; |
| 393 | for (int v = 0; v < P->n_obs; v++) { int64_t lo = r->before[v] < r->after[v] ? r->before[v] : r->after[v], hi = r->before[v] > r->after[v] ? r->before[v] : r->after[v]; |
| 394 | if (first || lo < d->var_min[v]) d->var_min[v] = lo; if (first || hi > d->var_max[v]) d->var_max[v] = hi; } |
| 395 | if (r->kind == PD0_KIND_STEP && r->channel < P->n_channels) { uint8_t ch = r->channel; if (d->chan_min[ch] == 0 && d->chan_max[ch] == 0) { d->chan_min[ch] = d->chan_max[ch] = r->applied; } if (r->applied < d->chan_min[ch]) d->chan_min[ch] = r->applied; if (r->applied > d->chan_max[ch]) d->chan_max[ch] = r->applied; } |
| 396 | first = 0; } |
| 397 | if (used) d->n_episodes++; } |
| 398 | } |
| 399 | |
| 400 | int pd0_ladder_check(const uint8_t *ledger, size_t len, const pd0_ladder_params *P, pd0_ladder_report *R) |
| 401 | { |
| 402 | ctx *c = calloc(1, sizeof *c); if (!c) return PD0V_TOO_LARGE; |
| 403 | c->rec = malloc(sizeof(pd0_rec) * MAX_REC); if (!c->rec) { free(c); return PD0V_TOO_LARGE; } |
| 404 | memset(R, 0, sizeof *R); c->P = P; c->R = R; R->state = LS_START; R->code = PD0V_T1_TOO_FEW_RECORDS; R->transition = 1; |
| 405 | uint8_t prev[PD0_HASH] = { 0 }; size_t off = 0; int rc = 0; |
| 406 | while (off < len) { |
| 407 | pd0_entry e; rc = pd0_ledg_next(ledger, len, &off, prev, &e); if (rc) break; |
| 408 | memcpy(prev, e.entry_hash, PD0_HASH); memcpy(R->chain_root, e.entry_hash, PD0_HASH); R->n_entries++; c->entry_idx++; |
| 409 | switch (e.kind) { |
| 410 | case LEDG_OBS: { |
| 411 | if (c->nrec >= MAX_REC) { rc = PD0V_TOO_LARGE; break; } |
| 412 | pd0_rec *r = &c->rec[c->nrec]; size_t used; rc = pd0_rec_parse(e.payload, e.payload_len, r, &used); if (rc) break; |
| 413 | if (used != e.payload_len || r->n_obs != P->n_obs) { rc = PD0V_BAD_FIELD; break; } |
| 414 | if (c->have_rec) { if (memcmp(r->prev_hash, c->last_rec_hash, PD0_HASH) || r->seq != c->rec[c->nrec - 1].seq + 1) { rc = PD0V_CHAIN_BROKEN; break; } } |
| 415 | else { uint8_t z[PD0_HASH] = { 0 }; if (memcmp(r->prev_hash, z, PD0_HASH) || r->seq != 0) { rc = PD0V_CHAIN_BROKEN; break; } } |
| 416 | memcpy(c->last_rec_hash, r->record_hash, PD0_HASH); c->have_rec = 1; |
| 417 | episode *ep = find_ep(c, r->episode, 1); if (!ep) { rc = PD0V_TOO_LARGE; break; } |
| 418 | if (ep->first == UINT32_MAX) { ep->first = c->nrec; ep->first_entry = c->entry_idx; if (r->kind != PD0_KIND_RESET) { rc = PD0V_BAD_FIELD; break; } } |
| 419 | else if (ep->first + ep->n != c->nrec) { rc = PD0V_BAD_FIELD; break; } /* episodes are contiguous */ |
| 420 | ep->n++; c->nrec++; R->n_records++; |
| 421 | if (ep->has_tag && ep->tag == TAG_TRIAL && ep_ok_steps(c, ep) == P->rollout_steps) { int found = 0; for (uint32_t k = 0; k < c->npre; k++) if (c->pre[k].entry < ep->first_entry && ep_matches_prereg(c, ep, &c->pre[k].e)) found = 1; |
| 422 | if (!found) { rc = PD0V_T6_TRIAL_NOT_PREREGISTERED; set_code(c, 6, rc); break; } } |
| 423 | if (ep->has_tag && (ep->tag == TAG_TRIAL || ep->tag == TAG_REP) && ep->tag_entry > ep->first_entry) { rc = PD0V_T6_TRIAL_NOT_PREREGISTERED; break; } |
| 424 | if (R->state == LS_START) try_t1(c); |
| 425 | else if (R->state == LS_PREDICTED) rc = try_t6(c); |
| 426 | else if (R->state == LS_INTERVENED) rc = try_t7(c); |
| 427 | else if (R->state == LS_REPLICATED) check_demotion(c, ep); |
| 428 | break; } |
| 429 | case LEDG_TAG: { pd0_tag t; rc = pd0_tag_parse(e.payload, e.payload_len, &t); if (rc) break; |
| 430 | episode *ep = find_ep(c, t.episode, 1); if (!ep) { rc = PD0V_TOO_LARGE; break; } |
| 431 | if ((t.tag == TAG_TRIAL || t.tag == TAG_REP) && ep->n) { rc = PD0V_T6_TRIAL_NOT_PREREGISTERED; break; } |
| 432 | ep->has_tag = 1; ep->tag = t.tag; ep->origin = t.origin; ep->batch_id = t.batch_id; ep->tag_entry = c->entry_idx; |
| 433 | if (R->state == LS_START) try_t1(c); |
| 434 | break; } |
| 435 | case LEDG_CORR: { pd0_corr k; rc = pd0_corr_parse(e.payload, e.payload_len, &k); if (rc) break; |
| 436 | if (R->state != LS_OBSERVATION) { if (R->state < LS_OBSERVATION) { rc = PD0V_T8_STATE_SKIPPED; set_code(c, 2, rc); } break; } |
| 437 | rc = try_t2(c, &k); break; } |
| 438 | case LEDG_RELATION: { if (c->nrels >= MAX_RELS) { rc = PD0V_TOO_LARGE; break; } relent *re = &c->rels[c->nrels]; size_t used; |
| 439 | if (e.payload_len < 1) { rc = PD0V_TRUNCATED; break; } re->role = e.payload[0]; |
| 440 | rc = pd0_rel_parse(e.payload + 1, e.payload_len - 1, &re->rel, &used); if (rc) break; if (used + 1 != e.payload_len) { rc = PD0V_BAD_FIELD; break; } |
| 441 | memcpy(re->hash, e.entry_hash, PD0_HASH); c->nrels++; |
| 442 | if (re->role == REL_CANDIDATE) { if (rep_exists(c)) { rc = PD0V_REP_INFLUENCED_FIT; set_code(c, 3, rc); break; } |
| 443 | if (R->state == LS_CORRELATION || R->state == LS_CANDIDATE) try_t3(c, re); |
| 444 | else if (R->state < LS_CORRELATION) { rc = PD0V_T8_STATE_SKIPPED; set_code(c, 3, rc); } } |
| 445 | break; } |
| 446 | case LEDG_FALSIFIER: { pd0_falsifier f; rc = pd0_fals_parse(e.payload, e.payload_len, &f); if (rc) break; |
| 447 | if (R->state != LS_CANDIDATE) { if (R->state < LS_CANDIDATE) { rc = PD0V_T8_STATE_SKIPPED; set_code(c, 4, rc); } break; } |
| 448 | rc = try_t4(c, &f, e.entry_hash); break; } |
| 449 | case LEDG_PREREG: { pd0_exp x; size_t used; rc = pd0_exp_parse(e.payload, e.payload_len, &x, &used); if (rc) break; |
| 450 | if (R->state != LS_HYPOTHESIS && R->state != LS_PREDICTED) { if (R->state < LS_HYPOTHESIS) { rc = PD0V_T8_STATE_SKIPPED; set_code(c, 5, rc); } break; } |
| 451 | rc = try_t5(c, &x, e.entry_hash); break; } |
| 452 | case LEDG_BATCH: { pd0_batch b; rc = pd0_batch_parse(e.payload, e.payload_len, &b); if (rc) break; |
| 453 | if (R->state < LS_INTERVENED) { rc = PD0V_T8_STATE_SKIPPED; set_code(c, 7, rc); break; } |
| 454 | for (uint32_t i = 0; i < c->nbat; i++) if (c->bat[i].b.stream_seed == b.stream_seed || c->bat[i].b.batch_id == b.batch_id) { rc = PD0V_T7_STREAM_REUSED; set_code(c, 7, rc); break; } |
| 455 | if (rc) break; if (c->nbat >= MAX_BATCH) { rc = PD0V_TOO_LARGE; break; } |
| 456 | c->bat[c->nbat].b = b; memcpy(c->bat[c->nbat].hash, e.entry_hash, PD0_HASH); c->bat[c->nbat].entry = c->entry_idx; c->nbat++; |
| 457 | break; } |
| 458 | default: rc = PD0V_BAD_FIELD; |
| 459 | } |
| 460 | if (rc) break; |
| 461 | } |
| 462 | if (!rc && R->state == LS_PREDICTED) { int r2 = try_t6(c); if (r2) rc = r2; } |
| 463 | if (!rc && R->state == LS_INTERVENED) { int r2 = try_t7(c); if (r2) rc = r2; } |
| 464 | compute_domain(c); |
| 465 | R->confidence_ppm = pd0_confidence_ppm(R->p, R->f); |
| 466 | R->n_void_episodes = 0; R->n_void_batches = 0; /* spec rev 7 diagnostics, counted once */ |
| 467 | for (uint32_t i = 0; i < c->nep; i++) if (ep_void(c, &c->ep[i])) R->n_void_episodes++; |
| 468 | for (uint32_t b = 0; b < c->nbat; b++) if (batch_voids(c, b) > 3) R->n_void_batches++; |
| 469 | if (rc) R->code = rc; |
| 470 | free(c->rec); free(c); |
| 471 | return rc; |
| 472 | } |
| 473 | |
| 474 | /* ---------- claim text and T8 ---------- */ |
| 475 | static void fmt_micro(char *o, size_t cap, int64_t v) |
| 476 | { |
| 477 | int64_t a = v < 0 ? -v : v; snprintf(o, cap, "%s%lld.%06lld", v < 0 ? "-" : "", (long long)(a / PD0_MICRO), (long long)(a % PD0_MICRO)); |
| 478 | } |
| 479 | uint32_t pd0_claim_text(const pd0_ladder_report *R, const pd0_ladder_params *P, char *out, size_t cap) |
| 480 | { |
| 481 | char dom[256] = "", a[32], b[32], eps[32]; size_t dl = 0; |
| 482 | for (int v = 0; v < P->n_obs; v++) { fmt_micro(a, sizeof a, R->dom.var_min[v]); fmt_micro(b, sizeof b, R->dom.var_max[v]); dl += (size_t)snprintf(dom + dl, sizeof dom - dl, "%ss%d in [%s, %s]", v ? "; " : "", v, a, b); if (dl >= sizeof dom) break; } |
| 483 | fmt_micro(eps, sizeof eps, R->eps_micro); |
| 484 | int n = snprintf(out, cap, "Across %llu observations under %s, this relation predicts within %s (rollout NRMSE, 20 steps). Confidence %u ppm. %u exceptions recorded.", |
| 485 | (unsigned long long)R->dom.n_observations, dom, eps, R->confidence_ppm, R->n_exceptions); |
| 486 | return n < 0 ? 0 : (uint32_t)n; |
| 487 | } |
| 488 | static int has_forbidden(const uint8_t *s, uint32_t n) |
| 489 | { |
| 490 | static const char *bad[] = { "always", "universally", "true", "Always", "Universally", "True" }; |
| 491 | char buf[PD0_MAX_CLAIM + 1]; if (n > PD0_MAX_CLAIM) return 1; memcpy(buf, s, n); buf[n] = 0; |
| 492 | for (size_t i = 0; i < sizeof bad / sizeof *bad; i++) if (strstr(buf, bad[i])) return 1; |
| 493 | return 0; |
| 494 | } |
| 495 | size_t pd0_ladder_emit_law(const pd0_ladder_report *R, const pd0_ladder_params *P, uint8_t *out, size_t cap) |
| 496 | { |
| 497 | pd0_law *l = calloc(1, sizeof *l); if (!l) return 0; |
| 498 | l->state = (R->state == LS_REPLICATED && !R->demoted) ? PDLAW_PROVISIONAL_LAW : (R->n_refutations && !R->have_candidate) ? PDLAW_REFUTED : R->have_candidate ? PDLAW_HYPOTHESIS : PDLAW_REJECTED; |
| 499 | l->rel = R->candidate; l->rel.description_bits = pd0_rel_bits(&l->rel); l->rel.n_refutations = (uint16_t)R->n_refutations; |
| 500 | l->dom = R->dom; l->confidence_ppm = R->confidence_ppm; |
| 501 | l->n_exceptions = R->n_exceptions; memcpy(l->exc, R->exc, sizeof(pd0_exception) * R->n_exceptions); |
| 502 | l->n_experiments = R->n_experiments; memcpy(l->exp, R->exp, sizeof(pd0_experiment) * R->n_experiments); |
| 503 | memcpy(l->chain_root, R->chain_root, PD0_HASH); |
| 504 | l->claim_len = pd0_claim_text(R, P, (char *)l->claim, sizeof l->claim); |
| 505 | size_t n = pd0_law_write(l, out, cap); free(l); return n; |
| 506 | } |
| 507 | int pd0_ladder_verify_law(const pd0_ladder_report *R, const pd0_ladder_params *P, const uint8_t *law, size_t law_len) |
| 508 | { |
| 509 | pd0_law *l = calloc(1, sizeof *l); if (!l) return PD0V_TOO_LARGE; int rc = pd0_law_parse(law, law_len, l); |
| 510 | if (rc) { free(l); return rc; } |
| 511 | if (l->state == PDLAW_PROVISIONAL_LAW) { |
| 512 | if (R->demoted) rc = PD0V_LAW_DEMOTED; |
| 513 | else if (R->state != LS_REPLICATED) rc = PD0V_T8_STATE_SKIPPED; |
| 514 | } else if (l->state == PDLAW_HYPOTHESIS && !(R->state >= LS_HYPOTHESIS || R->demoted)) rc = PD0V_T8_STATE_MISMATCH; |
| 515 | if (!rc && has_forbidden(l->claim, l->claim_len)) rc = PD0V_T8_CLAIM_FORBIDDEN_WORD; |
| 516 | if (!rc && l->state != PDLAW_REJECTED) { |
| 517 | pd0_rel want = R->candidate; want.description_bits = pd0_rel_bits(&want); want.n_refutations = (uint16_t)R->n_refutations; |
| 518 | uint8_t a[4096], b[4096]; size_t na = pd0_rel_write(&want, a, sizeof a), nb = pd0_rel_write(&l->rel, b, sizeof b); |
| 519 | if (l->rel.n_refutations != R->n_refutations) rc = PD0V_T8_REFUTATION_COUNT_MISMATCH; |
| 520 | else if (l->rel.description_bits != pd0_rel_bits(&l->rel)) rc = PD0V_SCORE_BITS_MISMATCH; |
| 521 | else if (!na || na != nb || memcmp(a, b, na)) rc = PD0V_T8_RELATION_MISMATCH; |
| 522 | } |
| 523 | if (!rc && l->confidence_ppm != R->confidence_ppm) rc = PD0V_T8_CONFIDENCE_MISMATCH; |
| 524 | if (!rc) { if (l->n_exceptions != R->n_exceptions) rc = PD0V_T8_EXCEPTIONS_MISMATCH; else for (uint32_t i = 0; i < R->n_exceptions; i++) if (l->exc[i].record_seq != R->exc[i].record_seq || memcmp(l->exc[i].record_hash, R->exc[i].record_hash, PD0_HASH)) { rc = PD0V_T8_EXCEPTIONS_MISMATCH; break; } } |
| 525 | if (!rc) for (uint32_t i = 0; i < R->n_experiments; i++) { int found = 0; for (uint32_t j = 0; j < l->n_experiments; j++) if (!memcmp(l->exp[j].experiment_id, R->exp[i].experiment_id, PD0_HASH) && !memcmp(l->exp[j].outcome_hash, R->exp[i].outcome_hash, PD0_HASH) && l->exp[j].result == R->exp[i].result) { found = 1; break; } if (!found) { rc = PD0V_T8_EXPERIMENT_MISSING; break; } } |
| 526 | if (!rc && memcmp(l->chain_root, R->chain_root, PD0_HASH)) rc = PD0V_T8_CHAIN_ROOT_MISMATCH; |
| 527 | if (!rc) { uint8_t a[512], b[512]; size_t na = pd0_dom_write(&R->dom, a), nb = pd0_dom_write(&l->dom, b); if (na != nb || memcmp(a, b, na)) rc = PD0V_T8_DOMAIN_MISMATCH; } |
| 528 | if (!rc) { char want[PD0_MAX_CLAIM]; uint32_t n = pd0_claim_text(R, P, want, sizeof want); if (n != l->claim_len || memcmp(want, l->claim, n)) rc = PD0V_T8_CLAIM_TEXT_MISMATCH; } |
| 529 | free(l); return rc; |
| 530 | } |