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 / est_eval.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 | /* EST-3 evaluation (protocol v1 sections 4 and 5; --protocol-v2 for EST23_PROTOCOL_V2). |
| 18 | * est_eval --params P --raw machine-state.ndjson --marks machine-state-marks.txt |
| 19 | * --out receipt.json [--recorded] [--synthetic-test] |
| 20 | * Takes the parameter file and the held-out file only; never fits. Refuses when |
| 21 | * the parameter file was not fit on run A (unless --synthetic-test), and |
| 22 | * refuses run B unless --recorded. Writes a JSON receipt. */ |
| 23 | #include <errno.h> |
| 24 | #include <math.h> |
| 25 | #include <stdint.h> |
| 26 | #include <sys/stat.h> |
| 27 | #include <unistd.h> |
| 28 | #include <stdio.h> |
| 29 | #include <stdlib.h> |
| 30 | #include <string.h> |
| 31 | |
| 32 | #include "est_replay.h" |
| 33 | |
| 34 | #define TWO_PI 6.283185307179586 |
| 35 | #define ZC50 0.674490 |
| 36 | #define ZC80 1.281552 |
| 37 | #define ZC95 1.959964 |
| 38 | #define TEN_STEP 10 |
| 39 | |
| 40 | typedef struct { double lo, hi; } band; |
| 41 | static const band B50 = { 0.46, 0.54 }, B80 = { 0.76, 0.84 }, B95 = { 0.93, 0.97 }; |
| 42 | static const band BNIS = { 0.80, 1.25 }, BQ = { 0.90, 0.99 }; |
| 43 | |
| 44 | typedef struct { |
| 45 | size_t n; |
| 46 | double cov[3], wlo[3], whi[3]; |
| 47 | double mean_nis, bias, lag1, ljung_box10; |
| 48 | size_t qn[4]; double qcov[4]; |
| 49 | size_t regime_n[2]; double regime_cov[2]; /* 0 idle, 1 in-trial */ |
| 50 | size_t ten_n; double ten_cov, ten_lo, ten_hi; |
| 51 | int64_t tmin_ns, tmax_ns; /* included-sample logical time span */ |
| 52 | double logscore, rmse, persist_rmse, zero_innov_frac; |
| 53 | int ok_cov[3], ok_nis, ok_bias, ok_lag1, ok_q[4], ok_regime[2], ok_ten, calibrated; |
| 54 | int rmse_le_persist; |
| 55 | } model_stats; |
| 56 | |
| 57 | #define MAX_PAIRS 512 |
| 58 | typedef struct { |
| 59 | int64_t b[MAX_PAIRS], e[MAX_PAIRS]; |
| 60 | size_t n, begins, ends, unclosed, nested_begins, stray_ends; |
| 61 | char sha[65]; |
| 62 | } marks; |
| 63 | |
| 64 | static void wilson(size_t k, size_t n, double *lo, double *hi) |
| 65 | { |
| 66 | double z = ZC95, p = (double)k / (double)n, z2 = z * z, dn = (double)n; |
| 67 | double den = 1.0 + z2 / dn, c = (p + z2 / (2.0 * dn)) / den; |
| 68 | double h = z * sqrt(p * (1.0 - p) / dn + z2 / (4.0 * dn * dn)) / den; |
| 69 | *lo = c - h; *hi = c + h; |
| 70 | } |
| 71 | |
| 72 | static int in_band(double v, band b) { return v >= b.lo && v <= b.hi; } |
| 73 | |
| 74 | static int load_marks(const char *path, marks *mk, char *err, size_t cap) |
| 75 | { |
| 76 | memset(mk, 0, sizeof *mk); |
| 77 | est_file f; |
| 78 | if (est_file_load(path, &f, err, cap)) return 1; |
| 79 | memcpy(mk->sha, f.sha_hex, 65); |
| 80 | int64_t open_t = 0; int is_open = 0; |
| 81 | for (size_t i = 0; i < f.nlines; i++) { |
| 82 | const char *ln = (const char *)f.data + f.off[i]; size_t ll = f.llen[i]; |
| 83 | int64_t t; size_t used; |
| 84 | if (est_parse_time_prefix(ln, ll, &t, &used)) continue; |
| 85 | const char *rest = ln + used; size_t rl = ll - used; |
| 86 | if (rl >= 7 && memcmp(rest, " begin ", 7) == 0) { |
| 87 | mk->begins++; |
| 88 | if (is_open) { /* nested begin: the earlier one ends where the new one starts */ |
| 89 | mk->nested_begins++; |
| 90 | if (mk->n >= MAX_PAIRS) { snprintf(err, cap, "more than %d marks pairs", MAX_PAIRS); est_file_free(&f); return 1; } |
| 91 | mk->b[mk->n] = open_t; mk->e[mk->n] = t; mk->n++; |
| 92 | } |
| 93 | open_t = t; is_open = 1; |
| 94 | } else if (rl >= 5 && memcmp(rest, " end ", 5) == 0) { |
| 95 | mk->ends++; |
| 96 | if (!is_open) { mk->stray_ends++; continue; } |
| 97 | if (mk->n >= MAX_PAIRS) { snprintf(err, cap, "more than %d marks pairs", MAX_PAIRS); est_file_free(&f); return 1; } |
| 98 | mk->b[mk->n] = open_t; mk->e[mk->n] = t; mk->n++; |
| 99 | is_open = 0; |
| 100 | } |
| 101 | } |
| 102 | if (is_open) { /* unclosed begin runs to the end of the file */ |
| 103 | if (mk->n >= MAX_PAIRS) { snprintf(err, cap, "more than %d marks pairs", MAX_PAIRS); est_file_free(&f); return 1; } |
| 104 | mk->b[mk->n] = open_t; mk->e[mk->n] = INT64_MAX; mk->n++; |
| 105 | mk->unclosed = 1; |
| 106 | } |
| 107 | est_file_free(&f); |
| 108 | return 0; |
| 109 | } |
| 110 | |
| 111 | |
| 112 | static int step_equal(const est_step *a, const est_step *b) |
| 113 | { |
| 114 | return a->line == b->line && a->L == b->L && a->prior == b->prior && a->coast == b->coast |
| 115 | && a->t_ok == b->t_ok && a->chain_ok == b->chain_ok && a->wall_ns == b->wall_ns |
| 116 | && a->t_ns == b->t_ns && a->horizon == b->horizon |
| 117 | && memcmp(&a->z, &b->z, sizeof(double)) == 0 && memcmp(&a->y_mean, &b->y_mean, sizeof(double)) == 0 |
| 118 | && memcmp(&a->S, &b->S, sizeof(double)) == 0 && memcmp(&a->nu, &b->nu, sizeof(double)) == 0 |
| 119 | && memcmp(&a->nis, &b->nis, sizeof(double)) == 0 |
| 120 | && memcmp(&a->evidence, &b->evidence, sizeof a->evidence) == 0 && memcmp(&a->obs_d, &b->obs_d, sizeof a->obs_d) == 0 |
| 121 | && memcmp(&a->pred_d, &b->pred_d, sizeof a->pred_d) == 0 && memcmp(&a->innov_d, &b->innov_d, sizeof a->innov_d) == 0 |
| 122 | && memcmp(&a->belief_d, &b->belief_d, sizeof a->belief_d) == 0 |
| 123 | && memcmp(a->post.x, b->post.x, sizeof a->post.x) == 0 && memcmp(a->post.P, b->post.P, sizeof a->post.P) == 0 |
| 124 | && a->post.generation == b->post.generation && a->post.t_ns == b->post.t_ns; |
| 125 | } |
| 126 | |
| 127 | static int in_trial(const marks *mk, int64_t t) |
| 128 | { |
| 129 | for (size_t i = 0; i < mk->n; i++) if (t >= mk->b[i] && t <= mk->e[i]) return 1; |
| 130 | return 0; |
| 131 | } |
| 132 | |
| 133 | /* mx == NULL: Gaussian intervals (v1). mx != NULL (protocol v2, M2): the |
| 134 | * h-step change has the mixture shape; intervals are its central quantiles and |
| 135 | * the log score is its log density. Thresholds are cached per horizon. */ |
| 136 | typedef struct { const est_mix *mx; double t[EST_MIX_MAX_H + 1][3]; int have[EST_MIX_MAX_H + 1]; size_t beyond; } shape_q; |
| 137 | static const double PCOV[3] = { 0.50, 0.80, 0.95 }; |
| 138 | static int shape_thr(shape_q *sq, uint32_t h, double out[3]) |
| 139 | { |
| 140 | if (h < 1 || h > EST_MIX_MAX_H) { sq->beyond++; return 1; } |
| 141 | if (!sq->have[h]) { |
| 142 | for (int k = 0; k < 3; k++) if (est_mix_quantile_abs(sq->mx, h, PCOV[k], &sq->t[h][k]) != EST_OK) return 1; |
| 143 | sq->have[h] = 1; |
| 144 | } |
| 145 | for (int k = 0; k < 3; k++) out[k] = sq->t[h][k]; |
| 146 | return 0; |
| 147 | } |
| 148 | |
| 149 | static void compute(const est_replay *rp, const marks *mk, model_stats *st, const est_mix *mx, size_t *beyond) |
| 150 | { |
| 151 | memset(st, 0, sizeof *st); |
| 152 | static shape_q sq; |
| 153 | memset(&sq, 0, sizeof sq); sq.mx = mx; |
| 154 | size_t cap = rp->nsteps; |
| 155 | double *w = malloc(cap * sizeof *w), *nu = malloc(cap * sizeof *nu); |
| 156 | size_t n = 0, hit[3] = { 0, 0, 0 }, zero = 0; |
| 157 | double snis = 0, sls = 0, sse = 0, ssp = 0, prev_z = 0; int have_prev = 0; |
| 158 | int64_t tmin = 0, tmax = 0; int first = 1; |
| 159 | for (size_t i = 0; i < rp->nsteps; i++) { /* time range of included samples */ |
| 160 | const est_step *s = &rp->steps[i]; |
| 161 | if (s->prior || s->coast || s->L < EST_BURN_IN) continue; |
| 162 | if (first) { tmin = tmax = s->t_ns; first = 0; } |
| 163 | if (s->t_ns < tmin) tmin = s->t_ns; |
| 164 | if (s->t_ns > tmax) tmax = s->t_ns; |
| 165 | } |
| 166 | size_t qh[4] = { 0 }; |
| 167 | size_t rh[2] = { 0 }; |
| 168 | for (size_t i = 0; i < rp->nsteps; i++) { |
| 169 | const est_step *s = &rp->steps[i]; |
| 170 | if (s->prior) { prev_z = s->z; have_prev = 1; continue; } |
| 171 | if (s->coast) continue; |
| 172 | if (s->L >= EST_BURN_IN) { |
| 173 | double sd = sqrt(s->S), a = fabs(s->nu); |
| 174 | double thr[3] = { ZC50 * sd, ZC80 * sd, ZC95 * sd }; |
| 175 | if (mx && shape_thr(&sq, s->horizon, thr)) thr[0] = thr[1] = thr[2] = -1.0; /* counted as misses, reported */ |
| 176 | nu[n] = s->nu; w[n] = s->nu / sd; n++; |
| 177 | if (a <= thr[0]) hit[0]++; |
| 178 | if (a <= thr[1]) hit[1]++; |
| 179 | int h95 = a <= thr[2]; |
| 180 | if (h95) hit[2]++; |
| 181 | snis += s->nis; |
| 182 | if (mx) { double lp = -INFINITY; if (s->horizon >= 1 && s->horizon <= EST_MIX_MAX_H) est_mix_logpdf(mx, s->horizon, s->nu, &lp); sls += lp; } |
| 183 | else sls += -0.5 * (log(TWO_PI * s->S) + s->nis); |
| 184 | sse += s->nu * s->nu; |
| 185 | if (s->nu == 0.0) zero++; |
| 186 | if (have_prev) { double e = s->z - prev_z; ssp += e * e; } |
| 187 | int q = (int)((4 * (s->t_ns - tmin)) / (tmax - tmin + 1)); |
| 188 | if (q < 0) q = 0; |
| 189 | if (q > 3) q = 3; |
| 190 | st->qn[q]++; if (h95) qh[q]++; |
| 191 | int rg = s->t_ok && in_trial(mk, s->wall_ns); |
| 192 | st->regime_n[rg]++; if (h95) rh[rg]++; |
| 193 | } |
| 194 | prev_z = s->z; have_prev = 1; |
| 195 | } |
| 196 | st->n = n; st->tmin_ns = tmin; st->tmax_ns = tmax; |
| 197 | if (n >= 3) { |
| 198 | double dn = (double)n; |
| 199 | for (int k = 0; k < 3; k++) { st->cov[k] = hit[k] / dn; wilson(hit[k], n, &st->wlo[k], &st->whi[k]); } |
| 200 | st->mean_nis = snis / dn; |
| 201 | double mn = 0; for (size_t i = 0; i < n; i++) mn += nu[i]; mn /= dn; |
| 202 | double v = 0; for (size_t i = 0; i < n; i++) v += (nu[i] - mn) * (nu[i] - mn); |
| 203 | double sdv = sqrt(v / (dn - 1.0)); |
| 204 | st->bias = sdv > 0 ? mn / sdv : INFINITY; |
| 205 | double wm = 0; for (size_t i = 0; i < n; i++) wm += w[i]; wm /= dn; |
| 206 | double den = 0; for (size_t i = 0; i < n; i++) den += (w[i] - wm) * (w[i] - wm); |
| 207 | double lb = 0; |
| 208 | for (int k = 1; k <= 10 && (size_t)k < n; k++) { |
| 209 | double num = 0; for (size_t i = 0; i + k < n; i++) num += (w[i] - wm) * (w[i + k] - wm); |
| 210 | double rk = den > 0 ? num / den : 0; |
| 211 | if (k == 1) st->lag1 = rk; |
| 212 | lb += rk * rk / (dn - k); |
| 213 | } |
| 214 | st->ljung_box10 = dn * (dn + 2.0) * lb; |
| 215 | st->logscore = sls / dn; st->rmse = sqrt(sse / dn); st->persist_rmse = sqrt(ssp / dn); |
| 216 | st->zero_innov_frac = (double)zero / dn; |
| 217 | } |
| 218 | for (int q = 0; q < 4; q++) st->qcov[q] = st->qn[q] ? (double)qh[q] / (double)st->qn[q] : 0; |
| 219 | for (int g = 0; g < 2; g++) st->regime_cov[g] = st->regime_n[g] ? (double)rh[g] / (double)st->regime_n[g] : 0; |
| 220 | /* ten-step coverage from each belief at L >= burn-in */ |
| 221 | size_t tn = 0, th = 0; |
| 222 | for (size_t i = 0; i < rp->nsteps; i++) { |
| 223 | const est_step *s = &rp->steps[i]; |
| 224 | if (s->prior || s->coast || s->L < EST_BURN_IN) continue; /* coasted origins are skipped */ |
| 225 | int64_t target = s->t_ns + (int64_t)TEN_STEP * 1000000000ll; |
| 226 | const est_step *tg = NULL; |
| 227 | for (size_t j = i + 1; j < rp->nsteps && rp->steps[j].t_ns <= target; j++) |
| 228 | if (rp->steps[j].t_ns == target && !rp->steps[j].coast) { tg = &rp->steps[j]; break; } |
| 229 | if (!tg) continue; |
| 230 | est_prediction p; |
| 231 | if (est_kf_predict(&rp->model, &s->post, NULL, TEN_STEP, &p) != EST_OK) continue; |
| 232 | tn++; |
| 233 | double t10 = ZC95 * sqrt(p.S[0]); |
| 234 | if (mx) { double tt[3]; if (shape_thr(&sq, TEN_STEP, tt)) t10 = -1.0; else t10 = tt[2]; } |
| 235 | if (fabs(tg->z - p.y_mean[0]) <= t10) th++; |
| 236 | } |
| 237 | st->ten_n = tn; |
| 238 | if (tn) { st->ten_cov = (double)th / (double)tn; wilson(th, tn, &st->ten_lo, &st->ten_hi); } |
| 239 | /* pass rules */ |
| 240 | st->ok_cov[0] = in_band(st->cov[0], B50); st->ok_cov[1] = in_band(st->cov[1], B80); |
| 241 | st->ok_cov[2] = in_band(st->cov[2], B95); |
| 242 | st->ok_nis = in_band(st->mean_nis, BNIS); |
| 243 | st->ok_bias = fabs(st->bias) <= 0.10; |
| 244 | st->ok_lag1 = fabs(st->lag1) <= 0.20; |
| 245 | st->calibrated = n >= 3 && st->ok_cov[0] && st->ok_cov[1] && st->ok_cov[2] && st->ok_nis && st->ok_bias && st->ok_lag1; |
| 246 | for (int q = 0; q < 4; q++) { st->ok_q[q] = st->qn[q] > 0 && in_band(st->qcov[q], BQ); if (!st->ok_q[q]) st->calibrated = 0; } |
| 247 | for (int g = 0; g < 2; g++) { |
| 248 | st->ok_regime[g] = st->regime_n[g] < 100 ? 1 : in_band(st->regime_cov[g], BQ); |
| 249 | if (!st->ok_regime[g]) st->calibrated = 0; |
| 250 | } |
| 251 | st->ok_ten = tn > 0 && in_band(st->ten_cov, BQ); |
| 252 | if (!st->ok_ten) st->calibrated = 0; |
| 253 | st->rmse_le_persist = n >= 3 && st->rmse <= st->persist_rmse; |
| 254 | if (beyond) *beyond = sq.beyond; |
| 255 | free(w); free(nu); |
| 256 | } |
| 257 | |
| 258 | static const char *b(int v) { return v ? "true" : "false"; } |
| 259 | static void js(FILE *fp, const char *s) |
| 260 | { |
| 261 | fputc('"', fp); |
| 262 | for (; *s; s++) { |
| 263 | unsigned char c = (unsigned char)*s; |
| 264 | if (c == '"' || c == '\\') { fputc('\\', fp); fputc(c, fp); } |
| 265 | else if (c < 0x20) fprintf(fp, "\\u%04x", c); |
| 266 | else fputc(c, fp); |
| 267 | } |
| 268 | fputc('"', fp); |
| 269 | } |
| 270 | /* est-json-1: a receipt never holds inf or nan; a non-finite number is written as null */ |
| 271 | static const char *numstr(double v, char *b) |
| 272 | { |
| 273 | if (isfinite(v)) snprintf(b, 40, "%.17g", v); else snprintf(b, 40, "null"); |
| 274 | return b; |
| 275 | } |
| 276 | #define N17(v) numstr((v), (char[40]){ 0 }) |
| 277 | static void jd(FILE *fp, const char *k, double v) |
| 278 | { |
| 279 | if (isfinite(v)) fprintf(fp, "\"%s\": %.17g", k, v); else fprintf(fp, "\"%s\": null", k); |
| 280 | } |
| 281 | |
| 282 | static void emit_model(FILE *fp, int m, double q, double r, double ll, const est_mix *mx, const model_stats *s, int last) |
| 283 | { |
| 284 | fprintf(fp, " \"M%d\": {\n \"q\": %s, \"r\": %s, \"fit_loglik\": %s,\n", m, N17(q), N17(r), N17(ll)); |
| 285 | if (mx) { |
| 286 | fprintf(fp, " \"predictive_shape\": {\"kind\": \"gaussian_scale_mixture\", \"k\": %u, \"w\": [", mx->k); |
| 287 | for (uint32_t j = 0; j < mx->k; j++) fprintf(fp, "%s%s", j ? ", " : "", N17(mx->w[j])); |
| 288 | fprintf(fp, "], \"v\": ["); |
| 289 | for (uint32_t j = 0; j < mx->k; j++) fprintf(fp, "%s%s", j ? ", " : "", N17(mx->v[j])); |
| 290 | fprintf(fp, "]},\n"); |
| 291 | } |
| 292 | fprintf(fp, " \"samples\": %zu, \"included_logical_span_ns\": [%lld, %lld],\n", s->n, (long long)s->tmin_ns, (long long)s->tmax_ns); |
| 293 | const char *nm[3] = { "50", "80", "95" }; |
| 294 | for (int k = 0; k < 3; k++) { |
| 295 | fprintf(fp, " \"coverage_%s\": {\"value\": %s, \"wilson95\": [%s, %s], \"pass\": %s},\n", |
| 296 | nm[k], N17(s->cov[k]), N17(s->wlo[k]), N17(s->whi[k]), b(s->ok_cov[k])); |
| 297 | } |
| 298 | fprintf(fp, " \"mean_nis\": {"); jd(fp, "value", s->mean_nis); fprintf(fp, ", \"pass\": %s},\n", b(s->ok_nis)); |
| 299 | fprintf(fp, " \"standardized_bias\": {"); jd(fp, "value", s->bias); fprintf(fp, ", \"pass\": %s},\n", b(s->ok_bias)); |
| 300 | fprintf(fp, " \"lag1_autocorr\": {"); jd(fp, "value", s->lag1); fprintf(fp, ", \"pass\": %s},\n", b(s->ok_lag1)); |
| 301 | fprintf(fp, " \"ljung_box_q10_reported_only\": "); if (isfinite(s->ljung_box10)) fprintf(fp, "%.17g", s->ljung_box10); else fprintf(fp, "null"); |
| 302 | fprintf(fp, ",\n \"quarters_coverage95\": [\n"); |
| 303 | for (int q = 0; q < 4; q++) |
| 304 | fprintf(fp, " {\"n\": %zu, \"value\": %s, \"pass\": %s}%s\n", s->qn[q], N17(s->qcov[q]), b(s->ok_q[q]), q < 3 ? "," : ""); |
| 305 | fprintf(fp, " ],\n \"regime_coverage95\": {\n"); |
| 306 | fprintf(fp, " \"idle\": {\"n\": %zu, \"value\": %s, \"gated\": %s, \"pass\": %s},\n", s->regime_n[0], N17(s->regime_cov[0]), b(s->regime_n[0] >= 100), b(s->ok_regime[0])); |
| 307 | fprintf(fp, " \"in_trial\": {\"n\": %zu, \"value\": %s, \"gated\": %s, \"pass\": %s}\n },\n", s->regime_n[1], N17(s->regime_cov[1]), b(s->regime_n[1] >= 100), b(s->ok_regime[1])); |
| 308 | fprintf(fp, " \"ten_step_coverage95\": {\"n\": %zu, \"value\": %s, \"wilson95\": [%s, %s], \"pass\": %s},\n", s->ten_n, N17(s->ten_cov), N17(s->ten_lo), N17(s->ten_hi), b(s->ok_ten)); |
| 309 | fprintf(fp, " \"log_score_per_step\": "); if (isfinite(s->logscore)) fprintf(fp, "%.17g", s->logscore); else fprintf(fp, "null"); |
| 310 | fprintf(fp, ",\n \"rmse_one_step\": %s, \"persistence_rmse\": %s, \"rmse_no_worse_than_persistence\": %s,\n", |
| 311 | N17(s->rmse), N17(s->persist_rmse), b(s->rmse_le_persist)); |
| 312 | fprintf(fp, " \"zero_innovation_fraction_extra\": %s,\n", N17(s->zero_innov_frac)); |
| 313 | fprintf(fp, " \"calibrated\": %s,\n \"failed_criteria\": [", b(s->calibrated)); |
| 314 | int first = 1; |
| 315 | #define FC(cond, name) do { if (!(cond)) { fprintf(fp, "%s\"%s\"", first ? "" : ", ", name); first = 0; } } while (0) |
| 316 | FC(s->ok_cov[0], "coverage_50"); FC(s->ok_cov[1], "coverage_80"); FC(s->ok_cov[2], "coverage_95"); |
| 317 | FC(s->ok_nis, "mean_nis"); FC(s->ok_bias, "standardized_bias"); FC(s->ok_lag1, "lag1_autocorr"); |
| 318 | FC(s->ok_q[0], "quarter_1"); FC(s->ok_q[1], "quarter_2"); FC(s->ok_q[2], "quarter_3"); FC(s->ok_q[3], "quarter_4"); |
| 319 | FC(s->ok_regime[0], "regime_idle"); FC(s->ok_regime[1], "regime_in_trial"); FC(s->ok_ten, "ten_step_coverage_95"); |
| 320 | fprintf(fp, "], \"failed_verdict_only\": ["); |
| 321 | first = 1; |
| 322 | FC(s->n >= 3, "samples_lt_3"); FC(s->rmse_le_persist, "rmse_vs_persistence"); |
| 323 | #undef FC |
| 324 | fprintf(fp, "]\n }%s\n", last ? "" : ","); |
| 325 | } |
| 326 | |
| 327 | #ifndef TOOL_COMMIT |
| 328 | #define TOOL_COMMIT "unknown" |
| 329 | #endif |
| 330 | #ifndef TOOL_DIRTY |
| 331 | #define TOOL_DIRTY 1 |
| 332 | #endif |
| 333 | |
| 334 | static int tool_dirty(void) |
| 335 | { |
| 336 | #ifdef EST_TEST_BUILD |
| 337 | const char *e = getenv("EST_TEST_DIRTY"); if (e && *e) return atoi(e); |
| 338 | #endif |
| 339 | return TOOL_DIRTY; |
| 340 | } |
| 341 | |
| 342 | static int open_excl(const char *path, FILE **out) |
| 343 | { |
| 344 | *out = fopen(path, "wbx"); |
| 345 | if (!*out) { fprintf(stderr, "refuse: cannot create %s (%s); existing outputs are never overwritten\n", path, strerror(errno)); return 1; } |
| 346 | return 0; |
| 347 | } |
| 348 | |
| 349 | static void dir_and_name(const char *path, char *dir, size_t cap, const char **name) |
| 350 | { |
| 351 | const char *slash = strrchr(path, '/'); |
| 352 | *name = slash ? slash + 1 : path; |
| 353 | if (slash) { size_t n = (size_t)(slash - path); if (n >= cap) n = cap - 1; memcpy(dir, path, n); dir[n] = 0; } |
| 354 | else snprintf(dir, cap, "."); |
| 355 | } |
| 356 | |
| 357 | /* Both the resolved path (component with run B's id) and the digest in the |
| 358 | * SHA256SUMS text beside the file identify the input as run B. */ |
| 359 | static int is_b_input(const char *path, const char *b_sha, int *by_path, int *by_sums) |
| 360 | { |
| 361 | char dir[1024], hex[65]; const char *name; |
| 362 | dir_and_name(path, dir, sizeof dir, &name); |
| 363 | *by_path = est_path_is_run_b(path); |
| 364 | *by_sums = (est_sums_lookup(dir, name, hex) == 0 && strcmp(hex, b_sha) == 0); |
| 365 | return *by_path || *by_sums; |
| 366 | } |
| 367 | |
| 368 | /* Physically truncate: write the first k lines to a temp file, replay that |
| 369 | * file from scratch, compare bit for bit with the first records of the full run. */ |
| 370 | static int prefix_check(const est_file *f, const est_replay *full, int nm, const int *ids, const double *q, const double *r, |
| 371 | const size_t *ks, int nk, size_t *ran) |
| 372 | { |
| 373 | const char *tb = getenv("TMPDIR"); if (!tb || !*tb) tb = "/tmp"; |
| 374 | char dir[600]; snprintf(dir, sizeof dir, "%s/est_eval_prefix_XXXXXX", tb); |
| 375 | if (!mkdtemp(dir)) return 0; |
| 376 | char path[700]; snprintf(path, sizeof path, "%s/prefix.ndjson", dir); |
| 377 | static est_replay pre; |
| 378 | int ok = 1; |
| 379 | for (int ki = 0; ki < nk; ki++) { |
| 380 | size_t k = ks[ki]; |
| 381 | if (k > f->nlines) { ok = 0; continue; } |
| 382 | FILE *fp = fopen(path, "wb"); |
| 383 | if (!fp) { ok = 0; break; } |
| 384 | for (size_t i = 0; i < k; i++) { |
| 385 | fwrite(f->data + f->off[i], 1, f->llen[i], fp); fputc('\n', fp); |
| 386 | } |
| 387 | if (fclose(fp)) { ok = 0; break; } |
| 388 | est_file pf; char err[300]; |
| 389 | if (est_file_load_raw(path, &pf, err, sizeof err)) { ok = 0; break; } |
| 390 | for (int m = 0; m < nm; m++) { |
| 391 | if (est_replay_run(&pf, (size_t)-1, ids[m], q[m], r[m], &pre)) { ok = 0; continue; } |
| 392 | size_t nn = pre.nsteps; |
| 393 | if (nn == 0 || nn > full[m].nsteps) { ok = 0; continue; } |
| 394 | for (size_t i = 0; i < nn; i++) if (!step_equal(&pre.steps[i], &full[m].steps[i])) { ok = 0; break; } |
| 395 | } |
| 396 | est_file_free(&pf); |
| 397 | (*ran)++; |
| 398 | } |
| 399 | est_replay_free(&pre); |
| 400 | unlink(path); rmdir(dir); |
| 401 | return ok; |
| 402 | } |
| 403 | |
| 404 | /* ---- Protocol v2 (docs/estimation/EST23_PROTOCOL_V2.md) ---- |
| 405 | * est_eval --protocol-v2 --params2 P2 --raw F --marks M --out R |
| 406 | * [--protocol-doc D] [--recorded] [--synthetic-test] |
| 407 | * Evaluates M0 and M1 with the frozen v1 parameters (named inside P2) and M2 |
| 408 | * with its fitted shape, on one file. --recorded only for held-out run C2. */ |
| 409 | static const char *v2_heldout_raw_sha(void) |
| 410 | { |
| 411 | #ifdef EST_TEST_BUILD |
| 412 | const char *e = getenv("EST_TEST_C2_RAW_SHA"); if (e && *e) return e; |
| 413 | #endif |
| 414 | return EST_V2_HELDOUT_RAW_SHA; |
| 415 | } |
| 416 | static const char *v2_heldout_marks_sha(void) |
| 417 | { |
| 418 | #ifdef EST_TEST_BUILD |
| 419 | const char *e = getenv("EST_TEST_C2_MARKS_SHA"); if (e && *e) return e; |
| 420 | #endif |
| 421 | return EST_V2_HELDOUT_MARKS_SHA; |
| 422 | } |
| 423 | static const char *v2_fit_sha(void) |
| 424 | { |
| 425 | #ifdef EST_TEST_BUILD |
| 426 | const char *e = getenv("EST_TEST_C1_SHA"); if (e && *e) return e; |
| 427 | #endif |
| 428 | return EST_V2_FIT_SHA; |
| 429 | } |
| 430 | static const char *v2_doc_sha(void) |
| 431 | { |
| 432 | #ifdef EST_TEST_BUILD |
| 433 | const char *e = getenv("EST_TEST_V2_DOC_SHA"); if (e && *e) return e; |
| 434 | #endif |
| 435 | return EST_V2_PROTOCOL_DOC_SHA; |
| 436 | } |
| 437 | static int is_c2_input(const char *path, const char *want, int *by_path, int *by_sums) |
| 438 | { |
| 439 | char dir[1024], hex[65]; const char *name; |
| 440 | dir_and_name(path, dir, sizeof dir, &name); |
| 441 | *by_path = est_path_is_heldout(path); |
| 442 | *by_sums = (est_sums_lookup(dir, name, hex) == 0 && strcmp(hex, want) == 0); |
| 443 | return *by_path || *by_sums; |
| 444 | } |
| 445 | |
| 446 | static int main_v2(int argc, char **argv) |
| 447 | { |
| 448 | const char *params = NULL, *raw = NULL, *mkp = NULL, *out = NULL, *pdoc = EST_V2_PROTOCOL_DOC; |
| 449 | int recorded = 0, synth = 0; |
| 450 | for (int i = 1; i < argc; i++) { |
| 451 | if (!strcmp(argv[i], "--params2") && i + 1 < argc) params = argv[++i]; |
| 452 | else if (!strcmp(argv[i], "--raw") && i + 1 < argc) raw = argv[++i]; |
| 453 | else if (!strcmp(argv[i], "--marks") && i + 1 < argc) mkp = argv[++i]; |
| 454 | else if (!strcmp(argv[i], "--out") && i + 1 < argc) out = argv[++i]; |
| 455 | else if (!strcmp(argv[i], "--protocol-doc") && i + 1 < argc) pdoc = argv[++i]; |
| 456 | else if (!strcmp(argv[i], "--recorded")) recorded = 1; |
| 457 | else if (!strcmp(argv[i], "--synthetic-test")) synth = 1; |
| 458 | else { fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; } |
| 459 | } |
| 460 | if (!params || !raw || !mkp || !out) { |
| 461 | fprintf(stderr, "usage: est_eval --protocol-v2 --params2 P2 --raw F --marks M --out R [--protocol-doc D] [--recorded] [--synthetic-test]\n"); |
| 462 | return 2; |
| 463 | } |
| 464 | if (recorded && synth) { fprintf(stderr, "refuse: --recorded and --synthetic-test are exclusive\n"); return 2; } |
| 465 | int bp, bs; |
| 466 | if (is_b_input(raw, est_run_b_raw_sha(), &bp, &bs) || is_b_input(mkp, est_run_b_marks_sha(), &bp, &bs)) { |
| 467 | fprintf(stderr, "refuse: run B is closed evidence under protocol v1 and is never read by protocol v2\n"); return 2; |
| 468 | } |
| 469 | int rp_path, rp_sums, mp_path, mp_sums; |
| 470 | int raw_c2 = is_c2_input(raw, v2_heldout_raw_sha(), &rp_path, &rp_sums); |
| 471 | int mk_c2 = is_c2_input(mkp, v2_heldout_marks_sha(), &mp_path, &mp_sums); |
| 472 | if (recorded) { |
| 473 | if (!(rp_path && rp_sums)) { fprintf(stderr, "refuse: --recorded is accepted only for held-out run C2's raw file (path and SHA256SUMS digest must both match)\n"); return 2; } |
| 474 | if (!(mp_path && mp_sums)) { fprintf(stderr, "refuse: --recorded needs C2's own marks file (path and SHA256SUMS digest must both match)\n"); return 2; } |
| 475 | if (tool_dirty()) { fprintf(stderr, "refuse: --recorded needs a clean working tree at build time (TOOL_DIRTY=%d)\n", tool_dirty()); return 2; } |
| 476 | } else if (raw_c2 || mk_c2) { |
| 477 | fprintf(stderr, "refuse: the held-out run may only be evaluated with --recorded (protocol v2)\n"); return 2; |
| 478 | } |
| 479 | char err[300], p2hex[65], p1hex[65], pdoc_hex[65], bin_hex[65]; |
| 480 | est_params2 p2; est_params p1; |
| 481 | if (est_params2_read(params, &p2)) { fprintf(stderr, "refuse: v2 parameter file is not exactly the expected format\n"); return 1; } |
| 482 | if (est_mix_check(&p2.mix) != EST_OK) { fprintf(stderr, "refuse: M2 shape is not a valid mixture\n"); return 1; } |
| 483 | double tv = est_mix_total_var(&p2.mix); |
| 484 | if (!(p2.r == EST_M2_R) || !(fabs(p2.q - tv) <= 1e-12 * tv)) { fprintf(stderr, "refuse: M2 q must be the shape's total variance and r must be %g\n", EST_M2_R); return 1; } |
| 485 | if (est_params_read(p2.v1_params_path, &p1) || est_params_validate(&p1, err, sizeof err)) { fprintf(stderr, "refuse: v1 parameter file %s is not valid\n", p2.v1_params_path); return 1; } |
| 486 | if (est_sha_file_hex(p2.v1_params_path, p1hex) || strcmp(p1hex, p2.v1_params_sha) != 0) { fprintf(stderr, "refuse: v1 parameter file digest differs from the one recorded in the v2 parameter file\n"); return 1; } |
| 487 | int v1_fit_is_a = strstr(p1.fit_path, EST_RUN_A_ID) != NULL && strcmp(p1.fit_sha, EST_RUN_A_SHA) == 0; |
| 488 | int fit_is_c1 = strstr(p2.fit_path, EST_V2_FIT_TAG) != NULL && strcmp(p2.fit_sha, v2_fit_sha()) == 0; |
| 489 | int fit_sums_ok = 0; |
| 490 | { |
| 491 | char dir[1024], hex[65]; const char *name; |
| 492 | dir_and_name(p2.fit_path, dir, sizeof dir, &name); |
| 493 | fit_sums_ok = (strcmp(name, "machine-state.ndjson") == 0 && est_sums_lookup(dir, name, hex) == 0 && strcmp(hex, p2.fit_sha) == 0); |
| 494 | } |
| 495 | if (!synth && !(v1_fit_is_a && fit_is_c1)) { fprintf(stderr, "refuse: M0/M1 must be fit on run A and M2 on run C1\n"); return 1; } |
| 496 | if (recorded && !fit_sums_ok) { fprintf(stderr, "refuse: --recorded needs the M2 fit file to match its SHA256SUMS line\n"); return 1; } |
| 497 | int pdoc_ok = !est_sha_file_hex(pdoc, pdoc_hex); |
| 498 | int pdoc_matches = pdoc_ok && strcmp(pdoc_hex, v2_doc_sha()) == 0; |
| 499 | if (recorded && !pdoc_matches) { fprintf(stderr, "refuse: --recorded needs the frozen v2 protocol document (SHA-256 %s)\n", v2_doc_sha()); return 1; } |
| 500 | if (!pdoc_ok) snprintf(pdoc_hex, sizeof pdoc_hex, "unavailable"); |
| 501 | if (est_sha_file_hex("/proc/self/exe", bin_hex)) snprintf(bin_hex, sizeof bin_hex, "unavailable"); |
| 502 | if (est_sha_file_hex(params, p2hex)) return 1; |
| 503 | |
| 504 | est_allow_heldout = recorded; /* only after every identity check above */ |
| 505 | est_file f; |
| 506 | if (est_file_load(raw, &f, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 1; } |
| 507 | if (recorded && strcmp(f.sha_hex, v2_heldout_raw_sha()) != 0) { fprintf(stderr, "refuse: raw digest is not C2's\n"); return 1; } |
| 508 | marks mk; |
| 509 | if (load_marks(mkp, &mk, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 1; } |
| 510 | if (recorded && strcmp(mk.sha, v2_heldout_marks_sha()) != 0) { fprintf(stderr, "refuse: marks digest is not C2's\n"); return 1; } |
| 511 | |
| 512 | enum { NM = 3 }; |
| 513 | const int ids[NM] = { 0, 1, 2 }; |
| 514 | const double q[NM] = { p1.q[0], p1.q[1], p2.q }, r[NM] = { p1.r[0], p1.r[1], p2.r }, ll[NM] = { p1.ll[0], p1.ll[1], p2.ll }; |
| 515 | FILE *fp = NULL, *sfp[NM] = { NULL, NULL, NULL }; |
| 516 | char spath[NM][1100]; |
| 517 | if (open_excl(out, &fp)) return 1; |
| 518 | for (int m = 0; m < NM; m++) { snprintf(spath[m], sizeof spath[m], "%s.M%d.stream", out, m); if (open_excl(spath[m], &sfp[m])) return 1; } |
| 519 | |
| 520 | static est_replay rp[NM]; |
| 521 | model_stats st[NM]; |
| 522 | memset(st, 0, sizeof st); |
| 523 | int replay_ok = 1, chain_ok = 1, m2_persist = 0; |
| 524 | size_t ks[3] = { 100, 500, 1000 }, prefix_ran = 0, expect_steps = 0, beyond = 0; |
| 525 | for (int m = 0; m < NM; m++) { |
| 526 | if (est_replay_run(&f, (size_t)-1, ids[m], q[m], r[m], &rp[m])) { replay_ok = 0; fprintf(stderr, "replay M%d: %s\n", m, rp[m].errmsg); continue; } |
| 527 | expect_steps = f.nlines - rp[m].leading_missing; |
| 528 | if (rp[m].nsteps != expect_steps) replay_ok = 0; |
| 529 | for (size_t i = 0; i < rp[m].nsteps; i++) if (!rp[m].steps[i].chain_ok) chain_ok = 0; |
| 530 | compute(&rp[m], &mk, &st[m], m == 2 ? &p2.mix : NULL, m == 2 ? &beyond : NULL); |
| 531 | } |
| 532 | if (replay_ok) { |
| 533 | double *e = malloc((rp[2].nsteps + 1) * sizeof *e); |
| 534 | m2_persist = e && est_m2_changes(&rp[2], e, rp[2].nsteps) != (size_t)-1; |
| 535 | free(e); |
| 536 | } |
| 537 | int prefix_ok = replay_ok && prefix_check(&f, rp, NM, ids, q, r, ks, 3, &prefix_ran); |
| 538 | char shash[NM][65] = { "unavailable", "unavailable", "unavailable" }; |
| 539 | int streams_ok = replay_ok; |
| 540 | for (int m = 0; m < NM; m++) { |
| 541 | if (replay_ok) est_replay_write_stream(sfp[m], &rp[m], m); |
| 542 | int bad = fclose(sfp[m]); |
| 543 | if (bad || (replay_ok && est_sha_file_hex(spath[m], shash[m]))) { fprintf(stderr, "cannot write stream %s\n", spath[m]); return 1; } |
| 544 | if (!strcmp(shash[m], "unavailable")) streams_ok = 0; |
| 545 | } |
| 546 | char after[65]; int raw_preserved = !est_sha_file_hex(raw, after) && strcmp(after, f.sha_hex) == 0; |
| 547 | int sel = -1; double best = -INFINITY; |
| 548 | if (replay_ok) { |
| 549 | for (int m = 0; m < NM; m++) if (st[m].calibrated && st[m].logscore > best) best = st[m].logscore; |
| 550 | for (int m = 0; m < NM && sel < 0; m++) if (st[m].calibrated && st[m].logscore >= best - 0.01) sel = m; |
| 551 | } |
| 552 | int real_signal = replay_ok && prefix_ok && raw_preserved && chain_ok && streams_ok && m2_persist; |
| 553 | int calib = 0; |
| 554 | if (replay_ok) for (int m = 0; m < NM; m++) if (st[m].calibrated && st[m].rmse_le_persist) calib = 1; |
| 555 | |
| 556 | fprintf(fp, "{\n \"receipt\": \"est_eval_v2\",\n \"protocol\": \"EST23_PROTOCOL_V2\",\n"); |
| 557 | fprintf(fp, " \"protocol_doc_sha256\": \"%s\",\n \"protocol_doc_matches_frozen_constant\": %s,\n", pdoc_hex, b(pdoc_matches)); |
| 558 | fprintf(fp, " \"tool_commit\": "); js(fp, TOOL_COMMIT); |
| 559 | fprintf(fp, ",\n \"tool_dirty\": %d,\n \"eval_binary_sha256\": \"%s\",\n", tool_dirty(), bin_hex); |
| 560 | fprintf(fp, " \"recorded\": %s,\n \"synthetic_test\": %s,\n", b(recorded), b(synth)); |
| 561 | fprintf(fp, " \"parameter_file_v2\": "); js(fp, params); |
| 562 | fprintf(fp, ",\n \"parameter_file_v2_sha256\": \"%s\",\n \"v1_parameter_file\": ", p2hex); js(fp, p2.v1_params_path); |
| 563 | fprintf(fp, ",\n \"v1_parameter_file_sha256\": \"%s\",\n \"v1_models_fit_on_run_A\": %s,\n", p1hex, b(v1_fit_is_a)); |
| 564 | fprintf(fp, " \"m2_fit_run_path\": "); js(fp, p2.fit_path); |
| 565 | fprintf(fp, ",\n \"m2_fit_file_sha256\": \"%s\",\n \"m2_fit_is_run_C1\": %s,\n \"m2_fit_sha_matches_SHA256SUMS_line\": %s,\n \"m2_fit_changes\": %zu,\n", |
| 566 | p2.fit_sha, b(fit_is_c1), b(fit_sums_ok), p2.fit_n); |
| 567 | fprintf(fp, " \"input_file\": "); js(fp, raw); |
| 568 | fprintf(fp, ",\n \"input_file_sha256\": \"%s\",\n \"input_sha_matches_SHA256SUMS\": true,\n \"input_is_heldout_C2\": %s,\n", f.sha_hex, b(raw_c2 && rp_path && rp_sums)); |
| 569 | fprintf(fp, " \"marks_file_sha256\": \"%s\",\n", mk.sha); |
| 570 | fprintf(fp, " \"lines\": %zu,\n \"marks\": {\"pairs\": %zu, \"begins\": %zu, \"ends\": %zu, \"unclosed_begin_ran_to_eof\": %s, \"nested_begins\": %zu, \"stray_ends\": %zu},\n", |
| 571 | f.nlines, mk.n, mk.begins, mk.ends, b(mk.unclosed), mk.nested_begins, mk.stray_ends); |
| 572 | fprintf(fp, " \"missing_observations\": {\"leading_before_first_valid\": %zu, \"coasted\": %zu, \"bad_value_lines\": %zu, \"bad_t_lines\": %zu, \"bad_t_overflow_lines\": %zu},\n", |
| 573 | rp[0].leading_missing, rp[0].coasts, rp[0].bad_value, rp[0].bad_t, rp[0].bad_t_overflow); |
| 574 | fprintf(fp, " \"time_gaps\": {\"duplicate_t\": %zu, \"backward_t\": %zu, \"steps_with_horizon_gt_1\": %zu, \"m2_steps_beyond_exact_horizon\": %zu},\n", |
| 575 | rp[0].gap_zero, rp[0].gap_backward, rp[0].multi_horizon, beyond); |
| 576 | fprintf(fp, " \"readings\": {\"burn_in\": \"steps with L<%u counted from the prior line (L=0) are excluded\", \"quarters\": \"four equal spans of included samples by logical time\", \"ten_step_origins\": \"coasted origins skipped\", \"m2_intervals\": \"central quantiles of the h-step mixture sum\"},\n", EST_BURN_IN); |
| 577 | fprintf(fp, " \"m2_mean_is_exact_persistence\": %s,\n", b(m2_persist)); |
| 578 | fprintf(fp, " \"replay\": {\"complete\": %s, \"steps\": %zu, \"expected_steps\": %zu, \"chain_recorded_every_step\": %s, \"raw_file_unchanged\": %s,\n", |
| 579 | b(replay_ok), rp[0].nsteps, expect_steps, b(chain_ok), b(raw_preserved)); |
| 580 | fprintf(fp, " \"prefix_invariance\": {\"method\": \"first k lines physically written to a temp file and replayed from scratch\", \"ks\": \"k=100,500,1000\", \"runs\": %zu, \"pass\": %s}},\n", prefix_ran, b(prefix_ok)); |
| 581 | fprintf(fp, " \"streams\": {"); |
| 582 | for (int m = 0; m < NM; m++) { fprintf(fp, "%s\"M%d\": {\"file\": ", m ? ", " : "", m); js(fp, spath[m]); fprintf(fp, ", \"sha256\": \"%s\"}", shash[m]); } |
| 583 | fprintf(fp, "},\n \"models\": {\n"); |
| 584 | if (replay_ok) for (int m = 0; m < NM; m++) emit_model(fp, m, q[m], r[m], ll[m], m == 2 ? &p2.mix : NULL, &st[m], m == NM - 1); |
| 585 | if (sel >= 0) fprintf(fp, " },\n \"selected_model\": \"M%d\",\n", sel); else fprintf(fp, " },\n \"selected_model\": null,\n"); |
| 586 | fprintf(fp, " \"failure_class_to_be_recorded_by_a_human_on_FAIL\": null,\n"); |
| 587 | fprintf(fp, " \"ESTIMATION_REAL_SIGNAL\": \"%s\",\n \"ESTIMATION_CALIBRATION\": \"%s\"\n}\n", real_signal ? "PASS" : "FAIL", calib ? "PASS" : "FAIL"); |
| 588 | if (fclose(fp)) return 1; |
| 589 | char rh[65]; est_sha_file_hex(out, rh); |
| 590 | printf("ESTIMATION_REAL_SIGNAL=%s ESTIMATION_CALIBRATION=%s selected=%s%d receipt_sha256=%s\n", real_signal ? "PASS" : "FAIL", calib ? "PASS" : "FAIL", sel >= 0 ? "M" : "none", sel, rh); |
| 591 | for (int m = 0; m < NM; m++) est_replay_free(&rp[m]); |
| 592 | est_file_free(&f); |
| 593 | return 0; |
| 594 | } |
| 595 | |
| 596 | int main(int argc, char **argv) |
| 597 | { |
| 598 | if (argc >= 2 && !strcmp(argv[1], "--protocol-v2")) return main_v2(argc - 1, argv + 1); |
| 599 | const char *params = NULL, *raw = NULL, *mkp = NULL, *out = NULL; |
| 600 | const char *pdoc = "docs/estimation/EST23_PROTOCOL_V1.md"; |
| 601 | const char *interp = "docs/estimation/EST23_PROTOCOL_V1_INTERPRETATIONS.md"; |
| 602 | int recorded = 0, synth = 0; |
| 603 | for (int i = 1; i < argc; i++) { |
| 604 | if (!strcmp(argv[i], "--params") && i + 1 < argc) params = argv[++i]; |
| 605 | else if (!strcmp(argv[i], "--raw") && i + 1 < argc) raw = argv[++i]; |
| 606 | else if (!strcmp(argv[i], "--marks") && i + 1 < argc) mkp = argv[++i]; |
| 607 | else if (!strcmp(argv[i], "--out") && i + 1 < argc) out = argv[++i]; |
| 608 | else if (!strcmp(argv[i], "--protocol-doc") && i + 1 < argc) pdoc = argv[++i]; |
| 609 | else if (!strcmp(argv[i], "--interpretations") && i + 1 < argc) interp = argv[++i]; |
| 610 | else if (!strcmp(argv[i], "--recorded")) recorded = 1; |
| 611 | else if (!strcmp(argv[i], "--synthetic-test")) synth = 1; |
| 612 | else { fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; } |
| 613 | } |
| 614 | if (!params || !raw || !mkp || !out) { |
| 615 | fprintf(stderr, "usage: est_eval --params P --raw F --marks M --out R [--protocol-doc D] [--interpretations I] [--recorded] [--synthetic-test]\n"); |
| 616 | return 2; |
| 617 | } |
| 618 | if (recorded && synth) { fprintf(stderr, "refuse: --recorded and --synthetic-test are exclusive\n"); return 2; } |
| 619 | |
| 620 | /* run B identity: by resolved path AND by the digest in the SHA256SUMS text */ |
| 621 | int rp_path, rp_sums, mp_path, mp_sums; |
| 622 | int raw_b = is_b_input(raw, est_run_b_raw_sha(), &rp_path, &rp_sums); |
| 623 | int mk_b = is_b_input(mkp, est_run_b_marks_sha(), &mp_path, &mp_sums); |
| 624 | if (recorded) { |
| 625 | if (!(rp_path && rp_sums)) { fprintf(stderr, "refuse: --recorded is accepted only for run B's raw file (path and SHA256SUMS digest must both match)\n"); return 2; } |
| 626 | if (!(mp_path && mp_sums)) { fprintf(stderr, "refuse: --recorded needs run B's own marks file (path and SHA256SUMS digest must both match)\n"); return 2; } |
| 627 | if (tool_dirty()) { fprintf(stderr, "refuse: --recorded needs a clean working tree at build time (TOOL_DIRTY=%d)\n", tool_dirty()); return 2; } |
| 628 | } else if (raw_b || mk_b) { |
| 629 | fprintf(stderr, "refuse: run B may only be evaluated with --recorded (protocol section 6)\n"); return 2; |
| 630 | } |
| 631 | est_params p; |
| 632 | char err[300], phex[65], pdoc_hex[65], interp_hex[65], bin_hex[65]; |
| 633 | if (est_params_read(params, &p)) { fprintf(stderr, "refuse: parameter file is not exactly the expected format\n"); return 1; } |
| 634 | if (est_params_validate(&p, err, sizeof err)) { fprintf(stderr, "refuse: parameter file: %s\n", err); return 1; } |
| 635 | int fit_is_a = strstr(p.fit_path, EST_RUN_A_ID) != NULL && strcmp(p.fit_sha, EST_RUN_A_SHA) == 0; |
| 636 | int fit_sums_ok = 0; |
| 637 | { |
| 638 | char dir[1024], hex[65]; const char *name; |
| 639 | dir_and_name(p.fit_path, dir, sizeof dir, &name); |
| 640 | fit_sums_ok = (strcmp(name, "machine-state.ndjson") == 0 && est_sums_lookup(dir, name, hex) == 0 && strcmp(hex, p.fit_sha) == 0); |
| 641 | } |
| 642 | if (!fit_is_a && !synth) { |
| 643 | fprintf(stderr, "refuse: parameter file was not fit on run A (%s)\n", p.fit_path); return 1; |
| 644 | } |
| 645 | if (recorded && !(fit_is_a && fit_sums_ok)) { |
| 646 | fprintf(stderr, "refuse: --recorded needs the fit file to be run A with a matching SHA256SUMS line\n"); return 1; |
| 647 | } |
| 648 | int pdoc_ok = !est_sha_file_hex(pdoc, pdoc_hex); |
| 649 | int interp_ok = !est_sha_file_hex(interp, interp_hex); |
| 650 | int pdoc_matches = pdoc_ok && strcmp(pdoc_hex, EST_PROTOCOL_DOC_SHA) == 0; |
| 651 | if (recorded && !(pdoc_matches && interp_ok)) { |
| 652 | fprintf(stderr, "refuse: --recorded needs the frozen protocol document (SHA-256 %s) and the interpretations file\n", EST_PROTOCOL_DOC_SHA); return 1; |
| 653 | } |
| 654 | if (!pdoc_ok) snprintf(pdoc_hex, sizeof pdoc_hex, "unavailable"); |
| 655 | if (!interp_ok) snprintf(interp_hex, sizeof interp_hex, "unavailable"); |
| 656 | if (est_sha_file_hex("/proc/self/exe", bin_hex)) snprintf(bin_hex, sizeof bin_hex, "unavailable"); |
| 657 | if (est_sha_file_hex(params, phex)) return 1; |
| 658 | |
| 659 | est_allow_run_b = recorded; /* only after every identity check above */ |
| 660 | est_file f; |
| 661 | if (est_file_load(raw, &f, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 1; } |
| 662 | if (recorded && strcmp(f.sha_hex, est_run_b_raw_sha()) != 0) { fprintf(stderr, "refuse: raw digest is not run B's\n"); return 1; } |
| 663 | marks mk; |
| 664 | if (load_marks(mkp, &mk, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 1; } |
| 665 | if (recorded && strcmp(mk.sha, est_run_b_marks_sha()) != 0) { fprintf(stderr, "refuse: marks digest is not run B's\n"); return 1; } |
| 666 | |
| 667 | /* outputs are created exclusively, before any evaluation work */ |
| 668 | FILE *fp = NULL, *sfp[2] = { NULL, NULL }; |
| 669 | char spath[2][1100]; |
| 670 | snprintf(spath[0], sizeof spath[0], "%s.M0.stream", out); |
| 671 | snprintf(spath[1], sizeof spath[1], "%s.M1.stream", out); |
| 672 | if (open_excl(out, &fp)) return 1; |
| 673 | for (int m = 0; m < 2; m++) if (open_excl(spath[m], &sfp[m])) return 1; |
| 674 | |
| 675 | static est_replay rp[2]; |
| 676 | model_stats st[2]; |
| 677 | memset(st, 0, sizeof st); |
| 678 | int replay_ok = 1, chain_ok = 1; |
| 679 | size_t ks[3] = { 100, 500, 1000 }, prefix_ran = 0; |
| 680 | size_t expect_steps = 0; |
| 681 | for (int m = 0; m < 2; m++) { |
| 682 | if (est_replay_run(&f, (size_t)-1, m, p.q[m], p.r[m], &rp[m])) { replay_ok = 0; fprintf(stderr, "replay M%d: %s\n", m, rp[m].errmsg); continue; } |
| 683 | expect_steps = f.nlines - rp[m].leading_missing; |
| 684 | if (rp[m].nsteps != expect_steps) replay_ok = 0; |
| 685 | for (size_t i = 0; i < rp[m].nsteps; i++) if (!rp[m].steps[i].chain_ok) chain_ok = 0; |
| 686 | compute(&rp[m], &mk, &st[m], NULL, NULL); |
| 687 | } |
| 688 | const int ids[2] = { 0, 1 }; |
| 689 | int prefix_ok = replay_ok && prefix_check(&f, rp, 2, ids, p.q, p.r, ks, 3, &prefix_ran); |
| 690 | /* per-step observation / prediction / innovation stream, every evaluated model */ |
| 691 | char shash[2][65] = { "unavailable", "unavailable" }; |
| 692 | for (int m = 0; m < 2; m++) { |
| 693 | if (replay_ok) est_replay_write_stream(sfp[m], &rp[m], m); |
| 694 | int bad = fclose(sfp[m]); |
| 695 | if (bad || (replay_ok && est_sha_file_hex(spath[m], shash[m]))) { fprintf(stderr, "cannot write stream %s\n", spath[m]); return 1; } |
| 696 | } |
| 697 | /* raw preserved: the file on disk still hashes to the verified digest */ |
| 698 | char after[65]; int raw_preserved = !est_sha_file_hex(raw, after) && strcmp(after, f.sha_hex) == 0; |
| 699 | if (!replay_ok) { fprintf(stderr, "replay did not complete\n"); } |
| 700 | |
| 701 | /* selection: simplest calibrated model within 0.01 nats of the best calibrated */ |
| 702 | int sel = -1; double best = -INFINITY; |
| 703 | if (replay_ok) { |
| 704 | for (int m = 0; m < 2; m++) if (st[m].calibrated && st[m].logscore > best) best = st[m].logscore; |
| 705 | for (int m = 0; m < 2 && sel < 0; m++) if (st[m].calibrated && st[m].logscore >= best - 0.01) sel = m; |
| 706 | } |
| 707 | int streams_ok = replay_ok && strcmp(shash[0], "unavailable") && strcmp(shash[1], "unavailable"); |
| 708 | int real_signal = replay_ok && prefix_ok && raw_preserved && chain_ok && streams_ok; |
| 709 | int calib = 0; |
| 710 | if (replay_ok) for (int m = 0; m < 2; m++) if (st[m].calibrated && st[m].rmse_le_persist) calib = 1; |
| 711 | |
| 712 | fprintf(fp, "{\n \"receipt\": \"est_eval_v1\",\n \"protocol\": \"EST23_PROTOCOL_V1\",\n \"protocol_commit\": "); |
| 713 | js(fp, EST_PROTOCOL_COMMIT); |
| 714 | fprintf(fp, ",\n \"protocol_doc_sha256\": \"%s\",\n \"protocol_doc_matches_frozen_constant\": %s,\n \"interpretations_sha256\": \"%s\",\n", |
| 715 | pdoc_hex, b(pdoc_matches), interp_hex); |
| 716 | fprintf(fp, " \"tool_commit\": "); js(fp, TOOL_COMMIT); |
| 717 | fprintf(fp, ",\n \"tool_dirty\": %d,\n \"eval_binary_sha256\": \"%s\",\n", tool_dirty(), bin_hex); |
| 718 | fprintf(fp, " \"recorded\": %s,\n \"synthetic_test\": %s,\n", b(recorded), b(synth)); |
| 719 | fprintf(fp, " \"parameter_file\": "); js(fp, params); |
| 720 | fprintf(fp, ",\n \"parameter_file_sha256\": \"%s\",\n \"parameter_file_validated_on_grid\": true,\n", phex); |
| 721 | fprintf(fp, " \"fit_run_path\": "); js(fp, p.fit_path); |
| 722 | fprintf(fp, ",\n \"fit_file_sha256\": \"%s\",\n \"fit_file_is_run_A\": %s,\n \"fit_sha_matches_run_A_SHA256SUMS_line\": %s,\n", p.fit_sha, b(fit_is_a), b(fit_sums_ok)); |
| 723 | fprintf(fp, " \"input_file\": "); js(fp, raw); |
| 724 | fprintf(fp, ",\n \"input_file_sha256\": \"%s\",\n \"input_sha_matches_SHA256SUMS\": true,\n", f.sha_hex); |
| 725 | fprintf(fp, " \"input_sha_note\": \"only the evaluated input is verified by this tool against its SHA256SUMS line (loading refuses otherwise); the fit file digest is as recorded in the parameter file\",\n"); |
| 726 | fprintf(fp, " \"marks_file_sha256\": \"%s\",\n", mk.sha); |
| 727 | fprintf(fp, " \"lines\": %zu,\n \"marks\": {\"pairs\": %zu, \"begins\": %zu, \"ends\": %zu, \"unclosed_begin_ran_to_eof\": %s, \"nested_begins\": %zu, \"stray_ends\": %zu},\n", |
| 728 | f.nlines, mk.n, mk.begins, mk.ends, b(mk.unclosed), mk.nested_begins, mk.stray_ends); |
| 729 | fprintf(fp, " \"missing_observations\": {\"leading_before_first_valid\": %zu, \"coasted\": %zu, \"bad_value_lines\": %zu, \"bad_t_lines\": %zu, \"bad_t_overflow_lines\": %zu},\n", |
| 730 | rp[0].leading_missing, rp[0].coasts, rp[0].bad_value, rp[0].bad_t, rp[0].bad_t_overflow); |
| 731 | fprintf(fp, " \"time_gaps\": {\"duplicate_t\": %zu, \"backward_t\": %zu, \"steps_with_horizon_gt_1\": %zu},\n", |
| 732 | rp[0].gap_zero, rp[0].gap_backward, rp[0].multi_horizon); |
| 733 | fprintf(fp, " \"readings\": {\"burn_in\": \"steps with L<%u counted from the prior line (L=0) are excluded\", \"quarters\": \"four equal spans of included samples by logical time\", \"ten_step_origins\": \"coasted origins skipped\"},\n", EST_BURN_IN); |
| 734 | fprintf(fp, " \"replay\": {\"complete\": %s, \"steps\": %zu, \"expected_steps\": %zu, \"chain_recorded_every_step\": %s, \"raw_file_unchanged\": %s,\n", |
| 735 | b(replay_ok), rp[0].nsteps, expect_steps, b(chain_ok), b(raw_preserved)); |
| 736 | fprintf(fp, " \"prefix_invariance\": {\"method\": \"first k lines physically written to a temp file and replayed from scratch\", \"ks\": \"k=100,500,1000\", \"runs\": %zu, \"pass\": %s}},\n", prefix_ran, b(prefix_ok)); |
| 737 | fprintf(fp, " \"streams\": {\"M0\": {\"file\": "); js(fp, spath[0]); |
| 738 | fprintf(fp, ", \"sha256\": \"%s\"}, \"M1\": {\"file\": ", shash[0]); js(fp, spath[1]); |
| 739 | fprintf(fp, ", \"sha256\": \"%s\"}},\n", shash[1]); |
| 740 | fprintf(fp, " \"models\": {\n"); |
| 741 | if (replay_ok) { emit_model(fp, 0, p.q[0], p.r[0], p.ll[0], NULL, &st[0], 0); emit_model(fp, 1, p.q[1], p.r[1], p.ll[1], NULL, &st[1], 1); } |
| 742 | fprintf(fp, " },\n \"selected_model\": %s%s%s,\n", sel >= 0 ? "\"M" : "null", sel >= 0 ? (sel ? "1" : "0") : "", sel >= 0 ? "\"" : ""); |
| 743 | fprintf(fp, " \"failure_class_to_be_recorded_by_a_human_on_FAIL\": null,\n"); |
| 744 | fprintf(fp, " \"ESTIMATION_REAL_SIGNAL\": \"%s\",\n \"ESTIMATION_CALIBRATION\": \"%s\"\n}\n", real_signal ? "PASS" : "FAIL", calib ? "PASS" : "FAIL"); |
| 745 | if (fclose(fp)) return 1; |
| 746 | char rh[65]; est_sha_file_hex(out, rh); |
| 747 | printf("ESTIMATION_REAL_SIGNAL=%s ESTIMATION_CALIBRATION=%s receipt_sha256=%s\n", real_signal ? "PASS" : "FAIL", calib ? "PASS" : "FAIL", rh); |
| 748 | est_replay_free(&rp[0]); est_replay_free(&rp[1]); est_file_free(&f); |
| 749 | return 0; |
| 750 | } |