interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / tools / estimation / est3c_common.c

1065 lines · 47046 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* EST-3c protocol v3 shared tool code. See est3c_common.h for the documented
18 * replay, tick, burn-in, E0 and statistic choices. */
19#include "est3c_common.h"
20
21#include <errno.h>
22#include <limits.h>
23#include <math.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/stat.h>
27
28#include "sha256.h"
29
30#define NS 1000000000ll
31
32static void msg(char *err, size_t cap, const char *fmt, const char *a)
33{
34 if (err && cap) snprintf(err, cap, fmt, a);
35}
36
37/* ------------------------------------------------------------------ fields */
38
39int c3_json_field(const char *s, size_t len, const char *key, const char **v, size_t *vl)
40{
41 size_t i = 0, kl = strlen(key);
42#define WS() while (i < len && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r')) i++
43 WS();
44 if (i >= len || s[i] != '{') return 1;
45 i++;
46 for (;;) {
47 WS();
48 if (i >= len || s[i] != '"') return 1;
49 size_t ks = ++i;
50 while (i < len && s[i] != '"') { if (s[i] == '\\') return 1; i++; }
51 if (i >= len) return 1;
52 size_t ke = i++;
53 WS();
54 if (i >= len || s[i] != ':') return 1;
55 i++;
56 WS();
57 if (i >= len) return 1;
58 size_t vs, ve;
59 if (s[i] == '"') {
60 /* a string value is skipped by looking only for its closing quote;
61 * its bytes are never converted unless this is the asked key */
62 vs = ++i;
63 while (i < len && s[i] != '"') { if (s[i] == '\\') i++; i++; }
64 if (i >= len) return 1;
65 ve = i++;
66 } else {
67 if (s[i] == '{' || s[i] == '[') return 1;
68 vs = i;
69 while (i < len && s[i] != ',' && s[i] != '}') i++;
70 ve = i;
71 while (ve > vs && s[ve - 1] == ' ') ve--;
72 }
73 if (ke - ks == kl && memcmp(s + ks, key, kl) == 0) { *v = s + vs; *vl = ve - vs; return 0; }
74 WS();
75 if (i < len && s[i] == ',') { i++; continue; }
76 return 1;
77 }
78#undef WS
79}
80
81/* zone 0 = first space-separated token of "thermal_mc". present = 0 when the
82 * key or the token is absent; value NaN when the token is not a number. */
83static void thermal0(const char *ln, size_t ll, int *present, double *value)
84{
85 const char *v; size_t vl;
86 *present = 0; *value = NAN;
87 if (c3_json_field(ln, ll, "thermal_mc", &v, &vl)) return;
88 size_t a = 0;
89 while (a < vl && v[a] == ' ') a++;
90 size_t b = a;
91 while (b < vl && v[b] != ' ') b++;
92 if (b == a) return;
93 *present = 1;
94 char tok[48];
95 if (b - a >= sizeof tok) return;
96 memcpy(tok, v + a, b - a); tok[b - a] = 0;
97 for (size_t i = 0; tok[i]; i++) {
98 char c = tok[i];
99 if (!((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E'
100 || c == 'i' || c == 'n' || c == 'f' || c == 'a' || c == 'I' || c == 'N' || c == 'F' || c == 'A')) return;
101 }
102 char *end; errno = 0;
103 double x = strtod(tok, &end);
104 if (*end != 0) return;
105 *value = x; /* may be inf / nan: classified NONFINITE by est_pred */
106}
107
108/* ------------------------------------------------------------------- ticks */
109
110static int push_tick(c3_ticks *tk, const c3_tick *t)
111{
112 if (tk->n == tk->cap) {
113 size_t nc = tk->cap ? tk->cap * 2 : 4096;
114 c3_tick *nt = realloc(tk->t, nc * sizeof *nt);
115 if (!nt) return 1;
116 tk->t = nt; tk->cap = nc;
117 }
118 tk->t[tk->n++] = *t;
119 return 0;
120}
121
122int c3_ticks_build(const est_file *f, c3_ticks *tk, char *err, size_t cap)
123{
124 memset(tk, 0, sizeof *tk);
125 tk->lines = f->nlines;
126 int64_t prev = 0; int prev_ok = 0;
127 static const char tag[] = "est3c.inserted-missing";
128 for (size_t li = 0; li < f->nlines; li++) {
129 const char *ln = (const char *)f->data + f->off[li];
130 size_t ll = f->llen[li];
131 int64_t w = 0;
132 int t_ok = est_parse_t(ln, ll, &w) == 0;
133 if (!t_ok) tk->bad_t++;
134 uint64_t h = 1;
135 if (t_ok && prev_ok) {
136 int64_t gap = w - prev;
137 if (gap == 0) tk->gap_zero++;
138 else if (gap < 0) tk->gap_backward++;
139 else {
140 int64_t hr = (gap + NS / 2) / NS;
141 if (hr < 1) hr = 1;
142 h = (uint64_t)hr;
143 }
144 }
145 if (t_ok) { prev = w; prev_ok = 1; }
146 else if (prev_ok) prev += NS; /* unparsable t: one nominal step */
147 if (h > 1) {
148 tk->lines_multi++;
149 uint64_t ins = h - 1;
150 if (ins > C3_MAX_INSERT) { ins = C3_MAX_INSERT; tk->gaps_capped++; }
151 for (uint64_t j = 0; j < ins; j++) {
152 c3_tick t; memset(&t, 0, sizeof t);
153 t.line = li; t.inserted = 1; t.value = NAN;
154 sha256_ctx c; sha256_init(&c);
155 sha256_update(&c, (const uint8_t *)tag, sizeof tag); /* includes the 0x00 */
156 sha256_update(&c, (const uint8_t *)ln, ll);
157 uint8_t le[8]; for (int k = 0; k < 8; k++) le[k] = (uint8_t)(j >> (8 * k));
158 sha256_update(&c, le, 8);
159 sha256_final(&c, t.ev.b);
160 if (push_tick(tk, &t)) { msg(err, cap, "out of memory%s", ""); return 1; }
161 tk->inserted++;
162 }
163 }
164 c3_tick t; memset(&t, 0, sizeof t);
165 t.line = li; t.t_ok = t_ok; t.wall_ns = t_ok ? w : 0;
166 thermal0(ln, ll, &t.present, &t.value);
167 if (!t.present) tk->absent_value++;
168 else if (!isfinite(t.value)) tk->unparsable_value++;
169 if (!t_ok) { t.present = 0; } /* v1: a line without a usable t is missing */
170 sha256_hash((const uint8_t *)ln, ll, t.ev.b);
171 if (push_tick(tk, &t)) { msg(err, cap, "out of memory%s", ""); return 1; }
172 }
173 return 0;
174}
175
176void c3_ticks_free(c3_ticks *tk) { free(tk->t); memset(tk, 0, sizeof *tk); }
177
178/* ------------------------------------------------------------------- marks */
179
180static int parse_name(const char *s, size_t n, int *level, int *index)
181{
182 *level = -1; *index = -1;
183 if (n < 6 || memcmp(s, "load-L", 6) != 0) return 1;
184 size_t i = 6; long lv = 0, ix = 0; size_t d = 0;
185 while (i < n && s[i] >= '0' && s[i] <= '9' && d < 6) { lv = lv * 10 + (s[i] - '0'); i++; d++; }
186 if (d == 0 || i >= n || s[i] != '-') return 1;
187 i++; d = 0;
188 while (i < n && s[i] >= '0' && s[i] <= '9' && d < 6) { ix = ix * 10 + (s[i] - '0'); i++; d++; }
189 if (d == 0 || (i < n && s[i] != ' ')) return 1;
190 *level = (int)lv; *index = (int)ix;
191 return 0;
192}
193
194int c3_marks_load(const char *path, int verify, c3_marks *mk, char *err, size_t cap)
195{
196 memset(mk, 0, sizeof *mk);
197 est_file f;
198 if (verify ? est_file_load(path, &f, err, cap) : est_file_load_raw(path, &f, err, cap)) return 1;
199 memcpy(mk->sha, f.sha_hex, 65);
200 int64_t open_t = 0; int is_open = 0, open_lv = -1, open_ix = -1;
201 for (size_t i = 0; i < f.nlines; i++) {
202 const char *ln = (const char *)f.data + f.off[i]; size_t ll = f.llen[i];
203 if (ll == 0) continue;
204 int64_t t; size_t used;
205 if (est_parse_time_prefix(ln, ll, &t, &used)) { mk->bad_lines++; continue; }
206 const char *rest = ln + used; size_t rl = ll - used;
207 int is_b = rl >= 7 && memcmp(rest, " begin ", 7) == 0;
208 int is_e = !is_b && rl >= 5 && memcmp(rest, " end ", 5) == 0;
209 if (!is_b && !is_e) { mk->bad_lines++; continue; }
210 int lv, ix;
211 size_t sk = is_b ? 7 : 5;
212 parse_name(rest + sk, rl - sk, &lv, &ix);
213 if (mk->nev < C3_MAX_EV) {
214 mk->ev_t[mk->nev] = t; mk->ev_end[mk->nev] = is_e; mk->ev_level[mk->nev] = lv; mk->ev_index[mk->nev] = ix;
215 mk->nev++;
216 } else mk->bad_lines++;
217 if (is_b) {
218 mk->begins++;
219 if (is_open) {
220 mk->nested_begins++;
221 if (mk->n >= C3_MAX_MARKS) { msg(err, cap, "too many marks pairs%s", ""); est_file_free(&f); return 1; }
222 mk->b[mk->n] = open_t; mk->e[mk->n] = t; mk->level[mk->n] = open_lv; mk->index[mk->n] = open_ix; mk->n++;
223 }
224 open_t = t; is_open = 1; open_lv = lv; open_ix = ix;
225 } else {
226 mk->ends++;
227 if (!is_open) { mk->stray_ends++; continue; }
228 if (mk->n >= C3_MAX_MARKS) { msg(err, cap, "too many marks pairs%s", ""); est_file_free(&f); return 1; }
229 mk->b[mk->n] = open_t; mk->e[mk->n] = t; mk->level[mk->n] = open_lv; mk->index[mk->n] = open_ix; mk->n++;
230 is_open = 0;
231 }
232 }
233 if (is_open) {
234 if (mk->n >= C3_MAX_MARKS) { msg(err, cap, "too many marks pairs%s", ""); est_file_free(&f); return 1; }
235 mk->b[mk->n] = open_t; mk->e[mk->n] = INT64_MAX; mk->level[mk->n] = open_lv; mk->index[mk->n] = open_ix; mk->n++;
236 mk->unclosed = 1;
237 }
238 est_file_free(&f);
239 return 0;
240}
241
242int c3_in_trial(const c3_marks *mk, int64_t t)
243{
244 if (!mk) return 0;
245 for (size_t i = 0; i < mk->n; i++) if (t >= mk->b[i] && t <= mk->e[i]) return 1;
246 return 0;
247}
248
249/* ------------------------------------------------------------------ models */
250
251const char *c3_name(int id)
252{
253 static const char *n[6] = { "E0", "F1", "F2", "F3", "F4", "F5" };
254 return (id >= 0 && id <= 5) ? n[id] : "??";
255}
256
257void c3_assumption_base(est_assumption *a, est_family fam)
258{
259 memset(a, 0, sizeof *a);
260 a->family = fam; a->unit = EST_UNIT_MILLI_CELSIUS;
261 a->quantum = C3_QUANTUM; a->lo = C3_LO; a->hi = C3_HI;
262}
263
264void c3_make_f1(c3_model *m, double q, double r)
265{
266 memset(m, 0, sizeof *m); m->id = 1;
267 c3_assumption_base(&m->a, EST_FAM_GAUSS_KF);
268 m->a.nparam = 3; m->a.param[0] = q; m->a.param[1] = r; m->a.param[2] = r; /* p0 = r */
269}
270void c3_make_f2(c3_model *m, double q, double r, double c)
271{
272 memset(m, 0, sizeof *m); m->id = 2;
273 c3_assumption_base(&m->a, EST_FAM_HUBER_KF);
274 m->a.nparam = 4; m->a.param[0] = q; m->a.param[1] = r; m->a.param[2] = r; m->a.param[3] = c;
275}
276void c3_make_f3(c3_model *m, double nu, double s)
277{
278 memset(m, 0, sizeof *m); m->id = 3;
279 c3_assumption_base(&m->a, EST_FAM_STUDENT_T);
280 m->a.nparam = 2; m->a.param[0] = nu; m->a.param[1] = s;
281}
282int c3_make_f4(c3_model *m, const est_mix *mx)
283{
284 memset(m, 0, sizeof *m); m->id = 4;
285 c3_assumption_base(&m->a, EST_FAM_SCALE_MIX);
286 if (!mx || mx->k < 1 || mx->k > 3) return 1;
287 m->a.nparam = 7; m->a.param[0] = (double)mx->k;
288 for (uint32_t j = 0; j < mx->k; j++) { m->a.param[1 + j] = mx->w[j]; m->a.param[4 + j] = mx->v[j]; }
289 return 0;
290}
291void c3_make_f5(c3_model *m, double lambda, double nu, double c, double floor_var)
292{
293 memset(m, 0, sizeof *m); m->id = 5;
294 c3_assumption_base(&m->a, EST_FAM_ADAPTIVE_T);
295 m->a.nparam = 5; m->a.param[0] = lambda; m->a.param[1] = nu; m->a.param[2] = c;
296 m->a.param[3] = floor_var; m->a.param[4] = sqrt(floor_var); /* s0^2 = floor */
297}
298void c3_make_e0(c3_model *m, const uint32_t *counts, uint64_t n)
299{
300 memset(m, 0, sizeof *m); m->id = 0;
301 c3_assumption_base(&m->a, EST_FAM_STUDENT_T); /* used only to classify observations */
302 /* one pseudo-observation spread uniformly (1/EST_PRED_N per bin): no zero bin,
303 * without the ~25 % uniform mass that add-one over 801 bins would add */
304 double den = (double)n + 1.0;
305 for (int i = 0; i < EST_PRED_N; i++) m->e0_one[i] = ((double)counts[i] + 1.0 / (double)EST_PRED_N) / den;
306}
307
308static est_obs_class classify(const c3_tick *t, est_pobs *ob)
309{
310 est_assumption a; c3_assumption_base(&a, EST_FAM_STUDENT_T);
311 a.nparam = 2; a.param[0] = 5; a.param[1] = 100;
312 if (est_pobs_classify(&a, t->value, t->present, &t->ev, ob) != EST_OK) return EST_OBS_CLASSES_;
313 return ob->cls;
314}
315
316size_t c3_h1_changes(const c3_ticks *tk, double *e, size_t cap)
317{
318 size_t n = 0; long first = -1; int prev_ok = 0; double prev_v = 0;
319 for (size_t t = 0; t < tk->n; t++) {
320 est_pobs ob;
321 int ok = classify(&tk->t[t], &ob) == EST_OBS_OK;
322 if (ok && first < 0) first = (long)t;
323 if (ok && prev_ok && first >= 0 && (long)t - first >= (long)C3_BURN_IN && n < cap)
324 e[n++] = tk->t[t].value - prev_v;
325 prev_ok = ok; if (ok) prev_v = tk->t[t].value;
326 }
327 return n;
328}
329
330void c3_e0_counts(const double *e, size_t n, uint32_t *counts)
331{
332 memset(counts, 0, EST_PRED_N * sizeof *counts);
333 for (size_t i = 0; i < n; i++) {
334 long k = lround(e[i] / C3_QUANTUM);
335 if (k < -EST_PRED_K) k = -EST_PRED_K;
336 if (k > EST_PRED_K) k = EST_PRED_K;
337 counts[k + EST_PRED_K]++;
338 }
339}
340
341/* -------------------------------------------------------------- statistics */
342
343const char *c3_stat_name(int s)
344{
345 static char buf[C3_ST_COUNT][24];
346 static int init;
347 if (!init) {
348 for (int i = 0; i < C3_ST_COUNT; i++) snprintf(buf[i], sizeof buf[i], "stat%d", i);
349 snprintf(buf[C3_ST_COV50], 24, "coverage50");
350 snprintf(buf[C3_ST_COV80], 24, "coverage80");
351 snprintf(buf[C3_ST_COV95], 24, "coverage95");
352 for (int j = 0; j < 10; j++) snprintf(buf[C3_ST_PIT0 + j], 24, "pit_bin%d", j);
353 snprintf(buf[C3_ST_BIAS], 24, "bias_mean_z");
354 snprintf(buf[C3_ST_LAG1], 24, "lag1_z");
355 for (int q = 0; q < 4; q++) snprintf(buf[C3_ST_Q0 + q], 24, "quarter%d_coverage95", q + 1);
356 snprintf(buf[C3_ST_REG_IDLE], 24, "regime_idle_cov95");
357 snprintf(buf[C3_ST_REG_TRIAL], 24, "regime_trial_cov95");
358 snprintf(buf[C3_ST_TEN], 24, "ten_step_coverage95");
359 snprintf(buf[C3_ST_N], 24, "n_scored");
360 init = 1;
361 }
362 return (s >= 0 && s < C3_ST_COUNT) ? buf[s] : "none";
363}
364
365static void e0_pmf(const c3_model *m, uint32_t H, double *out, double *cache10, int *have10)
366{
367 if (H == 1) { memcpy(out, m->e0_one, sizeof m->e0_one); return; }
368 if (H == C3_TEN && cache10 && *have10) { memcpy(out, cache10, EST_PRED_N * sizeof *out); return; }
369 est_pmf_conv_pow(m->e0_one, H, out);
370 est_pmf_floor(out);
371 if (H == C3_TEN && cache10) { memcpy(cache10, out, EST_PRED_N * sizeof *out); *have10 = 1; }
372}
373
374static int cmp_d(const void *a, const void *b)
375{
376 double x = *(const double *)a, y = *(const double *)b;
377 return (x > y) - (x < y);
378}
379
380static int serr(c3_stats *st, const char *what, size_t t, est_status s)
381{
382 st->error = 1;
383 snprintf(st->errmsg, sizeof st->errmsg, "%s at tick %zu: status %d", what, t, (int)s);
384 return 1;
385}
386
387int c3_score(const c3_ticks *tk, const c3_marks *mk, const c3_model *m, int full, c3_stats *st)
388{
389 memset(st, 0, sizeof *st);
390 est_calib_init(&st->c);
391 st->first_fail = -1;
392 est_dpred *ring = NULL, *p = NULL;
393 int ring_ok[C3_TEN];
394 double *cache10 = NULL; int have10 = 0;
395 memset(ring_ok, 0, sizeof ring_ok);
396 p = malloc(sizeof *p);
397 if (!p) return serr(st, "out of memory", 0, EST_OK);
398 if (full) {
399 st->cap = tk->n ? tk->n : 1;
400 st->cov95_step = malloc(st->cap * sizeof(double));
401 st->width_step = malloc(st->cap * sizeof(double));
402 st->regime_step = malloc(st->cap);
403 ring = malloc(C3_TEN * sizeof *ring);
404 cache10 = malloc(EST_PRED_N * sizeof(double));
405 if (!st->cov95_step || !st->width_step || !st->regime_step || !ring || !cache10) {
406 free(ring); free(cache10); free(p); return serr(st, "out of memory", 0, EST_OK);
407 }
408 }
409 est_bstate *b = malloc(sizeof *b);
410 if (!b) { free(ring); free(cache10); free(p); return serr(st, "out of memory", 0, EST_OK); }
411 est_status s;
412 if (m->id) {
413 s = est_pred_init(&m->a, b);
414 if (s != EST_OK) { free(b); free(ring); free(cache10); free(p); return serr(st, "init", 0, s); }
415 }
416 int e_has = 0; double e_anchor = 0; uint32_t e_gap = 0;
417 long first = -1;
418 int rc = 0;
419 for (size_t t = 0; t < tk->n && !rc; t++) {
420 const c3_tick *tc = &tk->t[t];
421 est_pobs ob;
422 est_obs_class cls = classify(tc, &ob);
423 if (cls == EST_OBS_CLASSES_) { rc = serr(st, "classify", t, EST_ERR_KIND); break; }
424 int ok = cls == EST_OBS_OK;
425 if (ok && first < 0) first = (long)t;
426 int scored_region = first >= 0 && (long)t - first >= (long)C3_BURN_IN;
427 est_pinnov iv;
428 /* ten-step target */
429 if (full && ring_ok[t % C3_TEN]) {
430 ring_ok[t % C3_TEN] = 0;
431 if (ok) {
432 s = est_dpred_score(&ring[t % C3_TEN], &ob, &iv);
433 if (s != EST_OK) { rc = serr(st, "ten-step score", t, s); break; }
434 if (iv.valid) { st->ten_cov += est_frac_cover(iv.F_lo, iv.F_hi, 0.95); st->ten_n++; }
435 }
436 }
437 /* one-step */
438 if (ok && scored_region) {
439 int have_p = 0;
440 if (m->id) {
441 s = est_pred_predict(&m->a, b, 1, p);
442 if (s == EST_ERR_TIME) st->unscorable++;
443 else if (s != EST_OK) { rc = serr(st, "predict", t, s); break; }
444 else {
445 s = est_pred_innov(b, p, &ob, &iv);
446 if (s != EST_OK) { rc = serr(st, "innov", t, s); break; }
447 have_p = 1;
448 }
449 } else if (e_has) {
450 uint32_t H = e_gap + 1;
451 if (H > EST_PRED_MAX_H) st->unscorable++;
452 else {
453 memset(p, 0, sizeof *p);
454 p->horizon = H; p->anchor = e_anchor; p->quantum = C3_QUANTUM;
455 p->family = (est_family)0; /* E0 is tool-built, not an est_pred family */
456 e0_pmf(m, H, p->pmf, NULL, NULL);
457 s = est_dpred_score(p, &ob, &iv);
458 if (s != EST_OK) { rc = serr(st, "E0 score", t, s); break; }
459 have_p = 1;
460 }
461 }
462 if (have_p && iv.valid) {
463 st->logsum += iv.logp; st->n++;
464 if (full) {
465 s = est_calib_add(&st->c, p, &iv);
466 if (s != EST_OK) { rc = serr(st, "calib", t, s); break; }
467 size_t k = st->n - 1;
468 st->cov95_step[k] = est_frac_cover(iv.F_lo, iv.F_hi, 0.95);
469 double w = NAN;
470 s = est_dpred_width80(p, &w);
471 if (s != EST_OK) { rc = serr(st, "width", t, s); break; }
472 st->width_step[k] = w;
473 st->regime_step[k] = (unsigned char)c3_in_trial(mk, tc->wall_ns);
474 }
475 }
476 }
477 /* update */
478 if (m->id) {
479 s = est_pred_update(&m->a, b, &ob);
480 if (s != EST_OK) { rc = serr(st, "update", t, s); break; }
481 } else {
482 if (ok) { e_has = 1; e_anchor = tc->value; e_gap = 0; }
483 else if (e_has) e_gap++;
484 }
485 /* ten-step origin */
486 if (full && ok && scored_region) {
487 est_dpred *q = &ring[t % C3_TEN];
488 if (m->id) {
489 s = est_pred_predict(&m->a, b, C3_TEN, q);
490 if (s == EST_OK) ring_ok[t % C3_TEN] = 1;
491 else if (s != EST_ERR_TIME) { rc = serr(st, "ten-step predict", t, s); break; }
492 } else {
493 memset(q, 0, sizeof *q);
494 q->horizon = C3_TEN; q->anchor = e_anchor; q->quantum = C3_QUANTUM; q->family = (est_family)0;
495 e0_pmf(m, C3_TEN, q->pmf, cache10, &have10);
496 ring_ok[t % C3_TEN] = 1;
497 }
498 }
499 }
500 free(b); free(ring); free(cache10); free(p);
501 if (rc) return rc;
502 st->logscore = st->n ? st->logsum / (double)st->n : -INFINITY;
503 if (full) c3_judge(st);
504 return 0;
505}
506
507static void band(c3_stats *st, int i, double v, double lo, double hi)
508{
509 st->value[i] = v; st->band_lo[i] = lo; st->band_hi[i] = hi; st->gated[i] = 1;
510 st->pass[i] = isfinite(v) && v >= lo && v <= hi;
511}
512
513void c3_judge(c3_stats *st)
514{
515 double n = (double)st->n;
516 double nn = st->n ? n : NAN;
517 band(st, C3_ST_COV50, st->c.cov[0] / nn, C3_COV50_LO, C3_COV50_HI);
518 band(st, C3_ST_COV80, st->c.cov[1] / nn, C3_COV80_LO, C3_COV80_HI);
519 band(st, C3_ST_COV95, st->c.cov[2] / nn, C3_COV95_LO, C3_COV95_HI);
520 for (int j = 0; j < 10; j++) band(st, C3_ST_PIT0 + j, st->c.pit[j] / nn, C3_PIT_LO, C3_PIT_HI);
521 band(st, C3_ST_BIAS, st->c.z_sum / nn, -C3_BIAS_MAX, C3_BIAS_MAX);
522 band(st, C3_ST_LAG1, st->n >= 2 ? est_calib_lag1(&st->c) : NAN, -C3_LAG1_MAX, C3_LAG1_MAX);
523 for (int q = 0; q < 4; q++) {
524 size_t lo = (size_t)q * st->n / 4, hi = (size_t)(q + 1) * st->n / 4;
525 double sum = 0;
526 for (size_t k = lo; k < hi; k++) sum += st->cov95_step[k];
527 st->sub_n[C3_ST_Q0 + q] = hi - lo;
528 band(st, C3_ST_Q0 + q, hi > lo ? sum / (double)(hi - lo) : NAN, C3_SUB95_LO, C3_SUB95_HI);
529 }
530 double rs[2] = { 0, 0 }; size_t rn[2] = { 0, 0 };
531 for (size_t k = 0; k < st->n; k++) { int g = st->regime_step[k] ? 1 : 0; rs[g] += st->cov95_step[k]; rn[g]++; }
532 for (int g = 0; g < 2; g++) {
533 int i = g ? C3_ST_REG_TRIAL : C3_ST_REG_IDLE;
534 st->sub_n[i] = rn[g];
535 band(st, i, rn[g] ? rs[g] / (double)rn[g] : NAN, C3_SUB95_LO, C3_SUB95_HI);
536 if (rn[g] < C3_REGIME_MIN) { st->gated[i] = 0; }
537 }
538 st->sub_n[C3_ST_TEN] = st->ten_n;
539 band(st, C3_ST_TEN, st->ten_n ? st->ten_cov / (double)st->ten_n : NAN, C3_SUB95_LO, C3_SUB95_HI);
540 band(st, C3_ST_N, n, (double)C3_MIN_N, INFINITY);
541 st->calibrated = 1; st->first_fail = -1;
542 for (int i = 0; i < C3_ST_COUNT; i++)
543 if (st->gated[i] && !st->pass[i]) { st->calibrated = 0; if (st->first_fail < 0) st->first_fail = i; }
544 st->width_mean = st->n ? st->c.width_sum / n : NAN;
545 st->width_median = NAN;
546 if (st->n) {
547 double *w = malloc(st->n * sizeof *w);
548 if (w) {
549 memcpy(w, st->width_step, st->n * sizeof *w);
550 qsort(w, st->n, sizeof *w, cmp_d);
551 st->width_median = (st->n % 2) ? w[st->n / 2] : 0.5 * (w[st->n / 2 - 1] + w[st->n / 2]);
552 free(w);
553 }
554 }
555}
556
557void c3_stats_free(c3_stats *st)
558{
559 free(st->cov95_step); free(st->width_step); free(st->regime_step);
560 st->cov95_step = NULL; st->width_step = NULL; st->regime_step = NULL;
561}
562
563/* ---------------------------------------------------------------- precheck */
564
565static int parse_cpu(const char *v, size_t vl, unsigned long long out[8])
566{
567 size_t i = 0;
568 for (int k = 0; k < 8; k++) {
569 while (i < vl && v[i] == ' ') i++;
570 if (i >= vl || v[i] < '0' || v[i] > '9') return 1;
571 unsigned long long x = 0; int d = 0;
572 while (i < vl && v[i] >= '0' && v[i] <= '9') {
573 if (d >= 19) return 1;
574 x = x * 10 + (unsigned long long)(v[i] - '0'); i++; d++;
575 }
576 out[k] = x;
577 }
578 while (i < vl && v[i] == ' ') i++;
579 return i != vl;
580}
581
582static double overlap(int64_t a0, int64_t a1, int64_t b0, int64_t b1)
583{
584 int64_t lo = a0 > b0 ? a0 : b0, hi = a1 < b1 ? a1 : b1;
585 return hi > lo ? (double)(hi - lo) : 0.0;
586}
587
588int c3_precheck(const char *dir, c3_pre *p, char *err, size_t cap)
589{
590 memset(p, 0, sizeof *p);
591 char path[1200];
592 snprintf(path, sizeof path, "%s/machine-state.ndjson", dir);
593 est_file f;
594 if (est_file_load(path, &f, err, cap)) return 1;
595 memcpy(p->raw_sha, f.sha_hex, 65);
596 static c3_marks mk;
597 snprintf(path, sizeof path, "%s/machine-state-marks.txt", dir);
598 char e2[256] = "";
599 int have_marks = c3_marks_load(path, 1, &mk, e2, sizeof e2) == 0;
600 if (have_marks) memcpy(p->marks_sha, mk.sha, 65); else snprintf(p->marks_sha, 65, "unavailable");
601
602 /* schedule */
603 int sidx[C3_MAX_MARKS], slv[C3_MAX_MARKS]; size_t ns = 0; int sched_bad = 0;
604 snprintf(path, sizeof path, "%s/schedule.txt", dir);
605 est_file sf;
606 char e3[256] = "";
607 snprintf(p->sched_sha, 65, "unavailable");
608 if (est_file_load(path, &sf, e3, sizeof e3) == 0) {
609 p->have_schedule = 1;
610 memcpy(p->sched_sha, sf.sha_hex, 65);
611 for (size_t i = 0; i < sf.nlines; i++) {
612 const char *ln = (const char *)sf.data + sf.off[i]; size_t ll = sf.llen[i];
613 if (ll < 9 || memcmp(ln, "schedule ", 9) != 0) continue;
614 char buf[128]; if (ll >= sizeof buf) { sched_bad = 1; continue; }
615 memcpy(buf, ln, ll); buf[ll] = 0;
616 int a, l; long s; char tail;
617 if (sscanf(buf, "schedule %d %d %ld%c", &a, &l, &s, &tail) != 3 || a < 0 || l < 0 || s <= 0) { sched_bad = 1; continue; }
618 if (ns >= C3_MAX_MARKS) { sched_bad = 1; continue; }
619 sidx[ns] = a; slv[ns] = l; ns++;
620 }
621 est_file_free(&sf);
622 p->sched_segments = ns;
623 for (size_t i = 0; i < ns; i++) if (slv[i] > 0) p->sched_trials++;
624 if (ns == 0) sched_bad = 1;
625 }
626
627 /* marks pair rule: the begin/end lines are exactly begin(i), end(i) for each
628 * scheduled trial i in schedule order, names "load-L<level>-<i>", times non-decreasing */
629 p->marks_ok = 1;
630 if (!p->have_schedule) { p->marks_ok = 0; snprintf(p->marks_why, sizeof p->marks_why, "schedule.txt missing or not in SHA256SUMS"); }
631 else if (sched_bad) { p->marks_ok = 0; snprintf(p->marks_why, sizeof p->marks_why, "schedule.txt malformed or empty"); }
632 else if (!have_marks) { p->marks_ok = 0; snprintf(p->marks_why, sizeof p->marks_why, "marks file unreadable or not in SHA256SUMS"); }
633 else if (mk.bad_lines) { p->marks_ok = 0; snprintf(p->marks_why, sizeof p->marks_why, "%zu marks lines are not begin/end lines", mk.bad_lines); }
634 else if (mk.nev != 2 * p->sched_trials) {
635 p->marks_ok = 0;
636 snprintf(p->marks_why, sizeof p->marks_why, "%zu begin/end lines for %zu scheduled trials", mk.nev, p->sched_trials);
637 } else {
638 size_t e = 0;
639 for (size_t i = 0; i < ns && p->marks_ok; i++) {
640 if (slv[i] <= 0) continue;
641 for (int k = 0; k < 2; k++, e++) {
642 if (mk.ev_end[e] != k || mk.ev_index[e] != sidx[i] || mk.ev_level[e] != slv[i]
643 || (e > 0 && mk.ev_t[e] < mk.ev_t[e - 1])) {
644 p->marks_ok = 0;
645 snprintf(p->marks_why, sizeof p->marks_why, "marks line %zu is not the %s of scheduled trial %d (level %d)",
646 e + 1, k ? "end" : "begin", sidx[i], slv[i]);
647 break;
648 }
649 }
650 }
651 }
652 if (p->marks_ok) snprintf(p->marks_why, sizeof p->marks_why, "one begin/end pair per scheduled trial");
653
654 /* times, gaps, loadavg, foreign load: only "t", "loadavg" and "cpu" are read */
655 p->lines = f.nlines;
656 int64_t pt = 0; int pt_ok = 0; int pc_ok = 0; unsigned long long pc[8] = { 0 };
657 double fsum = 0, lsum = 0;
658 for (size_t li = 0; li < f.nlines; li++) {
659 const char *ln = (const char *)f.data + f.off[li]; size_t ll = f.llen[li];
660 int64_t t = 0;
661 int t_ok = est_parse_t(ln, ll, &t) == 0;
662 if (!t_ok) p->bad_t++;
663 const char *v; size_t vl;
664 if (c3_json_field(ln, ll, "loadavg", &v, &vl) == 0) {
665 char buf[32]; size_t n = 0;
666 while (n < vl && v[n] != ' ' && n < sizeof buf - 1) { buf[n] = v[n]; n++; }
667 buf[n] = 0; char *end; double x = strtod(buf, &end);
668 if (n && *end == 0 && isfinite(x)) { lsum += x; p->loadavg_n++; }
669 }
670 unsigned long long c[8];
671 int c_ok = c3_json_field(ln, ll, "cpu", &v, &vl) == 0 && parse_cpu(v, vl, c) == 0;
672 if (li > 0) {
673 if (t_ok && pt_ok) {
674 p->gaps++;
675 if (t - pt > 1500000000ll) p->gaps_big++;
676 }
677 int measured = 0;
678 if (t_ok && pt_ok && c_ok && pc_ok && t > pt) {
679 unsigned long long d[8]; int mono = 1; double tot = 0;
680 for (int k = 0; k < 8; k++) { if (c[k] < pc[k]) mono = 0; d[k] = c[k] - pc[k]; tot += (double)d[k]; }
681 if (mono && tot > 0) {
682 double idle = (double)d[3] + (double)d[4];
683 double busy = C3_NCORES * (tot - idle) / tot;
684 double sched = 0;
685 if (have_marks)
686 for (size_t i = 0; i < mk.n; i++)
687 if (mk.level[i] > 0) sched += overlap(pt, t, mk.b[i], mk.e[i]) * (double)mk.level[i];
688 sched /= (double)(t - pt);
689 double fr = busy - sched;
690 fsum += fr; p->foreign_n++;
691 if (fr > 3.0) p->foreign_over3++;
692 measured = 1;
693 }
694 }
695 if (!measured) p->foreign_unmeasured++;
696 }
697 if (t_ok) { pt = t; pt_ok = 1; } else pt_ok = 0;
698 if (c_ok) { memcpy(pc, c, sizeof pc); pc_ok = 1; } else pc_ok = 0;
699 }
700 est_file_free(&f);
701 p->gap_big_frac = p->gaps ? (double)p->gaps_big / (double)p->gaps : 1.0;
702 p->foreign_mean = p->foreign_n ? fsum / (double)p->foreign_n : NAN;
703 p->foreign_over3_frac = p->foreign_n ? (double)p->foreign_over3 / (double)p->foreign_n : NAN;
704 p->loadavg1_mean = p->loadavg_n ? lsum / (double)p->loadavg_n : NAN;
705
706 p->ok_lines = p->lines >= C3_MIN_LINES;
707 p->ok_gaps = p->gaps > 0 && p->gap_big_frac <= 0.02;
708 p->ok_marks = p->marks_ok;
709 size_t pairs = p->lines ? p->lines - 1 : 0;
710 p->ok_foreign_measured = p->foreign_n > 0 && (double)p->foreign_unmeasured <= 0.01 * (double)pairs;
711 p->ok_foreign_mean = p->foreign_n > 0 && p->foreign_mean <= 1.5;
712 p->ok_foreign_tail = p->foreign_n > 0 && p->foreign_over3_frac <= 0.10;
713 p->valid = p->ok_lines && p->ok_gaps && p->ok_marks && p->ok_foreign_measured && p->ok_foreign_mean && p->ok_foreign_tail;
714 p->why[0] = 0;
715 size_t w = 0;
716#define WHY(c, s) do { if (!(c) && w < sizeof p->why) w += (size_t)snprintf(p->why + w, sizeof p->why - w, "%s%s", w ? "; " : "", s); } while (0)
717 WHY(p->ok_lines, "fewer than 2030 lines");
718 WHY(p->ok_gaps, "more than 2 % of gaps above 1.5 s");
719 WHY(p->ok_marks, "marks do not hold exactly one begin/end pair per scheduled trial");
720 WHY(p->ok_foreign_measured, "foreign load not measurable on more than 1 % of samples");
721 WHY(p->ok_foreign_mean || !p->foreign_n, "mean foreign busy cores above 1.5");
722 WHY(p->ok_foreign_tail || !p->foreign_n, "more than 10 % of samples with foreign busy cores above 3.0");
723#undef WHY
724 if (p->valid) snprintf(p->why, sizeof p->why, "all section 7 rules hold");
725 return 0;
726}
727
728/* ------------------------------------------------------------ params read */
729
730static int is_hex64(const char *s)
731{
732 if (strlen(s) != 64) return 0;
733 for (int i = 0; i < 64; i++) if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0;
734 return 1;
735}
736
737int c3_params_read(const char *path, c3_params *p, char *err, size_t cap)
738{
739 /* Every parsed key may appear once; family and screen_result once per
740 * family id, e0_count once per k. Unparsed record lines (rule, screen,
741 * ticks, marks, ...) are not checked. */
742 static const char *const single[] = { "est3c_params", "protocol_doc_sha256", "tool_commit", "tool_dirty", "synthetic_test",
743 "fit_raw_path", "fit_raw_sha256", "fit_marks_path", "fit_marks_sha256", "fit_lines",
744 "phase_a", "selected", "e0_changes", "assumption" };
745 enum { NSINGLE = (int)(sizeof single / sizeof single[0]) };
746 unsigned char seen[NSINGLE], seen_fam[6], seen_scr[6], seen_k[EST_PRED_N];
747 memset(seen, 0, sizeof seen); memset(seen_fam, 0, sizeof seen_fam); memset(seen_scr, 0, sizeof seen_scr); memset(seen_k, 0, sizeof seen_k);
748 memset(p, 0, sizeof *p);
749 FILE *fp = fopen(path, "r");
750 if (!fp) { msg(err, cap, "cannot open %s", path); return 1; }
751 char line[4096];
752 int have_magic = 0, have_phase = 0, have_sel = 0, have_e0n = 0;
753 p->tool_dirty = -1; p->synthetic = -1;
754 uint64_t e0sum = 0;
755 while (fgets(line, sizeof line, fp)) {
756 size_t l = strlen(line);
757 while (l && (line[l - 1] == '\n' || line[l - 1] == '\r')) line[--l] = 0;
758 char k[64], v[2048];
759 if (sscanf(line, "%63s %2047s", k, v) < 1) continue;
760 for (int i = 0; i < NSINGLE; i++) if (!strcmp(k, single[i])) { if (seen[i]++) goto dup; break; }
761 if (!strcmp(k, "est3c_params")) have_magic = 1;
762 else if (!strcmp(k, "protocol_doc_sha256")) { if (strlen(v) >= sizeof p->protocol_sha) goto bad; memcpy(p->protocol_sha, v, strlen(v) + 1); }
763 else if (!strcmp(k, "tool_commit")) { if (strlen(v) >= sizeof p->tool_commit) goto bad; memcpy(p->tool_commit, v, strlen(v) + 1); }
764 else if (!strcmp(k, "tool_dirty")) p->tool_dirty = atoi(v);
765 else if (!strcmp(k, "synthetic_test")) p->synthetic = atoi(v);
766 else if (!strcmp(k, "fit_raw_path")) { if (strlen(v) >= sizeof p->fit_raw_path) goto bad; memcpy(p->fit_raw_path, v, strlen(v) + 1); }
767 else if (!strcmp(k, "fit_raw_sha256")) { if (strlen(v) >= sizeof p->fit_raw_sha) goto bad; memcpy(p->fit_raw_sha, v, strlen(v) + 1); }
768 else if (!strcmp(k, "fit_marks_path")) { if (strlen(v) >= sizeof p->fit_marks_path) goto bad; memcpy(p->fit_marks_path, v, strlen(v) + 1); }
769 else if (!strcmp(k, "fit_marks_sha256")) { if (strlen(v) >= sizeof p->fit_marks_sha) goto bad; memcpy(p->fit_marks_sha, v, strlen(v) + 1); }
770 else if (!strcmp(k, "fit_lines")) p->fit_lines = (size_t)strtoull(v, NULL, 10);
771 else if (!strcmp(k, "phase_a")) { have_phase = 1; p->phase_a_pass = !strcmp(v, "PASS"); if (strcmp(v, "PASS") && strcmp(v, "PHASE_A_FAIL")) goto bad; }
772 else if (!strcmp(k, "selected")) {
773 have_sel = 1;
774 if (!strcmp(v, "none")) p->selected = 0;
775 else if (v[0] == 'F' && v[1] >= '1' && v[1] <= '5' && v[2] == 0) p->selected = v[1] - '0';
776 else goto bad;
777 } else if (!strcmp(k, "e0_changes")) { have_e0n = 1; p->e0_n = strtoull(v, NULL, 10); }
778 else if (!strcmp(k, "e0_count")) {
779 long kk; unsigned long cc; char tail;
780 if (sscanf(line, "e0_count %ld %lu%c", &kk, &cc, &tail) != 2 || kk < -EST_PRED_K || kk > EST_PRED_K) goto bad;
781 if (seen_k[kk + EST_PRED_K]++) goto dup;
782 p->e0_count[kk + EST_PRED_K] = (uint32_t)cc; e0sum += cc;
783 } else if (!strcmp(k, "family")) {
784 /* family F<i> available <0|1> nparam <n> param <8 values> logscore <v> */
785 char fn[8]; int av; unsigned np; double pr[8], ls;
786 int got = sscanf(line, "family %7s available %d nparam %u param %lg %lg %lg %lg %lg %lg %lg %lg logscore %lg",
787 fn, &av, &np, &pr[0], &pr[1], &pr[2], &pr[3], &pr[4], &pr[5], &pr[6], &pr[7], &ls);
788 if (got != 12 || fn[0] != 'F' || fn[1] < '1' || fn[1] > '5' || fn[2] || np > EST_PRED_NPARAM) goto bad;
789 int id = fn[1] - '0';
790 if (seen_fam[id]++) goto dup;
791 static const est_family fams[6] = { 0, EST_FAM_GAUSS_KF, EST_FAM_HUBER_KF, EST_FAM_STUDENT_T, EST_FAM_SCALE_MIX, EST_FAM_ADAPTIVE_T };
792 c3_assumption_base(&p->fam[id], fams[id]);
793 p->fam[id].nparam = np;
794 for (int j = 0; j < 8; j++) p->fam[id].param[j] = pr[j];
795 p->have[id] = av; p->logscore[id] = ls;
796 } else if (!strcmp(k, "screen_result")) {
797 char fn[8]; int ps;
798 if (sscanf(line, "screen_result %7s pass %d", fn, &ps) == 2 && fn[0] == 'F' && fn[1] >= '1' && fn[1] <= '5' && !fn[2]) {
799 if (seen_scr[fn[1] - '0']++) goto dup;
800 p->screen_pass[fn[1] - '0'] = ps;
801 }
802 } else if (!strcmp(k, "assumption")) {
803 double q, lo, hi;
804 if (sscanf(line, "assumption quantum %lg lo %lg hi %lg", &q, &lo, &hi) != 3 || q != C3_QUANTUM || lo != C3_LO || hi != C3_HI) goto bad;
805 }
806 }
807 fclose(fp);
808 if (!have_magic || !have_phase || !have_sel || !have_e0n || e0sum != p->e0_n || !is_hex64(p->fit_raw_sha)
809 || p->tool_dirty < 0 || p->synthetic < 0) {
810 msg(err, cap, "%s: incomplete or inconsistent parameter file", path);
811 return 1;
812 }
813 if (p->phase_a_pass && (p->selected < 1 || !p->have[p->selected] || !p->have[1])) {
814 msg(err, cap, "%s: PASS without an available selected family and F1", path);
815 return 1;
816 }
817 return 0;
818bad:
819 fclose(fp);
820 msg(err, cap, "%s: malformed line in parameter file", path);
821 return 1;
822dup:
823 fclose(fp);
824 msg(err, cap, "%s: duplicate key in parameter file", path);
825 return 1;
826}
827
828int c3_model_from_params(const c3_params *p, int id, c3_model *m)
829{
830 memset(m, 0, sizeof *m);
831 if (id == 0) { c3_make_e0(m, p->e0_count, p->e0_n); return 0; }
832 if (id < 1 || id > 5 || !p->have[id]) return 1;
833 m->id = id; m->a = p->fam[id];
834 return est_assumption_check(&m->a) != EST_OK;
835}
836
837/* ------------------------------------------------------------------- misc */
838
839int c3_path_is_heldout(const char *path)
840{
841 char rp[PATH_MAX];
842 if (strstr(path, C3_HELDOUT_TAG)) return 1;
843 if (realpath(path, rp) && strstr(rp, C3_HELDOUT_TAG)) return 1;
844 return 0;
845}
846
847int c3_write_sums(const char *dir, const char *const *names, size_t n)
848{
849 char p[1200];
850 snprintf(p, sizeof p, "%s/SHA256SUMS", dir);
851 FILE *fp = fopen(p, "w");
852 if (!fp) return 1;
853 for (size_t i = 0; i < n; i++) {
854 char f[1200], hex[65];
855 snprintf(f, sizeof f, "%s/%s", dir, names[i]);
856 if (est_sha_file_hex(f, hex)) { fclose(fp); return 1; }
857 fprintf(fp, "%s %s\n", hex, names[i]);
858 }
859 return fclose(fp) != 0;
860}
861
862void c3_json_str(FILE *fp, const char *s)
863{
864 fputc('"', fp);
865 for (; *s; s++) {
866 unsigned char c = (unsigned char)*s;
867 if (c == '"' || c == '\\') fprintf(fp, "\\%c", c);
868 else if (c < 0x20) fprintf(fp, "\\u%04x", c);
869 else fputc(c, fp);
870 }
871 fputc('"', fp);
872}
873
874
875/* ---- strict-JSON receipt numbers (est-json-1) ---- */
876void c3_json_num(FILE *fp, double v)
877{
878 if (isfinite(v)) fprintf(fp, "%.17g", v); else fputs("null", fp);
879}
880
881/* A gated statistic that is not finite is invalid (it also fails its gate: band() sets pass only
882 * for finite values). An ungated one (a regime with too few steps) is merely unmeasured. */
883static int stat_value_state(const c3_stats *st, int i) /* 0 ok, 1 unmeasured, 2 invalid */
884{
885 if (isfinite(st->value[i])) return 0;
886 return st->gated[i] ? 2 : 1;
887}
888
889static int bound_invalid(double b) { return isnan(b); }
890
891/* names (optional) receives the invalid field names; returns how many */
892static size_t stats_invalid_list(const c3_stats *st, int ten_mode, double ls10, char (*names)[56], size_t cap)
893{
894 size_t k = 0;
895#define NOTE(cond, text) do { if (cond) { if (names && k < cap) snprintf(names[k], 56, "%s", text); k++; } } while (0)
896 NOTE(!isfinite(st->logscore), "mean_log_score");
897 NOTE(!isfinite(st->width_mean), "width80_mean_mc");
898 NOTE(!isfinite(st->width_median), "width80_median_mc");
899 NOTE(ten_mode == C3_TEN_MEASURED && !isfinite(ls10), "ten_log_score");
900 for (int i = 0; i < C3_ST_COUNT; i++) {
901 char t[56];
902 snprintf(t, sizeof t, "stats.%s.value", c3_stat_name(i));
903 NOTE(stat_value_state(st, i) == 2, t);
904 snprintf(t, sizeof t, "stats.%s.bound", c3_stat_name(i));
905 NOTE(bound_invalid(st->band_lo[i]) || bound_invalid(st->band_hi[i]), t);
906 }
907#undef NOTE
908 return k;
909}
910
911size_t c3_stats_invalid(const c3_stats *st, int ten_mode, double ls10)
912{
913 return stats_invalid_list(st, ten_mode, ls10, NULL, 0);
914}
915
916size_t c3_json_stats(FILE *o, const char *name, const c3_stats *st, int ten_mode, double ls10)
917{
918 char names[C3_ST_COUNT * 2 + 8][56];
919 size_t bad = stats_invalid_list(st, ten_mode, ls10, names, sizeof names / sizeof names[0]);
920 fprintf(o, " \"%s\": {\"n\": %zu, \"unscorable\": %zu, \"mean_log_score\": ", name, st->n, st->unscorable);
921 c3_json_num(o, st->logscore);
922 if (ten_mode != C3_TEN_ABSENT) {
923 fputs(", \"ten_log_score\": ", o);
924 c3_json_num(o, ls10);
925 fprintf(o, ", \"ten_log_score_status\": \"%s\"", ten_mode == C3_TEN_UNAVAILABLE ? "unavailable" : isfinite(ls10) ? "ok" : "invalid");
926 }
927 fprintf(o, ", \"calibrated\": %s, \"first_fail\": ", st->calibrated ? "true" : "false");
928 if (st->calibrated) fputs("null", o); else c3_json_str(o, c3_stat_name(st->first_fail));
929 fputs(", \"width80_mean_mc\": ", o); c3_json_num(o, st->width_mean);
930 fputs(", \"width80_median_mc\": ", o); c3_json_num(o, st->width_median);
931 fputs(", \"invalid_fields\": [", o);
932 for (size_t k = 0; k < bad && k < sizeof names / sizeof names[0]; k++) fprintf(o, "%s\"%s\"", k ? ", " : "", names[k]);
933 fputs("], \"stats\": {", o);
934 for (int i = 0; i < C3_ST_COUNT; i++) {
935 static const char *const vs[3] = { "ok", "unmeasured", "invalid" };
936 fprintf(o, "%s\"%s\": {\"value\": ", i ? ", " : "", c3_stat_name(i));
937 c3_json_num(o, st->value[i]);
938 fprintf(o, ", \"value_status\": \"%s\", \"lo\": ", vs[stat_value_state(st, i)]);
939 c3_json_num(o, st->band_lo[i]);
940 fprintf(o, ", \"lo_unbounded\": %s, \"hi\": ", isinf(st->band_lo[i]) ? "true" : "false");
941 c3_json_num(o, st->band_hi[i]);
942 fprintf(o, ", \"hi_unbounded\": %s, \"n\": %zu, \"gated\": %s, \"pass\": %s}", isinf(st->band_hi[i]) ? "true" : "false",
943 (i >= C3_ST_Q0 && i <= C3_ST_TEN) ? st->sub_n[i] : st->n, st->gated[i] ? "true" : "false", st->pass[i] ? "true" : "false");
944 }
945 fputs("}}", o);
946 return bad;
947}
948/* -------------------------------------------------------------- synthetic */
949
950static uint64_t sm64(uint64_t *s)
951{
952 uint64_t z = (*s += 0x9e3779b97f4a7c15ull);
953 z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
954 z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
955 return z ^ (z >> 31);
956}
957static double u01(uint64_t *s) { return (double)(sm64(s) >> 11) * (1.0 / 9007199254740992.0); }
958
959static int draw_k(uint64_t *s, int heavy)
960{
961 double u = u01(s);
962 if (!heavy) {
963 if (u < 0.60) return 0;
964 if (u < 0.75) return 1;
965 if (u < 0.90) return -1;
966 if (u < 0.95) return 2;
967 return -2;
968 }
969 if (u < 0.30) return 0;
970 if (u < 0.50) return 1;
971 if (u < 0.70) return -1;
972 if (u < 0.80) return 2;
973 if (u < 0.90) return -2;
974 if (u < 0.95) return 3;
975 return -3;
976}
977
978int c3_synth_write(const char *dir, const c3_synth *sy)
979{
980 if (mkdir(dir, 0755) && errno != EEXIST) return 1;
981 uint64_t s = sy->seed;
982 long total = (long)sy->lines + 10;
983 static const int levels[4] = { 0, 6, 12, 18 };
984 int seg_lv[C3_MAX_MARKS]; long seg_s[C3_MAX_MARKS]; int nseg = 0; long acc = 0;
985 while (acc < total && nseg < C3_MAX_MARKS) {
986 int lv = levels[sm64(&s) % 4u];
987 long d = 20 + (long)(sm64(&s) % 101u);
988 if (acc + d > total) d = total - acc;
989 seg_lv[nseg] = lv; seg_s[nseg] = d; acc += d; nseg++;
990 }
991 const int64_t t0 = 1790000000ll * NS + 123456789ll;
992 char p[1200];
993 snprintf(p, sizeof p, "%s/schedule.txt", dir);
994 FILE *fs = fopen(p, "w"); if (!fs) return 1;
995 fprintf(fs, "est_load seed %llu seconds %ld segments %d\n", (unsigned long long)sy->seed, total, nseg);
996 for (int i = 0; i < nseg; i++) fprintf(fs, "schedule %d %d %ld\n", i, seg_lv[i], seg_s[i]);
997 fprintf(fs, "est_load done\n");
998 fclose(fs);
999 snprintf(p, sizeof p, "%s/machine-state-marks.txt", dir);
1000 FILE *fm = fopen(p, "w"); if (!fm) return 1;
1001 long st = 0; int dropped = 0;
1002 for (int i = 0; i < nseg; i++) {
1003 if (seg_lv[i] > 0) {
1004 int64_t b = t0 + (int64_t)st * NS + 510000000ll, e = t0 + (int64_t)(st + seg_s[i]) * NS + 510000000ll;
1005 fprintf(fm, "%lld.%09lld begin load-L%d-%03d\n", (long long)(b / NS), (long long)(b % NS), seg_lv[i], i);
1006 if (sy->drop_end_mark && !dropped) dropped = 1;
1007 else fprintf(fm, "%lld.%09lld end load-L%d-%03d exit 0\n", (long long)(e / NS), (long long)(e % NS), seg_lv[i], i);
1008 }
1009 st += seg_s[i];
1010 }
1011 fclose(fm);
1012 snprintf(p, sizeof p, "%s/machine-state.ndjson", dir);
1013 FILE *fn = fopen(p, "w"); if (!fn) return 1;
1014 long y = 40000; unsigned long long cpu[8] = { 100000, 10, 5000, 900000, 300, 0, 50, 0 };
1015 long sec = 0;
1016 for (size_t i = 0; i < sy->lines; i++) {
1017 long step = (sy->gap_every && i > 0 && i % sy->gap_every == 0) ? 3 : 1;
1018 if (i > 0) {
1019 for (long k = 0; k < step; k++) {
1020 long at = sec + k; int lv = 0; long a2 = 0;
1021 for (int g = 0; g < nseg; g++) { if (at >= a2 && at < a2 + seg_s[g]) { lv = seg_lv[g]; break; } a2 += seg_s[g]; }
1022 double busy = lv + sy->foreign + ((sy->spike_every && (at % (long)sy->spike_every) == 0) ? 4.0 : 0.0);
1023 if (busy > C3_NCORES) busy = C3_NCORES;
1024 unsigned long long bj = (unsigned long long)llround(busy * 100.0);
1025 cpu[0] += bj; cpu[3] += 2000ull - bj;
1026 y += 100 * draw_k(&s, sy->heavy_trial_noise && lv > 0);
1027 }
1028 sec += step;
1029 }
1030 int64_t t = t0 + (int64_t)sec * NS + 500000000ll + (int64_t)(sm64(&s) % 20000000ull);
1031 fprintf(fn, "{\"t\":%lld.%09lld,\"thermal_mc\":\"%ld 31800 31900 \",\"loadavg\":\"%.2f 1.00 1.00\",\"cpu\":\"%llu %llu %llu %llu %llu %llu %llu %llu\"}\n",
1032 (long long)(t / NS), (long long)(t % NS), y, 0.5 + sy->foreign,
1033 cpu[0], cpu[1], cpu[2], cpu[3], cpu[4], cpu[5], cpu[6], cpu[7]);
1034 }
1035 fclose(fn);
1036 static const char *const names[3] = { "machine-state.ndjson", "machine-state-marks.txt", "schedule.txt" };
1037 return c3_write_sums(dir, names, 3);
1038}
1039
1040int c3_grid_take(int have, double ls, double best)
1041{
1042 return isfinite(ls) && (!have || ls > best);
1043}
1044
1045int c3_select(const int *avail, const int *pass, const double *ls)
1046{
1047 double best = -INFINITY; int any = 0;
1048 for (int id = 1; id <= 5; id++) if (avail[id] && pass[id] && isfinite(ls[id]) && (!any || ls[id] > best)) { best = ls[id]; any = 1; }
1049 if (!any) return 0;
1050 for (int id = 1; id <= 5; id++) if (avail[id] && pass[id] && isfinite(ls[id]) && ls[id] >= best - C3_TIE_NATS) return id;
1051 return 0;
1052}
1053
1054/* Runtime clean-tree check (in addition to the build-time TOOL_DIRTY flag):
1055 * runs `git status --porcelain` in the current directory. Any output line, a
1056 * failure to run git, or a non-zero exit status counts as dirty (returns 1). */
1057int c3_tree_dirty_now(void)
1058{
1059 FILE *p = popen("git status --porcelain 2>&1", "r");
1060 if (!p) return 1;
1061 int any = 0, ch;
1062 while ((ch = fgetc(p)) != EOF) any = 1;
1063 int st = pclose(p);
1064 return (any || st != 0) ? 1 : 0;
1065}