gdp-wired 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@ import { proveCyclic } from "./cyclic.js";
5
5
  import { solve } from "./solver.js";
6
6
  import { grow, proveLaws, proveLiveness, proveStepLaws, withDeadline } from "../kernel/prove.js";
7
7
  import { inferLaws } from "./infer.js";
8
+ import { generators, houdini, relationOf } from "./relation.js";
8
9
  // --- terms ----------------------------------------------------------------------------------------------------------
9
10
  const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
10
11
  const add = (a, b) => ({ op: 'add', a, b }), sub = (a, b) => ({ op: 'sub', a, b });
@@ -392,7 +393,7 @@ const valueAt = (l, w) => Object.entries(l).reduce((s, [x, c]) => s + c * (x ===
392
393
  // either sign, each bound doubled up to 4 and the constants' first small, then up to the samples' size: the first found
393
394
  // is small (x + y, not 33·x + y; total − cur, not 26 − cur), and a rank the samples' size bounds is left to the next
394
395
  // component (two phases: (x, y)). A fit's coefficients (c:) go up to 128.
395
- function lp(must, pool, until, scale = 1, signs = [true, false]) {
396
+ function lp(must, pool, until, scale = 1, signs = [true, false], whole = false) {
396
397
  const unknowns = [...new Set([...must, ...pool].flatMap(l => Object.keys(l)).filter(x => x !== '1'))];
397
398
  const fit = unknowns.some(x => x.startsWith('c:')), bounds = fit ? [1, 2, 4, 16, 128] : [1, 2, 4];
398
399
  const stage = (natural, bound, wide) => {
@@ -415,7 +416,7 @@ function lp(must, pool, until, scale = 1, signs = [true, false]) {
415
416
  // The widest box first: where it has no solution, none of the smaller has. Past it, a rank's rows (homogeneous in the
416
417
  // unknowns, the drop's constant aside) are solved exactly over the rationals, the solution scaled to whole numbers.
417
418
  if (!stage(signs.at(-1), bounds.at(-1), true))
418
- return fit ? undefined : exactLp(must, pool, until);
419
+ return fit ? undefined : exactLp(must, pool, until, whole);
419
420
  for (const natural of signs)
420
421
  for (const bound of bounds)
421
422
  for (const wide of [false, true]) {
@@ -556,11 +557,12 @@ function exactSolve(rows, until) {
556
557
  // turn's change) and kept only where it holds of all of them: a coefficient the runs' size forces (32·x + y where x
557
558
  // reaches 33, a reset y := x − 1 in the runs) grows with the runs, and is refused, where one a turn's change forces
558
559
  // (11·x + 2·y, six tokens for a coin and a coin for five) is the same on both.
559
- function exactLp(must, pool, until) {
560
+ // `whole`: rows that are facts, not samples (a path's generators, core/relation.ts), solved over all of them.
561
+ function exactLp(must, pool, until, whole = false) {
560
562
  const size = (l) => { let m = 0; for (const x in l)
561
563
  if (x !== '1')
562
564
  m = Math.max(m, Math.abs(l[x])); return m; };
563
- const sizes = pool.map(size), half = sizes.reduce((a, b) => Math.max(a, b), 0) / 2, small = pool.filter((_, i) => sizes[i] <= half), rows = [...must];
565
+ const sizes = pool.map(size), half = sizes.reduce((a, b) => Math.max(a, b), 0) / 2, small = whole ? pool : pool.filter((_, i) => sizes[i] <= half), rows = [...must];
564
566
  for (let round = 0; round < 40 && performance.now() < until; round++) {
565
567
  const w = exactSolve(rows, until);
566
568
  if (!w)
@@ -962,6 +964,401 @@ export function findCycles(facts, claims, opts = {}) {
962
964
  }
963
965
  return last;
964
966
  }
967
+ const plusL = (a, b, f = 1) => { const o = { ...a }; for (const x in b) {
968
+ o[x] = (o[x] ?? 0) + f * b[x];
969
+ if (!o[x])
970
+ delete o[x];
971
+ } return o; };
972
+ const konstL = (c) => (c ? { 1: c } : {});
973
+ const scaleL = (a, f) => { const o = {}; if (f)
974
+ for (const x in a)
975
+ o[x] = a[x] * f; return o; };
976
+ // A form over the relation's names as the kernel's term (an integer's coefficient on its two parts), read truncated.
977
+ const termOf = (rel, f) => {
978
+ const coef = {};
979
+ for (const [x, a] of Object.entries(f)) {
980
+ if (x === '1')
981
+ continue;
982
+ const p = rel.ints.get(x);
983
+ if (p) {
984
+ coef[p[0]] = a;
985
+ coef[p[1]] = -a;
986
+ }
987
+ else
988
+ coef[x] = a;
989
+ }
990
+ return linE(coef, f['1'] ?? 0);
991
+ };
992
+ export function rankOfRelation(l, laws, until) {
993
+ const rel = relationOf(l, laws);
994
+ return rel ? relationRank(l, rel, until) : { why: 'the turn is not linear (a map, a flag, or past the paths\' cap)' };
995
+ }
996
+ // `extra`: atoms (each ≤ 0) that hold at each location (by its index among the locations' values), read as rows of the
997
+ // paths that leave it.
998
+ // The locations (the values of the location natural, sorted; one with none), and the names each location's rank may
999
+ // read: those its paths' rows read, and what the values after read of the names read where the paths go (live).
1000
+ const locations = (rel) => {
1001
+ const values = rel.loc ? [...new Set([...rel.from, ...rel.to])].sort((a, b) => a - b) : [0];
1002
+ const fromOf = (i) => (rel.loc ? values.indexOf(rel.from[i]) : 0), toOf = (i) => (rel.loc ? values.indexOf(rel.to[i]) : 0);
1003
+ const names = new Set([...rel.state, ...rel.params]), live = values.map(() => new Set());
1004
+ for (const [i, p] of rel.paths.entries())
1005
+ for (const r of p.rows)
1006
+ for (const x of Object.keys(r))
1007
+ if (names.has(x))
1008
+ live[fromOf(i)].add(x);
1009
+ for (let grew = true; grew;) {
1010
+ grew = false;
1011
+ for (const [i, p] of rel.paths.entries())
1012
+ for (const x of live[toOf(i)])
1013
+ for (const y of p.post[x] ? Object.keys(p.post[x]) : [x])
1014
+ if (names.has(y) && !live[fromOf(i)].has(y)) {
1015
+ live[fromOf(i)].add(y);
1016
+ grew = true;
1017
+ }
1018
+ }
1019
+ return { values, fromOf, toOf, names, at: live.map(s => [...s].sort()) };
1020
+ };
1021
+ function relationRank(l, rel, until, extra = []) {
1022
+ const { values, fromOf, toOf, names, at } = locations(rel);
1023
+ const every = [...new Set(at.flat())].sort();
1024
+ const gpaths = [];
1025
+ for (const [i, p] of rel.paths.entries()) {
1026
+ if (performance.now() > until)
1027
+ return { why: 'out of time on the relation' };
1028
+ const rows = [...p.rows, ...(extra[fromOf(i)] ?? [])];
1029
+ const ns = [...new Set([...rows.flatMap(r => Object.keys(r)), ...Object.values(p.post).flatMap(r => Object.keys(r)), ...every])].filter(x => x !== '1').sort();
1030
+ const gens = generators(rows, ns, rel.nats, 600, until);
1031
+ if (!gens)
1032
+ return { why: 'a path past the generators\' cap' };
1033
+ if (gens.vertices.length)
1034
+ gpaths.push({ from: fromOf(i), to: toOf(i), gens, post: p.post, rows });
1035
+ }
1036
+ // A template's value at a generator (x, t), as a form over the unknowns; after the turn, through the path's values.
1037
+ const unknown = (tp, j, n, x) => (x === 1 ? `b:${tp.tag}${j}:${n}` : `a:${tp.tag}${j}:${tp.own ? n : '*'}:${x}`);
1038
+ // a node: a location, or one side of an atom at a location (regions, below)
1039
+ const nodeLoc = values.map((_, n) => n);
1040
+ const varsAt = (tp, n) => (tp.own ? at[nodeLoc[n]] : every);
1041
+ const fAt = (tp, j, n, x, t) => {
1042
+ const out = {};
1043
+ for (const v of varsAt(tp, n))
1044
+ if (x[v])
1045
+ out[unknown(tp, j, n, v)] = x[v];
1046
+ if (t)
1047
+ out[unknown(tp, j, n, 1)] = t;
1048
+ return out;
1049
+ };
1050
+ const postAt = (p, x, t) => {
1051
+ const out = { ...x };
1052
+ for (const [v, f] of Object.entries(p.post)) {
1053
+ let s = 0;
1054
+ for (const [u, c] of Object.entries(f))
1055
+ s += c * (u === '1' ? t : x[u] ?? 0);
1056
+ out[v] = s;
1057
+ }
1058
+ return out;
1059
+ };
1060
+ // Rows (≤ 0) saying h ≥ c at every point of the path: at each vertex h(x, t) ≥ c·t, along each ray h's linear part
1061
+ // ≥ 0, along each line = 0.
1062
+ const holds = (p, h, c) => {
1063
+ const env = (g) => Object.fromEntries(p.gens.names.map((x, i) => [x, g[i]]));
1064
+ const tOf = (g) => g[p.gens.names.length];
1065
+ return [
1066
+ ...p.gens.vertices.map(g => plusL(scaleL(h(env(g), tOf(g)), -1), { 1: c * tOf(g) })),
1067
+ ...p.gens.rays.map(g => scaleL(h(env(g), 0), -1)),
1068
+ ...p.gens.lines.flatMap(g => [h(env(g), 0), scaleL(h(env(g), 0), -1)]),
1069
+ ];
1070
+ };
1071
+ const delta = (tp, j, p) => (x, t) => plusL(fAt(tp, j, p.from, x, t), fAt(tp, j, p.to, postAt(p, x, t), t), -1);
1072
+ const strictRows = (tp, p) => [
1073
+ ...holds(p, delta(tp, 0, p), 1),
1074
+ ...Array.from({ length: tp.depth - 1 }, (_, j) => holds(p, (x, t) => plusL(delta(tp, j + 1, p)(x, t), fAt(tp, j, p.from, x, t)), 1)).flat(),
1075
+ ...holds(p, (x, t) => fAt(tp, tp.depth - 1, p.from, x, t), tp.depth === 1 ? 1 : 0),
1076
+ ];
1077
+ const weakRows = (tp, p) => Array.from({ length: tp.depth }, (_, j) => holds(p, delta(tp, j, p), 0)).flat();
1078
+ const scale = 1 + Math.max(0, ...gpaths.flatMap(p => p.gens.vertices.flatMap(g => g.map(Math.abs))));
1079
+ const sat = (w, rows) => rows.every(r => valueAt(r, w) <= 0);
1080
+ // One block over the paths left: strict on all of them at once, else on as many as one after another allows.
1081
+ const block = (tp, left, greedy, until) => {
1082
+ // (each path's rows made once for the template)
1083
+ const strict = new Map(left.map(p => [p, strictRows(tp, p)])), weak = new Map();
1084
+ const weakOf = (q) => { let r = weak.get(q); if (!r)
1085
+ weak.set(q, r = weakRows(tp, q)); return r; };
1086
+ // all at once (a greedy try follows the same template's try of this, so it doesn't make it again)
1087
+ if (!greedy) {
1088
+ const all = lp(left.flatMap(p => strict.get(p)), [], until, scale, undefined, true);
1089
+ return all && { w: all, strict: left };
1090
+ }
1091
+ const must = [];
1092
+ let w;
1093
+ for (const p of left) {
1094
+ if (performance.now() > until)
1095
+ break;
1096
+ if (w && sat(w, strict.get(p)))
1097
+ continue;
1098
+ const rows = strict.get(p), w2 = lp([...must, ...rows], left.filter(q => q !== p).flatMap(weakOf), until, scale, undefined, true);
1099
+ if (w2) {
1100
+ must.push(...rows);
1101
+ w = w2;
1102
+ }
1103
+ }
1104
+ return w && { w, strict: left.filter(p => sat(w, strict.get(p))) };
1105
+ };
1106
+ // The locations' components: a path between two drops by the first part of the rank, the component's height; the
1107
+ // paths within each are ranked on their own (their locations are no other's, so the parts line up per location).
1108
+ const graph = values.map(() => new Set());
1109
+ for (const p of gpaths)
1110
+ graph[p.from].add(p.to);
1111
+ const comp = sccs(graph.map(g => [...g])), height = [];
1112
+ const heightOf = (c) => (height[c] ??= Math.max(0, ...values.flatMap((_, n) => (comp[n] === c ? [...graph[n]].filter(m => comp[m] !== c).map(m => heightOf(comp[m]) + 1) : []))));
1113
+ // The paths of one component in order of blocks: each component a form per node.
1114
+ const ranked = (paths, tag0, until) => {
1115
+ let left = paths;
1116
+ const mine = [], sizes = [];
1117
+ while (left.length && mine.length < 8 && performance.now() < until) {
1118
+ const tag = `${tag0}${mine.length}.`;
1119
+ // depth 1 first, all at once then one path after another; then deeper
1120
+ const order = [1, 2, 3].flatMap(depth => [false, true].flatMap(greedy => [false, true].map((own) => [{ depth, own, tag }, greedy])));
1121
+ let found;
1122
+ for (const [tp, greedy] of order) {
1123
+ if (found || performance.now() > until)
1124
+ break;
1125
+ const t1 = performance.now(), b = block(tp, left, greedy, until);
1126
+ if (trace)
1127
+ console.error(`[cycles] ${l.name}: block ${tag} depth ${tp.depth}${tp.own ? ' own' : ''}${greedy ? ' greedy' : ''}: ${b ? b.strict.length : 'none'} of ${left.length} paths, ${Math.round(performance.now() - t1)} ms`);
1128
+ if (b && b.strict.length)
1129
+ found = { ...b, tp };
1130
+ }
1131
+ if (!found)
1132
+ return { why: `no block of a nested rank per location is strict on any of the ${left.length} paths left (of ${gpaths.length})` };
1133
+ const { w, tp, strict } = found;
1134
+ for (let j = 0; j < tp.depth; j++)
1135
+ mine.push(nodeLoc.map((_, n) => {
1136
+ const f = {};
1137
+ for (const x of varsAt(tp, n)) {
1138
+ const a = w[unknown(tp, j, n, x)] ?? 0;
1139
+ if (a)
1140
+ f[x] = a;
1141
+ }
1142
+ return plusL(f, { 1: (tp.depth === 1 ? 0 : 1) + (w[unknown(tp, j, n, 1)] ?? 0) });
1143
+ }));
1144
+ sizes.push(tp.depth);
1145
+ left = left.filter(p => !strict.includes(p));
1146
+ }
1147
+ if (left.length)
1148
+ return { why: performance.now() >= until ? 'out of time on the relation' : 'past 8 components' };
1149
+ return { parts: mine, sizes };
1150
+ };
1151
+ // Regions: a component with no rank, its locations split by an atom its paths read (q < p: min(p, q); y ≥ 2: a
1152
+ // sign), each side a node of its own, its paths split by the side before and after; the kernel's term reads the atom
1153
+ // (if atom then f else g).
1154
+ const after1 = (p, a) => { let o = {}; for (const [x, c] of Object.entries(a))
1155
+ o = plusL(o, x !== '1' && p.post[x] ? scaleL(p.post[x], c) : { [x]: c }); return o; };
1156
+ const side = (a, yes) => (yes ? a : plusL({ 1: 1 }, a, -1));
1157
+ const regions = (c, paths) => {
1158
+ const seen = new Set(), atoms = [];
1159
+ for (const r of paths.flatMap(p => p.rows)) {
1160
+ if (!Object.keys(r).every(x => x === '1' || names.has(x)) || Object.keys(r).length < 2)
1161
+ continue;
1162
+ const key = [id(Object.keys(r).sort().map(x => [x, r[x]])), id(Object.keys(side(r, false)).sort().map(x => [x, side(r, false)[x]]))].sort().join();
1163
+ if (!seen.has(key)) {
1164
+ seen.add(key);
1165
+ atoms.push(r);
1166
+ }
1167
+ }
1168
+ atoms.sort((a, b) => Object.keys(b).length - Object.keys(a).length);
1169
+ const locs = values.flatMap((_, n) => (comp[n] === c ? [n] : []));
1170
+ for (const [ai, a] of atoms.slice(0, 8).entries()) {
1171
+ if (performance.now() > until)
1172
+ return undefined;
1173
+ const base = nodeLoc.length, node = (n, yes) => base + 2 * locs.indexOf(n) + (yes ? 0 : 1);
1174
+ for (const n of locs)
1175
+ nodeLoc.push(n, n);
1176
+ const split = [];
1177
+ for (const p of paths)
1178
+ for (const yes of [true, false])
1179
+ for (const yes2 of [true, false]) {
1180
+ const rows = [...p.rows, side(a, yes), side(after1(p, a), yes2)];
1181
+ const gens = generators(rows, p.gens.names, rel.nats, 600, until);
1182
+ if (gens?.vertices.length)
1183
+ split.push({ from: node(p.from, yes), to: node(p.to, yes2), gens, post: p.post, rows });
1184
+ }
1185
+ const out = ranked(split, `${c}.r${ai}.`, until);
1186
+ if (trace)
1187
+ console.error(`[cycles] ${l.name}: component ${c} split by ${showC(leC(rel, a))}: ${'parts' in out ? out.parts.length + ' parts' : out.why}`);
1188
+ if ('parts' in out) {
1189
+ const cond = leC(rel, a);
1190
+ return { parts: out.parts.map(fs => values.map((_, n) => (locs.includes(n) ? { op: 'if', c: cond, then: termOf(rel, fs[node(n, true)]), else: termOf(rel, fs[node(n, false)]) } : k(0)))), sizes: out.sizes };
1191
+ }
1192
+ }
1193
+ return undefined;
1194
+ };
1195
+ const parts = []; // per component of the locations: its parts, each a term per location
1196
+ const sizes = [];
1197
+ for (const c of [...new Set(comp)].sort((a, b) => a - b)) {
1198
+ // (half the time left for the component as it is: the regions have the rest)
1199
+ const inner = gpaths.filter(p => comp[p.from] === c && comp[p.to] === c), out = ranked(inner, `${c}.`, performance.now() + (until - performance.now()) / 2);
1200
+ if ('parts' in out) {
1201
+ parts[c] = out.parts.map(fs => values.map((_, n) => termOf(rel, fs[n])));
1202
+ sizes.push(...out.sizes);
1203
+ continue;
1204
+ }
1205
+ const r = regions(c, inner);
1206
+ if (!r)
1207
+ return out;
1208
+ parts[c] = r.parts;
1209
+ sizes.push(...r.sizes);
1210
+ }
1211
+ // per location, its component's parts in order (0 past them), the heights first where paths join components
1212
+ const width = Math.max(0, ...parts.map(p => p?.length ?? 0));
1213
+ const columns = [...(gpaths.some(p => comp[p.from] !== comp[p.to]) ? [values.map((_, n) => termOf(rel, konstL(heightOf(comp[n]))))] : []),
1214
+ ...Array.from({ length: width }, (_, j) => values.map((_, n) => parts[comp[n]]?.[j]?.[n] ?? k(0)))];
1215
+ const rank = columns.map(terms => {
1216
+ let e = terms.at(-1) ?? k(0);
1217
+ for (let n = terms.length - 2; n >= 0; n--)
1218
+ if (id(terms[n]) !== id(e))
1219
+ e = { op: 'if', c: eqC(v(rel.loc), k(values[n])), then: terms[n], else: e };
1220
+ return e;
1221
+ });
1222
+ if (!rank.length)
1223
+ rank.push(k(0));
1224
+ return { rank, text: `(${rank.map(showE).join(', ')})`, blocks: sizes };
1225
+ }
1226
+ // Invariants first, so a rank may assume them: atoms per location (each name's bounds at the constants the paths
1227
+ // read, and the paths' own atoms over the state and params), those false at a start dropped (the loop's starts, run
1228
+ // from random params), then Houdini over the relation (core/relation.ts). Each kept as a law at its location
1229
+ // (pc ≠ ℓ ∨ atom), which the kernel proves inductive with the halting goals; then each dropped in turn where the
1230
+ // relation's rank is still found without it (and those that leaned on it).
1231
+ const leC = (rel, f) => {
1232
+ const pos = [], neg = [];
1233
+ for (const [x, a] of Object.entries(f)) {
1234
+ if (x === '1') {
1235
+ if (a > 0)
1236
+ pos.push(k(a));
1237
+ else if (a < 0)
1238
+ neg.push(k(-a));
1239
+ continue;
1240
+ }
1241
+ const p = rel.ints.get(x), parts = p ? [[p[0], a], [p[1], -a]] : [[x, a]];
1242
+ for (const [y, c] of parts)
1243
+ (c > 0 ? pos : neg).push(Math.abs(c) === 1 ? v(y) : { op: 'mul', k: Math.abs(c), a: v(y) });
1244
+ }
1245
+ const sum = (xs) => (xs.length ? xs.reduce((s, x) => add(s, x)) : k(0));
1246
+ return le(sum(pos), sum(neg));
1247
+ };
1248
+ // The relation's rank with invariants: Houdini's set, then each atom dropped in turn where the set without it, closed
1249
+ // again (those that leaned on it dropped too), still gives a rank.
1250
+ export function rankWithInvariants(l, laws, until) {
1251
+ const rel = relationOf(l, laws);
1252
+ if (!rel)
1253
+ return { why: 'the turn is not linear' };
1254
+ const { values, fromOf, toOf, names, at } = locations(rel);
1255
+ const locOf = (i) => [fromOf(i), toOf(i)];
1256
+ const consts = new Set([0, 1, -1]);
1257
+ for (const p of rel.paths)
1258
+ for (const r of p.rows) {
1259
+ const c = r['1'] ?? 0, xs = Object.keys(r).filter(x => x !== '1');
1260
+ if (Math.abs(c) <= 1_000_000)
1261
+ for (const d of xs.length === 1 ? [c / Math.abs(r[xs[0]])] : [c])
1262
+ if (Number.isInteger(d)) {
1263
+ consts.add(d);
1264
+ consts.add(-d);
1265
+ consts.add(d + 1);
1266
+ consts.add(d - 1);
1267
+ consts.add(-d + 1);
1268
+ consts.add(-d - 1);
1269
+ }
1270
+ }
1271
+ const K = [...consts].sort((a, b) => Math.abs(a) - Math.abs(b) || a - b).slice(0, 24);
1272
+ const atoms = [...new Map(rel.paths.flatMap(p => p.rows).filter(r => Object.keys(r).filter(x => x !== '1').length > 1 && Object.keys(r).every(x => x === '1' || names.has(x))).map(r => [id(Object.keys(r).sort().map(x => [x, r[x]])), r])).values()];
1273
+ // per location, over the names live there: their bounds at the constants, then (a second try) the paths' atoms too
1274
+ const bounds = values.map((_, n) => at[n].flatMap(x => K.flatMap((c) => [plusL({ [x]: 1 }, konstL(-c)), plusL({ [x]: -1 }, konstL(c))])));
1275
+ const withAtoms = values.map((_, n) => [...bounds[n], ...atoms.filter(a => Object.keys(a).every(x => x === '1' || at[n].includes(x)))]);
1276
+ // the starts: random params (the precondition's), the state they begin in
1277
+ const cx = { eqs: new Map(), arity: new Map(), values: {}, memo: new Map(), fuel: Infinity, depth: 0 }, rand = seeded(31);
1278
+ const starts = [];
1279
+ for (let s = 0; s < 400; s++) {
1280
+ const big = [2, 8, 64, 1000, 1_000_000][s % 5], ps = Object.fromEntries(l.params.map(p => [p, rand(big + 1)]));
1281
+ if (l.pre && evC(cx, l.pre, ps) !== true)
1282
+ continue;
1283
+ const st = { ...ps };
1284
+ for (const [x, e] of Object.entries(l.state))
1285
+ st[x] = ev(cx, e, ps) ?? 0;
1286
+ const n = rel.loc ? values.indexOf(st[rel.loc] ?? -1) : 0;
1287
+ if (n < 0)
1288
+ continue;
1289
+ starts.push([n, Object.fromEntries([...names].map(x => { const p = rel.ints.get(x); return [x, p ? st[p[0]] - st[p[1]] : st[x] ?? 0]; }))]);
1290
+ }
1291
+ const atStarts = (cs) => cs.map((c, n) => c.filter(h => starts.every(([m, env]) => m !== n || valueAt(h, env) <= 0)));
1292
+ const asLaws = (H) => {
1293
+ const out = [], texts = [];
1294
+ for (const [n, hs] of H.entries())
1295
+ for (const [i, h] of hs.entries()) {
1296
+ const atom = leC(rel, h);
1297
+ out.push({ name: `invariant ${n}.${i}`, holds: rel.loc ? { op: 'or', xs: [{ op: 'not', x: eqC(v(rel.loc), k(values[n])) }, atom] } : atom });
1298
+ texts.push(`${rel.loc ? `${rel.loc} = ${values[n]} → ` : ''}${showC(atom)}`);
1299
+ }
1300
+ return { laws: out, texts };
1301
+ };
1302
+ // of the bounds on one name each way, the tightest (the others follow from it: the same set)
1303
+ const tightest = (hs) => {
1304
+ const best = new Map(), rest = [];
1305
+ for (const c of hs) {
1306
+ const xs = Object.keys(c).filter(x => x !== '1');
1307
+ if (xs.length !== 1) {
1308
+ rest.push(c);
1309
+ continue;
1310
+ }
1311
+ const x = xs[0], key = `${x}${Math.sign(c[x])}`, b = (c['1'] ?? 0) / Math.abs(c[x]), was = best.get(key);
1312
+ if (!was || b > (was['1'] ?? 0) / Math.abs(was[x]))
1313
+ best.set(key, c);
1314
+ }
1315
+ return [...best.values(), ...rest];
1316
+ };
1317
+ let H = [], found = { why: 'no invariant' };
1318
+ const t1 = performance.now();
1319
+ for (const [i, cands] of [bounds, withAtoms].entries()) {
1320
+ if (performance.now() > until)
1321
+ break;
1322
+ const closed = houdini(rel, atStarts(cands), locOf, i ? until : performance.now() + (until - performance.now()) / 2);
1323
+ if (!closed || !closed.some(h => h.length))
1324
+ continue;
1325
+ H = closed.map(tightest);
1326
+ found = relationRank(l, rel, until, H);
1327
+ if ('rank' in found)
1328
+ break;
1329
+ found = { why: `with ${H.flat().length} invariants: ${found.why}` };
1330
+ }
1331
+ if (!('rank' in found))
1332
+ return found;
1333
+ // fewer: a location's atoms at once, then one atom at a time, within ten times the first search's time
1334
+ const stop = Math.min(until, performance.now() + Math.max(500, 10 * (performance.now() - t1)));
1335
+ const without = (drop) => {
1336
+ const fewer = houdini(rel, H.map((g, n) => g.filter(h => !drop(n, h))), locOf, stop);
1337
+ if (!fewer || fewer.flat().length === H.flat().length)
1338
+ return false;
1339
+ const r = relationRank(l, rel, stop, fewer);
1340
+ if ('rank' in r) {
1341
+ H = fewer;
1342
+ found = r;
1343
+ return true;
1344
+ }
1345
+ return false;
1346
+ };
1347
+ for (const n of H.keys()) {
1348
+ if (performance.now() > stop)
1349
+ break;
1350
+ if (H[n].length)
1351
+ without(m => m === n);
1352
+ }
1353
+ for (const [n, hs] of H.map((h, n) => [n, [...h]]))
1354
+ for (const h of hs) {
1355
+ if (performance.now() > stop)
1356
+ break;
1357
+ if (H[n].includes(h))
1358
+ without((m, g) => m === n && g === h);
1359
+ }
1360
+ return { rank: found.rank, text: found.text, ...asLaws(H) };
1361
+ }
965
1362
  const seeded = (seed) => { let x = seed; return (n) => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * n); }; };
966
1363
  const goalsProven = (goals) => {
967
1364
  const trees = {};
@@ -1020,7 +1417,8 @@ export function findRank(l, laws = [], opts = {}) {
1020
1417
  }
1021
1418
  }
1022
1419
  const samples = [[...points.values()].map(env => ({ env, calls: new Set() }))];
1023
- const { comps, left } = lexRanks([0], [node], samples, [...edges.values()], shared, until);
1420
+ // (the runs' LP within 10% of the time: the relation's search below has its share)
1421
+ const { comps, left } = lexRanks([0], [node], samples, [...edges.values()], shared, Math.min(until, t0 + 0.1 * (opts.ms ?? 10_000)));
1024
1422
  // Ranks of degree 2 where the linear one leaves turns or the kernel refuses it (while i < N·M: N·M − i, where the runs
1025
1423
  // alone give 299 − i): one product of two variables at a time. The products the loop's own terms read first (a rank
1026
1424
  // of degree 2 measures what its terms of degree 2 bound), before the invariants; the others after them, within a
@@ -1055,12 +1453,52 @@ export function findRank(l, laws = [], opts = {}) {
1055
1453
  let tried = [];
1056
1454
  if (comps.length && !left) {
1057
1455
  seen.add(id(linear));
1058
- tried.push({ rank: linear, verdict: withDeadline(until, () => goalsProven(loopObligations(l, laws, linear))) });
1456
+ // (its check within 20% of the time: the relation's search below has its share)
1457
+ tried.push({ rank: linear, verdict: withDeadline(Math.min(until, t0 + 0.2 * (opts.ms ?? 10_000)), () => goalsProven(loopObligations(l, laws, linear))) });
1458
+ if ('trees' in tried[0].verdict)
1459
+ return done(linear, tried[0].verdict.trees);
1460
+ }
1461
+ // The relation's rank (per location, in phases), within half the time left; then degree 2 over the products the loop
1462
+ // reads; then the relation's rank with invariants. (A search that throws, a stack too deep for a large loop say,
1463
+ // gives way to the rest.)
1464
+ const safely = (f) => { try {
1465
+ return f();
1466
+ }
1467
+ catch (e) {
1468
+ return { why: `the relation's search threw: ${e.message.slice(0, 120)}` };
1469
+ } };
1470
+ const relT0 = performance.now(), rel = safely(() => rankOfRelation(l, laws, performance.now() + (until - performance.now()) / 2));
1471
+ let relWhy = 'rank' in rel ? `the kernel refused ${rel.text}` : rel.why;
1472
+ if (trace)
1473
+ console.error(`[cycles] ${l.name}: the relation's rank ${'rank' in rel ? rel.text : rel.why} (from ${Math.round(relT0 - t0)} ms to ${Math.round(performance.now() - t0)} ms)`);
1474
+ if ('rank' in rel) {
1475
+ const verdict = withDeadline(until, () => goalsProven(loopObligations(l, laws, rel.rank)));
1476
+ if ('trees' in verdict)
1477
+ return done(rel.rank, verdict.trees);
1478
+ if (trace)
1479
+ console.error(`[cycles] ${l.name}: the kernel refused ${rel.text} at ${verdict.goal}`);
1480
+ relWhy = `the kernel refused ${rel.text.slice(0, 300)} at ${verdict.goal}`;
1059
1481
  }
1060
1482
  tried.push(...quadratic(read, until));
1061
1483
  const won = tried.find(t => 'trees' in t.verdict);
1062
1484
  if (won && 'trees' in won.verdict)
1063
1485
  return done(won.rank, won.verdict.trees);
1486
+ if (!('rank' in rel)) {
1487
+ // invariants first: the relation's rank where they hold, with as few of them as it needs
1488
+ const inv = safely(() => rankWithInvariants(l, laws, performance.now() + (until - performance.now()) / 2));
1489
+ if (trace)
1490
+ console.error(`[cycles] ${l.name}: the relation's rank with invariants ${'rank' in inv ? `${inv.text} with ${inv.texts.join('; ')}` : inv.why}`);
1491
+ if ('rank' in inv) {
1492
+ const verdict = withDeadline(until, () => goalsProven(loopObligations(l, [...laws, ...inv.laws], inv.rank)));
1493
+ if ('trees' in verdict)
1494
+ return done(inv.rank, verdict.trees, inv.laws, inv.texts);
1495
+ if (trace)
1496
+ console.error(`[cycles] ${l.name}: the kernel refused ${inv.text} with ${inv.laws.length} invariants at ${verdict.goal}`);
1497
+ relWhy = `${relWhy}; with ${inv.laws.length} invariants, the kernel refused ${inv.text.slice(0, 300)} at ${verdict.goal}`;
1498
+ }
1499
+ else
1500
+ relWhy = `${relWhy}; ${inv.why}`;
1501
+ }
1064
1502
  if (!tried.length && comps.length)
1065
1503
  tried.push({ rank: linear, verdict: withDeadline(until, () => goalsProven(loopObligations(l, laws, linear))) });
1066
1504
  // Invariants the rank needs: the descent as the loop's step laws, inferLaws's candidates chosen by its counterexamples
@@ -1085,9 +1523,9 @@ export function findRank(l, laws = [], opts = {}) {
1085
1523
  if (late && 'trees' in late.verdict)
1086
1524
  return done(late.rank, late.verdict.trees);
1087
1525
  if (!base || 'trees' in base.verdict)
1088
- return { proven: false, checked: false, why: `no rank, linear or of degree 2, in order, drops on every turn of ${edges.size} sampled` };
1526
+ return { proven: false, checked: false, why: `no rank, linear or of degree 2, in order, drops on every turn of ${edges.size} sampled; the relation: ${relWhy}` };
1089
1527
  const text = `(${base.rank.map(showE).join(', ')})`, first = base.verdict;
1090
- return { proven: false, checked: false, rank: base.rank, found: { rank: text, laws: [] }, goal: first.goal, stuck: first.stuck, ...(first.witness ? { witness: first.witness } : {}), why: `rank ${text} from the runs; no invariant found that it needs` };
1528
+ return { proven: false, checked: false, rank: base.rank, found: { rank: text, laws: [] }, goal: first.goal, stuck: first.stuck, ...(first.witness ? { witness: first.witness } : {}), why: `rank ${text} from the runs; no invariant found that it needs; the relation: ${relWhy}` };
1091
1529
  }
1092
1530
  export function findLeadsTo(m, laws, l, sample, opts = {}) {
1093
1531
  const t0 = performance.now(), until = t0 + (opts.ms ?? 10_000), rand = seeded(29), run = interpret(m);
@@ -204,6 +204,7 @@ export declare class Data {
204
204
  readonly group: string[];
205
205
  readonly ctors: Ctor[];
206
206
  readonly seq: number;
207
+ abstract: boolean;
207
208
  constructor(name: string, decl: Record<string, Record<string, FieldSort>>, group?: string[]);
208
209
  index(ctor: string): number;
209
210
  get nullary(): number;
@@ -293,7 +294,7 @@ export declare function evalY(y: Y, env: Env, params: Record<string, (n: number)
293
294
  export declare const showValue: (d: Sort, v: Value) => string;
294
295
  type Rand = () => number;
295
296
  export declare const rng: (seed: number) => Rand;
296
- export declare function randomValue(s: Sort, rand: Rand, size: number, natMax?: number): Value;
297
+ export declare function randomValue(s: Sort, rand: Rand, size: number, natMax?: number, full?: boolean): Value;
297
298
  export declare const randomFn: (rand: Rand, natMax?: number) => ((n: number) => number);
298
299
  export type Sample = {
299
300
  env: Env;
@@ -408,6 +409,7 @@ type Companion = {
408
409
  };
409
410
  uses: SchemeUse[];
410
411
  };
412
+ export declare const rankWidth: (p: Program) => number;
411
413
  export declare const schemesOf: (p: Program, l: DataLaw) => Scheme[];
412
414
  export type Proven = {
413
415
  law: DataLaw;
@@ -437,4 +439,17 @@ export declare function searchIn(l: DataLaw, opts: Options, until: number, ctx?:
437
439
  out?: Proven;
438
440
  };
439
441
  export declare const proveDataToday: (l: DataLaw) => DataVerdict;
442
+ export declare function opaque(name: string): Data;
443
+ export declare function unknownFn(name: string, from: Sort[], to: Sort): ((...args: unknown[]) => Nat | Bool | Val | Integer) & {
444
+ param: string;
445
+ };
446
+ export declare function closures(name: string, args: Record<string, Sort>, ret: Sort, cases: Record<string, {
447
+ fields?: Record<string, unknown>;
448
+ apply: (fields: Record<string, any>, args: Record<string, any>) => Nat | Bool | Val | Integer | number;
449
+ }>, opts?: {
450
+ unknown?: string;
451
+ }): {
452
+ data: Data & Record<string, any>;
453
+ apply: Callable;
454
+ };
440
455
  export {};