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 / tests / physics0 / learner / pd0_harness.c

321 lines · 29703 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/* PD-0 development harness for the learner (spec section 11 roles: the harness
18 * owns the split, the tags, the ledger and the scoring; the learner only sees
19 * FIT/SELECT records). Verifier-side build: links pd0_fmt/pd0_ladder/pd0_score/
20 * pd0_controls and the learner library, never the generators. The world and the
21 * truth are separate processes (build/physics0/pd0-world, pd0-truth).
22 * Usage: pd0-harness <world-bin> <truth-bin|-> <level|null> <seed> <out-dir>
23 * With "-" for the truth binary the world binary also answers the protocol v2 score and shape ops (external-world mode).
24 * Prints one PD0L result line; writes <out-dir>/pd0l-L<level>-s<seed>.{ledger,law,json}. */
25#include "pd0_learner.h"
26#include "pd0_ladder.h"
27#include "pd0_codes.h"
28#include "pd0_score.h"
29#include "pd0_controls.h"
30#include "pd0_rng.h"
31#include "sha256.h"
32#include <errno.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36#include <unistd.h>
37#include <sys/wait.h>
38
39#define EP_LEN 20u
40#define LCAP (64u << 20)
41#define MAX_EP 1024
42
43typedef struct { pid_t pid; int in, out; FILE *rd, *wr; } proc;
44static int spawn(proc *p, char *const argv[])
45{
46 int a[2], b[2]; if (pipe(a) || pipe(b)) return -1;
47 p->pid = fork(); if (p->pid < 0) return -1;
48 if (p->pid == 0) { dup2(a[0], 0); dup2(b[1], 1); close(a[0]); close(a[1]); close(b[0]); close(b[1]); execv(argv[0], argv); _exit(127); }
49 close(a[0]); close(b[1]); p->out = a[1]; p->in = b[0]; p->rd = fdopen(p->in, "r"); p->wr = fdopen(p->out, "w"); return 0;
50}
51static int rd_full(int fd, uint8_t *b, size_t n) { while (n) { ssize_t k = read(fd, b, n); if (k <= 0) return -1; b += k; n -= (size_t)k; } return 0; }
52static int wr_full(int fd, const uint8_t *b, size_t n) { while (n) { ssize_t k = write(fd, b, n); if (k <= 0) return -1; b += k; n -= (size_t)k; } return 0; }
53/* one framed world call; returns response length or 0 */
54static size_t world_call(proc *w, const uint8_t *req, size_t n, uint8_t *resp, size_t cap)
55{
56 uint8_t l4[4]; pd0_put_u32(l4, (uint32_t)n); if (wr_full(w->out, l4, 4) || wr_full(w->out, req, n) || rd_full(w->in, l4, 4)) return 0;
57 uint32_t rn = pd0_get_u32(l4); if (rn == 0 || rn > cap || rd_full(w->in, resp, rn)) return 0; return rn;
58}
59typedef struct { int version; pd0l_desc d; } describe;
60static int parse_describe(const uint8_t *b, size_t n, describe *D)
61{
62 memset(D, 0, sizeof *D); if (n < 10) return -1;
63 if (!memcmp(b, "PD0DESC2", 8)) D->version = 2; else return -1; /* PD0DESC1 (one reset pair) is refused */
64 pd0l_desc *d = &D->d; d->n_obs = b[8]; d->n_channels = b[9]; size_t o = 10; if (d->n_obs == 0 || d->n_obs > PD0_MAX_OBS || d->n_channels > PD0_MAX_CHAN) return -1;
65 size_t nr = d->n_obs; if (n < o + 8 + 16u * d->n_channels + 16u * nr + 12) return -1;
66 d->dt_micro = (int64_t)pd0_get_u64(b + o); o += 8;
67 for (int c = 0; c < d->n_channels; c++, o += 8) d->chan_min[c] = (int64_t)pd0_get_u64(b + o);
68 for (int c = 0; c < d->n_channels; c++, o += 8) d->chan_max[c] = (int64_t)pd0_get_u64(b + o);
69 int64_t mn[PD0_MAX_OBS], mx[PD0_MAX_OBS];
70 for (size_t j = 0; j < nr; j++, o += 8) mn[j] = (int64_t)pd0_get_u64(b + o);
71 for (size_t j = 0; j < nr; j++, o += 8) mx[j] = (int64_t)pd0_get_u64(b + o);
72 for (int j = 0; j < d->n_obs; j++) { d->reset_min[j] = mn[nr == 1 ? 0 : (size_t)j]; d->reset_max[j] = mx[nr == 1 ? 0 : (size_t)j]; }
73 d->episode_max_steps = pd0_get_u32(b + o); d->budget_steps = pd0_get_u32(b + o + 4); d->budget_episodes = pd0_get_u32(b + o + 8);
74 return 0;
75}
76
77/* ---- run state ---- */
78typedef struct {
79 describe D; int level; uint64_t seed; proc world, truth; int ext, sealed, dims_ok; int dims[4]; pd0_learner *L;
80 uint8_t *ledger; size_t llen; uint8_t last[PD0_HASH];
81 pd0_ladder_params P;
82 uint32_t next_episode, n_episodes, steps_used, episodes_used;
83 /* per episode bookkeeping: tag, schedule hash, record range */
84 uint8_t ep_tag[MAX_EP]; uint8_t ep_hash[MAX_EP][PD0_HASH]; uint32_t ep_first[MAX_EP], ep_n[MAX_EP]; int ep_ok[MAX_EP]; int ep_void[MAX_EP]; /* spec rev 7: TRIAL/REP ended OUT_OF_BOUNDS before the horizon */
85 pd0_rec *recs; uint32_t nrec;
86 pd0_transition *fit; uint32_t nfit;
87 /* truth */
88 pd0_rel truth_rel; int truth_size, truth_n_latent; int have_truth;
89 /* counters for the report */
90 uint32_t n_oob, n_refused, n_propose_fail, n_trial_random, n_attempts, n_budget, n_void_ep, n_void_batch;
91} run;
92
93static void append(run *R, uint8_t kind, const uint8_t *p, uint32_t n) { R->llen = pd0_ledg_append(R->ledger, R->llen, LCAP, kind, p, n, R->last); }
94static void tag(run *R, uint32_t ep, uint8_t t, uint32_t batch, uint8_t origin) { pd0_tag T = { ep, t, batch, origin }; uint8_t p[32]; append(R, LEDG_TAG, p, (uint32_t)pd0_tag_write(&T, p)); }
95
96/* one episode against the world: TAG first, then reset + steps; records go to the ledger, FIT/SELECT ones to the learner.
97 * returns the episode index (bookkeeping slot) or -1 on budget exhaustion */
98static int episode(run *R, uint8_t t, uint32_t batch, uint8_t origin, const int64_t *reset, const pd0_step *steps, uint32_t n)
99{
100 if (R->n_episodes >= MAX_EP) return -1;
101 uint32_t ep = R->next_episode; uint32_t slot = R->n_episodes; uint8_t req[128], resp[1024]; pd0_rec r;
102 tag(R, ep, t, batch, origin);
103 req[0] = 1; req[1] = R->D.d.n_obs; for (int j = 0; j < R->D.d.n_obs; j++) pd0_put_u64(req + 2 + 8 * j, (uint64_t)reset[j]);
104 size_t rn = world_call(&R->world, req, 2 + 8u * R->D.d.n_obs, resp, sizeof resp); if (!rn) { fprintf(stderr, "world: reset call failed\n"); exit(3); }
105 if (pd0_rec_parse(resp, rn, &r, NULL) != PD0V_OK) { fprintf(stderr, "world: bad reset record\n"); exit(3); }
106 if (r.status == PD0_ST_BUDGET_EXHAUSTED) { R->n_budget++; return -1; }
107 if (r.episode != ep) { fprintf(stderr, "harness: episode numbering drift (%u vs %u)\n", r.episode, ep); exit(3); }
108 R->next_episode = ep + 1; R->episodes_used++;
109 R->ep_tag[slot] = t; R->ep_first[slot] = R->nrec; R->ep_n[slot] = 0; R->ep_ok[slot] = 0; R->ep_void[slot] = 0; R->n_episodes++;
110 append(R, LEDG_OBS, resp, (uint32_t)rn); R->recs[R->nrec++] = r; R->ep_n[slot]++;
111 if (t == TAG_FIT || t == TAG_SELECT) pd0_learner_observe(R->L, &r, t);
112 if (r.status != PD0_ST_OK) { R->n_refused++; memset(R->ep_hash[slot], 0, PD0_HASH); return (int)slot; }
113 pd0_step applied[PD0_MAX_STEPS]; uint32_t n_ok = 0;
114 for (uint32_t s = 0; s < n; s++) {
115 req[0] = 2; req[1] = steps[s].channel; pd0_put_u64(req + 2, (uint64_t)steps[s].value);
116 rn = world_call(&R->world, req, 10, resp, sizeof resp); if (!rn) { fprintf(stderr, "world: step call failed\n"); exit(3); }
117 if (pd0_rec_parse(resp, rn, &r, NULL) != PD0V_OK) { fprintf(stderr, "world: bad step record\n"); exit(3); }
118 append(R, LEDG_OBS, resp, (uint32_t)rn); R->recs[R->nrec++] = r; R->ep_n[slot]++;
119 if (t == TAG_FIT || t == TAG_SELECT) pd0_learner_observe(R->L, &r, t);
120 if (r.status == PD0_ST_BUDGET_EXHAUSTED) { R->n_budget++; break; }
121 R->steps_used++;
122 if (r.status == PD0_ST_OK || r.status == PD0_ST_EPISODE_END) { if (n_ok < PD0_MAX_STEPS) { applied[n_ok].channel = r.channel; applied[n_ok].value = r.applied; } n_ok++;
123 if (t == TAG_FIT && R->nfit < 65536) { pd0_transition *f = &R->fit[R->nfit++]; memcpy(f->before, r.before, sizeof f->before); f->chan = r.channel; f->value = r.applied; memcpy(f->after, r.after, sizeof f->after); } }
124 if (r.status == PD0_ST_OUT_OF_BOUNDS) { R->n_oob++; if (t == TAG_TRIAL || t == TAG_REP) { R->ep_void[slot] = 1; R->n_void_ep++; } break; }
125 if (r.status == PD0_ST_REFUSED_RANGE) { R->n_refused++; continue; }
126 if (r.status == PD0_ST_EPISODE_END) break;
127 }
128 R->ep_ok[slot] = n_ok >= EP_LEN;
129 pd0_schedule_hash(R->D.d.n_obs, reset, (uint8_t)(n_ok < PD0_MAX_STEPS ? n_ok : PD0_MAX_STEPS), applied, R->ep_hash[slot]);
130 return (int)slot;
131}
132
133/* ---- truth process ---- */
134static int ext_rel(run *R);
135static int ext_episode(run *R, const int64_t *reset, const pd0_step *steps, uint32_t n, int64_t out[][PD0_MAX_OBS]);
136static int truth_rel(run *R)
137{
138 if (R->ext) return ext_rel(R);
139 fprintf(R->truth.wr, "rel\n"); fflush(R->truth.wr); char line[1024]; unsigned nv, nl, nc, ne; int sz, tsz;
140 if (!fgets(line, sizeof line, R->truth.rd) || sscanf(line, "rel %u %u %u %u %d %d", &nv, &nl, &nc, &ne, &sz, &tsz) != 6) return -1;
141 pd0_rel *t = &R->truth_rel; memset(t, 0, sizeof *t); t->n_vars = (uint8_t)nv; t->n_latent = (uint8_t)nl; t->n_channels = (uint8_t)nc; R->truth_size = tsz; R->truth_n_latent = (int)nl;
142 while (fgets(line, sizeof line, R->truth.rd) && strncmp(line, "end", 3)) { unsigned tg; long long coef; int off; if (sscanf(line, "term %u %lld%n", &tg, &coef, &off) != 2) return -1;
143 int e; for (e = 0; e < t->n_equations; e++) if (t->eq[e].target == tg) break; if (e == t->n_equations) { t->eq[t->n_equations++].target = (uint8_t)tg; }
144 pd0_eq *q = &t->eq[e]; int k = q->n_terms++; q->coef[k] = coef; char *p = line + off; for (unsigned i = 0; i < nv + nc; i++) q->expo[k][i] = (uint8_t)strtoul(p, &p, 10); }
145 t->description_bits = pd0_rel_bits(t); R->have_truth = 1; return 0;
146}
147/* noise-free truth trajectory; returns 1 if it stayed in bounds */
148static int truth_episode(run *R, const int64_t *reset, const pd0_step *steps, uint32_t n, int64_t out[][PD0_MAX_OBS])
149{
150 if (R->ext) return ext_episode(R, reset, steps, n, out);
151 fprintf(R->truth.wr, "ep %u", R->D.d.n_obs); for (int j = 0; j < R->D.d.n_obs; j++) fprintf(R->truth.wr, " %lld", (long long)reset[j]); fprintf(R->truth.wr, " %u", n);
152 for (uint32_t s = 0; s < n; s++) fprintf(R->truth.wr, " %d %lld", steps[s].channel == PD0_CHAN_NONE ? -1 : steps[s].channel, (long long)steps[s].value); fprintf(R->truth.wr, "\n"); fflush(R->truth.wr);
153 char line[1024]; if (!fgets(line, sizeof line, R->truth.rd)) return 0; uint32_t got = 0; int ok = 1;
154 while (fgets(line, sizeof line, R->truth.rd) && strncmp(line, "end", 3)) { if (!strncmp(line, "oob", 3)) { ok = 0; continue; } char *p = line; for (int j = 0; j < R->D.d.n_obs; j++) out[got][j] = strtoll(p, &p, 10); got++; }
155 return ok && got == n;
156}
157
158/* ---- external-world mode (PD0 protocol v2, docs/physics0/PD0_PROTOCOL_V2.md): truth comes from the same world binary ---- */
159static int ext_rel(run *R)
160{
161 uint8_t req[1] = { 4 }, b[2048]; size_t n = world_call(&R->world, req, 1, b, sizeof b);
162 if (n < 8 + 4 + 8 + 2 || memcmp(b, "PD0SHAP1", 8)) return -1;
163 unsigned nv = b[8], nl = b[9], nc = b[10], ne = b[11]; uint32_t tsz = pd0_get_u32(b + 12); unsigned nt = pd0_get_u16(b + 20); size_t o = 22;
164 if (nv > PD0_MAX_VARS || nc > PD0_MAX_CHAN || n != o + (size_t)nt * (9 + nv + nc)) return -1;
165 pd0_rel *t = &R->truth_rel; memset(t, 0, sizeof *t); t->n_vars = (uint8_t)nv; t->n_latent = (uint8_t)nl; t->n_channels = (uint8_t)nc; R->truth_size = (int)tsz; R->truth_n_latent = (int)nl; (void)ne;
166 for (unsigned k = 0; k < nt; k++) { unsigned tg = b[o++]; long long coef = (long long)pd0_get_u64(b + o); o += 8;
167 int e; for (e = 0; e < t->n_equations; e++) if (t->eq[e].target == tg) break; if (e == t->n_equations) { t->eq[t->n_equations++].target = (uint8_t)tg; }
168 pd0_eq *q = &t->eq[e]; int kk = q->n_terms++; q->coef[kk] = coef; for (unsigned i = 0; i < nv + nc; i++) q->expo[kk][i] = b[o++]; }
169 t->description_bits = pd0_rel_bits(t); R->have_truth = 1; return 0;
170}
171static int ext_episode(run *R, const int64_t *reset, const pd0_step *steps, uint32_t n, int64_t out[][PD0_MAX_OBS])
172{
173 uint8_t req[3 + 8 * PD0_MAX_OBS + 9 * PD0_MAX_STEPS], resp[2 + 8 * PD0_MAX_OBS * PD0_MAX_STEPS]; unsigned no = R->D.d.n_obs; size_t o = 0;
174 req[o++] = 3; req[o++] = (uint8_t)no; for (unsigned j = 0; j < no; j++, o += 8) pd0_put_u64(req + o, (uint64_t)reset[j]); req[o++] = (uint8_t)n;
175 for (uint32_t s = 0; s < n; s++, o += 8) { req[o++] = steps[s].channel; pd0_put_u64(req + o, (uint64_t)steps[s].value); }
176 size_t rn = world_call(&R->world, req, o, resp, sizeof resp); if (rn < 2) return 0; unsigned got = resp[1]; if (rn != 2 + 8u * no * got || got > n) return 0;
177 for (unsigned s = 0; s < got; s++) for (unsigned j = 0; j < no; j++) out[s][j] = (int64_t)pd0_get_u64(resp + 2 + 8 * (s * no + j));
178 return resp[0] == 0 && got == n;
179}
180
181static const char *lvl_name(int level) { static char b[8]; if (level < 0) return "null"; snprintf(b, sizeof b, "L%d", level); return b; }
182
183int main(int argc, char **argv)
184{
185 if (argc < 6) { fprintf(stderr, "usage: pd0-harness <world> <truth> <level|null> <seed> <out-dir>\n"); return 2; }
186 static run R; memset(&R, 0, sizeof R); R.level = strcmp(argv[3], "null") == 0 ? -1 : atoi(argv[3]); R.seed = strtoull(argv[4], NULL, 0);
187 char *wargv[] = { argv[1], argv[3], argv[4], NULL }, *targv[] = { argv[2], argv[3], argv[4], NULL };
188 R.ext = strcmp(argv[2], "-") == 0; /* "-": external-world mode, truth over protocol v2 from the world binary */
189 if (spawn(&R.world, wargv) || (!R.ext && spawn(&R.truth, targv))) { perror("spawn"); return 3; }
190 R.ledger = malloc(LCAP); R.recs = malloc(sizeof(pd0_rec) * 65536); R.fit = malloc(sizeof(pd0_transition) * 65536);
191 /* describe */
192 uint8_t req[128], resp[1024]; req[0] = 0; size_t rn = world_call(&R.world, req, 1, resp, sizeof resp);
193 if (!rn || parse_describe(resp, rn, &R.D)) { fprintf(stderr, "world: bad describe\n"); return 3; }
194 const pd0l_desc *d = &R.D.d;
195 { const char *e = getenv("PD0B"); const char *bn = strrchr(argv[1], '/'); bn = bn ? bn + 1 : argv[1]; R.sealed = (e && !strcmp(e, "1")) || strcmp(bn, "pd0-world") != 0; } /* PD-0 mode = the omega world; anything else (or PD0B=1) is sealed mode */
196 if (R.ext) { /* shape before final answers dimensions only (n_vars, n_latent, n_channels, S*); the size bound S*+2 comes from it */
197 if (ext_rel(&R)) { fprintf(stderr, "world: bad pre-final shape\n"); return 3; }
198 R.dims[0] = R.truth_rel.n_vars; R.dims[1] = R.truth_rel.n_latent; R.dims[2] = R.truth_rel.n_channels; R.dims[3] = R.truth_size; R.have_truth = 0; R.dims_ok = 1;
199 if (!R.sealed) { static const int pub0[8] = { 2, 3, 4, 8, 4, 4, 7, 0 }; if (R.level >= 0 && R.level < 8 && R.truth_size != pub0[R.level]) R.dims_ok = 0; }
200 }
201 else if (truth_rel(&R)) { fprintf(stderr, "truth: bad relation\n"); return 3; }
202 /* ladder parameters: spec section 6 bounds for the level; harness knowledge, never the learner's */
203 pd0_ladder_params_default(&R.P, d->n_obs, d->n_channels);
204 for (int c = 0; c < d->n_channels; c++) { R.P.chan_min[c] = d->chan_min[c]; R.P.chan_max[c] = d->chan_max[c]; }
205 R.P.reset_min = d->reset_min[0]; R.P.reset_max = d->reset_max[0]; for (int j = 1; j < d->n_obs; j++) { if (d->reset_min[j] < R.P.reset_min) R.P.reset_min = d->reset_min[j]; if (d->reset_max[j] > R.P.reset_max) R.P.reset_max = d->reset_max[j]; }
206 R.P.episode_len = EP_LEN; R.P.dt_micro = d->dt_micro; R.P.size_bound = (uint32_t)(R.truth_size > 0 ? R.truth_size : 4) + 2;
207 R.P.eps_bound_micro = R.level == 5 ? 50000 : R.level == 6 ? 30000 : 20000; R.P.noisy = R.level == 5;
208 R.L = pd0_learner_new(d, R.seed);
209 /* 1. exploration: FIT FIT FIT SELECT HOLDOUT per five (60/20/20), 20-step episodes; HOLDOUT never reaches the learner */
210 uint32_t reserve = 5 * EP_LEN + 3 * 10 * EP_LEN + 100; uint32_t n_explore = (d->budget_steps > reserve ? (d->budget_steps - reserve) / EP_LEN : 0);
211 if (n_explore + 40 > d->budget_episodes) n_explore = d->budget_episodes > 40 ? d->budget_episodes - 40 : 0;
212 int64_t reset[PD0_MAX_OBS]; pd0_step steps[PD0_MAX_STEPS];
213 for (uint32_t e = 0; e < n_explore; e++) { uint8_t t = (e % 5) < 3 ? TAG_FIT : (e % 5) == 3 ? TAG_SELECT : TAG_HOLDOUT;
214 pd0_learner_explore(R.L, e, reset, steps, EP_LEN); if (episode(&R, t, 0, 0, reset, steps, EP_LEN) < 0) break; }
215 /* 2. candidate, falsifier, preregistered trials; on refutation the trial records become FIT and the learner refits */
216 pd0_ladder_report rep; memset(&rep, 0, sizeof rep); int checker_rc = pd0_ladder_check(R.ledger, R.llen, &R.P, &rep);
217 pd0_corr corr; int have_corr = 0; const pd0l_candidate *best = NULL; uint8_t cand_hash[PD0_HASH] = { 0 }; pd0_rel hyps[PD0_MAX_HYP]; int n_hyp = 0; uint8_t pl[16384];
218 static uint8_t forbidden[PD0L_MAX_FORBID][PD0_HASH]; uint32_t n_forb = 0;
219 for (uint32_t a = 0; a < 3; a++) {
220 R.n_attempts++; pd0_learner_fit(R.L); int nc = pd0_learner_n_candidates(R.L);
221 if (!have_corr && pd0_learner_correlation(R.L, R.seed ^ 0xC0DEu, 2000, &corr) == 0) { append(&R, LEDG_CORR, pl, (uint32_t)pd0_corr_write(&corr, pl)); have_corr = 1; }
222 best = NULL; for (int i = 0; i < nc; i++) if (!pd0_learner_candidate(R.L, i)->is_null) { best = pd0_learner_candidate(R.L, i); break; }
223 if (!best || pd0_learner_candidate(R.L, 0)->is_null) { best = NULL; break; } /* nothing beats the null: stop honestly */
224 n_hyp = 0; hyps[n_hyp++] = best->rel;
225 pl[0] = REL_CANDIDATE; size_t n = pd0_rel_write(&hyps[0], pl + 1, sizeof pl - 1); append(&R, LEDG_RELATION, pl, (uint32_t)n + 1); memcpy(cand_hash, R.last, PD0_HASH);
226 pd0_falsifier f; memset(&f, 0, sizeof f); memcpy(f.candidate, cand_hash, PD0_HASH); f.eps_micro = R.P.eps_bound_micro; f.min_trials = 5;
227 for (int i = 0; i < nc && n_hyp < 4; i++) { const pd0l_candidate *c = pd0_learner_candidate(R.L, i); if (c == best || c->is_null) continue;
228 hyps[n_hyp++] = c->rel; pl[0] = REL_RIVAL; n = pd0_rel_write(&c->rel, pl + 1, sizeof pl - 1); append(&R, LEDG_RELATION, pl, (uint32_t)n + 1); memcpy(f.rival[f.n_rivals++], R.last, PD0_HASH); }
229 { pd0_rel nullr; memset(&nullr, 0, sizeof nullr); nullr.n_vars = d->n_obs; nullr.n_channels = d->n_channels; hyps[n_hyp++] = nullr;
230 pl[0] = REL_NULL; n = pd0_rel_write(&nullr, pl + 1, sizeof pl - 1); append(&R, LEDG_RELATION, pl, (uint32_t)n + 1); memcpy(f.rival[f.n_rivals++], R.last, PD0_HASH); }
231 append(&R, LEDG_FALSIFIER, pl, (uint32_t)pd0_fals_write(&f, pl));
232 checker_rc = pd0_ladder_check(R.ledger, R.llen, &R.P, &rep); if (rep.state < LS_HYPOTHESIS) break; /* no admissible candidate: no trials */
233 n_forb = 0; for (uint32_t s = 0; s < R.n_episodes && n_forb < PD0L_MAX_FORBID; s++) memcpy(forbidden[n_forb++], R.ep_hash[s], PD0_HASH);
234 for (int t = 0, voids = 0; t < 5 + voids; t++) { static pd0_exp x; memset(&x, 0, sizeof x);
235 int64_t div = pd0_learner_propose(R.L, hyps, n_hyp, R.seed * 1000 + a * 10 + (uint64_t)t, 256, (const uint8_t (*)[PD0_HASH])forbidden, n_forb, &x);
236 if (div < 0) { R.n_propose_fail++; R.n_trial_random++; x.n_obs = d->n_obs; x.n_hyp = (uint8_t)n_hyp; x.n_steps = PD0_MAX_STEPS;
237 pd0_learner_random_schedule(d, R.seed * 7919 + a, "trial", (uint32_t)t, x.reset, x.steps, PD0_MAX_STEPS);
238 for (int h = 0; h < n_hyp; h++) { int64_t tmp[PD0_MAX_STEPS * PD0_MAX_OBS]; pd0_learner_rollout(&hyps[h], x.reset, x.steps, PD0_MAX_STEPS, tmp); for (int s = 0; s < PD0_MAX_STEPS; s++) for (int j = 0; j < d->n_obs; j++) x.expected[h][s][j] = tmp[s * d->n_obs + j]; }
239 x.divergence_micro = 0; }
240 size_t xn = pd0_exp_write(&x, pl, sizeof pl); append(&R, LEDG_PREREG, pl, (uint32_t)xn);
241 int slot = episode(&R, TAG_TRIAL, 0, 0, x.reset, x.steps, PD0_MAX_STEPS); if (slot >= 0 && n_forb < PD0L_MAX_FORBID) memcpy(forbidden[n_forb++], R.ep_hash[slot], PD0_HASH);
242 if (slot >= 0 && R.ep_void[slot] && voids < 3) voids++; }
243 checker_rc = pd0_ladder_check(R.ledger, R.llen, &R.P, &rep);
244 if (rep.state >= LS_INTERVENED) break;
245 if (rep.code == PD0V_T6_TRIAL_FAILED) { /* refuted: the trial records are FIT from now on */
246 for (uint32_t s = 0; s < R.n_episodes; s++) if (R.ep_tag[s] == TAG_TRIAL) { for (uint32_t i = 0; i < R.ep_n[s]; i++) pd0_learner_observe(R.L, &R.recs[R.ep_first[s] + i], TAG_FIT); R.ep_tag[s] = TAG_FIT; }
247 continue; }
248 break;
249 }
250 /* 3. replication: three batches of ten episodes, planner and random halves */
251 if (rep.state >= LS_INTERVENED) {
252 for (uint32_t bt = 0; bt < 3; bt++) for (uint32_t redraw = 0; redraw <= 3; redraw++) { pd0_batch bb = { bt + 1 + 10 * redraw, R.seed * 100 + bt + 1 + 50 * redraw, 10 }; append(&R, LEDG_BATCH, pl, (uint32_t)pd0_batch_write(&bb, pl));
253 uint32_t good = 0, voids = 0;
254 for (uint32_t e = 0; good < 10 && voids <= 3; e++) { uint8_t origin = (good & 1) ? ORIGIN_RANDOM : ORIGIN_PLANNER; static pd0_exp x;
255 if (origin == ORIGIN_PLANNER && pd0_learner_propose(R.L, hyps, n_hyp, bb.stream_seed * 31 + e, 128, (const uint8_t (*)[PD0_HASH])forbidden, n_forb, &x) >= 0) { memcpy(reset, x.reset, sizeof reset); memcpy(steps, x.steps, sizeof steps); }
256 else { if (origin == ORIGIN_PLANNER) R.n_propose_fail++; pd0_learner_random_schedule(d, bb.stream_seed, "rep", e, reset, steps, PD0_MAX_STEPS); }
257 int slot = episode(&R, TAG_REP, bb.batch_id, origin, reset, steps, PD0_MAX_STEPS); if (slot >= 0 && n_forb < PD0L_MAX_FORBID) memcpy(forbidden[n_forb++], R.ep_hash[slot], PD0_HASH);
258 if (slot >= 0 && R.ep_void[slot]) voids++; else good++; }
259 if (voids <= 3) break; /* batch complete */
260 R.n_void_batch++; }
261 checker_rc = pd0_ladder_check(R.ledger, R.llen, &R.P, &rep);
262 }
263 /* 4. law record + independent re-verification */
264 static uint8_t law[65536]; size_t law_len = pd0_ladder_emit_law(&rep, &R.P, law, sizeof law); int law_rc = law_len ? pd0_ladder_verify_law(&rep, &R.P, law, law_len) : -1;
265 /* 5. scoring against the truth: 10 in-box + 10 extrapolation (1.5x box) episodes from the "score" stream */
266 pd0_score_result S; memset(&S, 0, sizeof S); S.code = -1; const pd0_rel *scored = rep.have_candidate ? &rep.candidate : best ? &best->rel : NULL; int n_score_eps = 0;
267 /* 5a. external world (protocol v2 rev 2): the learner has submitted to the checker; bind the final relation bundle with `final`,
268 * and only then ask for shape and score. The bundle is the emitted PDLAW1 record, else the candidate bytes, else nothing. */
269 uint8_t fhash[PD0_HASH]; int fin_status = -1, fin_ok = 1; uint32_t cnt[4] = { 0, 0, 0, 0 }; int audit_ok = 0;
270 if (R.ext) {
271 static uint8_t cb[16384]; const uint8_t *fb = law; size_t fn = law_len;
272 if (!fn && scored) { fn = pd0_rel_write(scored, cb, sizeof cb); fb = cb; }
273 sha256_hash(fb, fn, fhash);
274 uint8_t fq[1 + PD0_HASH], fr[16]; fq[0] = 5; memcpy(fq + 1, fhash, PD0_HASH);
275 size_t frn = world_call(&R.world, fq, sizeof fq, fr, sizeof fr); fin_status = frn == 1 ? fr[0] : -1; if (fin_status != 0) fin_ok = 0;
276 if (fin_ok && ext_rel(&R)) { fprintf(stderr, "world: bad shape after final\n"); fin_ok = 0; }
277 if (fin_ok && (R.dims[0] != R.truth_rel.n_vars || R.dims[1] != R.truth_rel.n_latent || R.dims[2] != R.truth_rel.n_channels || R.dims[3] != R.truth_size)) { fprintf(stderr, "world: shape dimensions changed across final\n"); fin_ok = 0; }
278 static const int pub_s[8] = { 2, 3, 4, 8, 4, 4, 7, 0 }; /* S* per level, public spec table (6.2); shape must agree */
279 if (fin_ok && (!R.dims_ok || (!R.sealed && R.level >= 0 && R.level < 8 && R.truth_size != pub_s[R.level]))) { fprintf(stderr, "world: shape S* %d differs from the public table %d\n", R.truth_size, pub_s[R.level]); fin_ok = 0; }
280 if (!fin_ok) R.have_truth = 0;
281 }
282 if (scored && R.have_truth && R.level >= 0) {
283 static pd0_score_episode eps[20]; pd0_rng g; pd0_rng_stream(&g, R.seed + 500, "score"); pd0l_desc box = *d;
284 for (int i = 0; i < 20 && n_score_eps < 20; ) { pd0_score_episode *e = &eps[n_score_eps]; memset(e, 0, sizeof *e); e->in_box = i < 10;
285 for (int j = 0; j < d->n_obs; j++) { box.reset_min[j] = e->in_box ? d->reset_min[j] : d->reset_min[j] * 3 / 2; box.reset_max[j] = e->in_box ? d->reset_max[j] : d->reset_max[j] * 3 / 2; }
286 pd0_learner_random_schedule(&box, R.seed + 500, e->in_box ? "score-in" : "score-ex", (uint32_t)pd0_rng_next(&g), e->init, e->steps, PD0_MAX_STEPS);
287 if (truth_episode(&R, e->init, e->steps, PD0_MAX_STEPS, e->truth)) { n_score_eps++; i++; } else if (pd0_rng_next(&g) % 64 == 0) i++; }
288 pd0_score_params SP; memset(&SP, 0, sizeof SP); SP.n_obs = d->n_obs; SP.n_channels = d->n_channels; SP.size_bound = R.P.size_bound;
289 SP.inbox_bound = R.level == 6 ? 30000 : 20000; SP.extrap_bound = R.level == 6 ? 80000 : 60000; SP.onestep_bound = R.level == 6 ? 0 : 10000;
290 SP.score_constants = R.level != 6; SP.const_tol_ppm = R.level == 5 ? 100000 : 50000; SP.require_latent = R.level == 6; SP.latent_ref_factor = 3;
291 if (R.level != 6) for (int e = 0; e < R.truth_rel.n_equations; e++) for (int t = 0; t < R.truth_rel.eq[e].n_terms && SP.n_true_terms < PD0_MAX_TRUE_TERMS; t++) { pd0_true_term *tt = &SP.true_terms[SP.n_true_terms++]; tt->target = R.truth_rel.eq[e].target; memcpy(tt->expo, R.truth_rel.eq[e].expo[t], sizeof tt->expo); tt->coef = R.truth_rel.eq[e].coef[t]; }
292 pd0_rel rc = *scored; pd0_score(&SP, &rc, 0, pd0_rel_rollout_fn, pd0_rel_predict_fn, &rc, eps, (uint32_t)n_score_eps, R.fit, R.nfit, &S);
293 }
294 /* 6. outputs */
295 char path[1024]; snprintf(path, sizeof path, "%s/pd0l-%s-s%llu.ledger", argv[5], lvl_name(R.level), (unsigned long long)R.seed); FILE *fo = fopen(path, "wb"); if (fo) { fwrite(R.ledger, 1, R.llen, fo); fclose(fo); }
296 if (law_len) { snprintf(path, sizeof path, "%s/pd0l-%s-s%llu.law", argv[5], lvl_name(R.level), (unsigned long long)R.seed); fo = fopen(path, "wb"); if (fo) { fwrite(law, 1, law_len, fo); fclose(fo); } }
297 static char jb[1 << 20]; pd0_learner_report(R.L, jb, sizeof jb); snprintf(path, sizeof path, "%s/pd0l-%s-s%llu.json", argv[5], lvl_name(R.level), (unsigned long long)R.seed); fo = fopen(path, "w");
298 if (fo) { fprintf(fo, "{\"level\":\"%s\",\"seed\":%llu,\"describe_version\":%d,\"state\":\"%s\",\"code\":%d,\"refutations\":%u,\"score_code\":%d,\"score_mask\":%u,\"learner\":%s}\n", lvl_name(R.level), (unsigned long long)R.seed, R.D.version, pd0_ladder_state_name(rep.state), rep.code, rep.n_refutations, S.code, S.fail_mask, jb); fclose(fo); }
299 uint32_t cbits = scored ? pd0_rel_bits(scored) : 0, csize = scored ? pd0_rel_size(scored) : 0; int hidden = best ? best->hidden_state_suspected : 0;
300 printf("PD0L level=%s seed=%llu desc=v%d episodes=%u steps=%u fit=%u select=%u state=%s code=%d stall=%d refutations=%u attempts=%u "
301 "cand_size=%u cand_bits=%u size_bound=%u fit_nrmse=%lld select_nrmse=%lld hidden_state=%d "
302 "score=%s score_code=%d mask=0x%x inbox=%lld extrap=%lld onestep=%lld ref=%lld score_eps=%d law=%d checker_rc=%d "
303 "oob=%u refused=%u budget_hits=%u propose_fail=%u trial_random=%u void_ep=%u void_batch=%u\n",
304 lvl_name(R.level), (unsigned long long)R.seed, R.D.version, R.n_episodes, R.steps_used, pd0_learner_n_transitions(R.L, TAG_FIT), pd0_learner_n_transitions(R.L, TAG_SELECT),
305 pd0_ladder_state_name(rep.state), rep.code, rep.stall_code, rep.n_refutations, R.n_attempts,
306 csize, cbits, R.P.size_bound, (long long)(best ? best->fit_nrmse_micro : -1), (long long)(best ? best->select_nrmse_micro : -1), hidden,
307 !scored ? "NO_CANDIDATE" : S.code == 0 ? "PASS" : S.code < 0 ? "NOT_SCORED" : "FAIL", S.code, S.fail_mask, (long long)S.inbox_nrmse, (long long)S.extrap_nrmse, (long long)S.onestep_nrmse, (long long)S.ref_nrmse, n_score_eps, law_rc, checker_rc,
308 R.n_oob, R.n_refused, R.n_budget, R.n_propose_fail, R.n_trial_random, R.n_void_ep, R.n_void_batch);
309 if (R.ext) { /* audit: the world's own account of the final gate; a valid instance has every refusal counter at 0 */
310 uint8_t aq[1] = { 6 }, ar[128]; size_t arn = world_call(&R.world, aq, 1, ar, sizeof ar); char hx[2 * PD0_HASH + 1]; int valid = 0;
311 for (int i = 0; i < PD0_HASH; i++) snprintf(hx + 2 * i, 3, "%02x", fhash[i]);
312 if (arn == 57 && !memcmp(ar, "PD0AUDT1", 8)) { audit_ok = 1; for (int i = 0; i < 4; i++) cnt[i] = pd0_get_u32(ar + 9 + 4 * i); audit_ok = ar[8] == 1 && !memcmp(ar + 25, fhash, PD0_HASH); }
313 valid = fin_ok && audit_ok && !cnt[0] && !cnt[1] && !cnt[2] && !cnt[3];
314 printf("PD0F level=%s seed=%llu final=%s final_status=%d score_before_final=%u shape_before_final=%u play_after_final=%u dup_final=%u audit_ok=%d mode=%s s_star=%d n_vars=%d n_latent=%d n_channels=%d valid=%s\n",
315 lvl_name(R.level), (unsigned long long)R.seed, hx, fin_status, cnt[0], cnt[1], cnt[2], cnt[3], audit_ok, R.sealed ? "SEALED" : "PD0", R.dims[3], R.dims[0], R.dims[1], R.dims[2], valid ? "VALID" : "INVALID");
316 }
317 if (!R.ext) { fprintf(R.truth.wr, "quit\n"); fflush(R.truth.wr); fclose(R.truth.wr); }
318 fclose(R.world.wr); waitpid(R.world.pid, NULL, 0); if (!R.ext) waitpid(R.truth.pid, NULL, 0);
319 pd0_learner_free(R.L); free(R.ledger); free(R.recs); free(R.fit);
320 return 0;
321}