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 / test_est_tools.c

748 lines · 43253 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/* Tests for est_replay / est_fit / est_eval (protocol v1 and v2). Run A and synthetic
18 * data only; this program never names run B's data file.
19 * test_est_tools <est_fit> <est_eval> <workdir> */
20#pragma GCC diagnostic ignored "-Wformat-truncation"
21#include <math.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25
26#include "est_replay.h"
27#include "test_est_ka.inc"
28
29static int g_checks, g_fail;
30#define CHECK(c) do { g_checks++; if (!(c)) { g_fail++; fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0)
31
32#define RUN_A_DIR "evidence/R15/raw/" EST_RUN_A_ID
33static char *g_fit, *g_eval, *g_evalt, *g_work;
34
35static uint64_t g_rng;
36static uint64_t rnd(void) { g_rng ^= g_rng >> 12; g_rng ^= g_rng << 25; g_rng ^= g_rng >> 27; return g_rng * 0x2545F4914F6CDD1Dull; }
37static double unif(void) { return ((double)(rnd() >> 11) + 0.5) / 9007199254740992.0; }
38static double gauss(void) { return sqrt(-2.0 * log(unif())) * cos(6.283185307179586 * unif()); }
39
40static void sh(const char *fmt, const char *a, const char *b, const char *c, const char *d)
41{
42 char cmd[16384]; snprintf(cmd, sizeof cmd, fmt, a, b, c, d);
43 int rc = system(cmd); (void)rc;
44}
45static int sh_rc(const char *fmt, const char *a, const char *b, const char *c, const char *d)
46{
47 char cmd[16384]; snprintf(cmd, sizeof cmd, fmt, a, b, c, d);
48 return system(cmd);
49}
50
51static char *slurp(const char *path)
52{
53 FILE *fp = fopen(path, "rb"); if (!fp) return NULL;
54 char *buf = malloc(1 << 20); size_t n = fread(buf, 1, (1 << 20) - 1, fp); buf[n] = 0; fclose(fp); return buf;
55}
56
57/* Random-walk + noise series with known q, r; optional damage. Writes the
58 * dir with machine-state.ndjson, machine-state-marks.txt and SHA256SUMS. */
59static void make_series(const char *dir, size_t n, double q, double r, uint64_t seed, int damage)
60{
61 char p[1024];
62 sh("rm -rf %s && mkdir -p %s", dir, dir, "", "");
63 snprintf(p, sizeof p, "%s/machine-state.ndjson", dir);
64 FILE *fp = fopen(p, "wb");
65 g_rng = seed; double x = 45000.0; long long wall = 1790000000ll; int extra = 0;
66 for (size_t i = 0; i < n; i++) {
67 x += sqrt(q) * gauss();
68 double z = floor(x + sqrt(r) * gauss() + 0.5);
69 if (damage && i == 100) extra = 2; /* a 3 s gap */
70 long long t = wall + (long long)i + extra;
71 int jit = (int)(rnd() % 3000000); /* 0..3 ms jitter */
72 if (damage && i == 0) fprintf(fp, "garbage line\n");
73 else if (damage && i == 50) fprintf(fp, "{\"t\":%lld.%09d,\"thermal_mc\":\"nan 1 2 \"}\n", t, jit);
74 else if (damage && i == 51) fprintf(fp, "{\"t\":%lld.%09d,\"spbm_uj\":1}\n", t, jit);
75 else if (damage && i == 52) fprintf(fp, "not json at all\n");
76 else fprintf(fp, "{\"t\":%lld.%09d,\"spbm_uj\":%zu,\"thermal_mc\":\"%.0f 30000 \",\"gpu\":\"x\"}\n", t, jit, i, z);
77 }
78 fclose(fp);
79 snprintf(p, sizeof p, "%s/machine-state-marks.txt", dir);
80 fp = fopen(p, "wb");
81 fprintf(fp, "%lld.000000001 begin trial-1.jsonl\n%lld.000000001 end trial-1.jsonl exit 0\n",
82 wall + (long long)(n / 5), wall + (long long)(n * 3 / 5));
83 fclose(fp);
84 char h1[65], h2[65], a[1024], b[1024];
85 snprintf(a, sizeof a, "%s/machine-state.ndjson", dir); snprintf(b, sizeof b, "%s/machine-state-marks.txt", dir);
86 est_sha_file_hex(a, h1); est_sha_file_hex(b, h2);
87 snprintf(p, sizeof p, "%s/SHA256SUMS", dir);
88 fp = fopen(p, "wb");
89 fprintf(fp, "%s machine-state.ndjson\n%s machine-state-marks.txt\n", h1, h2);
90 fclose(fp);
91}
92
93static int step_bits_equal(const est_step *a, const est_step *b)
94{
95 return a->line == b->line && a->coast == b->coast && a->t_ns == b->t_ns && a->horizon == b->horizon
96 && memcmp(&a->z, &b->z, 8) == 0 && memcmp(&a->y_mean, &b->y_mean, 8) == 0
97 && memcmp(&a->S, &b->S, 8) == 0 && memcmp(&a->nu, &b->nu, 8) == 0 && memcmp(&a->nis, &b->nis, 8) == 0
98 && memcmp(&a->obs_d, &b->obs_d, 32) == 0 && memcmp(&a->pred_d, &b->pred_d, 32) == 0
99 && memcmp(&a->innov_d, &b->innov_d, 32) == 0 && memcmp(&a->belief_d, &b->belief_d, 32) == 0
100 && memcmp(a->post.x, b->post.x, sizeof a->post.x) == 0 && memcmp(a->post.P, b->post.P, sizeof a->post.P) == 0;
101}
102
103static void test_prefix_run_a(void)
104{
105 est_file f; char err[300];
106 CHECK(est_file_load(RUN_A_DIR "/machine-state.ndjson", &f, err, sizeof err) == 0);
107 CHECK(strcmp(f.sha_hex, EST_RUN_A_SHA) == 0);
108 static est_replay full, pre;
109 size_t ks[3] = { 100, 500, 1000 };
110 int all = 1;
111 for (int m = 0; m < 2; m++) {
112 CHECK(est_replay_run(&f, (size_t)-1, m, 100.0, 10000.0, &full) == 0);
113 CHECK(full.nsteps + full.leading_missing == f.nlines);
114 for (int ki = 0; ki < 3; ki++) {
115 CHECK(est_replay_run(&f, ks[ki], m, 100.0, 10000.0, &pre) == 0);
116 CHECK(pre.nsteps == ks[ki] - pre.leading_missing);
117 for (size_t i = 0; i < pre.nsteps; i++) if (!step_bits_equal(&pre.steps[i], &full.steps[i])) all = 0;
118 }
119 for (size_t i = 0; i < full.nsteps; i++) CHECK(full.steps[i].chain_ok);
120 }
121 CHECK(all);
122 printf("test_est_tools: prefix invariance on run A, k=100,500,1000, M0 and M1: %s\n", all ? "PASS" : "FAIL");
123 est_replay_free(&full); est_replay_free(&pre); est_file_free(&f);
124}
125
126static void test_coasting(void)
127{
128 char dir[1024]; snprintf(dir, sizeof dir, "%s/coast", g_work);
129 make_series(dir, 300, 30.0, 3000.0, 7, 1);
130 char path[1100]; snprintf(path, sizeof path, "%s/machine-state.ndjson", dir);
131 est_file f; char err[300];
132 CHECK(est_file_load(path, &f, err, sizeof err) == 0);
133 static est_replay rp;
134 CHECK(est_replay_run(&f, (size_t)-1, 0, 30.0, 3000.0, &rp) == 0);
135 CHECK(rp.leading_missing == 1);
136 CHECK(rp.coasts == 3);
137 CHECK(rp.bad_value == 4);
138 CHECK(rp.nsteps == 299);
139 /* steps: index = line - 1; lines 50,51,52 coast */
140 CHECK(rp.steps[49].coast && rp.steps[50].coast && rp.steps[51].coast);
141 CHECK(!rp.steps[48].coast && !rp.steps[52].coast);
142 CHECK(rp.steps[52].horizon == 1);
143 CHECK(rp.steps[98].horizon == 1 && rp.steps[99].horizon == 3);
144 CHECK(rp.steps[99].t_ns == rp.steps[98].t_ns + 3000000000ll);
145 /* coasting inflates uncertainty: variance after 3 coasts exceeds before */
146 CHECK(rp.steps[51].post.P[0] > rp.steps[48].post.P[0]);
147 CHECK(est_digest_is_zero(&rp.steps[50].obs_d) && !est_digest_is_zero(&rp.steps[50].pred_d));
148 CHECK(rp.steps[50].chain_ok);
149 printf("test_est_tools: missing-value coasting: leading=%zu coasted=%zu steps=%zu PASS\n", rp.leading_missing, rp.coasts, rp.nsteps);
150 est_replay_free(&rp); est_file_free(&f);
151}
152
153static void test_sha_refusal(void)
154{
155 char dir[1024]; snprintf(dir, sizeof dir, "%s/sha", g_work);
156 make_series(dir, 200, 30.0, 3000.0, 11, 0);
157 char path[1100]; snprintf(path, sizeof path, "%s/machine-state.ndjson", dir);
158 est_file f; char err[300] = "";
159 CHECK(est_file_load(path, &f, err, sizeof err) == 0);
160 est_file_free(&f);
161 FILE *fp = fopen(path, "r+b"); fseek(fp, 20, SEEK_SET); int c = fgetc(fp); fseek(fp, 20, SEEK_SET);
162 fputc(c == '5' ? '6' : '5', fp); fclose(fp);
163 CHECK(est_file_load(path, &f, err, sizeof err) != 0);
164 CHECK(strstr(err, "mismatch") != NULL);
165 char out[1100], par[1100];
166 snprintf(out, sizeof out, "%s/sha/params", g_work);
167 CHECK(sh_rc("%s --synthetic-test %s %s >/dev/null 2>&1", g_fit, path, out, "") != 0);
168 /* a file with no SHA256SUMS line is refused too */
169 snprintf(par, sizeof par, "%s/sha/other.ndjson", g_work);
170 sh("cp %s %s", path, par, "", "");
171 CHECK(est_file_load(par, &f, err, sizeof err) != 0);
172 printf("test_est_tools: SHA-256 mismatch and missing-SUMS refusal (%s) PASS\n", err);
173}
174
175static double param_val(const char *txt, const char *tag, const char *key)
176{
177 const char *p = strstr(txt, tag); if (!p) return NAN;
178 p = strstr(p, key); if (!p) return NAN;
179 return atof(p + strlen(key));
180}
181
182static void test_synthetic(void)
183{
184 char d1[1024], d2[1024], par[1100], rec[1100], f1[1100], f2[1100], m2[1100], cmd[16384];
185 snprintf(d1, sizeof d1, "%s/synth-fit", g_work); snprintf(d2, sizeof d2, "%s/synth-eval", g_work);
186 double q = pow(10.0, 1.5), r = pow(10.0, 3.5);
187 make_series(d1, 5000, q, r, 101, 0);
188 make_series(d2, 4000, q, r, 202, 0);
189 snprintf(f1, sizeof f1, "%s/machine-state.ndjson", d1); snprintf(f2, sizeof f2, "%s/machine-state.ndjson", d2);
190 snprintf(m2, sizeof m2, "%s/machine-state-marks.txt", d2);
191 snprintf(par, sizeof par, "%s/params.txt", d1); snprintf(rec, sizeof rec, "%s/receipt.json", d2);
192 CHECK(sh_rc("%s --synthetic-test %s %s >/dev/null 2>&1", g_fit, f1, par, "") == 0);
193 est_params p; CHECK(est_params_read(par, &p) == 0);
194 double dq = fabs(log10(p.q[0]) - 1.5), dr = fabs(log10(p.r[0]) - 3.5);
195 CHECK(dq <= 0.5 + 1e-9);
196 CHECK(dr <= 0.25 + 1e-9);
197 printf("test_est_tools: synthetic fit M0 true q=%.4g r=%.4g, fitted q=%.4g r=%.4g (grid steps %.1f, %.1f) %s\n",
198 q, r, p.q[0], p.r[0], dq / 0.5, dr / 0.25, (dq <= 0.5 + 1e-9 && dr <= 0.25 + 1e-9) ? "PASS" : "FAIL");
199 /* eval on an independent series with the same true q, r */
200 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s --synthetic-test >%s/eval.out 2>&1",
201 g_eval, par, f2, m2, rec, d2);
202 CHECK(system(cmd) == 0);
203 char *js = slurp(rec); CHECK(js != NULL);
204 if (js) {
205 const char *m0 = strstr(js, "\"M0\": {");
206 CHECK(m0 != NULL);
207 const char *cal = m0 ? strstr(m0, "\"calibrated\":") : NULL;
208 CHECK(cal && strncmp(cal + 14, "true", 4) == 0);
209 CHECK(strstr(js, "\"ESTIMATION_REAL_SIGNAL\": \"PASS\"") != NULL);
210 CHECK(strstr(js, "\"ESTIMATION_CALIBRATION\": \"PASS\"") != NULL);
211 CHECK(strstr(js, "\"selected_model\": \"M0\"") != NULL);
212 CHECK(strstr(js, "\"recorded\": false") != NULL);
213 CHECK(strstr(js, "\"protocol_commit\": \"" EST_PROTOCOL_COMMIT "\"") != NULL);
214 double c95 = m0 ? param_val(m0, "coverage_95", "\"value\": ") : NAN;
215 printf("test_est_tools: synthetic eval, right model: 95%% coverage %.4f, M0 calibrated PASS\n", c95);
216 free(js);
217 }
218 /* (c) deliberately wrong observation noise: r far too small */
219 char bad[1100]; snprintf(bad, sizeof bad, "%s/params-bad.txt", d1);
220 p.r[0] = 1.0; p.r[1] = 1.0;
221 CHECK(est_params_write(bad, &p) == 0);
222 snprintf(rec, sizeof rec, "%s/receipt-bad.json", d2);
223 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s --synthetic-test >%s/eval-bad.out 2>&1",
224 g_eval, bad, f2, m2, rec, d2);
225 CHECK(system(cmd) == 0);
226 js = slurp(rec); CHECK(js != NULL);
227 if (js) {
228 const char *m0 = strstr(js, "\"M0\": {");
229 const char *cal = m0 ? strstr(m0, "\"calibrated\":") : NULL;
230 CHECK(cal && strncmp(cal + 14, "false", 5) == 0);
231 CHECK(strstr(js, "\"ESTIMATION_CALIBRATION\": \"FAIL\"") != NULL);
232 CHECK(strstr(js, "\"failed_criteria\": [\"coverage_50\"") != NULL);
233 printf("test_est_tools: synthetic eval, wrong r: ESTIMATION_CALIBRATION FAIL as expected, M0 95%% coverage %.4f\n",
234 m0 ? param_val(m0, "coverage_95", "\"value\": ") : NAN);
235 free(js);
236 }
237 /* eval refuses non-run-A parameters without --synthetic-test */
238 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s/x.json >/dev/null 2>&1", g_eval, par, f2, m2, d2);
239 CHECK(system(cmd) != 0);
240}
241
242
243/* value of the first number after `key` following `scope` (or from the start) */
244static double jv(const char *js, const char *scope, const char *key)
245{
246 const char *p = scope ? strstr(js, scope) : js; if (!p) return NAN;
247 p = strstr(p, key); if (!p) return NAN;
248 return atof(p + strlen(key));
249}
250static int near(double a, double b) { return fabs(a - b) <= 1e-9 * (1.0 + fabs(b)); }
251
252static void test_run_a_and_flags(void)
253{
254 char par[4096], rec[4096], cmd[16384], fake[4096];
255 snprintf(par, sizeof par, "%s/paramsA.txt", g_work);
256 snprintf(cmd, sizeof cmd, "%s %s %s > %s/fitA.out 2> %s/fitA.err", g_fit, RUN_A_DIR "/machine-state.ndjson", par, g_work, g_work);
257 CHECK(system(cmd) == 0);
258 est_params p; CHECK(est_params_read(par, &p) == 0);
259 CHECK(strcmp(p.fit_sha, EST_RUN_A_SHA) == 0);
260 printf("test_est_tools: run A fit: M0 q=%.17g r=%.17g | M1 q=%.17g r=%.17g\n", p.q[0], p.r[0], p.q[1], p.r[1]);
261 /* eval on run A (test use): receipt, both streams, and the stream digests in the receipt */
262 snprintf(rec, sizeof rec, "%s/receiptA.json", g_work);
263 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s > %s/evalA.out 2>&1",
264 g_eval, par, RUN_A_DIR "/machine-state.ndjson", RUN_A_DIR "/machine-state-marks.txt", rec, g_work);
265 CHECK(system(cmd) == 0);
266 char *js = slurp(rec); CHECK(js != NULL);
267 if (js) {
268 CHECK(strstr(js, "\"recorded\": false") != NULL);
269 CHECK(strstr(js, "\"fit_file_is_run_A\": true") != NULL);
270 CHECK(strstr(js, "\"fit_sha_matches_run_A_SHA256SUMS_line\": true") != NULL);
271 CHECK(strstr(js, "\"ESTIMATION_REAL_SIGNAL\": \"PASS\"") != NULL);
272 CHECK(strstr(js, "\"protocol_doc_matches_frozen_constant\": true") != NULL);
273 CHECK(strstr(js, "\"prefix_invariance\": {\"method\": \"first k lines physically written") != NULL);
274 CHECK(strstr(js, "\"runs\": 3, \"pass\": true") != NULL);
275 for (int m = 0; m < 2; m++) {
276 char sp[4096], hx[65], want[200];
277 snprintf(sp, sizeof sp, "%s.M%d.stream", rec, m);
278 CHECK(est_sha_file_hex(sp, hx) == 0);
279 snprintf(want, sizeof want, "\"sha256\": \"%s\"", hx);
280 CHECK(strstr(js, want) != NULL);
281 char *st = slurp(sp);
282 CHECK(st && strstr(st, " obs=") && strstr(st, "innov=") && strstr(st, "pred="));
283 free(st);
284 }
285 free(js);
286 }
287 printf("test_est_tools: run A eval writes receipt + M0/M1 streams with digests in one run PASS\n");
288 /* existing outputs are never overwritten */
289 CHECK(system(cmd) != 0);
290 /* --recorded is refused for anything that is not run B (run A here) */
291 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --recorded --out %s/rec-on-A.json >/dev/null 2>&1",
292 g_eval, par, RUN_A_DIR "/machine-state.ndjson", RUN_A_DIR "/machine-state-marks.txt", g_work);
293 CHECK(system(cmd) != 0);
294 snprintf(cmd, sizeof cmd, "test ! -e %s/rec-on-A.json", g_work);
295 CHECK(system(cmd) == 0);
296 printf("test_est_tools: receipt/stream files are exclusive-create; --recorded refused on run A PASS\n");
297
298 /* run-B guards, without any run B data. (1) path with the B id */
299 snprintf(fake, sizeof fake, "%s/raw/x-%s-silicon/machine-state.ndjson", g_work, EST_RUN_B_ID);
300 CHECK(sh_rc("%s %s %s/none >/dev/null 2>&1", g_fit, fake, g_work, "") != 0);
301 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s/nb.json >/dev/null 2>&1", g_eval, par, fake, fake, g_work);
302 CHECK(system(cmd) != 0);
303 snprintf(cmd, sizeof cmd, "test ! -e %s/nb.json", g_work);
304 CHECK(system(cmd) == 0);
305 /* (2) relative path and symlink into a directory named for B: resolved components decide */
306 char d[4096]; snprintf(d, sizeof d, "%s/bdir/20260929T025735Z-%s-silicon", g_work, EST_RUN_B_ID);
307 sh("mkdir -p %s && cp %s/machine-state.ndjson %s/", d, RUN_A_DIR, d, "");
308 sh("cp %s/SHA256SUMS %s/SHA256SUMS", RUN_A_DIR, d, "", "");
309 snprintf(cmd, sizeof cmd, "cd %s && %s --synthetic-test machine-state.ndjson %s/relB.params >/dev/null 2>&1", d, g_fit, g_work);
310 CHECK(system(cmd) != 0);
311 snprintf(cmd, sizeof cmd, "cd %s && %s --params %s --raw machine-state.ndjson --marks machine-state.ndjson --out %s/relB.json >/dev/null 2>&1", d, g_eval, par, g_work);
312 CHECK(system(cmd) != 0);
313 sh("ln -sfn %s %s/linkB", d, g_work, "", "");
314 snprintf(cmd, sizeof cmd, "%s --synthetic-test %s/linkB/machine-state.ndjson %s/linkB.params >/dev/null 2>&1", g_fit, g_work, g_work);
315 CHECK(system(cmd) != 0);
316 /* (3) a copy in an innocent directory whose SHA256SUMS line carries B's digest */
317 snprintf(d, sizeof d, "%s/copyB", g_work);
318 sh("rm -rf %s && mkdir -p %s", d, d, "", "");
319 snprintf(cmd, sizeof cmd, "cp %s/machine-state.ndjson %s/machine-state.ndjson && echo '%s machine-state.ndjson' > %s/SHA256SUMS",
320 RUN_A_DIR, d, EST_RUN_B_RAW_SHA_DEFAULT, d);
321 CHECK(system(cmd) == 0);
322 snprintf(cmd, sizeof cmd, "%s --synthetic-test %s/machine-state.ndjson %s/copyB.params >/dev/null 2>&1", g_fit, d, g_work);
323 CHECK(system(cmd) != 0);
324 snprintf(cmd, sizeof cmd, "%s/est_replay 0 100 1000 %s/machine-state.ndjson >/dev/null 2>&1", g_work, d);
325 est_file lf; char err[300];
326 CHECK(est_file_load(RUN_A_DIR "/machine-state.ndjson", &lf, err, sizeof err) == 0); est_file_free(&lf);
327 char cpath[4096]; snprintf(cpath, sizeof cpath, "%s/machine-state.ndjson", d);
328 CHECK(est_file_load(cpath, &lf, err, sizeof err) != 0);
329 CHECK(strstr(err, "run B") != NULL);
330 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s/copyB.json >/dev/null 2>&1", g_eval, par, cpath, cpath, g_work);
331 CHECK(system(cmd) != 0);
332 /* est_fit refuses a non-run-A file unless --synthetic-test */
333 snprintf(cmd, sizeof cmd, "%s %s/synth-eval/machine-state.ndjson %s/notA.params >/dev/null 2>&1", g_fit, g_work, g_work);
334 CHECK(system(cmd) != 0);
335 printf("test_est_tools: run B refused by resolved path, relative path, symlink and SUMS digest (fit, eval, replay lib) PASS\n");
336}
337
338/* --recorded end to end with the test build, on a synthetic directory standing in for run B */
339static void test_recorded_path(void)
340{
341 char d[4096], par[4096], cmd[16384], rec[4096], marks[4096], raw[4096], hx1[65], hx2[65];
342 snprintf(d, sizeof d, "%s/rb/synthB-silicon", g_work);
343 make_series(d, 3000, 100.0, 3000.0, 909, 0);
344 snprintf(raw, sizeof raw, "%s/machine-state.ndjson", d); snprintf(marks, sizeof marks, "%s/machine-state-marks.txt", d);
345 est_sha_file_hex(raw, hx1); est_sha_file_hex(marks, hx2);
346 snprintf(par, sizeof par, "%s/paramsA.txt", g_work);
347 snprintf(rec, sizeof rec, "%s/rb/receiptB.json", g_work);
348 char envs[512];
349 snprintf(envs, sizeof envs, "EST_TEST_B_ID=synthB EST_TEST_B_RAW_SHA=%s EST_TEST_B_MARKS_SHA=%s", hx1, hx2);
350 /* not recorded: refused */
351 snprintf(cmd, sizeof cmd, "%s %s --params %s --raw %s --marks %s --out %s/rb/x0.json >/dev/null 2>&1", envs, g_evalt, par, raw, marks, g_work);
352 CHECK(system(cmd) != 0);
353 /* recorded, dirty tree: refused */
354 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=1 %s --params %s --raw %s --marks %s --recorded --out %s/rb/x1.json >/dev/null 2>&1", envs, g_evalt, par, raw, marks, g_work);
355 CHECK(system(cmd) != 0);
356 /* recorded, synthetic fit params (not run A): refused */
357 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=0 %s --params %s/synth-fit/params.txt --raw %s --marks %s --recorded --out %s/rb/x2.json >/dev/null 2>&1", envs, g_evalt, g_work, raw, marks, g_work);
358 CHECK(system(cmd) != 0);
359 /* recorded, clean, run A fit: one execution gives receipt + streams */
360 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=0 %s --params %s --raw %s --marks %s --recorded --out %s > %s/rb/out.txt 2>&1", envs, g_evalt, par, raw, marks, rec, g_work);
361 CHECK(system(cmd) == 0);
362 char *js = slurp(rec); CHECK(js != NULL);
363 if (js) {
364 CHECK(strstr(js, "\"recorded\": true") != NULL);
365 CHECK(strstr(js, "\"tool_commit\": \"test-build\"") != NULL);
366 CHECK(strstr(js, "\"tool_dirty\": 0") != NULL);
367 CHECK(strstr(js, "\"fit_file_is_run_A\": true") != NULL);
368 CHECK(strstr(js, "\"ESTIMATION_REAL_SIGNAL\": \"PASS\"") != NULL);
369 char want[200];
370 snprintf(want, sizeof want, "\"marks_file_sha256\": \"%s\"", hx2); CHECK(strstr(js, want) != NULL);
371 snprintf(want, sizeof want, "\"input_file_sha256\": \"%s\"", hx1); CHECK(strstr(js, want) != NULL);
372 CHECK(strstr(js, "\"eval_binary_sha256\": \"") != NULL && !strstr(js, "\"eval_binary_sha256\": \"unavailable\""));
373 CHECK(strstr(js, "\"interpretations_sha256\": \"") != NULL && !strstr(js, "\"interpretations_sha256\": \"unavailable\""));
374 for (int m = 0; m < 2; m++) {
375 char sp[4096], hx[65];
376 snprintf(sp, sizeof sp, "%s.M%d.stream", rec, m);
377 CHECK(est_sha_file_hex(sp, hx) == 0);
378 snprintf(want, sizeof want, "\"sha256\": \"%s\"", hx); CHECK(strstr(js, want) != NULL);
379 }
380 free(js);
381 }
382 /* second recorded execution: refused, nothing overwritten */
383 char before[65], after[65];
384 est_sha_file_hex(rec, before);
385 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=0 %s --params %s --raw %s --marks %s --recorded --out %s >/dev/null 2>&1", envs, g_evalt, par, raw, marks, rec);
386 CHECK(system(cmd) != 0);
387 est_sha_file_hex(rec, after);
388 CHECK(strcmp(before, after) == 0);
389 /* a recorded run whose marks file is not B's marks: refused */
390 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=0 %s --params %s --raw %s --marks %s/synth-eval/machine-state-marks.txt --recorded --out %s/rb/x3.json >/dev/null 2>&1", envs, g_evalt, par, raw, g_work, g_work);
391 CHECK(system(cmd) != 0);
392 printf("test_est_tools: --recorded end to end (test build): streams+digests in one run, dirty/non-A/second-run/wrong-marks refused PASS\n");
393}
394
395static void test_params_validation(void)
396{
397 char pth[4096]; est_params p; char err[200];
398 snprintf(pth, sizeof pth, "%s/pv.txt", g_work);
399 memset(&p, 0, sizeof p);
400 snprintf(p.fit_path, sizeof p.fit_path, "x/%s/machine-state.ndjson", EST_RUN_A_ID);
401 memset(p.fit_sha, 'a', 64);
402 for (int m = 0; m < 2; m++) { p.q[m] = est_grid_q(8); p.r[m] = est_grid_r(10); p.ll[m] = -1.0; }
403 CHECK(est_params_write(pth, &p) == 0);
404 est_params q; CHECK(est_params_read(pth, &q) == 0);
405 CHECK(est_params_validate(&q, err, sizeof err) == 0);
406 p.q[0] = 12.0; /* off grid */
407 CHECK(est_params_write(pth, &p) == 0 && est_params_read(pth, &q) == 0 && est_params_validate(&q, err, sizeof err) != 0);
408 p.q[0] = est_grid_q(8); p.r[1] = NAN;
409 CHECK(est_params_write(pth, &p) == 0 && est_params_read(pth, &q) == 0 && est_params_validate(&q, err, sizeof err) != 0);
410 p.r[1] = est_grid_r(10); CHECK(est_params_write(pth, &p) == 0);
411 sh("echo 'extra_key 1' >> %s", pth, "", "", "");
412 CHECK(est_params_read(pth, &q) != 0); /* unexpected extra key */
413 CHECK(est_params_write(pth, &p) == 0);
414 sh("sed -i '/^fit_lines/d' %s", pth, "", "", "");
415 CHECK(est_params_read(pth, &q) != 0); /* missing key */
416 printf("test_est_tools: parameter file: exact keys, finite, on the protocol grid PASS\n");
417}
418
419static void test_fit_tie_break(void)
420{
421 static double ll[EST_NQ][EST_NR];
422 for (int i = 0; i < EST_NQ; i++) for (int j = 0; j < EST_NR; j++) ll[i][j] = -100.0 - i - j;
423 ll[5][7] = -3.0; ll[5][9] = -3.0; ll[7][2] = -3.0; ll[7][7] = -3.0; /* four-way tie */
424 int bi = -1, bj = -1;
425 CHECK(est_fit_pick((const double (*)[EST_NR])ll, &bi, &bj) == 0);
426 CHECK(bi == 5 && bj == 7); /* smaller q, then smaller r */
427 ll[3][3] = NAN; ll[3][4] = INFINITY; /* non-finite never wins */
428 CHECK(est_fit_pick((const double (*)[EST_NR])ll, &bi, &bj) == 0 && bi == 5 && bj == 7);
429 printf("test_est_tools: fit tie-break keeps smaller q then smaller r PASS\n");
430}
431
432static void test_parse_and_gaps(void)
433{
434 int64_t t;
435 static const char ok[] = "{\"t\":1790000002.500000000,\"x\":1}";
436 CHECK(est_parse_t(ok, sizeof ok - 1, &t) == 0 && t == 1790000002500000000ll);
437 static const char big[] = "{\"t\":12345678901.000000000,\"x\":1}";
438 CHECK(est_parse_t(big, sizeof big - 1, &t) == 2);
439 static const char ov[] = "{\"t\":9999999999.000000000,\"x\":1}";
440 CHECK(est_parse_t(ov, sizeof ov - 1, &t) == 2);
441 static const char shortf[] = "{\"t\":1790000002.5,\"x\":1}";
442 CHECK(est_parse_t(shortf, sizeof shortf - 1, &t) != 0);
443 /* duplicate, backward and overflow t, and a parsable value with an unparsable t */
444 char dir[4096], path[4096];
445 snprintf(dir, sizeof dir, "%s/gaps", g_work);
446 sh("rm -rf %s && mkdir -p %s", dir, dir, "", "");
447 snprintf(path, sizeof path, "%s/g.ndjson", dir);
448 FILE *fp = fopen(path, "wb");
449 const char *ts[] = { "1790000000.000000000", "1790000001.000000000", "1790000001.000000000", "1790000000.000000000",
450 "1790000001.000000000", "99999999999.000000000", "1790000003.000000000" };
451 for (int i = 0; i < 7; i++) fprintf(fp, "{\"t\":%s,\"thermal_mc\":\"%d 1 \"}\n", ts[i], 45000 + i);
452 fclose(fp);
453 est_file f; char err[300];
454 CHECK(est_file_load_raw(path, &f, err, sizeof err) == 0);
455 static est_replay rp;
456 CHECK(est_replay_run(&f, (size_t)-1, 0, 10.0, 100.0, &rp) == 0);
457 CHECK(rp.gap_zero == 1 && rp.gap_backward == 1);
458 CHECK(rp.bad_t == 1 && rp.bad_t_overflow == 1);
459 CHECK(rp.coasts == 1 && rp.steps[5].coast); /* t unparsable, value fine: still missing */
460 CHECK(rp.steps[2].horizon == 1 && rp.steps[3].horizon == 1);
461 CHECK(rp.steps[1].horizon == 1 && rp.multi_horizon == 0);
462 est_replay_free(&rp); est_file_free(&f);
463 printf("test_est_tools: t parsing (overflow, short fraction), duplicate/backward gaps, bad-t = missing PASS\n");
464}
465
466static void run_eval_ka(const char *tag, const char *marks_path, char *rec_out, size_t cap)
467{
468 char dir[4096], par[4096], raw[4096], cmd[8192];
469 snprintf(dir, sizeof dir, "%s/ka-%s", g_work, tag);
470 sh("rm -rf %s && mkdir -p %s", dir, dir, "", "");
471 snprintf(raw, sizeof raw, "%s/machine-state.ndjson", dir);
472 FILE *fp = fopen(raw, "wb");
473 for (int i = 0; i < 60; i++) fprintf(fp, "%s\n", KA_LINES[i]);
474 fclose(fp);
475 char h[65]; est_sha_file_hex(raw, h);
476 snprintf(cmd, sizeof cmd, "%s/SHA256SUMS", dir);
477 fp = fopen(cmd, "wb"); fprintf(fp, "%s machine-state.ndjson\n", h); fclose(fp);
478 est_params p; memset(&p, 0, sizeof p);
479 snprintf(p.fit_path, sizeof p.fit_path, "synthetic/ka");
480 memset(p.fit_sha, 'b', 64);
481 for (int m = 0; m < 2; m++) { p.q[m] = est_grid_q(8); p.r[m] = est_grid_r(8); p.ll[m] = -1.0; }
482 snprintf(par, sizeof par, "%s/params.txt", dir);
483 est_params_write(par, &p);
484 snprintf(rec_out, cap, "%s/receipt.json", dir);
485 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s --synthetic-test >%s/out.txt 2>&1", g_eval, par, raw, marks_path, rec_out, dir);
486 CHECK(system(cmd) == 0);
487}
488
489#define NEAR(a, b) CHECK(near((a), (b)))
490static void check_ka_model(const char *js0, int m, const double *ex)
491{
492 /* ex: nis bias lag1 rmse persist logscore cov50 cov80 cov95 w50lo w50hi w80lo w80hi w95lo w95hi tcov tlo thi */
493 const char *js = strstr(js0, "\"models\":"); char sc[8]; snprintf(sc, sizeof sc, "\"M%d\": {", m);
494 const char *keys[] = { "\"mean_nis\": {\"value\": ", "\"standardized_bias\": {\"value\": ", "\"lag1_autocorr\": {\"value\": ",
495 "\"rmse_one_step\": ", "\"persistence_rmse\": ", "\"log_score_per_step\": " };
496 for (int i = 0; i < 6; i++) NEAR(jv(js, sc, keys[i]), ex[i]);
497 const char *cn[3] = { "coverage_50", "coverage_80", "coverage_95" };
498 for (int k = 0; k < 3; k++) {
499 char key[64]; snprintf(key, sizeof key, "\"%s\": {\"value\": ", cn[k]);
500 NEAR(jv(js, sc, key), ex[6 + k]);
501 const char *p = strstr(strstr(js, sc), key); p = strstr(p, "wilson95\": [");
502 NEAR(atof(p + 12), ex[9 + 2 * k]);
503 NEAR(atof(strchr(p + 12, ',') + 1), ex[10 + 2 * k]);
504 }
505 NEAR(jv(js, sc, "\"ten_step_coverage95\": {\"n\": "), 16.0);
506 const char *tp = strstr(strstr(js, sc), "\"ten_step_coverage95\"");
507 NEAR(jv(tp, NULL, "\"value\": "), ex[15]);
508 const char *wp = strstr(tp, "wilson95\": [");
509 NEAR(atof(wp + 12), ex[16]);
510 NEAR(atof(strchr(wp + 12, ',') + 1), ex[17]);
511}
512
513static void test_known_answers(void)
514{
515 char rec[4096], mk[4096];
516 snprintf(mk, sizeof mk, "%s/ka-marks", g_work);
517 sh("rm -rf %s && mkdir -p %s", mk, mk, "", "");
518 char mp[4096]; snprintf(mp, sizeof mp, "%s/machine-state-marks.txt", mk);
519 FILE *fp = fopen(mp, "wb");
520 fprintf(fp, "1790000032.000000000 begin trial-ka.jsonl\n1790000047.500000000 end trial-ka.jsonl exit 0\n");
521 fclose(fp);
522 char h[65]; est_sha_file_hex(mp, h);
523 char sp[4096]; snprintf(sp, sizeof sp, "%s/SHA256SUMS", mk);
524 fp = fopen(sp, "wb"); fprintf(fp, "%s machine-state-marks.txt\n", h); fclose(fp);
525 run_eval_ka("a", mp, rec, sizeof rec);
526 char *js = slurp(rec); CHECK(js != NULL);
527 if (!js) return;
528 /* values from an independent scalar / 2x2 Kalman oracle written outside the repo */
529 static const double m0[18] = { 2.086259463846454, 0.06467032815179131, -0.02771647957840814, 17.05425813763435,
530 20.979581910582898, -4.4320995834844865, 0.2857142857142857, 0.6071428571428571, 0.8928571428571429,
531 0.15253995979312637, 0.47059288582378966, 0.42409044159980325, 0.7643431355917387, 0.7280414829086315,
532 0.962881633460356, 0.6875, 0.4440435565274821, 0.858353562348491 };
533 static const double m1[18] = { 1.8281515606971528, 0.016086778302452025, -0.179859160525074, 20.539325725342962,
534 20.979581910582898, -4.573313892158871, 0.32142857142857145, 0.5714285714285714, 0.8214285714285714,
535 0.179332468369093, 0.5066115696450038, 0.39070785495839777, 0.7349145298359636, 0.6440857505322257,
536 0.9212149810424002, 1.0, 0.8063923170025951, 1.0 };
537 check_ka_model(js, 0, m0);
538 check_ka_model(js, 1, m1);
539 /* counts: samples, quarters, regimes, coasts, gaps */
540 const char *s0 = strstr(strstr(js, "\"models\":"), "\"M0\": {");
541 NEAR(jv(s0, NULL, "\"samples\": "), 28.0);
542 const char *q0 = strstr(s0, "\"quarters_coverage95\"");
543 static const int qn[4] = { 6, 7, 7, 8 }, qh0[4] = { 5, 7, 6, 7 };
544 const char *p = q0;
545 for (int q = 0; q < 4; q++) {
546 p = strstr(p, "{\"n\": ");
547 NEAR(atof(p + 6), (double)qn[q]);
548 p = strstr(p, "\"value\": ");
549 NEAR(atof(p + 9), (double)qh0[q] / (double)qn[q]);
550 p += 9;
551 }
552 const char *r0 = strstr(s0, "\"idle\": {\"n\": ");
553 NEAR(atof(r0 + 14), 15.0); NEAR(jv(r0, NULL, "\"value\": "), 13.0 / 15.0);
554 const char *r1 = strstr(s0, "\"in_trial\": {\"n\": ");
555 NEAR(atof(r1 + 18), 13.0); NEAR(jv(r1, NULL, "\"value\": "), 12.0 / 13.0);
556 /* M1 regime and quarter hits */
557 const char *s1 = strstr(strstr(js, "\"models\":"), "\"M1\": {");
558 const char *r1i = strstr(s1, "\"idle\": {\"n\": "); NEAR(jv(r1i, NULL, "\"value\": "), 11.0 / 15.0);
559 const char *r1t = strstr(s1, "\"in_trial\": {\"n\": "); NEAR(jv(r1t, NULL, "\"value\": "), 12.0 / 13.0);
560 CHECK(strstr(js, "\"coasted\": 2,") != NULL);
561 CHECK(strstr(js, "\"bad_value_lines\": 1,") != NULL);
562 CHECK(strstr(js, "\"bad_t_lines\": 1,") != NULL);
563 CHECK(strstr(js, "\"steps_with_horizon_gt_1\": 1}") != NULL);
564 CHECK(strstr(js, "\"unclosed_begin_ran_to_eof\": false") != NULL);
565 NEAR(jv(js, "\"zero_innovation_fraction_extra\": ", "\"zero_innovation_fraction_extra\": "), 0.0);
566 /* included logical span 30..61 (2.5 s gap made line 35 a horizon-3 step) */
567 CHECK(strstr(s0, "\"included_logical_span_ns\": [30000000000, 61000000000]") != NULL);
568 free(js);
569 printf("test_est_tools: known-answer statistics (coverage, Wilson, NIS, bias, lag-1, RMSE, persistence, quarters, regimes, ten-step) match the independent oracle PASS\n");
570
571 /* unclosed begin runs to end of file and is reported */
572 snprintf(mk, sizeof mk, "%s/ka-marks2", g_work);
573 sh("rm -rf %s && mkdir -p %s", mk, mk, "", "");
574 snprintf(mp, sizeof mp, "%s/machine-state-marks.txt", mk);
575 fp = fopen(mp, "wb"); fprintf(fp, "1790000032.000000000 begin trial-ka.jsonl\n"); fclose(fp);
576 est_sha_file_hex(mp, h);
577 snprintf(sp, sizeof sp, "%s/SHA256SUMS", mk);
578 fp = fopen(sp, "wb"); fprintf(fp, "%s machine-state-marks.txt\n", h); fclose(fp);
579 run_eval_ka("b", mp, rec, sizeof rec);
580 js = slurp(rec); CHECK(js != NULL);
581 if (js) {
582 CHECK(strstr(js, "\"unclosed_begin_ran_to_eof\": true") != NULL);
583 CHECK(strstr(js, "\"begins\": 1, \"ends\": 0") != NULL);
584 const char *m0s = strstr(strstr(js, "\"models\":"), "\"M0\": {");
585 const char *ri = strstr(m0s, "\"idle\": {\"n\": "), *rt = strstr(m0s, "\"in_trial\": {\"n\": ");
586 NEAR(atof(ri + 14), 2.0); NEAR(atof(rt + 18), 26.0);
587 free(js);
588 }
589 printf("test_est_tools: unclosed begin runs to end of file and is reported PASS\n");
590}
591
592/* ---- protocol v2: noise shape, M2 fit/eval, held-out guard ---- */
593static void test_mix_known_answers(void)
594{
595 est_mix g = { 1, { 1.0 }, { 1.0 } };
596 double c, t, l;
597 CHECK(est_mix_cdf_abs(&g, 1, 1.959963984540054, &c) == EST_OK && fabs(c - 0.95) < 1e-12);
598 CHECK(est_mix_quantile_abs(&g, 1, 0.95, &t) == EST_OK && fabs(t - 1.959963984540054) < 1e-9);
599 CHECK(est_mix_quantile_abs(&g, 4, 0.95, &t) == EST_OK && fabs(t - 2.0 * 1.959963984540054) < 1e-9);
600 CHECK(est_mix_logpdf(&g, 1, 0.0, &l) == EST_OK && fabs(l + 0.5 * log(6.283185307179586)) < 1e-14);
601 est_mix m = { 2, { 0.5, 0.5 }, { 1.0, 4.0 } };
602 double want1 = 0.5 * erf(1.5 / sqrt(2.0)) + 0.5 * erf(1.5 / sqrt(8.0));
603 CHECK(est_mix_cdf_abs(&m, 1, 1.5, &c) == EST_OK && fabs(c - want1) < 1e-14);
604 /* two draws: variance 2 w.p. 1/4, 5 w.p. 1/2, 8 w.p. 1/4 */
605 double want2 = 0.25 * erf(3.0 / sqrt(4.0)) + 0.5 * erf(3.0 / sqrt(10.0)) + 0.25 * erf(3.0 / sqrt(16.0));
606 CHECK(est_mix_cdf_abs(&m, 2, 3.0, &c) == EST_OK && fabs(c - want2) < 1e-14);
607 double lw = log(0.25 * exp(-0.5 * (log(6.283185307179586 * 2.0) + 1.0 / 2.0)) + 0.5 * exp(-0.5 * (log(6.283185307179586 * 5.0) + 1.0 / 5.0))
608 + 0.25 * exp(-0.5 * (log(6.283185307179586 * 8.0) + 1.0 / 8.0)));
609 CHECK(est_mix_logpdf(&m, 2, 1.0, &l) == EST_OK && fabs(l - lw) < 1e-13);
610 CHECK(fabs(est_mix_total_var(&m) - 2.5) < 1e-15);
611 est_mix bad = { 2, { 0.5, 0.6 }, { 1.0, 4.0 } };
612 CHECK(est_mix_check(&bad) != EST_OK);
613 CHECK(est_mix_cdf_abs(&m, 0, 1.0, &c) != EST_OK && est_mix_cdf_abs(&m, EST_MIX_MAX_H + 1, 1.0, &c) != EST_OK);
614 /* EM recovers a known two-scale mixture; same input gives the same bits */
615 size_t n = 20000; double *e = malloc(n * sizeof *e);
616 g_rng = 777;
617 for (size_t i = 0; i < n; i++) e[i] = (unif() < 0.3 ? 10.0 : 1000.0) * gauss();
618 est_mix f1, f2; double l1, l2;
619 CHECK(est_mix_fit_em(e, n, 2, 1.0, 500, &f1, &l1) == EST_OK);
620 CHECK(est_mix_fit_em(e, n, 2, 1.0, 500, &f2, &l2) == EST_OK);
621 CHECK(memcmp(&f1, &f2, sizeof f1) == 0 && memcmp(&l1, &l2, sizeof l1) == 0);
622 CHECK(fabs(f1.w[0] - 0.3) < 0.02 && fabs(sqrt(f1.v[0]) - 10.0) < 1.0 && fabs(sqrt(f1.v[1]) - 1000.0) < 30.0);
623 free(e);
624 printf("test_est_tools: noise shape known answers and EM recovery (w0=%.3f sd=%.2f,%.1f)\n", f1.w[0], sqrt(f1.v[0]), sqrt(f1.v[1]));
625}
626
627/* Random walk whose steps have a three-scale shape, observed exactly to 1 mC. */
628static void make_mix_series(const char *dir, size_t n, uint64_t seed)
629{
630 char p[1024], a[1024], b[1024], h1[65], h2[65];
631 sh("rm -rf %s && mkdir -p %s", dir, dir, "", "");
632 snprintf(a, sizeof a, "%s/machine-state.ndjson", dir); snprintf(b, sizeof b, "%s/machine-state-marks.txt", dir);
633 FILE *fp = fopen(a, "wb");
634 g_rng = seed; double x = 45000.0; long long wall = 1790000000ll;
635 for (size_t i = 0; i < n; i++) {
636 double u = unif();
637 x = floor(x + (u < 0.4 ? 20.0 : (u < 0.8 ? 300.0 : 2000.0)) * gauss() + 0.5);
638 fprintf(fp, "{\"t\":%lld.%09d,\"thermal_mc\":\"%.0f 30000 \"}\n", wall + (long long)i, (int)(rnd() % 3000000), x);
639 }
640 fclose(fp);
641 fp = fopen(b, "wb"); fclose(fp); /* no trials, like the EST-3b collections */
642 est_sha_file_hex(a, h1); est_sha_file_hex(b, h2);
643 snprintf(p, sizeof p, "%s/SHA256SUMS", dir);
644 fp = fopen(p, "wb");
645 fprintf(fp, "%s machine-state.ndjson\n%s machine-state-marks.txt\n", h1, h2);
646 fclose(fp);
647}
648
649static void test_m2(void)
650{
651 char fd[1024], hd[1024], fr[1100], hr[1100], hm[1100], p2[1100], p2b[1100], rec[1100], v1[1100], cmd[16384], envs[1024];
652 char h1[65], h2[65], hf[65], hdoc[65];
653 snprintf(fd, sizeof fd, "%s/v2/s-est3b-fit-silicon", g_work);
654 snprintf(hd, sizeof hd, "%s/v2/s-est3b-heldout-silicon", g_work);
655 make_mix_series(fd, 4000, 4242);
656 make_mix_series(hd, 4000, 5353);
657 snprintf(fr, sizeof fr, "%s/machine-state.ndjson", fd);
658 snprintf(hr, sizeof hr, "%s/machine-state.ndjson", hd); snprintf(hm, sizeof hm, "%s/machine-state-marks.txt", hd);
659 snprintf(v1, sizeof v1, "%s/paramsA.txt", g_work); /* fit on run A by test_run_a_and_flags */
660 snprintf(p2, sizeof p2, "%s/v2/params2.txt", g_work); snprintf(p2b, sizeof p2b, "%s/v2/params2b.txt", g_work);
661 /* fit refuses the held-out run, by path, before opening it */
662 CHECK(sh_rc("%s --m2 --synthetic-test %s %s %s/v2/no.txt >/dev/null 2>&1", g_fit, hr, v1, g_work) != 0);
663 /* without --synthetic-test only run C1 (fixed SHA) is accepted */
664 CHECK(sh_rc("%s --m2 %s %s %s/v2/no.txt >/dev/null 2>&1", g_fit, fr, v1, g_work) != 0);
665 CHECK(sh_rc("%s --m2 --synthetic-test %s %s %s >/dev/null 2>&1", g_fit, fr, v1, p2) == 0);
666 CHECK(sh_rc("%s --m2 --synthetic-test %s %s %s >/dev/null 2>&1", g_fit, fr, v1, p2b) == 0);
667 sh("cmp -s %s %s || echo nondeterministic-fit > %s/v2/NONDET", p2, p2b, g_work, "");
668 snprintf(cmd, sizeof cmd, "%s/v2/NONDET", g_work);
669 FILE *nd = fopen(cmd, "r"); CHECK(nd == NULL); if (nd) fclose(nd);
670 /* persistence round trip: read then write gives the same bytes */
671 est_params2 pp; CHECK(est_params2_read(p2, &pp) == 0);
672 CHECK(pp.mix.k == EST_M2_K && pp.r == EST_M2_R && fabs(pp.q - est_mix_total_var(&pp.mix)) <= 1e-12 * pp.q);
673 snprintf(cmd, sizeof cmd, "%s/v2/params2c.txt", g_work);
674 CHECK(est_params2_write(cmd, &pp) == 0);
675 CHECK(sh_rc("cmp -s %s %s", p2, cmd, "", "") == 0);
676 sh("sed 's/^c2 w/c9 w/' %s > %s/v2/params2bad.txt", p2, g_work, "", "");
677 snprintf(cmd, sizeof cmd, "%s/v2/params2bad.txt", g_work);
678 CHECK(est_params2_read(cmd, &pp) != 0);
679 /* M2 replay mean is exactly the previous observation */
680 est_file f; char err[300]; static est_replay rp;
681 CHECK(est_file_load(fr, &f, err, sizeof err) == 0);
682 CHECK(est_params2_read(p2, &pp) == 0);
683 CHECK(est_replay_run(&f, (size_t)-1, 2, pp.q, pp.r, &rp) == 0);
684 double *e = malloc(rp.nsteps * sizeof *e);
685 CHECK(est_m2_changes(&rp, e, rp.nsteps) == pp.fit_n);
686 free(e); est_replay_free(&rp); est_file_free(&f);
687 /* held-out: v1 and v2 evaluation refuse it unless recorded */
688 snprintf(cmd, sizeof cmd, "%s --protocol-v2 --synthetic-test --params2 %s --raw %s --marks %s --out %s/v2/x.json 2>%s/v2/x.err", g_eval, p2, hr, hm, g_work, g_work);
689 CHECK(system(cmd) != 0);
690 snprintf(cmd, sizeof cmd, "%s --params %s --raw %s --marks %s --out %s/v2/y.json 2>%s/v2/y.err", g_eval, v1, hr, hm, g_work, g_work);
691 CHECK(system(cmd) != 0);
692 snprintf(cmd, sizeof cmd, "%s/v2/x.err", g_work); { char *t = slurp(cmd); CHECK(t && strstr(t, "held-out")); free(t); }
693 snprintf(cmd, sizeof cmd, "%s/v2/y.err", g_work); { char *t = slurp(cmd); CHECK(t && strstr(t, "held-out")); free(t); }
694 CHECK(est_file_load(hr, &f, err, sizeof err) != 0 && strstr(err, "held-out") != NULL);
695 /* recorded, test build: C2, C1, doc identities from the environment */
696 est_sha_file_hex(hr, h1); est_sha_file_hex(hm, h2); est_sha_file_hex(fr, hf);
697 snprintf(cmd, sizeof cmd, "%s/v2/doc.md", g_work);
698 sh("echo frozen-v2 > %s", cmd, "", "", ""); est_sha_file_hex(cmd, hdoc);
699 snprintf(envs, sizeof envs, "EST_TEST_C2_RAW_SHA=%s EST_TEST_C2_MARKS_SHA=%s EST_TEST_C1_SHA=%s EST_TEST_V2_DOC_SHA=%s", h1, h2, hf, hdoc);
700 snprintf(rec, sizeof rec, "%s/v2/receipt.json", g_work);
701 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=1 %s --protocol-v2 --params2 %s --raw %s --marks %s --protocol-doc %s/v2/doc.md --recorded --out %s/v2/z.json >/dev/null 2>&1", envs, g_evalt, p2, hr, hm, g_work, g_work);
702 CHECK(system(cmd) != 0);
703 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=0 %s --protocol-v2 --params2 %s --raw %s --marks %s --protocol-doc %s/v2/doc.md --recorded --out %s > %s/v2/eval.out 2>&1", envs, g_evalt, p2, hr, hm, g_work, rec, g_work);
704 CHECK(system(cmd) == 0);
705 char *js = slurp(rec); CHECK(js != NULL);
706 if (js) {
707 CHECK(strstr(js, "\"receipt\": \"est_eval_v2\"") != NULL);
708 CHECK(strstr(js, "\"recorded\": true") != NULL && strstr(js, "\"input_is_heldout_C2\": true") != NULL);
709 CHECK(strstr(js, "\"m2_mean_is_exact_persistence\": true") != NULL);
710 const char *mods = strstr(js, "\"models\": {");
711 const char *m2 = mods ? strstr(mods, "\"M2\": {") : NULL;
712 CHECK(m2 != NULL);
713 const char *cal = m2 ? strstr(m2, "\"calibrated\": ") : NULL;
714 CHECK(cal && strncmp(cal + 14, "true", 4) == 0);
715 CHECK(m2 && strstr(m2, "\"rmse_no_worse_than_persistence\": true") != NULL);
716 CHECK(strstr(js, "\"selected_model\": \"M2\"") != NULL);
717 CHECK(strstr(js, "\"ESTIMATION_REAL_SIGNAL\": \"PASS\"") != NULL);
718 CHECK(strstr(js, "\"ESTIMATION_CALIBRATION\": \"PASS\"") != NULL);
719 free(js);
720 }
721 /* a second recorded execution would overwrite: refused */
722 snprintf(cmd, sizeof cmd, "%s EST_TEST_DIRTY=0 %s --protocol-v2 --params2 %s --raw %s --marks %s --protocol-doc %s/v2/doc.md --recorded --out %s >/dev/null 2>&1", envs, g_evalt, p2, hr, hm, g_work, rec);
723 CHECK(system(cmd) != 0);
724 printf("test_est_tools: M2 fit deterministic, params v2 round trip, exact persistence, held-out guard, recorded v2 receipt\n");
725}
726
727int main(int argc, char **argv)
728{
729 if (argc != 5) { fprintf(stderr, "usage: test_est_tools est_fit est_eval est_eval_test_build workdir\n"); return 2; }
730 g_fit = argv[1]; g_eval = argv[2]; g_evalt = argv[3]; g_work = argv[4];
731 sh("mkdir -p %s", g_work, "", "", "");
732 test_prefix_run_a();
733 test_coasting();
734 test_sha_refusal();
735 test_synthetic();
736 test_run_a_and_flags();
737 test_recorded_path();
738 test_params_validation();
739 test_fit_tie_break();
740 test_parse_and_gaps();
741 test_known_answers();
742 test_mix_known_answers();
743 test_m2();
744 printf("test_est_tools: %d checks, %d failed\n", g_checks, g_fail);
745 if (g_fail) { printf("test_est_tools: FAIL\n"); return 1; }
746 printf("test_est_tools: PASS\n");
747 return 0;
748}