Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/tools/turing_cal_eval.c # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / tools / turing_cal_eval.c` 1776 lines ยท 95076 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 /* turing-cal-eval: the EXP-001 / EXP-001R primary evaluator (Turing-profile-v1.0 / v1.1, chosen by env EXP_ID). 18 * Normative description: calibration/docs/EVALUATOR.md. Statistics: 19 * calibration/docs/UNCERTAINTY_PROTOCOL.md. Coders: calibration/docs/CODER_SPEC.md. 20 * 21 * turing-cal-eval run [--dry-run] --repo DIR --manifest CAND_MANIFEST --cand-dir DIR [--cand-dir DIR ...] 22 * --dataset DATASET_MANIFEST [--overlap OVERLAP_AUDIT] --out DIR --work DIR 23 * [--only NAME,NAME,...] (dry run only) 24 * turing-cal-eval gate [--dry-run] --bundle DIR --independent SCORER_INDEPENDENT_JSON 25 * 26 * run: checks the freeze order and every digest (refuses, exit 2, void_receipt_.json, on any mismatch), 27 * then for each candidate and sealed file: produce TPS1 + TSY1, write them, re-read and parse them, encode 28 * with coder A (TCR1 range) and coder B (TCA1 rANS) from the same parsed TPS1, write the coded files, 29 * re-read them, decode, compare. Per crumb: ideal length, both coders on the crumb alone (+56-byte header), 30 * round trip. Then the per-crumb bootstrap, envelope (per file and per crumb), reversal audit, S1-S7 and S9. 31 * Writes ideal_lengths.json, scorer_primary.json, uncertainty.json, probability_streams/INDEX, 32 * arithmetic/results.json, ans/results.json, encoded_artifacts/INDEX, decoder_receipts/, and the pending 33 * final receipt + report. gate: compares scorer_independent.json with scorer_primary.json exactly (S8), 34 * fixes the verdict and writes final_receipt.json + REPORT.md exactly once. 35 * 36 * All decisions use int64 micro-bits (ub, 1 bit = 1e6 ub). C and POSIX only. */ 37 #include "sha256.h" 38 #include "turing/tc_produce.h" 39 #include "turing/tc_pstream.h" 40 #include "turing/tc_range.h" 41 #include "turing/tc_rans.h" 42 #include "turing/ty_ctr1.h" 43 #include "turing/ty_model.h" 44 45 #include 46 #include 47 #include 48 #include 49 #include 50 #include 51 #include 52 #include 53 #include 54 #include 55 #include 56 #include 57 #include 58 59 #define UB INT64_C(`1000000`) 60 #define ENV_CENTER INT64_C(`448000000`) 61 #define ENV_A INT64_C(`64000000`) 62 #define ENV_B INT64_C(1000) 63 #define BOOT_B 10000 64 #define BOOT_LO 250 65 #define BOOT_HI 9749 66 #define BOOT_SEED 0x4558503030315543ULL 67 #define MAXC 16 68 #define MAXF 16 69 #define BASELINE "B2_order1" 70 #define CANDIDATE "M_candidate" 71 #define MEM1 "M_mem" 72 #define MEM2 "M_mem_seed1" 73 #define DRY_FORBIDDEN g_forb 74 /* Experiment selection, the same way as calibration/scripts/tc_exp.sh: env EXP_ID = EXP-001 (default, profile v1.0) 75 * or EXP-001R (profile v1.1). The bridge key name EXP_001_COMPRESSION_BRIDGE is the same for both (decision record). */ 76 static const char *g_exp = "EXP-001"; 77 static char g_expdir[64], g_forb[64], g_profid[32], g_prof[128], g_side[128]; 78 static int exp_select(void) { 79 const char *e = getenv("EXP_ID"), *v; 80 if (!e || !*e) e = "EXP-001"; 81 if (!strcmp(e, "EXP-001")) v = "1.0"; 82 else if (!strcmp(e, "EXP-001R")) v = "1.1"; 83 else { fprintf(stderr, "turing-cal-eval: unknown EXP_ID (EXP-001 or EXP-001R)\n"); return 1; } 84 g_exp = !strcmp(e, "EXP-001") ? "EXP-001" : "EXP-001R"; 85 snprintf(g_expdir, sizeof g_expdir, "calibration/experiments/%s", g_exp); 86 snprintf(g_forb, sizeof g_forb, "%s", g_expdir); 87 snprintf(g_profid, sizeof g_profid, "Turing-profile-v%s", v); 88 snprintf(g_prof, sizeof g_prof, "calibration/profiles/%s.toml", g_profid); 89 snprintf(g_side, sizeof g_side, "calibration/profiles/%s.sha256", g_profid); 90 return 0; 91 } 92 93 static char why[1024]; 94 static const char *g_out; 95 static int g_dry; 96 /* g_scored: set once the first probability stream has been produced. From then on the verdict is final 97 * (FAILURE_REPORTING.md section 2): a failure is written as a final FAIL receipt, never as a void. */ 98 static int g_scored; 99 static char g_cmd[4096]; /* the command line, recorded in every void receipt (identical-retry check) */ 100 static char g_inputs[1024]; /* " " pairs of the input files, same purpose */ 101 #define MAX_ATTEMPTS 3 102 /* Receipt binding (every void and terminal receipt carries these three; CAL-0 review 2 Q5). Filled by a pre-pass 103 * before any receipt can be written: run hashes the profile and candidate manifest it was given and reads 104 * freeze_commit from the dataset manifest ("DRY_RUN" in a dry run); gate copies them from the pending receipt. */ 105 static char g_rprof[65], g_rman[65], g_rfreeze[48]; 106 107 /* ---------- small helpers ---------- */ 108 109 static void utc_now(char out[32]) { 110 time_t t = time(NULL); 111 struct tm tm; 112 gmtime_r(&t, &tm); 113 strftime(out, 32, "%Y-%m-%dT%H:%M:%SZ", &tm); 114 } 115 116 static void jclean(char *s) { 117 for (; *s; ++s) 118 if (*s == '"' || *s == '\\' || (unsigned char)*s < 0x20) *s = '\''; 119 } 120 121 /* Exclusive create of /; NULL if it exists or cannot be made. */ 122 static FILE *excl_open(const char *name) { 123 char p[PATH_MAX]; 124 snprintf(p, sizeof p, "%s/%s", g_out, name); 125 int fd = open(p, O_WRONLY | O_CREAT | O_EXCL, 0644); 126 return fd >= 0 ? fdopen(fd, "w") : NULL; 127 } 128 129 /* Terminal failure after scoring started: final_receipt.json with verdict FAIL, the failing criterion FAIL and 130 * every other criterion NOT_REACHED (prereg section 5a: NOT_REACHED counts as FAIL). Exit status 1. */ 131 static int fail_final(const char *crit, const char *step, const char *code, const char *msg) { 132 fprintf(stderr, "FAILED %s: %s: %s (%s; the verdict is final)\n", step, code, msg, crit); 133 if (!g_out) return 1; 134 FILE *f = excl_open("final_receipt.json"); 135 if (!f) return 1; 136 char t[32], m[1024]; 137 utc_now(t); 138 snprintf(m, sizeof m, "%s", msg); 139 jclean(m); 140 fprintf(f, "{\n \"schema\": \"turing.cal.terminal_receipt.v1\",\n \"experiment\": \"%s\",\n \"kind\": \"terminal_fail\",\n" 141 " \"dry_run\": %s,\n \"created_utc\": \"%s\",\n \"verdict\": \"FAIL\",\n \"criteria\": {", 142 g_exp, g_dry ? "true" : "false", t); 143 for (int i = 1; i <= 9; ++i) { 144 char nm[4]; 145 snprintf(nm, sizeof nm, "S%d", i); 146 fprintf(f, "%s\"%s\": \"%s\"", i > 1 ? ", " : "", nm, strcmp(nm, crit) ? "NOT_REACHED" : "FAIL"); 147 } 148 fprintf(f, "},\n \"failed_criterion\": \"%s\",\n \"step\": \"%s\",\n \"code\": \"%s\",\n \"reason\": \"%s\",\n" 149 " \"profile_digest\": \"%s\",\n \"freeze_commit\": \"%s\",\n \"candidate_manifest_sha256\": \"%s\",\n" 150 " \"EXP_001_COMPRESSION_BRIDGE\": \"%s\"\n}\n", 151 crit, step, code, m, g_rprof, g_rfreeze, g_rman, g_dry ? "DRY_RUN_NOT_EVIDENCE" : "FAIL"); 152 fclose(f); 153 return 1; 154 } 155 156 /* Refusal before any score exists: the attempt is VOID. Writes /void_receipt_.json (n = attempt number, the 157 * first free one, exclusive create, never overwritten) when the out dir exists. In sealed mode the third void 158 * attempt also writes final_receipt.json with verdict INCONCLUSIVE, reason INFRA (FAILURE_REPORTING.md section 2). 159 * After scoring started, a refusal is a terminal FAIL of the named criterion (see fail_final). */ 160 static int refuse_c(const char *crit, const char *step, const char *code, const char *fmt, ...) { 161 char msg[1024]; 162 va_list ap; 163 va_start(ap, fmt); 164 vsnprintf(msg, sizeof msg, fmt, ap); 165 va_end(ap); 166 if (g_scored) return fail_final(crit, step, code, msg); 167 fprintf(stderr, "REFUSED %s: %s: %s\n", step, code, msg); 168 if (g_out) { 169 char t[32], name[64]; 170 FILE *f = NULL; 171 int n = 1; 172 for (; n < 1000 && !f; ++n) { 173 snprintf(name, sizeof name, "void_receipt_%d.json", n); 174 f = excl_open(name); 175 if (!f && errno != EEXIST) break; 176 } 177 --n; 178 if (f) { 179 utc_now(t); 180 jclean(msg); 181 fprintf(f, 182 "{\n \"schema\": \"turing.cal.void_receipt.v1\",\n \"experiment\": \"%s\",\n" 183 " \"kind\": \"void\",\n \"stage\": \"evaluation\",\n \"dry_run\": %s,\n \"created_utc\": \"%s\",\n" 184 " \"attempt\": %d,\n \"step\": \"%s\",\n \"code\": \"%s\",\n \"reason\": \"%s\",\n \"command\": \"%s\",\n" 185 " \"inputs\": \"%s\",\n \"profile_digest\": \"%s\",\n \"freeze_commit\": \"%s\",\n" 186 " \"candidate_manifest_sha256\": \"%s\"\n}\n", 187 g_exp, g_dry ? "true" : "false", t, n, step, code, msg, g_cmd, g_inputs, g_rprof, g_rfreeze, g_rman); 188 fclose(f); 189 if (!g_dry && n >= MAX_ATTEMPTS && (f = excl_open("final_receipt.json"))) { 190 fprintf(f, 191 "{\n \"schema\": \"turing.cal.terminal_receipt.v1\",\n \"experiment\": \"%s\",\n" 192 " \"kind\": \"inconclusive_infra\",\n \"dry_run\": false,\n \"created_utc\": \"%s\",\n" 193 " \"verdict\": \"INCONCLUSIVE\",\n \"reason\": \"INFRA\",\n \"void_attempts\": %d,\n" 194 " \"last_step\": \"%s\",\n \"last_code\": \"%s\",\n" 195 " \"profile_digest\": \"%s\",\n \"freeze_commit\": \"%s\",\n \"candidate_manifest_sha256\": \"%s\",\n" 196 " \"EXP_001_COMPRESSION_BRIDGE\": \"INCONCLUSIVE\"\n}\n", 197 g_exp, t, n, step, code, g_rprof, g_rfreeze, g_rman); 198 fclose(f); 199 fprintf(stderr, "attempt %d of %d was void: verdict INCONCLUSIVE (INFRA), final_receipt.json written\n", n, 200 MAX_ATTEMPTS); 201 } 202 } 203 } 204 return 2; 205 } 206 #define refuse(...) refuse_c("NONE", __VA_ARGS__) 207 208 /* A freeze-order violation fixed by the frozen and published inputs (overlap audit FAIL, candidate manifest or 209 * profile not the ones at C_f, freeze after release, seed not derived from C_f) is S2 FAIL, final, in sealed mode 210 * (FAILURE_REPORTING.md section 2): retrying with the same inputs cannot change it. In a dry run it is a void. */ 211 static int s2_fail(const char *step, const char *code, const char *fmt, ...) { 212 char msg[1024]; 213 va_list ap; 214 va_start(ap, fmt); 215 vsnprintf(msg, sizeof msg, fmt, ap); 216 va_end(ap); 217 if (g_dry) return refuse(step, code, "%s", msg); 218 return fail_final("S2", step, code, msg); 219 } 220 221 static void hexs(const uint8_t d[32], char o[65]) { tc_hex(d, o); } 222 223 /* Run argv (no shell), capture up to n-1 bytes of stdout (trailing newline stripped). Returns the exit status, 224 * -1 if it could not run. */ 225 static int run_capture(char *const argv[], char *buf, size_t n) { 226 int fd[2]; 227 buf[0] = 0; 228 if (pipe(fd)) return -1; 229 pid_t pid = fork(); 230 if (pid < 0) return close(fd[0]), close(fd[1]), -1; 231 if (pid == 0) { 232 dup2(fd[1], 1); 233 close(fd[0]), close(fd[1]); 234 int nul = open("/dev/null", O_WRONLY); 235 if (nul >= 0) dup2(nul, 2); 236 execvp(argv[0], argv); 237 _exit(127); 238 } 239 close(fd[1]); 240 size_t k = 0; 241 char tmp[4096]; 242 ssize_t r; 243 while ((r = read(fd[0], tmp, sizeof tmp)) > 0) 244 for (ssize_t i = 0; i < r; ++i) 245 if (k + 1 < n) buf[k++] = tmp[i]; 246 buf[k] = 0; 247 close(fd[0]); 248 int st; 249 if (waitpid(pid, &st, 0) < 0 || !WIFEXITED(st)) return -1; 250 while (k && (buf[k - 1] == '\n' || buf[k - 1] == '\r')) buf[--k] = 0; 251 return WEXITSTATUS(st); 252 } 253 254 /* Run argv (no shell) and SHA-256 its exact stdout bytes. Returns the exit status, -1 if it could not run. */ 255 static int run_sha(char *const argv[], char o[65]) { 256 int fd[2]; 257 o[0] = 0; 258 if (pipe(fd)) return -1; 259 pid_t pid = fork(); 260 if (pid < 0) return close(fd[0]), close(fd[1]), -1; 261 if (pid == 0) { 262 dup2(fd[1], 1); 263 close(fd[0]), close(fd[1]); 264 int nul = open("/dev/null", O_WRONLY); 265 if (nul >= 0) dup2(nul, 2); 266 execvp(argv[0], argv); 267 _exit(127); 268 } 269 close(fd[1]); 270 sha256_ctx c; 271 sha256_init(&c); 272 uint8_t tmp[4096], d[32]; 273 ssize_t r; 274 while ((r = read(fd[0], tmp, sizeof tmp)) > 0) sha256_update(&c, tmp, (size_t)r); 275 close(fd[0]); 276 sha256_final(&c, d); 277 tc_hex(d, o); 278 int st; 279 if (waitpid(pid, &st, 0) < 0 || !WIFEXITED(st)) return -1; 280 return WEXITSTATUS(st); 281 } 282 283 /* "YYYY-MM-DDTHH:MM:SSZ" -> seconds since 1970 (UTC), -1 if malformed. */ 284 static int64_t utc_epoch(const char *s) { 285 int y, mo, d, h, mi, se; 286 if (strlen(s) != 20 || sscanf(s, "%4d-%2d-%2dT%2d:%2d:%2dZ", &y, &mo, &d, &h, &mi, &se) != 6 || mo < 1 || mo > 12) 287 return -1; 288 y -= mo <= 2; 289 int64_t era = (y >= 0 ? y : y - 399) / 400, yoe = y - era * 400; 290 int64_t doy = (153 * (mo + (mo > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; 291 return (era * 146097 + doe - 719468) * 86400 + h * 3600 + mi * 60 + se; 292 } 293 294 /* Sealed seed rule turing.cal.sealed.v1 (generate_sealed_data.sh): first 16 hex of 295 * SHA-256("turing.cal.sealed.v1|||g|"), top bit cleared. */ 296 static int64_t sealed_seed(const char *commit, const char *digest, int g, int j) { 297 char m[256]; 298 uint8_t d[32]; 299 snprintf(m, sizeof m, "turing.cal.sealed.v1|%s|%s|g%d|%d", commit, digest, g, j); 300 sha256_ctx c; 301 sha256_init(&c); 302 sha256_update(&c, (const uint8_t *)m, strlen(m)); 303 sha256_final(&c, d); 304 uint64_t v = 0; 305 for (int i = 0; i < 8; ++i) v = v << 8 | d[i]; 306 return (int64_t)(v & 0x7fffffffffffffffULL); 307 } 308 309 /* Notebook record (lab protocol, notebook record): who ran it, where, from which commit, clean tree or not. */ 310 typedef struct { 311 char operator_[128], host[256], kernel[128], commit[64]; 312 int dirty; /* 0 clean, 1 dirty, -1 unknown (not a git checkout) */ 313 } notebook_t; 314 315 static void json_clean(char *s) { 316 for (; *s; ++s) 317 if (*s == '"' || *s == '\\' || (unsigned char)*s < 0x20) *s = '_'; 318 } 319 320 static void notebook_of(const char *repo, notebook_t *nb) { 321 char out[8192]; 322 char *a1[] = {"git", "-C", (char *)repo, "config", "user.name", NULL}; 323 if (run_capture(a1, nb->operator_, sizeof nb->operator_) != 0 || !nb->operator_[0]) snprintf(nb->operator_, sizeof nb->operator_, "UNKNOWN"); 324 char *a2[] = {"git", "-C", (char *)repo, "rev-parse", "HEAD", NULL}; 325 if (run_capture(a2, nb->commit, sizeof nb->commit) != 0 || strlen(nb->commit) != 40) snprintf(nb->commit, sizeof nb->commit, "UNKNOWN"); 326 char *a3[] = {"git", "-C", (char *)repo, "status", "--porcelain", NULL}; 327 int rc = run_capture(a3, out, sizeof out); 328 nb->dirty = rc != 0 ? -1 : (out[0] != 0); 329 /* --repo must be the top of its own checkout, not a folder inside another one. */ 330 char *a4[] = {"git", "-C", (char *)repo, "rev-parse", "--show-toplevel", NULL}; 331 char top[PATH_MAX], rr[PATH_MAX], rt[PATH_MAX]; 332 if (run_capture(a4, top, sizeof top) != 0 || !realpath(repo, rr) || !realpath(top, rt) || strcmp(rr, rt)) nb->dirty = -1; 333 if (gethostname(nb->host, sizeof nb->host)) snprintf(nb->host, sizeof nb->host, "UNKNOWN"); 334 nb->host[sizeof nb->host - 1] = 0; 335 struct utsname u; 336 if (uname(&u)) snprintf(nb->kernel, sizeof nb->kernel, "UNKNOWN"); 337 else snprintf(nb->kernel, sizeof nb->kernel, "%s %s %s", u.sysname, u.release, u.machine); 338 json_clean(nb->operator_), json_clean(nb->host), json_clean(nb->kernel); 339 } 340 341 static int sha_file_hex(const char *path, char o[65]) { 342 uint8_t d[32]; 343 if (tc_file_sha256(path, d) != TC_OK) return -1; 344 hexs(d, o); 345 return 0; 346 } 347 348 static char *slurp(const char *path, size_t *len) { 349 uint8_t *b; 350 size_t n; 351 if (tc_read_file(path, &b, &n) != TC_OK) return NULL; 352 char *s = realloc(b, n + 1); 353 if (!s) return free(b), NULL; 354 s[n] = 0; 355 if (len) *len = n; 356 return s; 357 } 358 359 /* Line-oriented JSON field access (our scripts write one entry per line). */ 360 static int jstr(const char *line, const char *key, char *out, size_t n) { 361 char pat[128]; 362 snprintf(pat, sizeof pat, "\"%s\":", key); 363 const char *p = strstr(line, pat); 364 if (!p) return -1; 365 p += strlen(pat); 366 while (*p == ' ') ++p; 367 if (*p != '"') return -1; 368 ++p; 369 size_t i = 0; 370 while (*p && *p != '"' && *p != '\n' && i + 1 < n) out[i++] = *p++; 371 out[i] = 0; 372 return *p == '"' ? 0 : -1; 373 } 374 static int jint(const char *line, const char *key, int64_t *v) { 375 char pat[128]; 376 snprintf(pat, sizeof pat, "\"%s\":", key); 377 const char *p = strstr(line, pat); 378 if (!p) return -1; 379 p += strlen(pat); 380 while (*p == ' ') ++p; 381 char *e; 382 errno = 0; 383 long long x = strtoll(p, &e, 10); 384 if (e == p || errno) return -1; 385 if (*e != ',' && *e != '}' && *e != ' ' && *e != '\n' && *e != '\r' && *e != 0) return -1; /* integers only */ 386 *v = x; 387 return 0; 388 } 389 /* First line of text containing key (as "key":), copied into buf. */ 390 static int jtop(const char *text, const char *key, char *out, size_t n) { 391 char pat[128]; 392 snprintf(pat, sizeof pat, "\"%s\":", key); 393 const char *p = strstr(text, pat); 394 if (!p) return -1; 395 const char *ls = p; 396 while (ls > text && ls[-1] != '\n') --ls; 397 const char *le = strchr(p, '\n'); 398 size_t l = le ? (size_t)(le - ls) : strlen(ls); 399 char line[4096]; 400 if (l >= sizeof line) return -1; 401 memcpy(line, ls, l); 402 line[l] = 0; 403 return jstr(line, key, out, n); 404 } 405 406 static int mkdir_p(const char *path) { 407 char tmp[PATH_MAX]; 408 snprintf(tmp, sizeof tmp, "%s", path); 409 for (char *p = tmp + 1; *p; ++p) 410 if (*p == '/') { 411 *p = 0; 412 if (mkdir(tmp, 0755) && errno != EEXIST) return -1; 413 *p = '/'; 414 } 415 return (mkdir(tmp, 0755) && errno != EEXIST) ? -1 : 0; 416 } 417 418 static void fmt_bits(int64_t ub, char *o, size_t n) { 419 uint64_t a = ub < 0 ? (uint64_t)(-(ub + 1)) + 1 : (uint64_t)ub; 420 snprintf(o, n, "%s%" PRIu64 ".%06" PRIu64, ub < 0 ? "-" : "", a / 1000000u, a % 1000000u); 421 } 422 423 static int cmp_i64(const void *a, const void *b) { 424 int64_t x = *(const int64_t *)a, y = *(const int64_t *)b; 425 return (x > y) - (x < y); 426 } 427 428 static uint64_t splitmix64(uint64_t *s) { 429 uint64_t z = (*s += 0x9E3779B97F4A7C15ULL); 430 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; 431 z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; 432 return z ^ (z >> 31); 433 } 434 435 static int64_t env_band(uint64_t n) { return ENV_A + ENV_B * (int64_t)n; } 436 static int64_t iabs64(int64_t x) { return x < 0 ? -x : x; } 437 438 /* ---------- inputs ---------- */ 439 440 typedef struct { 441 char name[64], file[128], file_sha[65], model_digest[65], path[PATH_MAX]; 442 int64_t lm_bits; 443 } cand_t; 444 445 typedef struct { 446 int g, j; 447 int64_t seed, bytes; 448 char sha[65], path[PATH_MAX]; 449 ty_stream s; 450 uint8_t dd[32]; 451 } dfile_t; 452 453 typedef struct { /* one crumb of one file */ 454 uint32_t ord; 455 uint64_t lo, hi; 456 } crumb_t; 457 458 /* Per (candidate, file) results. */ 459 typedef struct { 460 int64_t ideal_ub, crumb_sum_ub; 461 uint64_t nrange, nrans; /* coded file bytes (header included) */ 462 int lossless; 463 int64_t *crumb_ub; /* per crumb ideal */ 464 uint64_t *crumb_range, *crumb_rans; /* per crumb coded bytes (+56) */ 465 int env_file_fail[2]; 466 int env_crumb_fail[2]; 467 int64_t worst_crumb_margin[2]; /* min over crumbs of band - |ovh - 448e6| */ 468 char tps[65], tsy[65], range_sha[65], rans_sha[65]; 469 } res_t; 470 471 static cand_t C[MAXC]; 472 static int nc; 473 static dfile_t F[MAXF]; 474 static int nf; 475 static crumb_t *CR[MAXF]; 476 static size_t ncr[MAXF]; 477 static res_t R[MAXC][MAXF]; 478 479 static int cand_index(const char *name) { 480 for (int i = 0; i < nc; ++i) 481 if (!strcmp(C[i].name, name)) return i; 482 return -1; 483 } 484 485 /* ---------- run ---------- */ 486 487 typedef struct { 488 int64_t point, lo, hi; 489 } iv_t; 490 491 static iv_t interval_of(int64_t *tb, int64_t point) { 492 qsort(tb, BOOT_B, sizeof *tb, cmp_i64); 493 iv_t v = {point, tb[BOOT_LO], tb[BOOT_HI]}; 494 return v; 495 } 496 497 static int under_forbidden(const char *repo, const char *path) { 498 char rr[PATH_MAX], rp[PATH_MAX], forb[PATH_MAX]; 499 if (!realpath(repo, rr) || !realpath(path, rp)) return 1; 500 snprintf(forb, sizeof forb, "%s/%s", rr, DRY_FORBIDDEN); 501 size_t l = strlen(forb); 502 return !strncmp(rp, forb, l) && (rp[l] == 0 || rp[l] == '/'); 503 } 504 505 static int write_text(const char *dir, const char *name, const char *text) { 506 char p[PATH_MAX]; 507 snprintf(p, sizeof p, "%s/%s", dir, name); 508 FILE *f = fopen(p, "w"); 509 if (!f) return -1; 510 fputs(text, f); 511 return fclose(f); 512 } 513 514 static FILE *open_out(const char *rel) { 515 char p[PATH_MAX]; 516 snprintf(p, sizeof p, "%s/%s", g_out, rel); 517 return fopen(p, "w"); 518 } 519 520 /* Root over a set of files: SHA-256 over sorted " \n" lines (like sha256sum). */ 521 static int root_of(const char *dir, const char **rels, int n, char o[65]) { 522 char lines[64][PATH_MAX + 80]; 523 for (int i = 0; i < n; ++i) { 524 char p[PATH_MAX], h[65]; 525 snprintf(p, sizeof p, "%s/%s", dir, rels[i]); 526 if (sha_file_hex(p, h)) return -1; 527 snprintf(lines[i], sizeof lines[i], "%s %s\n", h, rels[i]); 528 } 529 for (int i = 1; i < n; ++i) /* insertion sort by line */ 530 for (int k = i; k > 0 && strcmp(lines[k - 1], lines[k]) > 0; --k) { 531 char t[PATH_MAX + 80]; 532 strcpy(t, lines[k]), strcpy(lines[k], lines[k - 1]), strcpy(lines[k - 1], t); 533 } 534 sha256_ctx c; 535 sha256_init(&c); 536 for (int i = 0; i < n; ++i) sha256_update(&c, (const uint8_t *)lines[i], strlen(lines[i])); 537 uint8_t d[32]; 538 sha256_final(&c, d); 539 hexs(d, o); 540 return 0; 541 } 542 543 static int self_sha(char o[65]) { 544 char p[PATH_MAX]; 545 ssize_t l = readlink("/proc/self/exe", p, sizeof p - 1); 546 if (l <= 0) return -1; 547 p[l] = 0; 548 return sha_file_hex(p, o); 549 } 550 551 static int cmd_run(int argc, char **argv) { 552 const char *repo = NULL, *manifest = NULL, *dataset = NULL, *overlap = NULL, *work = NULL, *only = NULL; 553 const char *cdirs[8]; 554 int ncd = 0; 555 for (int i = 2; i < argc; ++i) { 556 const char *a = argv[i]; 557 const char *v = i + 1 < argc ? argv[i + 1] : NULL; 558 if (!strcmp(a, "--dry-run")) g_dry = 1; 559 else if (!v) return refuse("args", "ARG", "%s needs a value", a); 560 else if (!strcmp(a, "--repo")) repo = v, ++i; 561 else if (!strcmp(a, "--manifest")) manifest = v, ++i; 562 else if (!strcmp(a, "--dataset")) dataset = v, ++i; 563 else if (!strcmp(a, "--overlap")) overlap = v, ++i; 564 else if (!strcmp(a, "--out")) g_out = v, ++i; 565 else if (!strcmp(a, "--work")) work = v, ++i; 566 else if (!strcmp(a, "--only")) only = v, ++i; 567 else if (!strcmp(a, "--cand-dir") && ncd < 8) cdirs[ncd++] = v, ++i; 568 else return refuse("args", "ARG", "unknown argument %s", a); 569 } 570 /* Command and input record for the identical-retry rule (FAILURE_REPORTING.md section 2). */ 571 for (int i = 0, k = 0; i < argc && k < (int)sizeof g_cmd - 2; ++i) 572 k += snprintf(g_cmd + k, sizeof g_cmd - (size_t)k, "%s%s", i ? " " : "", argv[i]); 573 { 574 const char *nm[] = {"turing-cal-eval", "manifest", "dataset", "overlap"}; 575 char self[PATH_MAX] = "/proc/self/exe"; 576 const char *pp[] = {self, manifest, dataset, overlap}; 577 for (int i = 0, k = 0; i < 4; ++i) { 578 char h[65] = "NONE"; 579 if (pp[i] && sha_file_hex(pp[i], h)) snprintf(h, sizeof h, "UNREADABLE"); 580 k += snprintf(g_inputs + k, sizeof g_inputs - (size_t)k, "%s%s %s", i ? " " : "", nm[i], h); 581 } 582 jclean(g_cmd); 583 } 584 const char *outp = g_out; 585 g_out = NULL; /* no void receipt until the out dir is checked */ 586 if (!repo || !manifest || !dataset || !outp || !work || !ncd) 587 return refuse("args", "ARG", "need --repo --manifest --cand-dir --dataset --out --work"); 588 if (only && !g_dry) return refuse("args", "ARG", "--only is allowed in a dry run only"); 589 /* Receipt-binding pre-pass (no receipt yet: a failure here is not an attempt, like a bad argument). */ 590 { 591 char pp[PATH_MAX]; 592 snprintf(pp, sizeof pp, "%s/%s", repo, g_prof); 593 if (sha_file_hex(pp, g_rprof)) return refuse("args", "IO", "cannot read %s", pp); 594 if (sha_file_hex(manifest, g_rman)) return refuse("args", "IO", "cannot read %s", manifest); 595 snprintf(g_rfreeze, sizeof g_rfreeze, "DRY_RUN"); 596 if (!g_dry) { 597 char *d0 = slurp(dataset, NULL); 598 char fc[64] = ""; 599 if (!d0) return refuse("args", "IO", "cannot read %s", dataset); 600 jtop(d0, "freeze_commit", fc, sizeof fc); 601 free(d0); 602 int ok = strlen(fc) == 40; 603 for (int i = 0; ok && i < 40; ++i) ok = (fc[i] >= '0' && fc[i] <= '9') || (fc[i] >= 'a' && fc[i] <= 'f'); 604 if (!ok) return refuse("args", "FREEZE_COMMIT", "dataset freeze_commit '%s' is not a 40-hex commit", fc); 605 snprintf(g_rfreeze, sizeof g_rfreeze, "%s", fc); 606 } 607 } 608 if (mkdir_p(outp) || mkdir_p(work)) return refuse("args", "IO", "cannot create out/work dirs"); 609 /* One VOID counter for all of one experiment (FAILURE_REPORTING.md section 2): in sealed mode the bundle must be 610 * //run/bundle, the directory where sealed generation and the frozen-tree tests also write their 611 * void receipts, so every void of the experiment lands in one numbered sequence. */ 612 if (!g_dry) { 613 char rp[PATH_MAX], suf[128]; 614 snprintf(suf, sizeof suf, "/%s/run/bundle", g_rfreeze); 615 size_t lr, ls = strlen(suf); 616 if (!realpath(outp, rp) || (lr = strlen(rp)) < ls || strcmp(rp + lr - ls, suf)) 617 return refuse("args", "OUT_PATH", "--out must resolve to /%s/run/bundle (one void counter per experiment)", 618 g_rfreeze); 619 int nv = 0; 620 for (int k = 1; k < 1000; ++k) { 621 char p[PATH_MAX]; 622 struct stat st; 623 snprintf(p, sizeof p, "%s/void_receipt_%d.json", outp, k); 624 if (stat(p, &st)) break; 625 ++nv; 626 } 627 if (nv >= MAX_ATTEMPTS) 628 return refuse("args", "ATTEMPTS", "%d void attempts already recorded: %s is INCONCLUSIVE (INFRA)", nv, g_exp); 629 } 630 if (g_dry && (under_forbidden(repo, outp) || under_forbidden(repo, work))) 631 return refuse("dry run", "DRY_RUN_TARGET", "a dry run may not write under %s", DRY_FORBIDDEN); 632 { 633 char p[PATH_MAX]; 634 struct stat st; 635 snprintf(p, sizeof p, "%s/final_receipt.json", outp); 636 if (!stat(p, &st)) return refuse("write once", "EXISTS", "%s already exists; a verdict is never replaced", p); 637 } 638 g_out = outp; 639 /* A sealed retry after a void evaluation attempt must be the byte-identical command on byte-identical inputs: 640 * it is compared with the first void receipt of stage "evaluation" (generation and test voids share the 641 * numbering but record other commands). */ 642 if (!g_dry) { 643 for (int k = 1; k < 1000; ++k) { 644 char p[PATH_MAX], stg[32] = ""; 645 snprintf(p, sizeof p, "%s/void_receipt_%d.json", g_out, k); 646 char *v1 = slurp(p, NULL); 647 if (!v1) break; 648 jtop(v1, "stage", stg, sizeof stg); 649 if (strcmp(stg, "evaluation")) { 650 free(v1); 651 continue; 652 } 653 char c1[sizeof g_cmd] = "", i1[sizeof g_inputs] = ""; 654 jtop(v1, "command", c1, sizeof c1); 655 jtop(v1, "inputs", i1, sizeof i1); 656 free(v1); 657 if (strcmp(c1, g_cmd) || strcmp(i1, g_inputs)) 658 return refuse("retry", "RETRY_DIFFERS", "a retry must repeat the first void evaluation attempt byte for byte (command and input digests)"); 659 break; 660 } 661 } 662 /* Notebook record; a non-dry run refuses a dirty or unverifiable tree. */ 663 notebook_t nb; 664 notebook_of(repo, &nb); 665 if (!g_dry && nb.dirty != 0) 666 return refuse("notebook", "DIRTY_TREE", "%s", nb.dirty < 0 ? "--repo is not a git checkout (clean state cannot be verified)" : "--repo has uncommitted changes (git status --porcelain is not empty)"); 667 char t0[32]; 668 utc_now(t0); 669 670 /* --- profile --- */ 671 char prof_path[PATH_MAX], side_path[PATH_MAX], prof_sha[65], side_sha[65] = ""; 672 snprintf(prof_path, sizeof prof_path, "%s/%s", repo, g_prof); 673 snprintf(side_path, sizeof side_path, "%s/%s", repo, g_side); 674 if (sha_file_hex(prof_path, prof_sha)) return refuse("profile", "IO", "cannot read %s", prof_path); 675 char *side = slurp(side_path, NULL); 676 if (!side || sscanf(side, "%64s", side_sha) != 1 || strcmp(side_sha, prof_sha)) 677 return refuse("profile", "PROFILE_DIGEST", "profile sha256 %s does not match the sidecar", prof_sha); 678 free(side); 679 char *prof = slurp(prof_path, NULL); 680 if (!prof) return refuse("profile", "IO", "profile"); 681 int prof_fill = strstr(prof, "FILL_AT_FREEZE") != NULL; 682 free(prof); 683 if (prof_fill && !g_dry) return refuse("freeze order", "NOT_FROZEN", "profile still contains FILL_AT_FREEZE"); 684 uint8_t pd[32]; 685 tc_unhex(prof_sha, pd); 686 687 /* --- candidate manifest --- */ 688 char man_sha[65]; 689 char *man = slurp(manifest, NULL); 690 if (!man || sha_file_hex(manifest, man_sha)) return refuse("manifest", "IO", "cannot read %s", manifest); 691 char status[32] = "", frozen_at[40] = "", m_prof[65] = ""; 692 jtop(man, "status", status, sizeof status); 693 jtop(man, "frozen_at", frozen_at, sizeof frozen_at); 694 jtop(man, "profile_sha256", m_prof, sizeof m_prof); 695 if (strcmp(m_prof, prof_sha)) 696 return refuse("manifest", "PROFILE_DIGEST", "manifest profile_sha256 %.16s differs from profile %.16s", m_prof, prof_sha); 697 if (!g_dry && strcmp(status, "frozen")) 698 return refuse("freeze order", "NOT_FROZEN", "candidate manifest status is '%s', not 'frozen'", status); 699 if (!g_dry && !frozen_at[0]) return refuse("freeze order", "NOT_FROZEN", "candidate manifest has no frozen_at"); 700 if (!g_dry) { /* the independent scorer source in --repo is the frozen one (it may not be revised after C_f) */ 701 char m_ind[80] = "", got[128] = "", scr[PATH_MAX]; 702 jtop(man, "independent_scorer_source_sha256", m_ind, sizeof m_ind); 703 snprintf(scr, sizeof scr, "%s/calibration/scripts/indep_source_digest.sh", repo); 704 char *ai[] = {"sh", scr, NULL}; 705 if (run_capture(ai, got, sizeof got) != 0 || strlen(m_ind) != 64 || strcmp(got, m_ind)) 706 return refuse("independent scorer", "INDEP_SOURCE", "tools/turing_verify_indep digest %.16s is not the frozen %.16s", got, 707 m_ind); 708 } 709 char self_hex[65] = "", m_eval[65] = ""; 710 int n_bg = 0; 711 { 712 int sect = 0; /* 1 = shared_background, 2 = runtime */ 713 for (char *l = man; l && *l;) { 714 char *e = strchr(l, '\n'); 715 if (e) *e = 0; 716 if (strstr(l, "\"shared_background_sha256\": {")) sect = 1; 717 else if (strstr(l, "\"runtime_sha256\": {")) sect = 2; 718 else if (sect && strchr(l, '}') && !strchr(l, ':')) sect = 0; 719 else if (strstr(l, "\"name\":") && strstr(l, "\"model_digest\":")) { 720 if (nc == MAXC) return refuse("manifest", "FORMAT", "too many candidates"); 721 cand_t *c = &C[nc]; 722 if (jstr(l, "name", c->name, sizeof c->name) || jstr(l, "file", c->file, sizeof c->file) || 723 jstr(l, "file_sha256", c->file_sha, sizeof c->file_sha) || 724 jstr(l, "model_digest", c->model_digest, sizeof c->model_digest) || jint(l, "lm_bits", &c->lm_bits)) 725 return refuse("manifest", "FORMAT", "bad candidate line"); 726 if (only) { 727 char lst[512]; 728 snprintf(lst, sizeof lst, ",%s,", only); 729 char pat[80]; 730 snprintf(pat, sizeof pat, ",%s,", c->name); 731 if (!strstr(lst, pat)) goto next; 732 } 733 ++nc; 734 } else if (sect == 1) { 735 char k[PATH_MAX], v[80], *q1 = strchr(l, '"'); 736 if (q1 && sscanf(q1, "\"%[^\"]\": \"%64[0-9a-f]\"", k, v) == 2) { 737 char p[PATH_MAX], h[65]; 738 snprintf(p, sizeof p, "%s/%s", repo, k); 739 if (sha_file_hex(p, h) || strcmp(h, v)) 740 return refuse("shared background", "DIGEST", "%s does not match the candidate manifest", k); 741 ++n_bg; 742 } 743 } else if (sect == 2) { 744 jstr(l, "turing-cal-eval", m_eval, sizeof m_eval); 745 } 746 next: 747 l = e ? e + 1 : NULL; 748 } 749 } 750 free(man); 751 if (n_bg == 0) return refuse("manifest", "FORMAT", "no shared_background_sha256 entries"); 752 if (self_sha(self_hex)) return refuse("runtime", "IO", "cannot hash own binary"); 753 if (!g_dry && strcmp(self_hex, m_eval)) 754 return refuse("runtime", "RUNTIME_DIGEST", "turing-cal-eval sha256 %.16s is not the frozen one", self_hex); 755 if (cand_index(BASELINE) < 0) return refuse("manifest", "FORMAT", "baseline %s missing", BASELINE); 756 if (!g_dry && (cand_index(CANDIDATE) < 0 || cand_index(MEM1) < 0 || cand_index(MEM2) < 0)) 757 return refuse("manifest", "FORMAT", "candidate or memorizer missing"); 758 for (int i = 0; i < nc; ++i) { 759 cand_t *c = &C[i]; 760 int found = 0; 761 for (int d = 0; d < ncd && !found; ++d) { 762 char cp_[sizeof c->path]; 763 snprintf(cp_, sizeof cp_, "%s/%s", cdirs[d], c->file); 764 memcpy(c->path, cp_, sizeof cp_); 765 found = access(c->path, R_OK) == 0; 766 } 767 if (!found) return refuse("candidate", "IO", "%s not found in any --cand-dir", c->file); 768 char h[65]; 769 if (sha_file_hex(c->path, h) || strcmp(h, c->file_sha)) 770 return refuse("candidate", "DIGEST", "%s file sha256 differs from the manifest", c->name); 771 } 772 773 /* --- dataset manifest --- */ 774 char ds_sha[65]; 775 char *ds = slurp(dataset, NULL); 776 if (!ds || sha_file_hex(dataset, ds_sha)) return refuse("dataset", "IO", "cannot read %s", dataset); 777 char split[32] = "", d_prof[65] = "", d_commit[64] = "", released[40] = "", payload[65] = "", dsid[160] = ""; 778 char sc_sha[80] = "", sm_sha[80] = ""; 779 jtop(ds, "split", split, sizeof split); 780 jtop(ds, "profile_digest", d_prof, sizeof d_prof); 781 jtop(ds, "freeze_commit", d_commit, sizeof d_commit); 782 jtop(ds, "released_utc", released, sizeof released); 783 jtop(ds, "payload_digest", payload, sizeof payload); 784 jtop(ds, "dataset_id", dsid, sizeof dsid); 785 jtop(ds, "seed_commitment_sha256", sc_sha, sizeof sc_sha); 786 jtop(ds, "sealed_manifest_sha256", sm_sha, sizeof sm_sha); 787 if (strcmp(d_prof, prof_sha)) return refuse("dataset", "PROFILE_DIGEST", "dataset manifest profile_digest differs"); 788 if (g_dry && strcmp(split, "development")) return refuse("dataset", "SPLIT", "a dry run scores development data only"); 789 if (!g_dry && strcmp(split, "sealed_test")) return refuse("dataset", "SPLIT", "split '%s' is not sealed_test", split); 790 { 791 sha256_ctx pc; 792 sha256_init(&pc); 793 for (char *l = ds; l && *l;) { 794 char *e = strchr(l, '\n'); 795 if (e) *e = 0; 796 if (strstr(l, "\"group\":") && strstr(l, "\"sha256\":")) { 797 if (nf == MAXF) return refuse("dataset", "FORMAT", "too many files"); 798 dfile_t *f = &F[nf]; 799 int64_t g, j; 800 if (jint(l, "group", &g) || jint(l, "index", &j) || jint(l, "seed", &f->seed) || 801 jstr(l, "sha256", f->sha, sizeof f->sha) || jint(l, "bytes", &f->bytes) || 802 jstr(l, "path", f->path, sizeof f->path) || (g != 1 && g != 2)) 803 return refuse("dataset", "FORMAT", "bad file line"); 804 f->g = (int)g, f->j = (int)j; 805 char pl[200]; 806 snprintf(pl, sizeof pl, "%d %d %" PRId64 " %s %" PRId64 "\n", f->g, f->j, f->seed, f->sha, f->bytes); 807 sha256_update(&pc, (const uint8_t *)pl, strlen(pl)); 808 ++nf; 809 } 810 l = e ? e + 1 : NULL; 811 } 812 uint8_t d[32]; 813 char h[65]; 814 sha256_final(&pc, d); 815 hexs(d, h); 816 if (strcmp(h, payload)) return refuse("dataset", "DATASET_DIGEST", "payload_digest does not match the file list"); 817 } 818 free(ds); 819 for (int i = 0; i < nf; ++i) /* group then index order, and both groups present */ 820 if (i && (F[i].g < F[i - 1].g || (F[i].g == F[i - 1].g && F[i].j != F[i - 1].j + 1))) 821 return refuse("dataset", "FORMAT", "files not in group/index order"); 822 if (!nf || F[0].g != 1 || F[nf - 1].g != 2) return refuse("dataset", "FORMAT", "need group 1 and group 2"); 823 824 /* --- freeze order (two-step freeze, BLINDING_PROTOCOL.md section 2) --- 825 * C_f = the dataset manifest's freeze_commit: the commit that holds the frozen candidate manifest, profile and 826 * sidecar. C_f names no commit of its own; the sealed seeds are derived from it. */ 827 char ov_result[16] = "", ov_commit[64] = "", origin_main[64] = "NONE"; 828 if (!g_dry) { 829 if (!overlap) return refuse("freeze order", "OVERLAP", "--overlap overlap_audit.json is required"); 830 char *ov = slurp(overlap, NULL); 831 if (!ov) return refuse("freeze order", "OVERLAP", "cannot read %s", overlap); 832 jtop(ov, "result", ov_result, sizeof ov_result); 833 jtop(ov, "freeze_commit", ov_commit, sizeof ov_commit); 834 free(ov); 835 if (strcmp(ov_result, "PASS")) return s2_fail("freeze order", "OVERLAP", "overlap audit result is '%s'", ov_result); 836 if (strlen(d_commit) != 40 || strspn(d_commit, "`0123456789abcdef`") != 40) 837 return refuse("freeze order", "FREEZE_COMMIT", "dataset freeze_commit '%s' is not a 40-hex commit", d_commit); 838 if (strcmp(ov_commit, d_commit)) 839 return refuse("freeze order", "FREEZE_COMMIT", "overlap audit commit differs from the sealed freeze_commit"); 840 char spec[128], out[256]; 841 char *a1[] = {"git", "-C", (char *)repo, "rev-parse", "--verify", "origin/main^{commit}", NULL}; 842 if (run_capture(a1, origin_main, sizeof origin_main) != 0 || strlen(origin_main) != 40) 843 return refuse("freeze order", "FREEZE_COMMIT", "origin/main is not available in --repo (fetch first)"); 844 char *a2[] = {"git", "-C", (char *)repo, "merge-base", "--is-ancestor", d_commit, "origin/main", NULL}; 845 if (run_capture(a2, out, sizeof out) != 0) 846 return refuse("freeze order", "FREEZE_COMMIT", "freeze commit %.12s is not an ancestor of origin/main %.12s", d_commit, 847 origin_main); 848 char h[65]; 849 snprintf(spec, sizeof spec, "%s:%s/candidate_manifest.json", d_commit, g_expdir); 850 char *a3[] = {"git", "-C", (char *)repo, "show", spec, NULL}; 851 if (run_sha(a3, h) != 0 || strcmp(h, man_sha)) 852 return s2_fail("freeze order", "FREEZE_COMMIT", "candidate manifest differs from the one at freeze commit %.12s", d_commit); 853 snprintf(spec, sizeof spec, "%s:%s", d_commit, g_prof); 854 char *a4[] = {"git", "-C", (char *)repo, "show", spec, NULL}; 855 if (run_sha(a4, h) != 0 || strcmp(h, prof_sha)) 856 return s2_fail("freeze order", "FREEZE_COMMIT", "profile differs from the one at freeze commit %.12s", d_commit); 857 char *a5[] = {"git", "-C", (char *)repo, "show", "-s", "--format=%ct", d_commit, NULL}; 858 long long ct = -1; 859 if (run_capture(a5, out, sizeof out) != 0 || sscanf(out, "%lld", &ct) != 1) 860 return refuse("freeze order", "FREEZE_COMMIT", "cannot read the commit time of %.12s", d_commit); 861 int64_t rel = utc_epoch(released); 862 if (rel < 0) return refuse("freeze order", "FREEZE_AFTER_RELEASE", "no data release time"); 863 if (ct >= rel) 864 return s2_fail("freeze order", "FREEZE_AFTER_RELEASE", "freeze commit time %lld is not before the data release %s", ct, 865 released); 866 for (int i = 0; i < nf; ++i) 867 if (F[i].seed != sealed_seed(d_commit, prof_sha, F[i].g, F[i].j)) 868 return s2_fail("freeze order", "SEED_DERIVATION", "g%d/%d seed %" PRId64 " is not derived from freeze commit %.12s", 869 F[i].g, F[i].j, F[i].seed, d_commit); 870 } 871 /* Both modes: a freeze receipt newer than the data release is refused when both times exist. */ 872 if (frozen_at[0] && released[0] && released[0] >= '0' && released[0] <= '9' && strcmp(frozen_at, released) >= 0) 873 return s2_fail("freeze order", "FREEZE_AFTER_RELEASE", "candidate frozen_at %s is not before data release %s", frozen_at, 874 released); 875 if (!g_dry && (!released[0] || released[0] < '0' || released[0] > '9')) 876 return refuse("freeze order", "FREEZE_AFTER_RELEASE", "no data release time"); 877 878 /* --- load and re-hash every trace --- */ 879 for (int i = 0; i < nf; ++i) { 880 char h[65]; 881 struct stat st; 882 if (sha_file_hex(F[i].path, h) || strcmp(h, F[i].sha) || stat(F[i].path, &st) || st.st_size != F[i].bytes) 883 return refuse("dataset", "DATASET_DIGEST", "g%d/%d %s differs from the dataset manifest", F[i].g, F[i].j, 884 F[i].path); 885 tc_unhex(h, F[i].dd); 886 ty_stream_init(&F[i].s); 887 if (ty_ctr1_read(F[i].path, &F[i].s, why, sizeof why) < 0) return refuse("dataset", "FORMAT", "%s", why); 888 } 889 890 /* --- bundle dirs --- */ 891 char wd[PATH_MAX]; 892 const char *sub[] = {"probability_streams", "arithmetic", "ans", "encoded_artifacts", "decoder_receipts"}; 893 for (int i = 0; i < 5; ++i) { 894 snprintf(wd, sizeof wd, "%s/%s", g_out, sub[i]); 895 if (mkdir_p(wd)) return refuse("out", "IO", "mkdir %s", wd); 896 } 897 const char *wsub[] = {"probability_streams", "symbols", "arithmetic", "ans"}; 898 for (int i = 0; i < 4; ++i) { 899 snprintf(wd, sizeof wd, "%s/%s", work, wsub[i]); 900 if (mkdir_p(wd)) return refuse("work", "IO", "mkdir %s", wd); 901 } 902 FILE *ps_idx = open_out("probability_streams/INDEX"), *enc_idx = open_out("encoded_artifacts/INDEX"); 903 FILE *ar_res = open_out("arithmetic/results.json"), *an_res = open_out("ans/results.json"); 904 if (!ps_idx || !enc_idx || !ar_res || !an_res) return refuse("out", "IO", "bundle files"); 905 fprintf(ar_res, "{\n \"schema\": \"turing.cal.coder_results.v1\",\n \"coder\": \"A TCR1 v1 range\",\n \"results\": [\n"); 906 fprintf(an_res, "{\n \"schema\": \"turing.cal.coder_results.v1\",\n \"coder\": \"B TCA1 v1 rANS L=2^23\",\n \"results\": [\n"); 907 fprintf(ps_idx, "# \n"); 908 fprintf(enc_idx, "# \n"); 909 int first_res = 1; 910 911 int S1 = 1, S3 = 1; 912 char tsy_digest[MAXF][65]; 913 memset(tsy_digest, 0, sizeof tsy_digest); 914 915 /* --- every candidate model is parsed and checked before the first score (one at a time, freed) --- */ 916 for (int ci = 0; ci < nc; ++ci) { 917 cand_t *c = &C[ci]; 918 ty_model m; 919 uint8_t md[32]; 920 uint64_t lm; 921 int rc = tc_load_model(c->path, &m, md, &lm, why, sizeof why); 922 if (rc != TC_OK) return refuse("candidate", tc_err_name(rc), "%s: %s", c->name, why); 923 char mh[65]; 924 hexs(md, mh); 925 ty_model_free(&m); 926 if (strcmp(mh, c->model_digest)) return refuse("candidate", "MODEL_DIGEST", "%s model digest differs", c->name); 927 if ((int64_t)lm != c->lm_bits) return refuse("candidate", "LM_BITS", "%s L(M) %" PRIu64 " differs", c->name, lm); 928 } 929 /* From here on a score exists: the verdict is final and nothing is VOID any more. */ 930 g_scored = 1; 931 932 /* --- per candidate, per file --- */ 933 for (int ci = 0; ci < nc; ++ci) { 934 cand_t *c = &C[ci]; 935 ty_model m; 936 uint8_t md[32]; 937 uint64_t lm; 938 int rc = tc_load_model(c->path, &m, md, &lm, why, sizeof why); 939 if (rc != TC_OK) return refuse("candidate", tc_err_name(rc), "%s: %s", c->name, why); 940 char mh[65]; 941 hexs(md, mh); 942 if (strcmp(mh, c->model_digest)) return refuse("candidate", "MODEL_DIGEST", "%s model digest differs", c->name); 943 if ((int64_t)lm != c->lm_bits) return refuse("candidate", "LM_BITS", "%s L(M) %" PRIu64 " differs", c->name, lm); 944 fprintf(stderr, "eval %s (L(M) = %" PRIu64 " bits)\n", c->name, lm); 945 for (int fi = 0; fi < nf; ++fi) { 946 dfile_t *f = &F[fi]; 947 res_t *r = &R[ci][fi]; 948 tc_pstream p0, p; 949 tc_symbols s0, s; 950 if ((rc = tc_produce(&m, &f->s, pd, md, f->dd, &p0, &s0, why, sizeof why)) != TC_OK) 951 return refuse_c("S3", "produce", tc_err_name(rc), "%s g%d/%d: %s", c->name, f->g, f->j, why); 952 uint8_t *pb, *sb; 953 size_t pn, sn; 954 if (tc_ps_serialize(&p0, &pb, &pn, why, sizeof why) != TC_OK || tc_sy_serialize(&s0, &sb, &sn, why, sizeof why) != TC_OK) 955 return refuse_c("S3", "serialize", "FORMAT", "%s", why); 956 tc_ps_free(&p0), tc_sy_free(&s0); 957 char psp[PATH_MAX], syp[PATH_MAX]; 958 snprintf(psp, sizeof psp, "%s/probability_streams/g%d_j%d_%s.tps", work, f->g, f->j, c->name); 959 snprintf(syp, sizeof syp, "%s/symbols/g%d_j%d_%s.tsy", work, f->g, f->j, c->name); 960 if (tc_write_file(psp, pb, pn) != TC_OK || tc_write_file(syp, sb, sn) != TC_OK) 961 return refuse("write", "IO", "%s", psp); 962 free(pb), free(sb); 963 /* The coders consume the stream as re-read from disk. */ 964 if (tc_read_file(psp, &pb, &pn) != TC_OK || tc_read_file(syp, &sb, &sn) != TC_OK) return refuse("read", "IO", "%s", psp); 965 if ((rc = tc_ps_parse(pb, pn, &p, why, sizeof why)) != TC_OK || (rc = tc_sy_parse(sb, sn, &s, why, sizeof why)) != TC_OK) 966 return refuse_c("S3", "parse", tc_err_name(rc), "%s", why); 967 if ((rc = tc_ps_expect(&p, pd, md, f->dd, why, sizeof why)) != TC_OK || (rc = tc_pair_check(&p, &s, why, sizeof why)) != TC_OK) 968 return refuse_c("S3", "stream binding", tc_err_name(rc), "%s", why); 969 free(pb), free(sb); 970 char fsha[65]; 971 sha_file_hex(psp, fsha); 972 hexs(p.digest, r->tps); 973 hexs(s.digest, r->tsy); 974 /* S3: one symbol stream per sealed file, identical for every candidate. */ 975 if (!tsy_digest[fi][0]) memcpy(tsy_digest[fi], r->tsy, 65); 976 else if (strcmp(tsy_digest[fi], r->tsy)) S3 = 0; 977 fprintf(ps_idx, "%s %s %s %d %d %s %zu %s\n", fsha, r->tps, r->tsy, f->g, f->j, c->name, pn, psp); 978 /* Crumb list: identical for every candidate (it comes from the data). */ 979 size_t k = 0; 980 for (uint64_t lo = 0; lo < p.n;) { 981 uint64_t hi = lo + 1; 982 while (hi < p.n && p.crumb[hi] == p.crumb[lo]) ++hi; 983 ++k; 984 lo = hi; 985 } 986 if (!CR[fi]) { 987 CR[fi] = calloc(k ? k : 1, sizeof(crumb_t)); 988 ncr[fi] = k; 989 size_t q = 0; 990 for (uint64_t lo = 0; lo < p.n;) { 991 uint64_t hi = lo + 1; 992 while (hi < p.n && p.crumb[hi] == p.crumb[lo]) ++hi; 993 CR[fi][q].ord = p.crumb[lo], CR[fi][q].lo = lo, CR[fi][q].hi = hi, ++q; 994 lo = hi; 995 } 996 } else { 997 if (k != ncr[fi]) S3 = 0; 998 for (size_t q = 0; q < k && q < ncr[fi]; ++q) 999 if (p.crumb[CR[fi][q].lo] != CR[fi][q].ord) S3 = 0; 1000 } 1001 if (!S3) return refuse_c("S3", "S3", "SYMBOL_STREAM", "g%d/%d: candidates see different symbol streams", f->g, f->j); 1002 tc_ideal_ub(&p, &s, 0, p.n, &r->ideal_ub); 1003 /* Coder A and coder B: same parsed TPS1, written, re-read, decoded. */ 1004 const char *cname[2] = {"range", "rans"}; 1005 const char *cext[2] = {"tcr", "tca"}; 1006 uint64_t *nbytes[2] = {&r->nrange, &r->nrans}; 1007 char *csha[2] = {r->range_sha, r->rans_sha}; 1008 int ok_c[2] = {0, 0}; 1009 char dec_digest[2][65] = {"", ""}; 1010 for (int x = 0; x < 2; ++x) { 1011 uint8_t *cb; 1012 size_t cn; 1013 rc = x == 0 ? tc_range_encode(&p, &s, &cb, &cn, why, sizeof why) : tc_rans_encode(&p, &s, &cb, &cn, why, sizeof why); 1014 if (rc != TC_OK) return refuse_c("S1", "encode", tc_err_name(rc), "%s %s: %s", cname[x], c->name, why); 1015 if (cn < TC_CODED_HEADER || memcmp(cb + 16, p.digest, 32)) 1016 return refuse_c("S3", "encode", "BINDING", "%s header is not bound to the TPS1 digest", cname[x]); 1017 char cp[PATH_MAX]; 1018 snprintf(cp, sizeof cp, "%s/%s/g%d_j%d_%s.%s", work, x ? "ans" : "arithmetic", f->g, f->j, c->name, cext[x]); 1019 if (tc_write_file(cp, cb, cn) != TC_OK) return refuse("write", "IO", "%s", cp); 1020 free(cb); 1021 if (tc_read_file(cp, &cb, &cn) != TC_OK) return refuse("read", "IO", "%s", cp); 1022 *nbytes[x] = cn; 1023 sha_file_hex(cp, csha[x]); 1024 tc_symbols dsy; 1025 rc = x == 0 ? tc_range_decode(&p, cb, cn, &dsy, why, sizeof why) : tc_rans_decode(&p, cb, cn, &dsy, why, sizeof why); 1026 if (rc == TC_OK) { 1027 ok_c[x] = dsy.n == s.n && !memcmp(dsy.sym, s.sym, s.n); 1028 uint8_t *db; 1029 size_t dn; 1030 memcpy(dsy.dataset, s.dataset, 32); 1031 if (tc_sy_serialize(&dsy, &db, &dn, why, sizeof why) == TC_OK) hexs(dsy.digest, dec_digest[x]), free(db); 1032 tc_sy_free(&dsy); 1033 } 1034 if (!ok_c[x]) S1 = 0; 1035 free(cb); 1036 fprintf(enc_idx, "%s %s %d %d %s %zu %s\n", csha[x], cname[x], f->g, f->j, c->name, cn, cp); 1037 FILE *cr = x ? an_res : ar_res; 1038 fprintf(cr, 1039 "%s {\"g\": %d, \"index\": %d, \"candidate\": \"%s\", \"tps1_digest\": \"%s\", \"symbols_digest\": \"%s\", \"source_dataset_digest\": \"%s\", " 1040 "\"count\": %" PRIu64 ", \"coded_bytes\": %zu, \"header_bits\": 448, \"payload_bits\": %zu, " 1041 "\"side_information_bits\": 0, \"coded_bits\": %zu, \"encoded_sha256\": \"%s\", \"decoded_digest\": \"%s\", " 1042 "\"lossless_roundtrip\": %s}", 1043 first_res ? "" : ",\n", f->g, f->j, c->name, r->tps, r->tsy, f->sha, s.n, cn, (cn - TC_CODED_HEADER) * 8, cn * 8, 1044 csha[x], dec_digest[x][0] ? dec_digest[x] : "NONE", ok_c[x] ? "true" : "false"); 1045 } 1046 first_res = 0; 1047 r->lossless = ok_c[0] && ok_c[1]; 1048 /* Decoder receipt. */ 1049 { 1050 char rel[PATH_MAX]; 1051 snprintf(rel, sizeof rel, "decoder_receipts/g%d_j%d_%s.json", f->g, f->j, c->name); 1052 FILE *dr = open_out(rel); 1053 if (!dr) return refuse("out", "IO", "%s", rel); 1054 fprintf(dr, 1055 "{\n \"schema\": \"turing.cal.decoder_receipt.v1\",\n \"g\": %d,\n \"index\": %d,\n \"candidate\": \"%s\",\n" 1056 " \"profile_digest\": \"%s\",\n \"model_digest\": \"%s\",\n \"dataset_digest\": \"%s\",\n" 1057 " \"tps1_digest\": \"%s\",\n \"symbols_digest\": \"%s\",\n \"count\": %" PRIu64 ",\n" 1058 " \"range\": {\"coded_sha256\": \"%s\", \"coded_bytes\": %" PRIu64 ", \"decoded_digest\": \"%s\", \"lossless\": %s},\n" 1059 " \"rans\": {\"coded_sha256\": \"%s\", \"coded_bytes\": %" PRIu64 ", \"decoded_digest\": \"%s\", \"lossless\": %s},\n" 1060 " \"same_tps1_for_both_coders\": true\n}\n", 1061 f->g, f->j, c->name, prof_sha, mh, f->sha, r->tps, r->tsy, s.n, r->range_sha, r->nrange, 1062 dec_digest[0][0] ? dec_digest[0] : "NONE", ok_c[0] ? "true" : "false", r->rans_sha, r->nrans, 1063 dec_digest[1][0] ? dec_digest[1] : "NONE", ok_c[1] ? "true" : "false"); 1064 fclose(dr); 1065 } 1066 /* Per crumb: ideal, both coders on the crumb alone, round trip, envelope. */ 1067 size_t K = ncr[fi]; 1068 r->crumb_ub = calloc(K, sizeof(int64_t)); 1069 r->crumb_range = calloc(K, sizeof(uint64_t)); 1070 r->crumb_rans = calloc(K, sizeof(uint64_t)); 1071 uint8_t *tmp = malloc(s.n ? s.n : 1); 1072 r->worst_crumb_margin[0] = r->worst_crumb_margin[1] = INT64_MAX; 1073 r->crumb_sum_ub = 0; 1074 for (size_t q = 0; q < K; ++q) { 1075 uint64_t lo = CR[fi][q].lo, hi = CR[fi][q].hi, n = hi - lo; 1076 tc_ideal_ub(&p, &s, lo, hi, &r->crumb_ub[q]); 1077 r->crumb_sum_ub += r->crumb_ub[q]; 1078 uint8_t *x, *y; 1079 size_t nx, ny; 1080 if (tc_range_encode_raw(p.q + lo * p.K, p.K, s.sym + lo, n, &x, &nx, NULL) != TC_OK || 1081 tc_rans_encode_raw(p.q + lo * p.K, p.K, s.sym + lo, n, &y, &ny) != TC_OK) 1082 return refuse_c("S1", "crumb encode", "CODER", "%s g%d/%d crumb %u", c->name, f->g, f->j, CR[fi][q].ord); 1083 if (tc_range_decode_raw(p.q + lo * p.K, p.K, x, nx, n, tmp, why, sizeof why) != TC_OK || memcmp(tmp, s.sym + lo, n) || 1084 tc_rans_decode_raw(p.q + lo * p.K, p.K, y, ny, n, tmp, why, sizeof why) != TC_OK || memcmp(tmp, s.sym + lo, n)) 1085 S1 = 0, r->lossless = 0; 1086 r->crumb_range[q] = nx + TC_CODED_HEADER; 1087 r->crumb_rans[q] = ny + TC_CODED_HEADER; 1088 free(x), free(y); 1089 for (int z = 0; z < 2; ++z) { 1090 uint64_t cb = z ? r->crumb_rans[q] : r->crumb_range[q]; 1091 int64_t ovh = (int64_t)cb * 8 * UB - r->crumb_ub[q]; 1092 int64_t margin = env_band(n) - iabs64(ovh - ENV_CENTER); 1093 if (margin < 0) r->env_crumb_fail[z]++; 1094 if (margin < r->worst_crumb_margin[z]) r->worst_crumb_margin[z] = margin; 1095 } 1096 } 1097 free(tmp); 1098 if (r->crumb_sum_ub != r->ideal_ub) 1099 return refuse_c("S4", "per-crumb sum", "CRUMB_SUM", "%s g%d/%d: crumb sum %" PRId64 " != file %" PRId64, c->name, f->g, f->j, 1100 r->crumb_sum_ub, r->ideal_ub); 1101 for (int z = 0; z < 2; ++z) { 1102 uint64_t cb = z ? r->nrans : r->nrange; 1103 int64_t ovh = (int64_t)cb * 8 * UB - r->ideal_ub; 1104 if (iabs64(ovh - ENV_CENTER) > env_band(s.n)) r->env_file_fail[z] = 1; 1105 } 1106 tc_ps_free(&p), tc_sy_free(&s); 1107 } 1108 ty_model_free(&m); 1109 } 1110 fprintf(ar_res, "\n ]\n}\n"); 1111 fprintf(an_res, "\n ]\n}\n"); 1112 fclose(ar_res), fclose(an_res), fclose(ps_idx), fclose(enc_idx); 1113 1114 /* --- group aggregates and bootstrap --- */ 1115 int b2 = cand_index(BASELINE); 1116 int64_t lm[MAXC], ideal[3][MAXC], coded[3][MAXC][2], events[3] = {0}, band_sum[3] = {0}; 1117 size_t pool_n[3] = {0}; 1118 iv_t Tv[3][MAXC][3]; /* [g][cand][ideal, range, rans] vs B2 */ 1119 iv_t Tb[3][MAXC][MAXC]; /* [g][cand][baseline] ideal */ 1120 int pgt0[3][MAXC] = {{0}}; /* bootstrap replicates with T_ideal vs B2 > 0 (reported only) */ 1121 int64_t *Sb[3][MAXC]; 1122 memset(ideal, 0, sizeof ideal), memset(coded, 0, sizeof coded); 1123 for (int ci = 0; ci < nc; ++ci) lm[ci] = C[ci].lm_bits; 1124 for (int g = 1; g <= 2; ++g) { 1125 for (int fi = 0; fi < nf; ++fi) 1126 if (F[fi].g == g) { 1127 pool_n[g] += ncr[fi]; 1128 events[g] += (int64_t)F[fi].s.n; 1129 band_sum[g] += env_band(F[fi].s.n); 1130 for (int ci = 0; ci < nc; ++ci) { 1131 ideal[g][ci] += R[ci][fi].ideal_ub; 1132 coded[g][ci][0] += (int64_t)R[ci][fi].nrange * 8; 1133 coded[g][ci][1] += (int64_t)R[ci][fi].nrans * 8; 1134 } 1135 } 1136 size_t Cn = pool_n[g]; 1137 if (Cn == 0) return refuse_c(g == 2 ? "S9" : "S6", "bootstrap", "NO_CRUMBS", "group %d has no crumbs", g); 1138 /* Pool: (seed order, crumb ordinal); per candidate crumb ideal. */ 1139 int64_t *pool[MAXC]; 1140 for (int ci = 0; ci < nc; ++ci) { 1141 pool[ci] = malloc(Cn * sizeof(int64_t)); 1142 size_t q = 0; 1143 for (int fi = 0; fi < nf; ++fi) 1144 if (F[fi].g == g) 1145 for (size_t z = 0; z < ncr[fi]; ++z) pool[ci][q++] = R[ci][fi].crumb_ub[z]; 1146 Sb[g][ci] = malloc(BOOT_B * sizeof(int64_t)); 1147 memset(Sb[g][ci], 0, BOOT_B * sizeof(int64_t)); 1148 } 1149 uint64_t st = BOOT_SEED + (uint64_t)g; 1150 uint64_t lim = UINT64_MAX - ((UINT64_MAX % Cn) + 1) % Cn; 1151 for (int b = 0; b < BOOT_B; ++b) 1152 for (size_t k = 0; k < Cn; ++k) { 1153 uint64_t rr; 1154 do rr = splitmix64(&st); 1155 while (rr > lim); 1156 size_t idx = (size_t)(rr % Cn); 1157 for (int ci = 0; ci < nc; ++ci) Sb[g][ci][b] += pool[ci][idx]; 1158 } 1159 int64_t *tb = malloc(BOOT_B * sizeof(int64_t)); 1160 for (int ci = 0; ci < nc; ++ci) { 1161 for (int bi = 0; bi < nc; ++bi) { 1162 int64_t shift = (lm[ci] - lm[bi]) * UB; 1163 for (int b = 0; b < BOOT_B; ++b) tb[b] = Sb[g][bi][b] - Sb[g][ci][b] - shift; 1164 if (bi == b2) 1165 for (int b = 0; b < BOOT_B; ++b) pgt0[g][ci] += tb[b] > 0; 1166 Tb[g][ci][bi] = interval_of(tb, ideal[g][bi] - ideal[g][ci] - shift); 1167 } 1168 Tv[g][ci][0] = Tb[g][ci][b2]; 1169 for (int x = 0; x < 2; ++x) { 1170 int64_t o_m = coded[g][ci][x] * UB - ideal[g][ci], o_b = coded[g][b2][x] * UB - ideal[g][b2]; 1171 int64_t sh = o_m - o_b; 1172 iv_t v = {Tv[g][ci][0].point - sh, Tv[g][ci][0].lo - sh, Tv[g][ci][0].hi - sh}; 1173 Tv[g][ci][1 + x] = v; 1174 } 1175 } 1176 free(tb); 1177 for (int ci = 0; ci < nc; ++ci) free(pool[ci]), free(Sb[g][ci]); 1178 } 1179 1180 /* --- S4 envelope --- */ 1181 int S4 = 1; 1182 for (int ci = 0; ci < nc; ++ci) 1183 for (int fi = 0; fi < nf; ++fi) 1184 for (int z = 0; z < 2; ++z) 1185 if (R[ci][fi].env_file_fail[z] || R[ci][fi].env_crumb_fail[z]) S4 = 0; 1186 1187 /* --- S5 reversals (prereg section 5, FAILURE_REPORTING section 5) --- */ 1188 int S5 = 1, n_rev = 0, n_rev_expl = 0; 1189 static char revlog[65536]; revlog[0] = 0; /* up to 84 DL + 36 T-sign entries, ~200 bytes each */ 1190 size_t rl = 0; 1191 for (int g = 1; g <= 2; ++g) 1192 for (int x = 0; x < 2; ++x) 1193 for (int a = 0; a < nc; ++a) 1194 for (int b = a + 1; b < nc; ++b) { 1195 int64_t di = (lm[a] * UB + ideal[g][a]) - (lm[b] * UB + ideal[g][b]); 1196 int64_t dc = (lm[a] - lm[b]) * UB + (coded[g][a][x] - coded[g][b][x]) * UB; 1197 int si = (di > 0) - (di < 0), sc = (dc > 0) - (dc < 0); 1198 if (si == sc) continue; 1199 ++n_rev; 1200 int expl = iabs64(di) <= 2 * band_sum[g]; 1201 n_rev_expl += expl; 1202 if (!expl) S5 = 0; 1203 if (rl < sizeof revlog - 200) 1204 rl += (size_t)snprintf(revlog + rl, sizeof revlog - rl, 1205 " {\"g\": %d, \"coder\": \"%s\", \"a\": \"%s\", \"b\": \"%s\", \"dl_diff_ideal_ub\": %" PRId64 1206 ", \"dl_diff_coded_ub\": %" PRId64 ", \"explained\": %s},\n", 1207 g, x ? "rans" : "range", C[a].name, C[b].name, di, dc, expl ? "true" : "false"); 1208 } 1209 /* Sign reversals of T: ideal vs coded (same group); group 1 vs group 2 (same measure). Material when the two 1210 * intervals exclude each other's point estimates. Ideal vs coded is explained when |o(M)-o(B2)| is within 1211 * the two groups' summed envelope band. */ 1212 for (int ci = 0; ci < nc; ++ci) { 1213 if (ci == b2) continue; 1214 for (int g = 1; g <= 2; ++g) 1215 for (int x = 1; x <= 2; ++x) { 1216 iv_t u = Tv[g][ci][0], v = Tv[g][ci][x]; 1217 int su = (u.point > 0) - (u.point < 0), sv = (v.point > 0) - (v.point < 0); 1218 int excl = (u.point < v.lo || u.point > v.hi) && (v.point < u.lo || v.point > u.hi); 1219 if (su == sv || !excl) continue; 1220 ++n_rev; 1221 int expl = iabs64(u.point - v.point) <= 2 * band_sum[g]; 1222 n_rev_expl += expl; 1223 if (!expl) S5 = 0; 1224 if (rl < sizeof revlog - 200) 1225 rl += (size_t)snprintf(revlog + rl, sizeof revlog - rl, 1226 " {\"g\": %d, \"kind\": \"T sign ideal vs %s\", \"candidate\": \"%s\", \"explained\": %s},\n", g, 1227 x == 1 ? "range" : "rans", C[ci].name, expl ? "true" : "false"); 1228 } 1229 for (int x = 0; x < 3; ++x) { 1230 iv_t u = Tv[1][ci][x], v = Tv[2][ci][x]; 1231 int su = (u.point > 0) - (u.point < 0), sv = (v.point > 0) - (v.point < 0); 1232 int excl = (u.point < v.lo || u.point > v.hi) && (v.point < u.lo || v.point > u.hi); 1233 if (su == sv || !excl) continue; 1234 ++n_rev, S5 = 0; 1235 if (rl < sizeof revlog - 200) 1236 rl += (size_t)snprintf(revlog + rl, sizeof revlog - rl, 1237 " {\"kind\": \"T sign group 1 vs group 2\", \"measure\": \"%s\", \"candidate\": \"%s\", \"explained\": false},\n", 1238 x == 0 ? "ideal" : x == 1 ? "range" : "rans", C[ci].name); 1239 } 1240 } 1241 if (rl >= 2 && revlog[rl - 2] == ',') revlog[rl - 2] = '\n', revlog[rl - 1] = 0; 1242 /* Spearman rho of the DL ordering, ideal vs each coder (reported only). */ 1243 double rho[3][2]; 1244 for (int g = 1; g <= 2; ++g) 1245 for (int x = 0; x < 2; ++x) { 1246 double d2 = 0; 1247 for (int a = 0; a < nc; ++a) { 1248 int ra = 0, rb = 0; 1249 for (int b = 0; b < nc; ++b) { 1250 if (lm[b] * UB + ideal[g][b] < lm[a] * UB + ideal[g][a]) ++ra; 1251 if (lm[b] + coded[g][b][x] < lm[a] + coded[g][a][x]) ++rb; 1252 } 1253 d2 += (double)(ra - rb) * (ra - rb); 1254 } 1255 rho[g][x] = nc > 1 ? 1.0 - 6.0 * d2 / ((double)nc * ((double)nc * nc - 1)) : 1.0; 1256 } 1257 1258 /* --- S6, S7, S9 (three-way: PASS, FAIL = interval entirely on the wrong side, INCONCLUSIVE = straddles 0) --- */ 1259 const char *crit[10] = {0}; 1260 int mi = cand_index(CANDIDATE), m1 = cand_index(MEM1), m2 = cand_index(MEM2); 1261 int s6[3] = {0}, s7[3] = {0}; /* 1 PASS, 0 INCONCLUSIVE, -1 FAIL, -2 not reached */ 1262 for (int g = 1; g <= 2; ++g) { 1263 s6[g] = mi < 0 ? -2 : 1; 1264 for (int x = 0; mi >= 0 && x < 3; ++x) { 1265 iv_t v = Tv[g][mi][x]; 1266 int e = v.lo > 0 ? 1 : v.hi < 0 ? -1 : 0; 1267 if (e < s6[g]) s6[g] = e; 1268 } 1269 s7[g] = (m1 < 0 && m2 < 0) ? -2 : 1; 1270 int mm[2] = {m1, m2}; 1271 for (int k = 0; k < 2; ++k) 1272 for (int x = 0; mm[k] >= 0 && x < 3; ++x) { 1273 iv_t v = Tv[g][mm[k]][x]; 1274 int e = v.hi < 0 ? 1 : v.lo > 0 ? -1 : 0; 1275 if (e < s7[g]) s7[g] = e; 1276 } 1277 } 1278 static const char *tri[] = {"FAIL", "INCONCLUSIVE", "PASS"}; 1279 #define TRI(v) ((v) == -2 ? "NOT_REACHED" : tri[(v) + 1]) 1280 int s9 = (s6[2] == -2 || s7[2] == -2) ? -2 : (s6[2] < s7[2] ? s6[2] : s7[2]); 1281 crit[1] = S1 ? "PASS" : "FAIL"; 1282 crit[2] = g_dry ? "NOT_CHECKED" : "PASS"; /* non-dry: every freeze-order check above refused on failure */ 1283 crit[3] = S3 ? "PASS" : "FAIL"; 1284 crit[4] = S4 ? "PASS" : "FAIL"; 1285 crit[5] = S5 ? "PASS" : "FAIL"; 1286 crit[6] = TRI(s6[1]); 1287 crit[7] = TRI(s7[1]); 1288 crit[9] = TRI(s9); 1289 1290 /* --- ideal_lengths.json --- */ 1291 FILE *il = open_out("ideal_lengths.json"); 1292 if (!il) return refuse("out", "IO", "ideal_lengths.json"); 1293 fprintf(il, "{\n \"schema\": \"turing.cal.ideal_lengths.v1\",\n \"unit\": \"ub (1 bit = `1000000` ub)\",\n \"files\": [\n"); 1294 for (int fi = 0; fi < nf; ++fi) 1295 for (int ci = 0; ci < nc; ++ci) 1296 fprintf(il, " {\"g\": %d, \"index\": %d, \"seed\": %" PRId64 ", \"candidate\": \"%s\", \"events\": %zu, \"crumbs\": %zu, \"ideal_ub\": %" PRId64 1297 ", \"range_bytes\": %" PRIu64 ", \"rans_bytes\": %" PRIu64 "}%s\n", 1298 F[fi].g, F[fi].j, F[fi].seed, C[ci].name, F[fi].s.n, ncr[fi], R[ci][fi].ideal_ub, R[ci][fi].nrange, 1299 R[ci][fi].nrans, (fi == nf - 1 && ci == nc - 1) ? "" : ","); 1300 fprintf(il, " ],\n \"crumbs\": [\n"); 1301 for (int fi = 0; fi < nf; ++fi) 1302 for (size_t q = 0; q < ncr[fi]; ++q) 1303 for (int ci = 0; ci < nc; ++ci) 1304 fprintf(il, " {\"g\": %d, \"index\": %d, \"crumb\": %u, \"n\": %" PRIu64 ", \"candidate\": \"%s\", \"ideal_ub\": %" PRId64 1305 ", \"range_bytes\": %" PRIu64 ", \"rans_bytes\": %" PRIu64 "}%s\n", 1306 F[fi].g, F[fi].j, CR[fi][q].ord, CR[fi][q].hi - CR[fi][q].lo, C[ci].name, R[ci][fi].crumb_ub[q], 1307 R[ci][fi].crumb_range[q], R[ci][fi].crumb_rans[q], 1308 (fi == nf - 1 && q == ncr[fi] - 1 && ci == nc - 1) ? "" : ","); 1309 fprintf(il, " ]\n}\n"); 1310 fclose(il); 1311 1312 /* --- scorer_primary.json: the values the independent scorer must reproduce exactly --- */ 1313 FILE *sp = open_out("scorer_primary.json"); 1314 if (!sp) return refuse("out", "IO", "scorer_primary.json"); 1315 fprintf(sp, "{\n \"schema\": \"turing.cal.scorer.v1\",\n \"scorer\": \"turing-cal-eval (primary)\",\n \"dry_run\": %s,\n", 1316 g_dry ? "true" : "false"); 1317 fprintf(sp, " \"profile_sha256\": \"%s\",\n \"candidate_manifest_sha256\": \"%s\",\n \"dataset_manifest_sha256\": \"%s\",\n", 1318 prof_sha, man_sha, ds_sha); 1319 fprintf(sp, " \"values\": [\n"); 1320 int firstv = 1; 1321 #define V(fmt, val, ...) \ 1322 do { \ 1323 fprintf(sp, "%s {\"key\": \"" fmt "\", \"value\": %" PRId64 "}", firstv ? "" : ",\n", __VA_ARGS__, (int64_t)(val)); \ 1324 firstv = 0; \ 1325 } while (0) 1326 static const char *mname[3] = {"ideal", "range", "rans"}; 1327 for (int g = 1; g <= 2; ++g) { 1328 V("g%d.crumbs", pool_n[g], g); 1329 V("g%d.events", events[g], g); 1330 for (int ci = 0; ci < nc; ++ci) { 1331 V("g%d.%s.lm_bits", lm[ci], g, C[ci].name); 1332 V("g%d.%s.ideal_ub", ideal[g][ci], g, C[ci].name); 1333 V("g%d.%s.range_bits", coded[g][ci][0], g, C[ci].name); 1334 V("g%d.%s.rans_bits", coded[g][ci][1], g, C[ci].name); 1335 for (int x = 0; x < 3; ++x) { 1336 V("g%d.%s.T_%s_vs_B2.point_ub", Tv[g][ci][x].point, g, C[ci].name, mname[x]); 1337 V("g%d.%s.T_%s_vs_B2.lo_ub", Tv[g][ci][x].lo, g, C[ci].name, mname[x]); 1338 V("g%d.%s.T_%s_vs_B2.hi_ub", Tv[g][ci][x].hi, g, C[ci].name, mname[x]); 1339 } 1340 } 1341 } 1342 for (int fi = 0; fi < nf; ++fi) 1343 for (int ci = 0; ci < nc; ++ci) { 1344 V("g%d.f%d.%s.ideal_ub", R[ci][fi].ideal_ub, F[fi].g, F[fi].j, C[ci].name); 1345 V("g%d.f%d.%s.range_bytes", R[ci][fi].nrange, F[fi].g, F[fi].j, C[ci].name); 1346 V("g%d.f%d.%s.rans_bytes", R[ci][fi].nrans, F[fi].g, F[fi].j, C[ci].name); 1347 } 1348 fprintf(sp, "\n ],\n \"criteria\": {\"S1\": \"%s\", \"S2\": \"%s\", \"S3\": \"%s\", \"S4\": \"%s\", \"S5\": \"%s\", \"S6\": \"%s\", " 1349 "\"S7\": \"%s\", \"S9\": \"%s\"}\n}\n", 1350 crit[1], crit[2], crit[3], crit[4], crit[5], crit[6], crit[7], crit[9]); 1351 fclose(sp); 1352 1353 /* --- uncertainty.json (intervals, envelope detail, sensitivity) --- */ 1354 FILE *un = open_out("uncertainty.json"); 1355 if (!un) return refuse("out", "IO", "uncertainty.json"); 1356 fprintf(un, "{\n \"schema\": \"turing.cal.uncertainty.v1\",\n \"method\": \"crumb percentile bootstrap, UNCERTAINTY_PROTOCOL.md\",\n" 1357 " \"resamples\": %d,\n \"lo_index\": %d,\n \"hi_index\": %d,\n \"groups\": [\n", 1358 BOOT_B, BOOT_LO, BOOT_HI); 1359 for (int g = 1; g <= 2; ++g) { 1360 fprintf(un, " {\"g\": %d, \"bootstrap_seed\": \"0x%016" PRIX64 "\", \"crumbs\": %zu, \"events\": %" PRId64 ",\n \"candidates\": [\n", g, 1361 (uint64_t)(BOOT_SEED + (uint64_t)g), pool_n[g], events[g]); 1362 for (int ci = 0; ci < nc; ++ci) { 1363 iv_t v = Tv[g][ci][0]; 1364 int64_t il_ = v.point - ((v.point - v.lo) * 204 + 50) / 100, ih_ = v.point + ((v.hi - v.point) * 204 + 50) / 100; 1365 int64_t lmr = (lm[ci] + 7) / 8 * 8, lb2r = (lm[b2] + 7) / 8 * 8; 1366 int64_t t_round = v.point - ((lmr - lm[ci]) - (lb2r - lm[b2])) * UB; 1367 int64_t t_double = v.point - (lm[ci] - lm[b2]) * UB; 1368 int64_t t_data = v.point + (lm[ci] - lm[b2]) * UB; 1369 fprintf(un, " {\"candidate\": \"%s\"", C[ci].name); 1370 for (int x = 0; x < 3; ++x) 1371 fprintf(un, ", \"T_%s_vs_B2\": [%" PRId64 ", %" PRId64 ", %" PRId64 "]", mname[x], Tv[g][ci][x].point, Tv[g][ci][x].lo, 1372 Tv[g][ci][x].hi); 1373 fprintf(un, ", \"T_ideal_vs_B2_inflated_x2.04\": [%" PRId64 ", %" PRId64 ", %" PRId64 "]", v.point, il_, ih_); 1374 for (int bi = 0; bi < nc; ++bi) 1375 if (bi != b2 && C[bi].name[0] == 'B') 1376 fprintf(un, ", \"T_ideal_vs_%s\": [%" PRId64 ", %" PRId64 ", %" PRId64 "]", C[bi].name, Tb[g][ci][bi].point, 1377 Tb[g][ci][bi].lo, Tb[g][ci][bi].hi); 1378 fprintf(un, ", \"T_ideal_lm_byte_rounded\": %" PRId64 ", \"T_ideal_lm_doubled\": %" PRId64 ", \"data_only_gain\": %" PRId64, 1379 t_round, t_double, t_data); 1380 fprintf(un, ", \"bootstrap_replicates_T_ideal_vs_B2_gt0\": %d", pgt0[g][ci]); 1381 int ef[2] = {0, 0}, ec[2] = {0, 0}; 1382 int64_t wm[2] = {INT64_MAX, INT64_MAX}; 1383 for (int fi = 0; fi < nf; ++fi) 1384 if (F[fi].g == g) 1385 for (int z = 0; z < 2; ++z) { 1386 ef[z] += R[ci][fi].env_file_fail[z], ec[z] += R[ci][fi].env_crumb_fail[z]; 1387 if (R[ci][fi].worst_crumb_margin[z] < wm[z]) wm[z] = R[ci][fi].worst_crumb_margin[z]; 1388 } 1389 fprintf(un, ", \"envelope\": {\"range_files_out\": %d, \"range_crumbs_out\": %d, \"range_worst_crumb_margin_ub\": %" PRId64 1390 ", \"rans_files_out\": %d, \"rans_crumbs_out\": %d, \"rans_worst_crumb_margin_ub\": %" PRId64 "}}%s\n", 1391 ef[0], ec[0], wm[0], ef[1], ec[1], wm[1], ci == nc - 1 ? "" : ","); 1392 } 1393 fprintf(un, " ],\n \"spearman_rho_dl_ideal_vs_range\": %.6f, \"spearman_rho_dl_ideal_vs_rans\": %.6f}%s\n", rho[g][0], rho[g][1], 1394 g == 2 ? "" : ","); 1395 } 1396 fprintf(un, " ],\n \"reversals_total\": %d,\n \"reversals_explained\": %d,\n \"reversals\": [\n%s ]\n}\n", n_rev, n_rev_expl, revlog); 1397 fclose(un); 1398 1399 /* --- profile.digest --- */ 1400 { 1401 char pdl[128]; 1402 snprintf(pdl, sizeof pdl, "%s %s.toml\n", prof_sha, g_profid); 1403 if (write_text(g_out, "profile.digest", pdl)) return refuse("out", "IO", "profile.digest"); 1404 } 1405 1406 /* --- roots --- */ 1407 char prob_root[65], coding_root[65]; 1408 const char *pr[] = {"probability_streams/INDEX"}; 1409 const char *cr_[] = {"arithmetic/results.json", "ans/results.json", "encoded_artifacts/INDEX"}; 1410 if (root_of(g_out, pr, 1, prob_root) || root_of(g_out, cr_, 3, coding_root)) return refuse("out", "IO", "roots"); 1411 1412 /* --- pending final receipt (verdict and S8 fixed by `gate`) --- */ 1413 char t1[32]; 1414 utc_now(t1); 1415 char ev_sha[65]; 1416 self_sha(ev_sha); 1417 1418 FILE *fr = open_out("final_receipt.pending.json"); 1419 if (!fr) return refuse("out", "IO", "pending receipt"); 1420 fprintf(fr, "{\n \"schema\": \"turing.cal.measurement_receipt.v1\",\n \"experiment\": \"%s\",\n \"kind\": \"%s\",\n", 1421 g_exp, g_dry ? "dry_run" : "final"); 1422 fprintf(fr, " \"EXP_001_COMPRESSION_BRIDGE\": \"@BRIDGE@\",\n \"verdict\": \"@VERDICT@\",\n"); 1423 fprintf(fr, " \"run_id\": \"%s-%s-%s\",\n \"created_utc\": \"@CREATED@\",\n \"started_utc\": \"%s\",\n \"scored_utc\": \"%s\",\n", 1424 g_exp, g_dry ? "dry" : "sealed", t0, t0, t1); 1425 fprintf(fr, " \"profile\": {\"path\": \"%s\", \"sha256\": \"%s\", \"sidecar_matches\": true},\n", 1426 g_prof, prof_sha); 1427 { 1428 char pj[PATH_MAX], prj[65] = ""; 1429 snprintf(pj, sizeof pj, "%s/%s/preregistration.json", repo, g_expdir); 1430 /* A dry run of an experiment without a committed preregistration.json (EXP-001R before its freeze) records NONE. */ 1431 if (sha_file_hex(pj, prj)) { if (!g_dry) return refuse("prereg", "IO", "%s", pj); snprintf(prj, sizeof prj, "NONE"); } 1432 fprintf(fr, " \"freeze\": {\"commit\": \"%s\", \"origin_main_checked\": \"%s\", \"status\": \"%s\", \"frozen_at\": \"%s\", " 1433 "\"candidate_manifest_sha256\": \"%s\", \"preregistration_sha256\": \"%s\"},\n", 1434 g_dry ? "NONE" : d_commit, origin_main, status, frozen_at[0] ? frozen_at : "NONE", man_sha, prj); 1435 } 1436 fprintf(fr, " \"notebook\": {\"operator\": \"%s\", \"host\": \"%s\", \"kernel\": \"%s\", \"commit\": \"%s\", \"tree_clean\": %s},\n", 1437 nb.operator_, nb.host, nb.kernel, nb.commit, nb.dirty == 0 ? "true" : "false"); 1438 fprintf(fr, " \"roots\": {\"candidate_root\": \"%s\", \"dataset_root\": \"%s\", \"probability_root\": \"%s\", \"coding_root\": \"%s\", " 1439 "\"analysis_root\": \"@ANALYSIS_ROOT@\"},\n", 1440 man_sha, payload, prob_root, coding_root); 1441 fprintf(fr, " \"runtime_sha256\": {\"turing-cal-eval\": \"%s\"},\n", ev_sha); 1442 fprintf(fr, " \"sealed\": {\"dataset_id\": \"%s\", \"split\": \"%s\", \"dataset_manifest_sha256\": \"%s\", \"seed_commitment_sha256\": \"%s\", " 1443 "\"manifest_sha256\": \"%s\", \"complete_utc\": \"%s\", \"overlap_audit_pass\": %s},\n", 1444 dsid, split, ds_sha, sc_sha, sm_sha, released, g_dry ? "false" : "true"); 1445 fprintf(fr, " \"groups\": [\n"); 1446 for (int g = 1; g <= 2; ++g) { 1447 fprintf(fr, " {\"g\": %d, \"seeds\": [", g); 1448 int fs = 1; 1449 for (int fi = 0; fi < nf; ++fi) 1450 if (F[fi].g == g) fprintf(fr, "%s%" PRId64, fs ? "" : ", ", F[fi].seed), fs = 0; 1451 fprintf(fr, "], \"stream_sha256\": ["); 1452 fs = 1; 1453 for (int fi = 0; fi < nf; ++fi) 1454 if (F[fi].g == g) fprintf(fr, "%s\"%s\"", fs ? "" : ", ", tsy_digest[fi]), fs = 0; 1455 fprintf(fr, "], \"crumbs\": %zu, \"events\": %" PRId64 ", \"bootstrap_seed\": \"0x%016" PRIX64 "\", \"resamples\": %d,\n \"candidates\": [\n", 1456 pool_n[g], events[g], (uint64_t)(BOOT_SEED + (uint64_t)g), BOOT_B); 1457 for (int ci = 0; ci < nc; ++ci) { 1458 int ok_sum = 1, dec[2] = {1, 1}, inenv[2] = {1, 1}; 1459 for (int fi = 0; fi < nf; ++fi) 1460 if (F[fi].g == g) { 1461 ok_sum &= R[ci][fi].crumb_sum_ub == R[ci][fi].ideal_ub; 1462 for (int z = 0; z < 2; ++z) { 1463 dec[z] &= R[ci][fi].lossless; 1464 inenv[z] &= !R[ci][fi].env_file_fail[z] && !R[ci][fi].env_crumb_fail[z]; 1465 } 1466 } 1467 fprintf(fr, " {\"name\": \"%s\", \"model_digest\": \"%s\", \"lm_bits\": %" PRId64 ", \"ld_ideal_ub\": %" PRId64 1468 ", \"per_crumb_sum_equals_file\": %s, \"t_vs_b2_ideal\": {\"point_ub\": %" PRId64 ", \"lo_ub\": %" PRId64 ", \"hi_ub\": %" PRId64 "},\n" 1469 " \"coded\": [", 1470 C[ci].name, C[ci].model_digest, lm[ci], ideal[g][ci], ok_sum ? "true" : "false", Tv[g][ci][0].point, Tv[g][ci][0].lo, 1471 Tv[g][ci][0].hi); 1472 for (int x = 0; x < 2; ++x) { 1473 int64_t bits = coded[g][ci][x]; 1474 fprintf(fr, "%s{\"coder\": \"%s\", \"coded_bytes\": %" PRId64 ", \"coded_bits\": %" PRId64 ", \"decoded_ok\": %s, \"overhead_ub\": %" PRId64 1475 ", \"inside_envelope\": %s, \"t_vs_b2\": {\"point_ub\": %" PRId64 ", \"lo_ub\": %" PRId64 ", \"hi_ub\": %" PRId64 "}}", 1476 x ? ", " : "", x ? "TCA1 rANS" : "TCR1 range", bits / 8, bits, dec[x] ? "true" : "false", bits * UB - ideal[g][ci], 1477 inenv[x] ? "true" : "false", Tv[g][ci][1 + x].point, Tv[g][ci][1 + x].lo, Tv[g][ci][1 + x].hi); 1478 } 1479 fprintf(fr, "]}%s\n", ci == nc - 1 ? "" : ","); 1480 } 1481 fprintf(fr, " ]}%s\n", g == 2 ? "" : ","); 1482 } 1483 fprintf(fr, " ],\n \"criteria\": {\"S1\": \"%s\", \"S2\": \"%s\", \"S3\": \"%s\", \"S4\": \"%s\", \"S5\": \"%s\", \"S6\": \"%s\", \"S7\": \"%s\", " 1484 "\"S8\": \"@S8@\", \"S9\": \"%s\"},\n", 1485 crit[1], crit[2], crit[3], crit[4], crit[5], crit[6], crit[7], crit[9]); 1486 fprintf(fr, " \"refusals\": [],\n \"deviations\": [\"see calibration/docs/PROTOCOL_CONFORMANCE.md (deviations D1-D9)\"%s],\n", 1487 g_dry ? ", \"DRY RUN on development data: not evidence, S2 not checked\"" : ""); 1488 fprintf(fr, " \"signed_by\": \"none (unsigned; git commit is the record)\",\n \"notes\": \"@NOTES@\"\n}\n"); 1489 fclose(fr); 1490 1491 /* --- pending REPORT.md --- */ 1492 FILE *rp_ = open_out("REPORT.pending.md"); 1493 if (!rp_) return refuse("out", "IO", "pending report"); 1494 fprintf(rp_, "# EXP-001 compression bridge: %s\n\nEXP_001_COMPRESSION_BRIDGE = @BRIDGE@\n\n", g_dry ? "DRY RUN (development data, not evidence)" : "report"); 1495 fprintf(rp_, "Profile sha256 %s. Candidate manifest sha256 %s (status %s). Dataset %s (%s), payload %s.\n\n", prof_sha, man_sha, status, 1496 dsid, split, payload); 1497 fprintf(rp_, "Criteria: S1 %s, S2 %s, S3 %s, S4 %s, S5 %s, S6 %s, S7 %s, S8 @S8@, S9 %s.\n\n", crit[1], crit[2], crit[3], crit[4], crit[5], 1498 crit[6], crit[7], crit[9]); 1499 for (int g = 1; g <= 2; ++g) { 1500 fprintf(rp_, "## Group %d (%s): seeds", g, g == 1 ? "primary" : "replication"); 1501 for (int fi = 0; fi < nf; ++fi) 1502 if (F[fi].g == g) fprintf(rp_, " %" PRId64, F[fi].seed); 1503 fprintf(rp_, ", %zu crumbs, %" PRId64 " events\n\n", pool_n[g], events[g]); 1504 fprintf(rp_, "All values in bits. T against B2; uncertainty = 95%% crumb-bootstrap interval of T_ideal (T_A, T_B intervals are the same interval shifted).\n\n"); 1505 fprintf(rp_, "| candidate | L(M) | ideal bits | coder-A bits | coder-B bits | T_ideal | T_A | T_B | uncertainty | result |\n"); 1506 fprintf(rp_, "|---|---:|---:|---:|---:|---:|---:|---:|---|---|\n"); 1507 for (int ci = 0; ci < nc; ++ci) { 1508 char a[40], b[40], c_[40], d[40], lo_[40], hi_[40]; 1509 fmt_bits(ideal[g][ci], a, sizeof a); 1510 fmt_bits(Tv[g][ci][0].point, b, sizeof b); 1511 fmt_bits(Tv[g][ci][1].point, c_, sizeof c_); 1512 fmt_bits(Tv[g][ci][2].point, d, sizeof d); 1513 fmt_bits(Tv[g][ci][0].lo, lo_, sizeof lo_); 1514 fmt_bits(Tv[g][ci][0].hi, hi_, sizeof hi_); 1515 const char *res; 1516 /* Same three-way rule as S6 / S7 (prereg section 5a): all three measures decide PASS, any one decides FAIL. */ 1517 int lop = Tv[g][ci][0].lo > 0 && Tv[g][ci][1].lo > 0 && Tv[g][ci][2].lo > 0; 1518 int hin = Tv[g][ci][0].hi < 0 && Tv[g][ci][1].hi < 0 && Tv[g][ci][2].hi < 0; 1519 int anylo = Tv[g][ci][0].lo > 0 || Tv[g][ci][1].lo > 0 || Tv[g][ci][2].lo > 0; 1520 int anyhi = Tv[g][ci][0].hi < 0 || Tv[g][ci][1].hi < 0 || Tv[g][ci][2].hi < 0; 1521 if (ci == b2) res = "baseline"; 1522 else if (ci == mi) res = lop ? "wins (S6 PASS rule)" : anyhi ? "loses (S6 FAIL rule)" : "straddles 0 (S6 INCONCLUSIVE rule)"; 1523 else if (ci == m1 || ci == m2) res = hin ? "loses (S7 PASS rule)" : anylo ? "wins (S7 FAIL rule)" : "straddles 0 (S7 INCONCLUSIVE rule)"; 1524 else res = lop ? "beats B2 (reported)" : hin ? "loses to B2 (reported)" : "mixed or ties B2 (reported)"; 1525 fprintf(rp_, "| %s | %" PRId64 " | %s | %" PRId64 " | %" PRId64 " | %s | %s | %s | [%s, %s] | %s |\n", C[ci].name, lm[ci], a, 1526 coded[g][ci][0], coded[g][ci][1], b, c_, d, lo_, hi_, res); 1527 } 1528 fprintf(rp_, "\nEnvelope (two-sided, per file and per crumb, |overhead - 448| <= 64 + 0.001 N bits):\n\n"); 1529 for (int ci = 0; ci < nc; ++ci) { 1530 int out_[2] = {0, 0}; 1531 int64_t wm[2] = {INT64_MAX, INT64_MAX}; 1532 for (int fi = 0; fi < nf; ++fi) 1533 if (F[fi].g == g) 1534 for (int z = 0; z < 2; ++z) { 1535 out_[z] += R[ci][fi].env_file_fail[z] + R[ci][fi].env_crumb_fail[z]; 1536 if (R[ci][fi].worst_crumb_margin[z] < wm[z]) wm[z] = R[ci][fi].worst_crumb_margin[z]; 1537 } 1538 char w0[40], w1[40], o0[40], o1[40]; 1539 fmt_bits(wm[0], w0, sizeof w0), fmt_bits(wm[1], w1, sizeof w1); 1540 fmt_bits(coded[g][ci][0] * UB - ideal[g][ci], o0, sizeof o0); 1541 fmt_bits(coded[g][ci][1] * UB - ideal[g][ci], o1, sizeof o1); 1542 fprintf(rp_, "- %s: overhead A %s bits, B %s bits over the group; units outside the band A %d, B %d; worst crumb margin A %s, B %s bits\n", 1543 C[ci].name, o0, o1, out_[0], out_[1], w0, w1); 1544 } 1545 fprintf(rp_, "\nSpearman rho of the description-length order, ideal vs A %.4f, ideal vs B %.4f (reported only).\n\n", rho[g][0], rho[g][1]); 1546 } 1547 fprintf(rp_, "Reversals: %d found, %d explained by the coder envelope (detail in uncertainty.json).\n\n", n_rev, n_rev_expl); 1548 fprintf(rp_, "Sensitivity (T against B0, B1, B3; L(M) byte-rounded and doubled; data-only gain; interval inflated x2.04) is in uncertainty.json; it is reported, not part of the verdict.\n\n"); 1549 /* Required report sections (laboratory execution protocol, EXP-001 final report). */ 1550 fprintf(rp_, "## Report sections\n\n"); 1551 fprintf(rp_, "- Preregistration: calibration/preregistration/%s.md and preregistration.json (sha256 in final_receipt.json freeze.preregistration_sha256).\n", g_exp); 1552 fprintf(rp_, "- Blinding: calibration/docs/BLINDING_PROTOCOL.md; overlap audit %s.\n", g_dry ? "not used (dry run)" : "PASS (overlap_audit.json)"); 1553 fprintf(rp_, "- Candidate freeze: candidate_manifest.json sha256 %s, status %s, frozen_at %s, freeze commit C_f %s.\n", man_sha, status, 1554 frozen_at[0] ? frozen_at : "NONE", g_dry ? "NONE (dry run)" : d_commit); 1555 fprintf(rp_, "- Model-cost accounting: L(M) = exact TYM0 bits (calibration/docs/MODEL_DESCRIPTION_ENCODING.md), re-checked against the manifest for every candidate.\n"); 1556 fprintf(rp_, "- Probability stream: one TPS1 per candidate and file, probability_root %s (probability_streams/INDEX).\n", prob_root); 1557 fprintf(rp_, "- Ideal codelength: ideal_lengths.json (per file and per crumb, int64 ub).\n"); 1558 fprintf(rp_, "- Actual coder results: arithmetic/results.json, ans/results.json, encoded_artifacts/INDEX, decoder_receipts/; coding_root %s.\n", coding_root); 1559 fprintf(rp_, "- Memorizer result: rows %s and %s in the tables above (criterion S7, S9).\n", MEM1, MEM2); 1560 fprintf(rp_, "- Independent verification: S8 = @S8@ (scorer_independent.json vs scorer_primary.json).\n"); 1561 fprintf(rp_, "- Uncertainty: uncertainty.json (calibration/docs/UNCERTAINTY_PROTOCOL.md).\n"); 1562 fprintf(rp_, "- Failures/deviations: calibration/docs/PROTOCOL_CONFORMANCE.md (D1-D9)%s.\n", g_dry ? "; DRY RUN on development data" : ""); 1563 fprintf(rp_, "- Gate decision: EXP_001_COMPRESSION_BRIDGE = @BRIDGE@ (rule: prereg section 5a).\n\n"); 1564 fprintf(rp_, "@NOTES@\n"); 1565 fclose(rp_); 1566 1567 for (int i = 0; i < nf; ++i) ty_stream_free(&F[i].s); 1568 fprintf(stderr, "run complete: S1 %s S2 %s S3 %s S4 %s S5 %s S6 %s S7 %s S9 %s; next: turing-cal-eval gate\n", crit[1], crit[2], crit[3], 1569 crit[4], crit[5], crit[6], crit[7], crit[9]); 1570 return 0; 1571 } 1572 1573 /* ---------- gate ---------- */ 1574 1575 typedef struct { 1576 char key[160]; 1577 int64_t v; 1578 } kv_t; 1579 1580 static int load_values(const char *path, kv_t **out, int *n) { 1581 char *t = slurp(path, NULL); 1582 if (!t) return -1; 1583 int cap = 1024; 1584 kv_t *a = malloc(cap * sizeof *a); 1585 *n = 0; 1586 for (char *l = t; l && *l;) { 1587 char *e = strchr(l, '\n'); 1588 if (e) *e = 0; 1589 char k[160]; 1590 int64_t v; 1591 if (!jstr(l, "key", k, sizeof k) && !jint(l, "value", &v)) { 1592 if (*n == cap) a = realloc(a, (cap *= 2) * sizeof *a); 1593 snprintf(a[*n].key, sizeof a[*n].key, "%s", k); 1594 a[*n].v = v; 1595 ++*n; 1596 } 1597 l = e ? e + 1 : NULL; 1598 } 1599 free(t); 1600 *out = a; 1601 return 0; 1602 } 1603 1604 static char *replace_all(const char *s, const char *from, const char *to) { 1605 size_t fl = strlen(from), tl = strlen(to), n = 0; 1606 for (const char *p = strstr(s, from); p; p = strstr(p + fl, from)) ++n; 1607 char *o = malloc(strlen(s) + n * (tl + 1) + 1), *w = o; 1608 for (const char *p = s;;) { 1609 const char *q = strstr(p, from); 1610 if (!q) { 1611 strcpy(w, p); 1612 break; 1613 } 1614 memcpy(w, p, (size_t)(q - p)), w += q - p; 1615 memcpy(w, to, tl), w += tl; 1616 p = q + fl; 1617 } 1618 return o; 1619 } 1620 1621 static int crit_of(const char *text, const char *k, char *o, size_t n) { 1622 char pat[16]; 1623 snprintf(pat, sizeof pat, "\"%s\": \"", k); 1624 const char *p = strstr(text, "\"criteria\""); 1625 if (!p || !(p = strstr(p, pat))) return -1; 1626 p += strlen(pat); 1627 size_t i = 0; 1628 while (*p && *p != '"' && i + 1 < n) o[i++] = *p++; 1629 o[i] = 0; 1630 return 0; 1631 } 1632 1633 static int cmd_gate(int argc, char **argv) { 1634 const char *bundle = NULL, *indep = NULL; 1635 for (int i = 2; i < argc; ++i) { 1636 if (!strcmp(argv[i], "--dry-run")) g_dry = 1; 1637 else if (!strcmp(argv[i], "--bundle") && i + 1 < argc) bundle = argv[++i]; 1638 else if (!strcmp(argv[i], "--independent") && i + 1 < argc) indep = argv[++i]; 1639 else return refuse("args", "ARG", "unknown argument %s", argv[i]); 1640 } 1641 if (!bundle || !indep) return refuse("args", "ARG", "need --bundle and --independent"); 1642 char p[PATH_MAX], q[PATH_MAX]; 1643 struct stat st; 1644 snprintf(p, sizeof p, "%s/final_receipt.json", bundle); 1645 if (!stat(p, &st)) return refuse("write once", "EXISTS", "%s already exists; a verdict is never replaced", p); 1646 /* Gate refusals before the comparison are operator errors: no receipt of any kind is written. */ 1647 snprintf(p, sizeof p, "%s/final_receipt.pending.json", bundle); 1648 char *rec = slurp(p, NULL); 1649 snprintf(q, sizeof q, "%s/REPORT.pending.md", bundle); 1650 char *rep = slurp(q, NULL); 1651 if (!rec || !rep) return refuse("gate", "IO", "pending receipt or report missing; run first"); 1652 int rec_dry = strstr(rec, "\"kind\": \"dry_run\"") != NULL; 1653 if (rec_dry != g_dry) return refuse("gate", "MODE", "bundle dry-run flag and --dry-run disagree"); 1654 /* Receipt binding for a terminal receipt written by the gate: taken from the pending receipt of the run. */ 1655 { 1656 char fc[48] = ""; 1657 if (jtop(rec, "sha256", g_rprof, sizeof g_rprof) || jtop(rec, "candidate_manifest_sha256", g_rman, sizeof g_rman) || 1658 jtop(rec, "commit", fc, sizeof fc) || strlen(g_rprof) != 64 || strlen(g_rman) != 64) 1659 return refuse("gate", "FORMAT", "pending receipt lacks profile, freeze commit or candidate manifest digest"); 1660 snprintf(g_rfreeze, sizeof g_rfreeze, "%s", g_dry ? "DRY_RUN" : fc); 1661 } 1662 char prim[PATH_MAX], ph[65], ih[65]; 1663 snprintf(prim, sizeof prim, "%s/scorer_primary.json", bundle); 1664 if (sha_file_hex(prim, ph)) return refuse("gate", "IO", "scorer_primary.json"); 1665 int indep_ok = !sha_file_hex(indep, ih); 1666 int self_cmp = indep_ok && !strcmp(ph, ih); 1667 if (self_cmp && !g_dry) return refuse("S8", "NOT_INDEPENDENT", "scorer_independent.json is byte-identical to scorer_primary.json"); 1668 /* The run already produced scores: from here on any failure is a final FAIL, never a void. A lane D crash, a 1669 * missing, unreadable or unparsable scorer_independent.json, or one that reports problems of its own, is S8 1670 * FAIL with no retry (EVALUATOR.md section 6). */ 1671 g_out = bundle; 1672 g_scored = 1; 1673 if (!indep_ok) return refuse_c("S8", "S8", "INDEP_MISSING", "independent scorer file %s is missing or unreadable", indep); 1674 /* S8: same key set, same int64 values. */ 1675 kv_t *a, *b; 1676 int na, nb; 1677 if (load_values(prim, &a, &na)) return refuse("gate", "IO", "values of scorer_primary.json"); 1678 if (load_values(indep, &b, &nb)) return refuse_c("S8", "S8", "INDEP_FORMAT", "values of %s cannot be parsed", indep); 1679 int s8 = na > 0 && na == nb, mism = 0; 1680 if (!self_cmp) { /* lane D records its own mismatches in "problems"; anything but 0 (or no field) fails S8 */ 1681 char *ti = slurp(indep, NULL); 1682 int64_t pr = -1; 1683 if (!ti || jint(ti, "problems", &pr) || pr != 0) ++mism; 1684 free(ti); 1685 } 1686 /* The independent file must name the same inputs and schema, and may not repeat a key. */ 1687 { 1688 static const char *hk[] = {"schema", "profile_sha256", "candidate_manifest_sha256", "dataset_manifest_sha256"}; 1689 char *ta = slurp(prim, NULL), *tb_ = slurp(indep, NULL); 1690 for (int i = 0; i < 4; ++i) { 1691 char va[128] = "", vb[128] = ""; 1692 if (!ta || !tb_ || jstr(ta, hk[i], va, sizeof va) || jstr(tb_, hk[i], vb, sizeof vb) || strcmp(va, vb)) ++mism; 1693 } 1694 free(ta), free(tb_); 1695 for (int i = 0; i < nb; ++i) 1696 for (int j = i + 1; j < nb; ++j) 1697 if (!strcmp(b[i].key, b[j].key)) ++mism; 1698 } 1699 for (int i = 0; i < na; ++i) { 1700 int found = 0; 1701 for (int j = 0; j < nb && !found; ++j) 1702 if (!strcmp(a[i].key, b[j].key)) found = 1, mism += a[i].v != b[j].v; 1703 if (!found) ++mism; 1704 } 1705 if (mism) s8 = 0; 1706 char c[10][32]; 1707 const char *names[] = {"", "S1", "S2", "S3", "S4", "S5", "S6", "S7", "", "S9"}; 1708 for (int i = 1; i <= 9; ++i) 1709 if (i != 8 && crit_of(rec, names[i], c[i], sizeof c[i])) return refuse("gate", "FORMAT", "criterion %s missing", names[i]); 1710 snprintf(c[8], sizeof c[8], "%s", s8 ? "PASS" : "FAIL"); 1711 /* Verdict (prereg section 5a). */ 1712 const char *verdict = "PASS"; 1713 int fail = 0, inc = 0; 1714 for (int i = 1; i <= 9; ++i) { 1715 if (!strcmp(c[i], "FAIL")) fail = 1; 1716 else if (!strcmp(c[i], "INCONCLUSIVE")) inc = 1; 1717 else if (strcmp(c[i], "PASS") && !(g_dry && i == 2)) fail = 1; /* NOT_REACHED counts against PASS */ 1718 } 1719 if (fail) verdict = "FAIL"; 1720 else if (inc) verdict = "INCONCLUSIVE"; 1721 char bridge[64], notes[512], created[32], s8s[64]; 1722 utc_now(created); 1723 snprintf(bridge, sizeof bridge, "%s", g_dry ? "DRY_RUN_NOT_EVIDENCE" : verdict); 1724 snprintf(s8s, sizeof s8s, "%s", c[8]); 1725 snprintf(notes, sizeof notes, "%s%s S8 compared %d values, %d mismatches.", 1726 g_dry ? "Dry run on development data; the verdict line below is what these numbers would give, not a result. " : "", 1727 self_cmp ? "S8 was a self-comparison (dry run only, not evidence)." : "S8 compared against an independent scorer file.", na, mism); 1728 /* analysis root over the scoring outputs, independent file included. */ 1729 char ind_copy[PATH_MAX]; 1730 snprintf(ind_copy, sizeof ind_copy, "%s/scorer_independent.json", bundle); 1731 if (strcmp(indep, ind_copy)) { 1732 uint8_t *buf; 1733 size_t len; 1734 if (tc_read_file(indep, &buf, &len) != TC_OK || tc_write_file(ind_copy, buf, len) != TC_OK) 1735 return refuse("gate", "IO", "copy independent scorer"); 1736 free(buf); 1737 } 1738 char aroot[65]; 1739 const char *ar[] = {"ideal_lengths.json", "scorer_primary.json", "scorer_independent.json", "uncertainty.json"}; 1740 if (root_of(bundle, ar, 4, aroot)) return refuse("gate", "IO", "analysis root"); 1741 char *r1 = replace_all(rec, "@BRIDGE@", bridge), *r2 = replace_all(r1, "@VERDICT@", verdict), *r3 = replace_all(r2, "@S8@", s8s), 1742 *r4 = replace_all(r3, "@ANALYSIS_ROOT@", aroot), *r5 = replace_all(r4, "@CREATED@", created), *r6 = replace_all(r5, "@NOTES@", notes); 1743 char vline[256]; 1744 snprintf(vline, sizeof vline, "%s\n\nVerdict rule result: %s.", notes, verdict); 1745 char *q1 = replace_all(rep, "@BRIDGE@", bridge), *q2 = replace_all(q1, "@S8@", s8s), *q3 = replace_all(q2, "@NOTES@", vline); 1746 snprintf(p, sizeof p, "%s/final_receipt.json", bundle); 1747 int fd_ok = 0; 1748 { 1749 FILE *f = fopen(p, "wx"); /* exclusive create: write once */ 1750 if (f) fd_ok = fputs(r6, f) >= 0, fd_ok &= fclose(f) == 0; 1751 } 1752 if (!fd_ok) return refuse("write once", "EXISTS", "cannot create %s exclusively", p); 1753 if (write_text(bundle, "REPORT.md", q3)) return refuse("gate", "IO", "REPORT.md"); 1754 snprintf(p, sizeof p, "%s/final_receipt.pending.json", bundle), unlink(p); 1755 unlink(q); 1756 printf("EXP_001_COMPRESSION_BRIDGE = %s (verdict rule: %s; S1 %s S2 %s S3 %s S4 %s S5 %s S6 %s S7 %s S8 %s S9 %s)\n", bridge, verdict, c[1], 1757 c[2], c[3], c[4], c[5], c[6], c[7], c[8], c[9]); 1758 free(r1), free(r2), free(r3), free(r4), free(r5), free(r6), free(q1), free(q2), free(q3), free(rec), free(rep), free(a), free(b); 1759 return 0; 1760 } 1761 1762 int main(int argc, char **argv) { 1763 int rc = -1; 1764 if (exp_select()) return 2; 1765 if (argc >= 2 && !strcmp(argv[1], "run")) rc = cmd_run(argc, argv); 1766 else if (argc >= 2 && !strcmp(argv[1], "gate")) rc = cmd_gate(argc, argv); 1767 /* A refusal ends the process at once: buffers of the abandoned run are not unwound (exit 2 stays exit 2 1768 * under the leak checker of the ASan test build). */ 1769 if (rc == 2) { 1770 fflush(NULL); 1771 _exit(2); 1772 } 1773 if (rc >= 0) return rc; 1774 fprintf(stderr, "usage: turing-cal-eval run|gate ... (see calibration/docs/EVALUATOR.md)\n"); 1775 return 2; 1776 }