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 / tools / estimation / est5.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 | /* ESTIMATION v5 tool (protocol docs/estimation/protocols/est-v5.md). |
| 18 | * |
| 19 | * est5 fit --raw <D1>/machine-state.ndjson --marks <D1>/machine-state-marks.txt |
| 20 | * --out <params.txt> [--synthetic-test [--grid-stride N]] |
| 21 | * Protocol section 5: two-stage grid fit of G1, G2, G3 on D1, the v3 F1 |
| 22 | * grid and the E0 histogram, in-sample screen (v3 section 6 rules, |
| 23 | * c3_judge), selection, PHASE_A verdict. Binding mode refuses: a dirty |
| 24 | * tree (build time and run time), a compiled protocol SHA that differs |
| 25 | * from the doc on disk, no compiled D1 identity, inputs whose SHA-256 |
| 26 | * differs from it or whose path lacks the D1 tag, an existing output. |
| 27 | * Every mode refuses a held-out path (v4 or v3 tag) before opening |
| 28 | * anything. |
| 29 | * est5 precheck --dir <D> |
| 30 | * v3 section 7 pre-check (c3_precheck; never reads thermal values). |
| 31 | * est5 recorded --dir <D2> --params <params.txt> --outdir <receipts/est-v5> |
| 32 | * [--synthetic-test] |
| 33 | * The single scored run: S, F1 and E0 on D2 with D1-frozen parameters. |
| 34 | * est5 make-synthetic <dir> [--seed N] [--lines N] |
| 35 | * Synthetic run folder (tests only), c3_synth_write. |
| 36 | */ |
| 37 | #include <dirent.h> |
| 38 | #include <errno.h> |
| 39 | #include <limits.h> |
| 40 | #include <math.h> |
| 41 | #include <stdio.h> |
| 42 | #include <stdlib.h> |
| 43 | #include <string.h> |
| 44 | |
| 45 | #include "est3c_common.h" |
| 46 | #include "est_v4.h" |
| 47 | #include "sha256.h" |
| 48 | |
| 49 | #ifndef TOOL_COMMIT |
| 50 | #define TOOL_COMMIT "unknown" |
| 51 | #endif |
| 52 | #ifndef TOOL_DIRTY |
| 53 | #define TOOL_DIRTY 1 |
| 54 | #endif |
| 55 | #ifndef E5_PROTOCOL_SHA |
| 56 | #define E5_PROTOCOL_SHA "unknown" |
| 57 | #endif |
| 58 | #ifndef E5_D1_RAW_SHA |
| 59 | #define E5_D1_RAW_SHA "absent" |
| 60 | #endif |
| 61 | #ifndef E5_D1_MARKS_SHA |
| 62 | #define E5_D1_MARKS_SHA "absent" |
| 63 | #endif |
| 64 | #ifndef E5_D2_RAW_SHA |
| 65 | #define E5_D2_RAW_SHA "absent" |
| 66 | #endif |
| 67 | #ifndef E5_D2_MARKS_SHA |
| 68 | #define E5_D2_MARKS_SHA "absent" |
| 69 | #endif |
| 70 | #ifndef E5_D2_SCHED_SHA |
| 71 | #define E5_D2_SCHED_SHA "absent" |
| 72 | #endif |
| 73 | #ifndef E5_PARAMS_SHA |
| 74 | #define E5_PARAMS_SHA "absent" |
| 75 | #endif |
| 76 | #ifndef E5_REPO_ROOT |
| 77 | #define E5_REPO_ROOT "unknown" |
| 78 | #endif |
| 79 | |
| 80 | #define E5_PROTOCOL_DOC "docs/estimation/protocols/est-v5.md" |
| 81 | #define E5_RECEIPT_SUBDIR "docs/estimation/receipts/est-v5" |
| 82 | #define E5_FIT_TAG "-est5-fit-" |
| 83 | #define E5_HELDOUT_TAG "-est5-heldout-" |
| 84 | #define E5_V4_HELDOUT_TAG "-est4-heldout-" |
| 85 | #define E5_AGREE 1e-6 /* fast vs pmf mean log score, nats/step */ |
| 86 | |
| 87 | static const char *envor(const char *name, const char *dflt) |
| 88 | { |
| 89 | #ifdef E5_TEST_BUILD |
| 90 | const char *e = getenv(name); if (e) return e; |
| 91 | #else |
| 92 | (void)name; |
| 93 | #endif |
| 94 | return dflt; |
| 95 | } |
| 96 | |
| 97 | static int tool_dirty(void) |
| 98 | { |
| 99 | static int cached = -1; |
| 100 | #ifdef E5_TEST_BUILD |
| 101 | const char *e = getenv("E5_TEST_DIRTY"); if (e && *e) return atoi(e); |
| 102 | #endif |
| 103 | if (cached < 0) cached = TOOL_DIRTY ? TOOL_DIRTY : c3_tree_dirty_now(); |
| 104 | return cached; |
| 105 | } |
| 106 | |
| 107 | /* held-out: the v4 tag or the v3 tag, on the path as given or resolved */ |
| 108 | static int e4_heldout(const char *path) |
| 109 | { |
| 110 | char rp[PATH_MAX]; |
| 111 | if (strstr(path, E5_HELDOUT_TAG) || strstr(path, E5_V4_HELDOUT_TAG) || strstr(path, C3_HELDOUT_TAG)) return 1; |
| 112 | if (realpath(path, rp) && (strstr(rp, E5_HELDOUT_TAG) || strstr(rp, E5_V4_HELDOUT_TAG) || strstr(rp, C3_HELDOUT_TAG))) return 1; |
| 113 | return 0; |
| 114 | } |
| 115 | |
| 116 | /* v5 window rule (protocol section 7): a collection folder is usable only when its |
| 117 | * WINDOW file (written by est5_collect.sh from the process monitor) says WINDOW_CLEAN |
| 118 | * and process-monitor.log exists. Reads no thermal value. */ |
| 119 | static int e5_window_clean(const char *dir, char *why, size_t cap) |
| 120 | { |
| 121 | char p[PATH_MAX + 32], line[256] = ""; |
| 122 | snprintf(p, sizeof p, "%s/WINDOW", dir); |
| 123 | FILE *fp = fopen(p, "r"); |
| 124 | if (!fp) { snprintf(why, cap, "no WINDOW file in %s (not collected by est5_collect.sh)", dir); return 1; } |
| 125 | if (!fgets(line, sizeof line, fp)) line[0] = 0; |
| 126 | fclose(fp); |
| 127 | if (strncmp(line, "WINDOW_CLEAN", 12)) { snprintf(why, cap, "window not clean in %s: %.100s", dir, line); return 1; } |
| 128 | snprintf(p, sizeof p, "%s/process-monitor.log", dir); |
| 129 | if (!(fp = fopen(p, "r"))) { snprintf(why, cap, "no process-monitor.log in %s", dir); return 1; } |
| 130 | fclose(fp); |
| 131 | return 0; |
| 132 | } |
| 133 | |
| 134 | /* directory part of a file path ("." when none) */ |
| 135 | static void e5_dirname(const char *path, char *out, size_t cap) |
| 136 | { |
| 137 | const char *sl = strrchr(path, '/'); |
| 138 | if (!sl) { snprintf(out, cap, "."); return; } |
| 139 | size_t n = (size_t)(sl - path); |
| 140 | if (n == 0) n = 1; |
| 141 | if (n >= cap) n = cap - 1; |
| 142 | memcpy(out, path, n); out[n] = 0; |
| 143 | } |
| 144 | |
| 145 | /* ------------------------------------------------------------ grids (s5) */ |
| 146 | static const double G1_TAU[] = { 0.5, 1, 2, 4, 10, 30 }; |
| 147 | static const double G2_RHO[] = { 0, 0.2, 0.4, 0.6, 0.8, 0.9 }; |
| 148 | static const double G3_TAU[] = { 0.5, 1, 2, 4, 10 }; |
| 149 | #define NQ4 9 /* q = 10^(2 + 0.5 i) */ |
| 150 | static const double LAM4[] = { 0.1, 0.2, 0.3, 0.5, 0.7, 0.9 }; |
| 151 | static const double NU4[] = { 0.8, 1, 1.25, 1.5, 2, 3, 5 }; |
| 152 | #define NC4 21 /* c = 0.20 + 0.05 i */ |
| 153 | static const double PHI4[] = { 1, 0.95, 0.9, 0.8, 0.6 }; |
| 154 | static const double NUH4[] = { 0.5, 0.6, 0.7, 0.8, 1, 1.25, 1.5, 2, 3, 5 }; |
| 155 | #define NCH4 31 /* c_h = 0.10 + 0.05 i */ |
| 156 | #define N_(a) ((int)(sizeof(a) / sizeof((a)[0]))) |
| 157 | static double gq4(int i) { return pow(10.0, 2.0 + 0.5 * (double)i); } |
| 158 | static double gc4(int i) { return (double)(20 + 5 * i) / 100.0; } |
| 159 | static double gch4(int i) { return (double)(10 + 5 * i) / 100.0; } |
| 160 | #define NQ1 25 |
| 161 | #define NR1 17 |
| 162 | static double gq1(int i) { return pow(10.0, 1.0 + 0.25 * (double)i); } |
| 163 | static double gr1(int j) { return pow(10.0, 2.0 + 0.25 * (double)j); } |
| 164 | |
| 165 | static const char *gname(int id) { return id == 1 ? "G1" : id == 2 ? "G2" : id == 3 ? "G3" : "none"; } |
| 166 | |
| 167 | /* ------------------------------------------------- tick walk (both paths) */ |
| 168 | static est_obs_class e4_classify(const c3_tick *t, est_pobs *ob) |
| 169 | { |
| 170 | est_assumption a; c3_assumption_base(&a, EST_FAM_STUDENT_T); |
| 171 | a.nparam = 2; a.param[0] = 5; a.param[1] = 100; |
| 172 | if (est_pobs_classify(&a, t->value, t->present, &t->ev, ob) != EST_OK) return EST_OBS_CLASSES_; |
| 173 | return ob->cls; |
| 174 | } |
| 175 | |
| 176 | /* Fast-path trace for one dynamic setting (dyn, q, lam): the scale-free parts |
| 177 | * of every scored one-step and ten-step predictive. */ |
| 178 | typedef struct { |
| 179 | size_t n1, n10, unscorable, cap; |
| 180 | double *y1, *m1, *b1, *a1; /* outcome, location, sqrt(g V_1), anchor */ |
| 181 | double *y10, *m10, *v10, *g10, *gl10, *a10; |
| 182 | } e4_trace; |
| 183 | |
| 184 | static int trace_alloc(e4_trace *tr, size_t n) |
| 185 | { |
| 186 | memset(tr, 0, sizeof *tr); |
| 187 | tr->cap = n ? n : 1; |
| 188 | double **f[10] = { &tr->y1, &tr->m1, &tr->b1, &tr->a1, &tr->y10, &tr->m10, &tr->v10, &tr->g10, &tr->gl10, &tr->a10 }; |
| 189 | for (int i = 0; i < 10; i++) if (!(*f[i] = malloc(tr->cap * sizeof(double)))) return 1; |
| 190 | return 0; |
| 191 | } |
| 192 | static void trace_free(e4_trace *tr) |
| 193 | { |
| 194 | free(tr->y1); free(tr->m1); free(tr->b1); free(tr->a1); free(tr->a10); free(tr->y10); free(tr->m10); free(tr->v10); free(tr->g10); free(tr->gl10); |
| 195 | memset(tr, 0, sizeof *tr); |
| 196 | } |
| 197 | |
| 198 | typedef struct { int ok; double m, v, g, gl, a; } e4_origin; |
| 199 | |
| 200 | static int trace_run(const c3_ticks *tk, const est4_params *p, e4_trace *tr) |
| 201 | { |
| 202 | est4_state s; |
| 203 | if (est4_init(p, &s) != EST_OK) return 1; |
| 204 | e4_origin ring[C3_TEN]; |
| 205 | memset(ring, 0, sizeof ring); |
| 206 | tr->n1 = tr->n10 = tr->unscorable = 0; |
| 207 | long first = -1; |
| 208 | for (size_t t = 0; t < tk->n; t++) { |
| 209 | est_pobs ob; |
| 210 | est_obs_class cls = e4_classify(&tk->t[t], &ob); |
| 211 | if (cls == EST_OBS_CLASSES_) return 1; |
| 212 | int ok = cls == EST_OBS_OK; |
| 213 | if (ok && first < 0) first = (long)t; |
| 214 | int scored = first >= 0 && (long)t - first >= (long)C3_BURN_IN; |
| 215 | e4_origin *o = &ring[t % C3_TEN]; |
| 216 | if (o->ok) { |
| 217 | o->ok = 0; |
| 218 | if (ok && tr->n10 < tr->cap) { |
| 219 | size_t k = tr->n10++; |
| 220 | tr->y10[k] = ob.value; tr->m10[k] = o->m; tr->v10[k] = o->v; tr->g10[k] = o->g; tr->gl10[k] = o->gl; tr->a10[k] = o->a; |
| 221 | } |
| 222 | } |
| 223 | if (ok && scored) { |
| 224 | if ((uint64_t)s.gap + 1u > EST_PRED_MAX_H) tr->unscorable++; |
| 225 | else { |
| 226 | double m, v; |
| 227 | if (est4_moments(&s, 1, &m, &v) != EST_OK) return 1; |
| 228 | if (tr->n1 < tr->cap) { size_t k = tr->n1++; tr->y1[k] = ob.value; tr->m1[k] = m; tr->b1[k] = sqrt(s.g * v); tr->a1[k] = s.anchor; } |
| 229 | } |
| 230 | } |
| 231 | if (est4_update(&s, ok, ok ? ob.value : NAN) != EST_OK) return 1; |
| 232 | if (ok && scored) { |
| 233 | double m, v; |
| 234 | if (est4_moments(&s, C3_TEN, &m, &v) != EST_OK) return 1; |
| 235 | o->ok = 1; o->m = m; o->v = v; o->g = s.g; o->gl = s.gl; o->a = s.anchor; |
| 236 | } |
| 237 | } |
| 238 | return 0; |
| 239 | } |
| 240 | |
| 241 | static double fast_ls1(const e4_trace *tr, double nu, double c) |
| 242 | { |
| 243 | double sum = 0.0; |
| 244 | for (size_t i = 0; i < tr->n1; i++) { |
| 245 | est4_pred pr = { 1u, tr->m1[i], c * tr->b1[i], nu }; |
| 246 | sum += est4_fast_logp(&pr, C3_QUANTUM, tr->a1[i], tr->y1[i], NULL, NULL); |
| 247 | } |
| 248 | return tr->n1 ? sum / (double)tr->n1 : -INFINITY; |
| 249 | } |
| 250 | |
| 251 | static double fast_ls10(const e4_trace *tr, double phi, double nuh, double ch) |
| 252 | { |
| 253 | double sum = 0.0; |
| 254 | for (size_t i = 0; i < tr->n10; i++) { |
| 255 | double gb = est4_gbar(tr->g10[i], tr->gl10[i], phi, C3_TEN); |
| 256 | est4_pred pr = { C3_TEN, tr->m10[i], ch * sqrt(gb * tr->v10[i]), nuh }; |
| 257 | sum += est4_fast_logp(&pr, C3_QUANTUM, tr->a10[i], tr->y10[i], NULL, NULL); |
| 258 | } |
| 259 | return tr->n10 ? sum / (double)tr->n10 : -INFINITY; |
| 260 | } |
| 261 | |
| 262 | /* Full path: discrete pmf predictives scored by est_dpred_score, statistics |
| 263 | * by c3_judge (v3 section 6), plus the ten-step mean log score. Mirrors |
| 264 | * c3_score tick for tick. */ |
| 265 | static int e4_score(const c3_ticks *tk, const c3_marks *mk, const est4_params *p, c3_stats *st, double *ls10) |
| 266 | { |
| 267 | memset(st, 0, sizeof *st); |
| 268 | est_calib_init(&st->c); |
| 269 | st->first_fail = -1; |
| 270 | st->cap = tk->n ? tk->n : 1; |
| 271 | st->cov95_step = malloc(st->cap * sizeof(double)); |
| 272 | st->width_step = malloc(st->cap * sizeof(double)); |
| 273 | st->regime_step = malloc(st->cap); |
| 274 | est_dpred *ring = malloc(C3_TEN * sizeof *ring), *dp = malloc(sizeof *dp); |
| 275 | int ring_ok[C3_TEN]; |
| 276 | memset(ring_ok, 0, sizeof ring_ok); |
| 277 | double l10 = 0.0; |
| 278 | int rc = 0; |
| 279 | est4_state s; |
| 280 | if (!st->cov95_step || !st->width_step || !st->regime_step || !ring || !dp) { rc = 1; snprintf(st->errmsg, sizeof st->errmsg, "out of memory"); goto done; } |
| 281 | if (est4_init(p, &s) != EST_OK) { rc = 1; snprintf(st->errmsg, sizeof st->errmsg, "params"); goto done; } |
| 282 | long first = -1; |
| 283 | for (size_t t = 0; t < tk->n && !rc; t++) { |
| 284 | const c3_tick *tc = &tk->t[t]; |
| 285 | est_pobs ob; est_pinnov iv; est_status r; |
| 286 | est_obs_class cls = e4_classify(tc, &ob); |
| 287 | if (cls == EST_OBS_CLASSES_) { rc = 1; break; } |
| 288 | int ok = cls == EST_OBS_OK; |
| 289 | if (ok && first < 0) first = (long)t; |
| 290 | int scored = first >= 0 && (long)t - first >= (long)C3_BURN_IN; |
| 291 | if (ring_ok[t % C3_TEN]) { |
| 292 | ring_ok[t % C3_TEN] = 0; |
| 293 | if (ok) { |
| 294 | if ((r = est_dpred_score(&ring[t % C3_TEN], &ob, &iv)) != EST_OK) { rc = 1; break; } |
| 295 | if (iv.valid) { st->ten_cov += est_frac_cover(iv.F_lo, iv.F_hi, 0.95); st->ten_n++; l10 += iv.logp; } |
| 296 | } |
| 297 | } |
| 298 | if (ok && scored) { |
| 299 | if ((uint64_t)s.gap + 1u > EST_PRED_MAX_H) st->unscorable++; |
| 300 | else { |
| 301 | est4_pred pr; |
| 302 | if (est4_predict(&s, 1, &pr) != EST_OK || est4_dpred(&s, &pr, dp) != EST_OK) { rc = 1; break; } |
| 303 | if ((r = est_dpred_score(dp, &ob, &iv)) != EST_OK) { rc = 1; break; } |
| 304 | if (iv.valid) { |
| 305 | st->logsum += iv.logp; st->n++; |
| 306 | if (est_calib_add(&st->c, dp, &iv) != EST_OK) { rc = 1; break; } |
| 307 | size_t k = st->n - 1; |
| 308 | st->cov95_step[k] = est_frac_cover(iv.F_lo, iv.F_hi, 0.95); |
| 309 | double w = NAN; |
| 310 | if (est_dpred_width80(dp, &w) != EST_OK) { rc = 1; break; } |
| 311 | st->width_step[k] = w; |
| 312 | st->regime_step[k] = (unsigned char)c3_in_trial(mk, tc->wall_ns); |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | if (est4_update(&s, ok, ok ? ob.value : NAN) != EST_OK) { rc = 1; break; } |
| 317 | if (ok && scored) { |
| 318 | est4_pred pr; |
| 319 | if (est4_predict(&s, C3_TEN, &pr) != EST_OK || est4_dpred(&s, &pr, &ring[t % C3_TEN]) != EST_OK) { rc = 1; break; } |
| 320 | ring_ok[t % C3_TEN] = 1; |
| 321 | } |
| 322 | } |
| 323 | if (rc && !st->errmsg[0]) snprintf(st->errmsg, sizeof st->errmsg, "v5 scoring error"); |
| 324 | st->error = rc; |
| 325 | st->logscore = st->n ? st->logsum / (double)st->n : -INFINITY; |
| 326 | *ls10 = st->ten_n ? l10 / (double)st->ten_n : -INFINITY; |
| 327 | if (!rc) c3_judge(st); |
| 328 | done: |
| 329 | free(ring); free(dp); |
| 330 | return rc; |
| 331 | } |
| 332 | |
| 333 | /* ------------------------------------------------------------- the fit */ |
| 334 | typedef struct { |
| 335 | int have; |
| 336 | est4_params p; |
| 337 | double fast1, fast10, full1, full10; |
| 338 | size_t points1, points2, n1, n10, skipped; /* skipped: (dyn, q, lam) points whose filter failed */ |
| 339 | int edge[8]; /* chosen value on a grid edge: dyn q lam nu c phi nu_h c_h */ |
| 340 | } g_fit; |
| 341 | |
| 342 | static int edge_of(double v, const double *g, int n) { return v == g[0] || v == g[n - 1]; } |
| 343 | |
| 344 | static int fit_family(const c3_ticks *tk, int id, int stride, g_fit *gf) |
| 345 | { |
| 346 | const double *dyn = id == 1 ? G1_TAU : id == 2 ? G2_RHO : G3_TAU; |
| 347 | int nd = id == 1 ? N_(G1_TAU) : id == 2 ? N_(G2_RHO) : N_(G3_TAU); |
| 348 | e4_trace tr; |
| 349 | if (trace_alloc(&tr, tk->n)) { trace_free(&tr); return 1; } |
| 350 | memset(gf, 0, sizeof *gf); |
| 351 | double best = -INFINITY; |
| 352 | est4_params p; |
| 353 | memset(&p, 0, sizeof p); |
| 354 | p.family = (est4_family)id; p.quantum = C3_QUANTUM; |
| 355 | p.phi = 1.0; p.nu_h = 1.0; p.c_h = 1.0; p.nu = 1.0; p.c = 1.0; |
| 356 | /* stage 1: one-step score over dyn, q, lam, nu, c */ |
| 357 | for (int a = 0; a < nd; a += stride) |
| 358 | for (int b = 0; b < NQ4; b += stride) |
| 359 | for (int l = 0; l < N_(LAM4); l += stride) { |
| 360 | p.dyn = dyn[a]; p.q = gq4(b); p.lam = LAM4[l]; |
| 361 | if (trace_run(tk, &p, &tr)) { gf->skipped++; continue; } |
| 362 | for (int u = 0; u < N_(NU4); u += stride) |
| 363 | for (int c = 0; c < NC4; c += stride) { |
| 364 | double ls = fast_ls1(&tr, NU4[u], gc4(c)); |
| 365 | gf->points1++; |
| 366 | if (isfinite(ls) && c3_grid_take(gf->have, ls, best)) { |
| 367 | gf->have = 1; best = ls; |
| 368 | gf->p = p; gf->p.nu = NU4[u]; gf->p.c = gc4(c); |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | if (!gf->have) { trace_free(&tr); return 0; } |
| 373 | gf->fast1 = best; |
| 374 | /* stage 2: ten-step score over phi, nu_h, c_h with stage 1 frozen */ |
| 375 | if (trace_run(tk, &gf->p, &tr)) { trace_free(&tr); gf->have = 0; return 0; } |
| 376 | int have2 = 0; double best2 = -INFINITY; |
| 377 | for (int a = 0; a < N_(PHI4); a += stride) |
| 378 | for (int u = 0; u < N_(NUH4); u += stride) |
| 379 | for (int c = 0; c < NCH4; c += stride) { |
| 380 | double ls = fast_ls10(&tr, PHI4[a], NUH4[u], gch4(c)); |
| 381 | gf->points2++; |
| 382 | if (isfinite(ls) && c3_grid_take(have2, ls, best2)) { |
| 383 | have2 = 1; best2 = ls; |
| 384 | gf->p.phi = PHI4[a]; gf->p.nu_h = NUH4[u]; gf->p.c_h = gch4(c); |
| 385 | } |
| 386 | } |
| 387 | if (!have2) { trace_free(&tr); gf->have = 0; return 0; } |
| 388 | gf->fast10 = best2; |
| 389 | gf->n1 = tr.n1; gf->n10 = tr.n10; |
| 390 | double cg[NC4], chg[NCH4], qg[NQ4]; |
| 391 | for (int i = 0; i < NC4; i++) cg[i] = gc4(i); |
| 392 | for (int i = 0; i < NCH4; i++) chg[i] = gch4(i); |
| 393 | for (int i = 0; i < NQ4; i++) qg[i] = gq4(i); |
| 394 | gf->edge[0] = edge_of(gf->p.dyn, dyn, nd); gf->edge[1] = edge_of(gf->p.q, qg, NQ4); |
| 395 | gf->edge[2] = edge_of(gf->p.lam, LAM4, N_(LAM4)); gf->edge[3] = edge_of(gf->p.nu, NU4, N_(NU4)); |
| 396 | gf->edge[4] = edge_of(gf->p.c, cg, NC4); gf->edge[5] = edge_of(gf->p.phi, PHI4, N_(PHI4)); |
| 397 | gf->edge[6] = edge_of(gf->p.nu_h, NUH4, N_(NUH4)); gf->edge[7] = edge_of(gf->p.c_h, chg, NCH4); |
| 398 | trace_free(&tr); |
| 399 | return 0; |
| 400 | } |
| 401 | |
| 402 | static void put_screen(FILE *fp, const char *name, const c3_stats *st, double ls10) |
| 403 | { |
| 404 | for (int i = 0; i < C3_ST_COUNT; i++) |
| 405 | fprintf(fp, "screen %s %s value %.17g band %.17g %.17g n %zu gated %d pass %d\n", name, c3_stat_name(i), |
| 406 | st->value[i], st->band_lo[i], st->band_hi[i], |
| 407 | (i >= C3_ST_Q0 && i <= C3_ST_TEN) ? st->sub_n[i] : st->n, st->gated[i], st->pass[i]); |
| 408 | fprintf(fp, "screen_sharpness %s width80_mean_mc %.17g width80_median_mc %.17g unscorable %zu ten_logscore %.17g\n", |
| 409 | name, st->width_mean, st->width_median, st->unscorable, ls10); |
| 410 | fprintf(fp, "screen_result %s pass %d first_fail %s n %zu logscore %.17g\n", name, st->calibrated, |
| 411 | st->calibrated ? "none" : c3_stat_name(st->first_fail), st->n, st->logscore); |
| 412 | } |
| 413 | |
| 414 | static int cmd_fit(int argc, char **argv) |
| 415 | { |
| 416 | const char *raw = NULL, *mkp = NULL, *out = NULL; |
| 417 | int synth = 0, stride = 1; |
| 418 | for (int i = 0; i < argc; i++) { |
| 419 | if (!strcmp(argv[i], "--raw") && i + 1 < argc) raw = argv[++i]; |
| 420 | else if (!strcmp(argv[i], "--marks") && i + 1 < argc) mkp = argv[++i]; |
| 421 | else if (!strcmp(argv[i], "--out") && i + 1 < argc) out = argv[++i]; |
| 422 | else if (!strcmp(argv[i], "--synthetic-test")) synth = 1; |
| 423 | else if (!strcmp(argv[i], "--grid-stride") && i + 1 < argc) stride = atoi(argv[++i]); |
| 424 | else { fprintf(stderr, "usage: est5 fit --raw R --marks M --out P [--synthetic-test [--grid-stride N]]\n"); return 2; } |
| 425 | } |
| 426 | if (!raw || !mkp || !out) { fprintf(stderr, "est5 fit: --raw, --marks and --out are required\n"); return 2; } |
| 427 | /* held-out guard first, before any file is opened, in every mode */ |
| 428 | if (e4_heldout(raw) || e4_heldout(mkp) || e4_heldout(out)) { fprintf(stderr, "refuse: a held-out path; fitting on it is not allowed\n"); return 2; } |
| 429 | if (stride < 1 || (stride != 1 && !synth)) { fprintf(stderr, "refuse: --grid-stride only with --synthetic-test\n"); return 2; } |
| 430 | const char *proto = envor("E5_TEST_PROTOCOL_SHA", E5_PROTOCOL_SHA); |
| 431 | const char *d1raw = envor("E5_TEST_D1_RAW_SHA", E5_D1_RAW_SHA), *d1mk = envor("E5_TEST_D1_MARKS_SHA", E5_D1_MARKS_SHA); |
| 432 | if (!synth) { |
| 433 | if (tool_dirty()) { fprintf(stderr, "refuse: the binding fit needs a clean tree (dirty=%d)\n", tool_dirty()); return 2; } |
| 434 | char doc[65] = ""; |
| 435 | if (!strcmp(proto, "unknown") || est_sha_file_hex(E5_PROTOCOL_DOC, doc) || strcmp(doc, proto)) { |
| 436 | fprintf(stderr, "refuse: compiled protocol SHA %s differs from %s on disk (%s)\n", proto, E5_PROTOCOL_DOC, doc[0] ? doc : "unreadable"); return 2; } |
| 437 | if (!strcmp(d1raw, "absent") || !strcmp(d1mk, "absent")) { fprintf(stderr, "refuse: no D1 identity compiled in (receipts/est-v5/d1.sha256)\n"); return 2; } |
| 438 | if (!strstr(raw, E5_FIT_TAG) || !strstr(mkp, E5_FIT_TAG)) { fprintf(stderr, "refuse: the binding fit opens only a %s run\n", E5_FIT_TAG); return 2; } |
| 439 | } |
| 440 | char err[512]; |
| 441 | if (!synth) { |
| 442 | char dd[PATH_MAX]; |
| 443 | e5_dirname(raw, dd, sizeof dd); |
| 444 | if (e5_window_clean(dd, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 2; } |
| 445 | } |
| 446 | est_file f; |
| 447 | if (est_file_load(raw, &f, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 1; } |
| 448 | static c3_marks mk; |
| 449 | if (c3_marks_load(mkp, 1, &mk, err, sizeof err)) { fprintf(stderr, "refuse: marks: %s\n", err); est_file_free(&f); return 1; } |
| 450 | if (!synth && (strcmp(f.sha_hex, d1raw) || strcmp(mk.sha, d1mk))) { |
| 451 | fprintf(stderr, "refuse: input SHA-256 differs from the compiled D1 identity\n"); est_file_free(&f); return 2; } |
| 452 | FILE *fp = fopen(out, "wbx"); |
| 453 | if (!fp) { fprintf(stderr, "refuse: cannot create %s (%s); outputs are never overwritten\n", out, strerror(errno)); est_file_free(&f); return 1; } |
| 454 | c3_ticks tk; |
| 455 | if (c3_ticks_build(&f, &tk, err, sizeof err)) { fprintf(stderr, "ticks: %s\n", err); fclose(fp); est_file_free(&f); return 1; } |
| 456 | |
| 457 | static g_fit gf[4]; |
| 458 | static c3_stats st[4]; |
| 459 | double full10[4] = { 0 }; |
| 460 | int agree[4] = { 0 }; |
| 461 | for (int id = 1; id <= 3; id++) { |
| 462 | if (fit_family(&tk, id, stride, &gf[id])) { fprintf(stderr, "out of memory\n"); fclose(fp); return 1; } |
| 463 | fprintf(stderr, "est5 fit: %s done (%zu + %zu points)\n", gname(id), gf[id].points1, gf[id].points2); |
| 464 | if (!gf[id].have) continue; |
| 465 | if (e4_score(&tk, &mk, &gf[id].p, &st[id], &full10[id])) { fprintf(stderr, "screen %s: %s\n", gname(id), st[id].errmsg); gf[id].have = 0; continue; } |
| 466 | gf[id].full1 = st[id].logscore; gf[id].full10 = full10[id]; |
| 467 | agree[id] = fabs(gf[id].full1 - gf[id].fast1) <= E5_AGREE && fabs(gf[id].full10 - gf[id].fast10) <= E5_AGREE && |
| 468 | st[id].n == gf[id].n1 && st[id].ten_n == gf[id].n10; |
| 469 | if (!agree[id]) { fprintf(stderr, "est5 fit: %s fast and pmf scores disagree; family unavailable\n", gname(id)); gf[id].have = 0; } |
| 470 | } |
| 471 | /* baselines (v3 definitions): F1 grid and E0 histogram on D1 */ |
| 472 | int f1have = 0; double f1ls = -INFINITY; c3_model m, f1m; |
| 473 | memset(&f1m, 0, sizeof f1m); |
| 474 | for (int i = 0; i < NQ1; i += stride) |
| 475 | for (int j = 0; j < NR1; j += stride) { |
| 476 | c3_stats s1; |
| 477 | c3_make_f1(&m, gq1(i), gr1(j)); |
| 478 | if (c3_score(&tk, NULL, &m, 0, &s1)) continue; |
| 479 | if (isfinite(s1.logscore) && c3_grid_take(f1have, s1.logscore, f1ls)) { f1have = 1; f1ls = s1.logscore; f1m = m; } |
| 480 | } |
| 481 | double *e = malloc((tk.n + 1) * sizeof *e); |
| 482 | uint32_t *e0c = calloc(EST_PRED_N, sizeof *e0c); |
| 483 | if (!e || !e0c) { fprintf(stderr, "out of memory\n"); fclose(fp); return 1; } |
| 484 | size_t ne = c3_h1_changes(&tk, e, tk.n + 1); |
| 485 | c3_e0_counts(e, ne, e0c); |
| 486 | |
| 487 | int av[6] = { 0 }, ps[6] = { 0 }; double lsv[6] = { 0 }; |
| 488 | for (int id = 1; id <= 3; id++) { av[id] = gf[id].have; ps[id] = gf[id].have && st[id].calibrated; lsv[id] = gf[id].have ? gf[id].full1 : -INFINITY; } |
| 489 | int sel = c3_select(av, ps, lsv); |
| 490 | |
| 491 | char doc_hex[65] = "unavailable"; |
| 492 | est_sha_file_hex(E5_PROTOCOL_DOC, doc_hex); |
| 493 | fprintf(fp, "est5_params v5\n"); |
| 494 | fprintf(fp, "protocol %s\nprotocol_doc_sha256 %s\nprotocol_doc_sha256_on_disk %s\n", E5_PROTOCOL_DOC, proto, doc_hex); |
| 495 | fprintf(fp, "tool_commit %s\ntool_dirty %d\nsynthetic_test %d\ngrid_stride %d\n", TOOL_COMMIT, tool_dirty(), synth, stride); |
| 496 | fprintf(fp, "fit_raw_path %s\nfit_raw_sha256 %s\nfit_marks_path %s\nfit_marks_sha256 %s\nfit_lines %zu\n", raw, f.sha_hex, mkp, mk.sha, f.nlines); |
| 497 | fprintf(fp, "d1_identity_compiled raw %s marks %s\n", d1raw, d1mk); |
| 498 | fprintf(fp, "ticks total %zu inserted %zu gaps_capped %zu bad_t %zu absent_value %zu unparsable_value %zu\n", |
| 499 | tk.n, tk.inserted, tk.gaps_capped, tk.bad_t, tk.absent_value, tk.unparsable_value); |
| 500 | fprintf(fp, "marks pairs %zu begins %zu ends %zu unclosed %zu\n", mk.n, mk.begins, mk.ends, mk.unclosed); |
| 501 | fprintf(fp, "rule stage1 maximise fast one-step mean log score over dyn q lam nu c (phi nu_h c_h unused)\n"); |
| 502 | fprintf(fp, "rule stage2 maximise fast ten-step mean log score over phi nu_h c_h with stage 1 frozen\n"); |
| 503 | fprintf(fp, "rule agreement fast vs pmf mean log score within %g nats, same step counts\n", E5_AGREE); |
| 504 | for (int id = 1; id <= 3; id++) { |
| 505 | const g_fit *g = &gf[id]; |
| 506 | fprintf(fp, "family %s available %d dyn %.17g q %.17g lam %.17g nu %.17g c %.17g phi %.17g nu_h %.17g c_h %.17g" |
| 507 | " logscore %.17g ten_logscore %.17g fast1 %.17g fast10 %.17g points1 %zu points2 %zu skipped %zu agree %d\n", |
| 508 | gname(id), g->have, g->p.dyn, g->p.q, g->p.lam, g->p.nu, g->p.c, g->p.phi, g->p.nu_h, g->p.c_h, |
| 509 | g->have ? g->full1 : -INFINITY, g->have ? g->full10 : -INFINITY, g->fast1, g->fast10, g->points1, g->points2, g->skipped, agree[id]); |
| 510 | fprintf(fp, "grid_edge %s dyn %d q %d lam %d nu %d c %d phi %d nu_h %d c_h %d\n", gname(id), |
| 511 | g->edge[0], g->edge[1], g->edge[2], g->edge[3], g->edge[4], g->edge[5], g->edge[6], g->edge[7]); |
| 512 | } |
| 513 | fprintf(fp, "baseline F1 available %d q_proc %.17g r %.17g logscore %.17g\n", f1have, f1m.a.param[0], f1m.a.param[1], f1ls); |
| 514 | for (int id = 1; id <= 3; id++) { |
| 515 | if (!gf[id].have) { fprintf(fp, "screen_result %s pass 0 first_fail unavailable n 0\n", gname(id)); continue; } |
| 516 | put_screen(fp, gname(id), &st[id], full10[id]); |
| 517 | } |
| 518 | fprintf(fp, "e0_changes %zu\n", ne); |
| 519 | for (int i = 0; i < EST_PRED_N; i++) if (e0c[i]) fprintf(fp, "e0_count %d %u\n", i - EST_PRED_K, e0c[i]); |
| 520 | fprintf(fp, "selection_rule best D1 one-step log score among screen-passers; earlier of G1 < G2 < G3 within %.2f nats preferred\n", C3_TIE_NATS); |
| 521 | if (sel) fprintf(fp, "selected %s\nphase_a PASS\n", gname(sel)); |
| 522 | else { |
| 523 | fprintf(fp, "selected none\nphase_a PHASE_A_FAIL\n"); |
| 524 | for (int id = 1; id <= 3; id++) { |
| 525 | fprintf(fp, "phase_a_fail %s", gname(id)); |
| 526 | if (!gf[id].have) fprintf(fp, " unavailable"); |
| 527 | else for (int i = 0; i < C3_ST_COUNT; i++) |
| 528 | if (st[id].gated[i] && !st[id].pass[i]) fprintf(fp, " %s=%.6g", c3_stat_name(i), st[id].value[i]); |
| 529 | fprintf(fp, "\n"); |
| 530 | } |
| 531 | } |
| 532 | int bad = ferror(fp) != 0; |
| 533 | if (fclose(fp) != 0) bad = 1; |
| 534 | if (bad) { |
| 535 | /* never leave a partial params file behind: it would block a rerun (wbx) */ |
| 536 | remove(out); |
| 537 | fprintf(stderr, "est5 fit: writing %s failed; partial file removed\n", out); |
| 538 | for (int id = 1; id <= 3; id++) if (gf[id].have) c3_stats_free(&st[id]); |
| 539 | free(e); free(e0c); c3_ticks_free(&tk); est_file_free(&f); |
| 540 | return 1; |
| 541 | } |
| 542 | char ph[65] = "unavailable"; |
| 543 | est_sha_file_hex(out, ph); |
| 544 | printf("EST5_FIT selected=%s phase_a=%s params_sha256=%s synthetic_test=%d\n", gname(sel), sel ? "PASS" : "PHASE_A_FAIL", ph, synth); |
| 545 | for (int id = 1; id <= 3; id++) if (gf[id].have) c3_stats_free(&st[id]); |
| 546 | free(e); free(e0c); c3_ticks_free(&tk); est_file_free(&f); |
| 547 | return bad ? 1 : 0; |
| 548 | } |
| 549 | |
| 550 | /* ------------------------------------------------------ params reader */ |
| 551 | typedef struct { |
| 552 | int phase_a_pass, selected, synthetic, tool_dirty; |
| 553 | int have[4], pass[4]; |
| 554 | est4_params g[4]; |
| 555 | double ls[4]; |
| 556 | double f1q, f1r; int f1have; |
| 557 | uint64_t e0_n; uint32_t e0[EST_PRED_N]; |
| 558 | char protocol_sha[65], fit_raw_sha[65], fit_marks_sha[65], fit_raw_path[1024]; |
| 559 | } e4_params_file; |
| 560 | |
| 561 | /* the whole key including its trailing space: no prefix of a longer key matches */ |
| 562 | static int key(const char *line, const char *k) { return !strncmp(line, k, strlen(k)); } |
| 563 | |
| 564 | static int gid(const char *s) { return !strcmp(s, "G1") ? 1 : !strcmp(s, "G2") ? 2 : !strcmp(s, "G3") ? 3 : 0; } |
| 565 | |
| 566 | static int params_read(const char *path, e4_params_file *P, char *err, size_t cap) |
| 567 | { |
| 568 | memset(P, 0, sizeof *P); |
| 569 | FILE *fp = fopen(path, "rb"); |
| 570 | if (!fp) { snprintf(err, cap, "cannot open %s", path); return 1; } |
| 571 | char line[4096], a[64], b[1100]; |
| 572 | int magic = 0, have_phase = 0, have_sel = 0; |
| 573 | P->selected = -1; |
| 574 | while (fgets(line, sizeof line, fp)) { |
| 575 | if (!strncmp(line, "est5_params v5", 14)) magic = 1; |
| 576 | else if (key(line, "protocol_doc_sha256 ") && sscanf(line + 20, "%64s", P->protocol_sha) == 1) {} |
| 577 | else if (key(line, "fit_raw_sha256 ") && sscanf(line + 15, "%64s", P->fit_raw_sha) == 1) {} |
| 578 | else if (key(line, "fit_marks_sha256 ") && sscanf(line + 17, "%64s", P->fit_marks_sha) == 1) {} |
| 579 | else if (key(line, "fit_raw_path ")) { size_t L = strcspn(line + 13, "\n"); if (L >= sizeof P->fit_raw_path) L = sizeof P->fit_raw_path - 1; memcpy(P->fit_raw_path, line + 13, L); P->fit_raw_path[L] = 0; } |
| 580 | else if (key(line, "synthetic_test ") && sscanf(line + 15, "%d", &P->synthetic) == 1) {} |
| 581 | else if (key(line, "tool_dirty ") && sscanf(line + 11, "%d", &P->tool_dirty) == 1) {} |
| 582 | else if (!strncmp(line, "family ", 7)) { |
| 583 | est4_params g; int av; double ls; |
| 584 | memset(&g, 0, sizeof g); |
| 585 | if (sscanf(line, "family %63s available %d dyn %lf q %lf lam %lf nu %lf c %lf phi %lf nu_h %lf c_h %lf logscore %lf", |
| 586 | a, &av, &g.dyn, &g.q, &g.lam, &g.nu, &g.c, &g.phi, &g.nu_h, &g.c_h, &ls) != 11 || !gid(a)) { |
| 587 | snprintf(err, cap, "bad family line"); fclose(fp); return 1; } |
| 588 | int id = gid(a); |
| 589 | g.family = (est4_family)id; g.quantum = C3_QUANTUM; |
| 590 | P->have[id] = av; P->g[id] = g; P->ls[id] = av ? ls : -INFINITY; |
| 591 | } else if (!strncmp(line, "baseline F1 ", 12)) { |
| 592 | if (sscanf(line, "baseline F1 available %d q_proc %lf r %lf", &P->f1have, &P->f1q, &P->f1r) != 3) { snprintf(err, cap, "bad F1 line"); fclose(fp); return 1; } |
| 593 | } else if (!strncmp(line, "screen_result ", 14)) { |
| 594 | int ps; |
| 595 | if (sscanf(line, "screen_result %63s pass %d", a, &ps) != 2 || !gid(a)) { snprintf(err, cap, "bad screen_result"); fclose(fp); return 1; } |
| 596 | P->pass[gid(a)] = ps; |
| 597 | } else if (!strncmp(line, "e0_count ", 9)) { |
| 598 | int k; unsigned c; |
| 599 | if (sscanf(line, "e0_count %d %u", &k, &c) != 2 || k < -EST_PRED_K || k > EST_PRED_K) { snprintf(err, cap, "bad e0_count"); fclose(fp); return 1; } |
| 600 | P->e0[k + EST_PRED_K] = c; P->e0_n += c; |
| 601 | } else if (!strncmp(line, "selected ", 9) && sscanf(line + 9, "%63s", a) == 1) { have_sel = 1; P->selected = gid(a); } |
| 602 | else if (!strncmp(line, "phase_a ", 8) && sscanf(line + 8, "%1099s", b) == 1) { have_phase = 1; P->phase_a_pass = !strcmp(b, "PASS"); } |
| 603 | } |
| 604 | fclose(fp); |
| 605 | if (!magic || !have_phase || !have_sel) { snprintf(err, cap, "not a v5 params file"); return 1; } |
| 606 | for (int id = 1; id <= 3; id++) if (P->have[id] && est4_params_check(&P->g[id]) != EST_OK) { snprintf(err, cap, "%s params invalid", gname(id)); return 1; } |
| 607 | return 0; |
| 608 | } |
| 609 | |
| 610 | /* ------------------------------------------------------ eval */ |
| 611 | static int has_receipt(const char *dir) |
| 612 | { |
| 613 | DIR *d = opendir(dir); |
| 614 | if (!d) return -1; |
| 615 | struct dirent *e; int found = 0; |
| 616 | while ((e = readdir(d))) if (!strncmp(e->d_name, "receipt-", 8)) found = 1; |
| 617 | closedir(d); |
| 618 | return found; |
| 619 | } |
| 620 | |
| 621 | static int cmd_recorded(int argc, char **argv) |
| 622 | { |
| 623 | const char *dir = NULL, *ppath = NULL, *outdir = NULL; |
| 624 | int synth = 0; |
| 625 | for (int i = 0; i < argc; i++) { |
| 626 | if (!strcmp(argv[i], "--dir") && i + 1 < argc) dir = argv[++i]; |
| 627 | else if (!strcmp(argv[i], "--params") && i + 1 < argc) ppath = argv[++i]; |
| 628 | else if (!strcmp(argv[i], "--outdir") && i + 1 < argc) outdir = argv[++i]; |
| 629 | else if (!strcmp(argv[i], "--synthetic-test")) synth = 1; |
| 630 | else { fprintf(stderr, "usage: est5 recorded --dir D2 --params P --outdir O [--synthetic-test]\n"); return 2; } |
| 631 | } |
| 632 | if (!dir || !ppath || !outdir) { fprintf(stderr, "est5 recorded: --dir, --params and --outdir are required\n"); return 2; } |
| 633 | char err[512]; |
| 634 | const char *proto = envor("E5_TEST_PROTOCOL_SHA", E5_PROTOCOL_SHA); |
| 635 | const char *d2r = envor("E5_TEST_D2_RAW_SHA", E5_D2_RAW_SHA), *d2m = envor("E5_TEST_D2_MARKS_SHA", E5_D2_MARKS_SHA), |
| 636 | *d2s = envor("E5_TEST_D2_SCHED_SHA", E5_D2_SCHED_SHA), *psha = envor("E5_TEST_PARAMS_SHA", E5_PARAMS_SHA); |
| 637 | if (!synth) { |
| 638 | if (tool_dirty()) { fprintf(stderr, "refuse: recorded needs a clean tree (dirty=%d)\n", tool_dirty()); return 2; } |
| 639 | if (!strcmp(d2r, "absent") || !strcmp(d2m, "absent") || !strcmp(d2s, "absent")) { fprintf(stderr, "refuse: no D2 identity compiled in (receipts/est-v5/d2.sha256)\n"); return 2; } |
| 640 | char doc[65] = ""; |
| 641 | if (est_sha_file_hex(E5_PROTOCOL_DOC, doc) || strcmp(doc, proto)) { fprintf(stderr, "refuse: protocol doc on disk differs from the compiled SHA\n"); return 2; } |
| 642 | char ph0[65] = ""; |
| 643 | if (!strcmp(psha, "absent") || est_sha_file_hex(ppath, ph0) || strcmp(ph0, psha)) { fprintf(stderr, "refuse: params SHA-256 differs from the compiled params SHA\n"); return 2; } |
| 644 | char want[PATH_MAX + 64], rw[PATH_MAX], ro[PATH_MAX]; |
| 645 | const char *root = envor("E5_TEST_REPO_ROOT", E5_REPO_ROOT); |
| 646 | if (!strcmp(root, "unknown")) { fprintf(stderr, "refuse: no repo root compiled in\n"); return 2; } |
| 647 | snprintf(want, sizeof want, "%s/%s", root, E5_RECEIPT_SUBDIR); |
| 648 | if (!realpath(want, rw) || !realpath(outdir, ro) || strcmp(rw, ro)) { fprintf(stderr, "refuse: a recorded receipt goes only to <repo>/%s\n", E5_RECEIPT_SUBDIR); return 2; } |
| 649 | if (!strstr(dir, E5_HELDOUT_TAG)) { fprintf(stderr, "refuse: the recorded run scores only a %s run\n", E5_HELDOUT_TAG); return 2; } |
| 650 | } else if (e4_heldout(dir) || strstr(dir, E5_FIT_TAG) || strstr(dir, C3_D1_ID)) { |
| 651 | fprintf(stderr, "refuse: --synthetic-test never runs on D1 or a held-out run\n"); return 2; |
| 652 | } |
| 653 | static e4_params_file P; |
| 654 | if (params_read(ppath, &P, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 2; } |
| 655 | if (!P.phase_a_pass) { fprintf(stderr, "refuse: params say PHASE_A_FAIL; D2 is NOT_RUN\n"); return 2; } |
| 656 | int av[6] = { 0 }, ps[6] = { 0 }; double lsv[6] = { 0 }; |
| 657 | for (int id = 1; id <= 3; id++) { av[id] = P.have[id]; ps[id] = P.pass[id]; lsv[id] = P.ls[id]; } |
| 658 | int resel = c3_select(av, ps, lsv); |
| 659 | if (resel != P.selected || P.selected < 1) { fprintf(stderr, "refuse: params selected %s but the rule gives %s\n", gname(P.selected), gname(resel)); return 2; } |
| 660 | if (!P.f1have) { fprintf(stderr, "refuse: params carry no F1 baseline\n"); return 2; } |
| 661 | if (!synth) { |
| 662 | if (P.synthetic || P.tool_dirty) { fprintf(stderr, "refuse: params are not a binding fit\n"); return 2; } |
| 663 | if (strcmp(P.protocol_sha, proto)) { fprintf(stderr, "refuse: params fitted under another protocol SHA\n"); return 2; } |
| 664 | if (strcmp(P.fit_raw_sha, envor("E5_TEST_D1_RAW_SHA", E5_D1_RAW_SHA)) || strcmp(P.fit_marks_sha, envor("E5_TEST_D1_MARKS_SHA", E5_D1_MARKS_SHA)) || !strstr(P.fit_raw_path, E5_FIT_TAG)) { |
| 665 | fprintf(stderr, "refuse: params are not a fit on the compiled D1\n"); return 2; } |
| 666 | } |
| 667 | int hr = has_receipt(outdir); |
| 668 | if (hr < 0) { fprintf(stderr, "refuse: outdir %s is not a readable directory\n", outdir); return 2; } |
| 669 | if (hr > 0) { fprintf(stderr, "refuse: %s already holds a receipt; a second scored run is a new protocol version\n", outdir); return 2; } |
| 670 | c3_pre pre; |
| 671 | if (e5_window_clean(dir, err, sizeof err)) { fprintf(stderr, "refuse: window: %s; D2 is INCONCLUSIVE and is not scored\n", err); return 3; } |
| 672 | if (c3_precheck(dir, &pre, err, sizeof err)) { fprintf(stderr, "refuse: precheck: %s\n", err); return 2; } |
| 673 | printf("precheck %s: %s\n", pre.valid ? "VALID" : "INCONCLUSIVE", pre.why); |
| 674 | if (!pre.valid) { fprintf(stderr, "refuse: the pre-check is INCONCLUSIVE; D2 is not scored\n"); return 3; } |
| 675 | if (!synth && (strcmp(pre.raw_sha, d2r) || strcmp(pre.marks_sha, d2m) || strcmp(pre.sched_sha, d2s))) { |
| 676 | fprintf(stderr, "refuse: D2 data SHA-256 differs from the compiled D2 identity\n"); return 2; } |
| 677 | char path[1200]; |
| 678 | est_file f; |
| 679 | snprintf(path, sizeof path, "%s/machine-state.ndjson", dir); |
| 680 | if (est_file_load(path, &f, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 2; } |
| 681 | /* the scored bytes are the identified bytes (the pre-check hashed a separate read) */ |
| 682 | if (!synth && strcmp(f.sha_hex, d2r)) { fprintf(stderr, "refuse: scored D2 bytes differ from the compiled D2 identity\n"); est_file_free(&f); return 2; } |
| 683 | if (synth && strcmp(d2r, "absent") && !strcmp(f.sha_hex, d2r)) { fprintf(stderr, "refuse: --synthetic-test never runs on D1 or a held-out run (D2 bytes)\n"); est_file_free(&f); return 2; } |
| 684 | c3_ticks tk; |
| 685 | if (c3_ticks_build(&f, &tk, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); est_file_free(&f); return 2; } |
| 686 | static c3_marks mk; |
| 687 | snprintf(path, sizeof path, "%s/machine-state-marks.txt", dir); |
| 688 | if (c3_marks_load(path, 1, &mk, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 2; } |
| 689 | static c3_stats sS, s1, s0; |
| 690 | static c3_model m1, m0; |
| 691 | double l10S = -INFINITY; |
| 692 | c3_make_f1(&m1, P.f1q, P.f1r); |
| 693 | c3_make_e0(&m0, P.e0, P.e0_n); |
| 694 | if (e4_score(&tk, &mk, &P.g[P.selected], &sS, &l10S) || c3_score(&tk, &mk, &m1, 1, &s1) || c3_score(&tk, &mk, &m0, 1, &s0)) { |
| 695 | fprintf(stderr, "scoring error: %s %s %s\n", sS.errmsg, s1.errmsg, s0.errmsg); return 1; } |
| 696 | int same = sS.n == s1.n && sS.n == s0.n && sS.unscorable == s1.unscorable && sS.unscorable == s0.unscorable; |
| 697 | int beat1 = sS.logscore >= s1.logscore - C3_TIE_NATS, beat0 = sS.logscore >= s0.logscore - C3_TIE_NATS; |
| 698 | /* est-json-1: a non-finite measured value is recorded as invalid and can never pass */ |
| 699 | size_t inv = c3_stats_invalid(&sS, C3_TEN_MEASURED, l10S) + c3_stats_invalid(&s1, C3_TEN_UNAVAILABLE, NAN) + c3_stats_invalid(&s0, C3_TEN_UNAVAILABLE, NAN); |
| 700 | int pass = inv == 0 && same && sS.calibrated && beat1 && beat0; |
| 701 | const char *verdict = pass ? "PASS" : "HELD_OUT_FAIL"; |
| 702 | const char *reason = inv ? "non-finite measured value (marked invalid in the receipt)" : !same ? "S, F1 and E0 were not scored on the same steps" : !sS.calibrated ? "S not calibrated" |
| 703 | : (!beat1 || !beat0) ? "calibrated but not better than a baseline" : "calibrated and no worse than F1 and E0"; |
| 704 | char *buf = NULL; size_t blen = 0; |
| 705 | FILE *o = open_memstream(&buf, &blen); |
| 706 | if (!o) { fprintf(stderr, "out of memory\n"); return 1; } |
| 707 | char pdisk[65] = "unavailable"; |
| 708 | est_sha_file_hex(ppath, pdisk); |
| 709 | fprintf(o, "{\n \"receipt\": \"est5 v5 sealed held-out run\",\n \"verdict\": \"%s\",\n \"reason\": \"%s\",\n", verdict, reason); |
| 710 | fprintf(o, " \"synthetic_test\": %s,\n \"tool_commit\": \"%s\",\n \"tool_dirty\": %d,\n \"protocol_sha256\": \"%s\",\n \"params_sha256\": \"%s\",\n", |
| 711 | synth ? "true" : "false", TOOL_COMMIT, tool_dirty(), proto, pdisk); |
| 712 | fprintf(o, " \"d2\": {\"dir\": "); c3_json_str(o, dir); |
| 713 | fprintf(o, ", \"raw_sha256\": \"%s\", \"marks_sha256\": \"%s\", \"schedule_sha256\": \"%s\", \"lines\": %zu},\n", pre.raw_sha, pre.marks_sha, pre.sched_sha, pre.lines); |
| 714 | fprintf(o, " \"selected\": \"%s\",\n \"comparisons\": {\"same_steps\": %s, \"no_worse_than_F1\": %s, \"no_worse_than_E0\": %s, \"tie_nats\": %.2f},\n", |
| 715 | gname(P.selected), same ? "true" : "false", beat1 ? "true" : "false", beat0 ? "true" : "false", C3_TIE_NATS); |
| 716 | fprintf(o, " \"json_rules\": \"est-json-1\",\n \"invalid_measurements\": %zu,\n", inv); |
| 717 | fprintf(o, " \"scores\": {\n"); |
| 718 | c3_json_stats(o, gname(P.selected), &sS, C3_TEN_MEASURED, l10S); fprintf(o, ",\n"); |
| 719 | c3_json_stats(o, "F1", &s1, C3_TEN_UNAVAILABLE, NAN); fprintf(o, ",\n"); |
| 720 | c3_json_stats(o, "E0", &s0, C3_TEN_UNAVAILABLE, NAN); fprintf(o, "\n }\n}\n"); |
| 721 | fclose(o); |
| 722 | uint8_t dg[32]; char hex[65]; |
| 723 | sha256_ctx c; sha256_init(&c); sha256_update(&c, (const uint8_t *)buf, blen); sha256_final(&c, dg); |
| 724 | est_hex(dg, 32, hex); |
| 725 | snprintf(path, sizeof path, "%s/receipt-%s.json", outdir, hex); |
| 726 | FILE *w = fopen(path, "wbx"); |
| 727 | if (!w || fwrite(buf, 1, blen, w) != blen || fclose(w)) { fprintf(stderr, "cannot write %s\n", path); free(buf); return 1; } |
| 728 | free(buf); |
| 729 | printf("EST5_RECORDED verdict=%s selected=%s receipt=%s reason=%s\n", verdict, gname(P.selected), path, reason); |
| 730 | c3_stats_free(&sS); c3_stats_free(&s1); c3_stats_free(&s0); c3_ticks_free(&tk); est_file_free(&f); |
| 731 | return 0; |
| 732 | } |
| 733 | |
| 734 | static int cmd_precheck(int argc, char **argv) |
| 735 | { |
| 736 | if (argc != 2 || strcmp(argv[0], "--dir")) { fprintf(stderr, "usage: est5 precheck --dir D\n"); return 2; } |
| 737 | char err[512]; c3_pre pre; |
| 738 | if (e5_window_clean(argv[1], err, sizeof err)) { printf("INCONCLUSIVE: %s\n", err); return 3; } |
| 739 | if (c3_precheck(argv[1], &pre, err, sizeof err)) { fprintf(stderr, "precheck: %s\n", err); return 2; } |
| 740 | printf("precheck lines %zu gaps_big %zu/%zu marks %s foreign_mean %.4f over3 %.4f unmeasured %zu\n", |
| 741 | pre.lines, pre.gaps_big, pre.gaps, pre.ok_marks ? "ok" : pre.marks_why, pre.foreign_mean, pre.foreign_over3_frac, pre.foreign_unmeasured); |
| 742 | printf("%s: %s\n", pre.valid ? "VALID" : "INCONCLUSIVE", pre.why); |
| 743 | return pre.valid ? 0 : 3; |
| 744 | } |
| 745 | |
| 746 | static int cmd_synth(int argc, char **argv) |
| 747 | { |
| 748 | if (argc < 1) { fprintf(stderr, "usage: est5 make-synthetic DIR [--seed N] [--lines N]\n"); return 2; } |
| 749 | c3_synth sy; memset(&sy, 0, sizeof sy); |
| 750 | sy.seed = 1; sy.lines = 2400; |
| 751 | for (int i = 1; i < argc; i++) { |
| 752 | if (!strcmp(argv[i], "--seed") && i + 1 < argc) sy.seed = strtoull(argv[++i], NULL, 0); |
| 753 | else if (!strcmp(argv[i], "--lines") && i + 1 < argc) sy.lines = (size_t)strtoull(argv[++i], NULL, 0); |
| 754 | else return 2; |
| 755 | } |
| 756 | if (c3_synth_write(argv[0], &sy)) return 1; |
| 757 | /* tests only: a synthetic folder carries a clean window so the v5 window rule passes */ |
| 758 | char p[PATH_MAX + 32]; |
| 759 | snprintf(p, sizeof p, "%s/WINDOW", argv[0]); |
| 760 | FILE *fp = fopen(p, "w"); |
| 761 | if (!fp) return 1; |
| 762 | fputs("WINDOW_CLEAN synthetic\n", fp); fclose(fp); |
| 763 | snprintf(p, sizeof p, "%s/process-monitor.log", argv[0]); |
| 764 | if (!(fp = fopen(p, "w"))) return 1; |
| 765 | fputs("synthetic\n", fp); fclose(fp); |
| 766 | return 0; |
| 767 | } |
| 768 | |
| 769 | int main(int argc, char **argv) |
| 770 | { |
| 771 | if (argc < 2) { fprintf(stderr, "usage: est5 fit|precheck|recorded|make-synthetic ...\n"); return 2; } |
| 772 | if (!strcmp(argv[1], "fit")) return cmd_fit(argc - 2, argv + 2); |
| 773 | if (!strcmp(argv[1], "recorded")) return cmd_recorded(argc - 2, argv + 2); |
| 774 | if (!strcmp(argv[1], "precheck")) return cmd_precheck(argc - 2, argv + 2); |
| 775 | if (!strcmp(argv[1], "make-synthetic")) return cmd_synth(argc - 2, argv + 2); |
| 776 | fprintf(stderr, "est5: unknown command %s\n", argv[1]); |
| 777 | return 2; |
| 778 | } |