gdp-wired 0.21.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.
Files changed (44) hide show
  1. package/README.md +16 -1
  2. package/dist/core/bmc.d.ts +38 -0
  3. package/dist/core/bmc.js +137 -0
  4. package/dist/core/check.d.ts +1 -1
  5. package/dist/core/check.js +19 -6
  6. package/dist/core/cycles.d.ts +15 -0
  7. package/dist/core/cycles.js +446 -8
  8. package/dist/core/cyclic.d.ts +6 -1
  9. package/dist/core/cyclic.js +13 -1
  10. package/dist/core/data.d.ts +17 -1
  11. package/dist/core/data.js +637 -97
  12. package/dist/core/dsl.d.ts +10 -1
  13. package/dist/core/dsl.js +47 -12
  14. package/dist/core/infer.js +518 -5
  15. package/dist/core/nonterm.d.ts +34 -0
  16. package/dist/core/nonterm.js +610 -0
  17. package/dist/core/q.d.ts +17 -0
  18. package/dist/core/q.js +52 -0
  19. package/dist/core/rationals.d.ts +112 -0
  20. package/dist/core/rationals.js +281 -0
  21. package/dist/core/relation.d.ts +28 -0
  22. package/dist/core/relation.js +480 -0
  23. package/dist/core/solver.d.ts +5 -2
  24. package/dist/core/solver.js +65 -20
  25. package/dist/core/transfer.d.ts +3 -3
  26. package/dist/core/transfer.js +77 -42
  27. package/dist/kernel/cdcl.d.ts +43 -0
  28. package/dist/kernel/cdcl.js +564 -0
  29. package/dist/kernel/kernel.d.ts +91 -0
  30. package/dist/kernel/kernel.js +310 -0
  31. package/dist/kernel/prove.d.ts +20 -1
  32. package/dist/kernel/prove.js +119 -44
  33. package/dist/kernel/qprove.d.ts +18 -0
  34. package/dist/kernel/qprove.js +157 -0
  35. package/dist/kernel/reader.d.ts +79 -0
  36. package/dist/kernel/reader.js +539 -0
  37. package/dist/kernel/simplex.d.ts +36 -0
  38. package/dist/kernel/simplex.js +259 -0
  39. package/dist/lean-kernel/emit.d.ts +19 -1
  40. package/dist/lean-kernel/emit.js +71 -3
  41. package/dist/lean-kernel/library.js +2 -0
  42. package/dist/lean-kernel/qlean.d.ts +26 -0
  43. package/dist/lean-kernel/qlean.js +105 -0
  44. package/package.json +6 -2
@@ -1091,6 +1091,84 @@ export function loopObligations(l, laws, rank) {
1091
1091
  const m = loopMachine(l), { stay, cover, helps } = livenessParts(m, loopLiveness(l, rank));
1092
1092
  return [...obligations(m, laws, {}), ...[stay, cover, ...helps].map(sl => stepLawObligations(m, laws, {}, sl)[0])];
1093
1093
  }
1094
+ // The closure goal, built as Lean's recurGoal builds it: [set, ¬(while ∧ (assume ∧ set after the body)), each read at the
1095
+ // witnessed request].
1096
+ export function recurGoal(l, r) {
1097
+ const w = { vars: r.wit, maps: {}, flags: {} };
1098
+ return { name: `${l.name} never ends: the set is closed`, hyps: [r.set, { op: 'not', x: { op: 'and', xs: [substC(l.while, w), substC(l.assume ?? trueC, w),
1099
+ substC(substC(r.set, { vars: l.body, maps: {}, flags: {} }), w)] } }] };
1100
+ }
1101
+ // Lean's evalE and evalC over naturals with every map cell 0 (NonTerm.lean's noMaps): exact, never rounded.
1102
+ const natE = (e, env) => {
1103
+ switch (e.op) {
1104
+ case 'var': return env[e.name] ?? 0n;
1105
+ case 'const': return BigInt(e.value);
1106
+ case 'add': return natE(e.a, env) + natE(e.b, env);
1107
+ case 'sub': {
1108
+ const d = natE(e.a, env) - natE(e.b, env);
1109
+ return d > 0n ? d : 0n;
1110
+ }
1111
+ case 'mul': return BigInt(e.k) * natE(e.a, env);
1112
+ case 'prod': return natE(e.a, env) * natE(e.b, env);
1113
+ case 'min': {
1114
+ const a = natE(e.a, env), b = natE(e.b, env);
1115
+ return a < b ? a : b;
1116
+ }
1117
+ case 'max': {
1118
+ const a = natE(e.a, env), b = natE(e.b, env);
1119
+ return a > b ? a : b;
1120
+ }
1121
+ case 'if': return natC(e.c, env) ? natE(e.then, env) : natE(e.else, env);
1122
+ case 'get': return 0n;
1123
+ default: return unreachable(e);
1124
+ }
1125
+ };
1126
+ const natC = (c, env) => {
1127
+ switch (c.op) {
1128
+ case '<=': return natE(c.a, env) <= natE(c.b, env);
1129
+ case '<': return natE(c.a, env) < natE(c.b, env);
1130
+ case '=': return natE(c.a, env) === natE(c.b, env);
1131
+ case 'and': return c.xs.every(x => natC(x, env));
1132
+ case 'or': return c.xs.some(x => natC(x, env));
1133
+ case 'not': return !natC(c.x, env);
1134
+ case 'flag':
1135
+ case 'all': throw new Error('a loop reads no flag');
1136
+ default: return unreachable(c);
1137
+ }
1138
+ };
1139
+ // Lean's checkRecur: the witness sets only inputs; the start meets the precondition; the stem's turns meet `while` and
1140
+ // the assumption, and the state after them is in the set; the closure goal's tree checks. A certificate outside the
1141
+ // language (names the loop doesn't declare, values that aren't naturals, a set reading a turn's input) is refused.
1142
+ export function checkRecur(l, r) {
1143
+ const names = [...l.params, ...l.inputs, ...Object.keys(l.state)], values = (o) => Object.values(o).every(x => Number.isSafeInteger(x) && x >= 0);
1144
+ distinct(l.name, names);
1145
+ for (const name of Object.keys(l.body))
1146
+ if (!(name in l.state))
1147
+ throw new Error(`${l.name}'s body sets ${name}, which isn't in its state`);
1148
+ inScope(`${l.name}'s start`, Object.values(l.state), l.params);
1149
+ inScope(l.name, [...Object.values(l.body), ...(l.assume ? [l.assume] : [])], names);
1150
+ inScope(`${l.name}'s while`, [l.while], [...l.params, ...Object.keys(l.state)]);
1151
+ inScope(`${l.name}'s precondition`, l.pre ? [l.pre] : [], l.params);
1152
+ inScope(`${l.name}'s recurrent set and witness`, [r.set, ...Object.values(r.wit)], [...l.params, ...Object.keys(l.state)]);
1153
+ if (![...Object.values(l.state), ...Object.values(l.body), ...Object.values(r.wit)].every(natural) || ![l.while, r.set, ...(l.pre ? [l.pre] : []), ...(l.assume ? [l.assume] : [])].every(naturalC))
1154
+ throw new Error('outside the kernel');
1155
+ if (!Object.keys(r.start).every(n => l.params.includes(n)) || !values(r.start) || !r.stem.every(t => Object.keys(t).every(n => l.inputs.includes(n)) && values(t)))
1156
+ throw new Error(`${l.name}: a start names params and a stem's turn inputs, each a natural`);
1157
+ if (!Object.keys(r.wit).every(n => l.inputs.includes(n)))
1158
+ return false;
1159
+ let env = Object.fromEntries(names.map(n => [n, BigInt(r.start[n] ?? 0)]));
1160
+ if (!natC(l.pre ?? trueC, env))
1161
+ return false;
1162
+ const apply = (body, at) => ({ ...at, ...Object.fromEntries(Object.entries(body).map(([n, e]) => [n, natE(e, at)])) });
1163
+ env = apply(l.state, env);
1164
+ for (const turn of r.stem) {
1165
+ const at = { ...env, ...Object.fromEntries(l.inputs.map(n => [n, BigInt(turn[n] ?? 0)])) };
1166
+ if (!natC(l.while, at) || !natC(l.assume ?? trueC, at))
1167
+ return false;
1168
+ env = apply(l.body, at);
1169
+ }
1170
+ return natC(r.set, env) && check(recurGoal(l, r), r.tree);
1171
+ }
1094
1172
  // --- progress: laws with "there is a request" ----------------------------------------------------------------------
1095
1173
  // "In every reachable state where `when` holds, some request makes `then` true of the step": proven by naming the
1096
1174
  // request (a term per input over the state and params) and proving it allowed (the machine's assumption holds of it)
@@ -1239,3 +1317,235 @@ export function foldObligations(f, laws) {
1239
1317
  const node = step(holds(from(), [...assume, ...laws.flatMap(h => [substC(h.holds, side('l_')), substC(h.holds, side('r_'))])]), { vars: f.node, maps: {} });
1240
1318
  return laws.flatMap(law => [goal(`${law.name} @leaf`, leaf, atEnd(leaf, law.holds)), goal(`${law.name} @node`, node, atEnd(node, law.holds))]);
1241
1319
  }
1320
+ const bgcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b)
1321
+ [a, b] = [b, a % b]; return a; };
1322
+ // Lean's q.num and q.den: the reduced fraction (a denominator <= 0 is no rational).
1323
+ export const ratNorm = (q) => {
1324
+ if (q.den <= 0n)
1325
+ throw new Error('a rational has a positive denominator');
1326
+ const g = bgcd(q.num, q.den) || 1n;
1327
+ return { num: q.num / g, den: q.den / g };
1328
+ };
1329
+ const rscale = (m, r) => ({ cs: new Map(m === 0n ? [] : [...r.cs].map(([x, c]) => [x, m * c])), c: m * r.c });
1330
+ const radd = (a, b) => {
1331
+ const cs = new Map(a.cs);
1332
+ for (const [x, c] of b.cs) {
1333
+ const s = (cs.get(x) ?? 0n) + c;
1334
+ if (s === 0n)
1335
+ cs.delete(x);
1336
+ else
1337
+ cs.set(x, s);
1338
+ }
1339
+ return { cs, c: a.c + b.c };
1340
+ };
1341
+ export const qdif = (a, b) => radd(rscale(b.den, a.row), rscale(-a.den, b.row));
1342
+ // A row as a Lin, its coefficients safe integers (else undefined: a row past 2^53 is not read, so the check is weaker,
1343
+ // never wrong); and its key, as `canon` writes a Lin (zero coefficients dropped: Lean's `same` compares by value).
1344
+ export const qLin = (r) => {
1345
+ const out = {};
1346
+ for (const [x, c] of r.cs) {
1347
+ if (c < -(2n ** 53n) + 1n || c > 2n ** 53n - 1n)
1348
+ return undefined;
1349
+ out[x] = Number(c);
1350
+ }
1351
+ if (r.c !== 0n) {
1352
+ if (r.c < -(2n ** 53n) + 1n || r.c > 2n ** 53n - 1n)
1353
+ return undefined;
1354
+ out['1'] = Number(r.c);
1355
+ }
1356
+ return out;
1357
+ };
1358
+ const linRow = (lin) => {
1359
+ if (!Object.values(lin).every(c => Number.isSafeInteger(c)))
1360
+ return undefined;
1361
+ const cs = new Map();
1362
+ for (const [x, c] of Object.entries(lin))
1363
+ if (x !== '1' && c !== 0)
1364
+ cs.set(x, BigInt(c));
1365
+ return { cs, c: BigInt(lin['1'] ?? 0) };
1366
+ };
1367
+ const rowKey = (r) => { const lin = qLin(r); return lin && canon(lin); };
1368
+ export function qdec(path, r) {
1369
+ if (r.cs.size === 0)
1370
+ return r.c <= 0n;
1371
+ const key = rowKey(r);
1372
+ return key === undefined ? undefined : path.get(key)?.holds;
1373
+ }
1374
+ export function qlinear(e, path) {
1375
+ switch (e.op) {
1376
+ case 'var': return e.name === '1' ? undefined : { row: { cs: new Map([[e.name, 1n]]), c: 0n }, den: 1n };
1377
+ case 'const': {
1378
+ const q = ratNorm(e.q);
1379
+ return { row: { cs: new Map(), c: q.num }, den: q.den };
1380
+ }
1381
+ case 'add':
1382
+ case 'sub': {
1383
+ const a = qlinear(e.a, path), b = qlinear(e.b, path);
1384
+ if (!a || !b)
1385
+ return undefined;
1386
+ return { row: e.op === 'add' ? radd(rscale(b.den, a.row), rscale(a.den, b.row)) : qdif(a, b), den: a.den * b.den };
1387
+ }
1388
+ case 'mul': {
1389
+ const k = ratNorm(e.k), a = qlinear(e.a, path);
1390
+ return a && { row: rscale(k.num, a.row), den: k.den * a.den };
1391
+ }
1392
+ case 'min':
1393
+ case 'max': {
1394
+ const a = qlinear(e.a, path), b = qlinear(e.b, path);
1395
+ if (!a || !b)
1396
+ return undefined;
1397
+ const d = qdec(path, qdif(a, b));
1398
+ return d === undefined ? undefined : (d === (e.op === 'min')) ? a : b;
1399
+ }
1400
+ case 'if': {
1401
+ const t = qtruth(e.c, path);
1402
+ return t === undefined ? undefined : qlinear(t ? e.then : e.else, path);
1403
+ }
1404
+ default: return unreachable(e);
1405
+ }
1406
+ }
1407
+ export function qtruth(c, path) {
1408
+ switch (c.op) {
1409
+ case '<=':
1410
+ case '<':
1411
+ case '=': {
1412
+ const a = qlinear(c.a, path), b = qlinear(c.b, path);
1413
+ if (!a || !b)
1414
+ return undefined;
1415
+ if (c.op === '<=')
1416
+ return qdec(path, qdif(a, b));
1417
+ if (c.op === '<') {
1418
+ const d = qdec(path, qdif(b, a));
1419
+ return d === undefined ? undefined : !d;
1420
+ }
1421
+ const d1 = qdec(path, qdif(a, b)), d2 = qdec(path, qdif(b, a));
1422
+ return d1 === false || d2 === false ? false : d1 === true && d2 === true ? true : undefined;
1423
+ }
1424
+ case 'and':
1425
+ case 'or': {
1426
+ const ta = qtruth(c.a, path), tb = qtruth(c.b, path), dominant = c.op === 'or';
1427
+ return ta === dominant || tb === dominant ? dominant : ta === !dominant && tb === !dominant ? !dominant : undefined;
1428
+ }
1429
+ case 'not': {
1430
+ const t = qtruth(c.x, path);
1431
+ return t === undefined ? undefined : !t;
1432
+ }
1433
+ default: return unreachable(c);
1434
+ }
1435
+ }
1436
+ // The rows (each with its strictness) a hypothesis gives under the path when it has the truth value `pos`.
1437
+ export function qfacts(c, path, pos = true) {
1438
+ switch (c.op) {
1439
+ case 'not': return qfacts(c.x, path, !pos);
1440
+ case 'and':
1441
+ case 'or': {
1442
+ // and when true, or when false: both parts; otherwise the part the other one's truth leaves.
1443
+ if ((c.op === 'and') === pos)
1444
+ return [...qfacts(c.a, path, pos), ...qfacts(c.b, path, pos)];
1445
+ if (qtruth(c.a, path) === !pos)
1446
+ return qfacts(c.b, path, pos);
1447
+ if (qtruth(c.b, path) === !pos)
1448
+ return qfacts(c.a, path, pos);
1449
+ return [];
1450
+ }
1451
+ case '<=':
1452
+ case '<':
1453
+ case '=': {
1454
+ const a = qlinear(c.a, path), b = qlinear(c.b, path);
1455
+ if (!a || !b)
1456
+ return [];
1457
+ if (c.op === '<=')
1458
+ return pos ? [[qdif(a, b), false]] : [[qdif(b, a), true]];
1459
+ if (c.op === '<')
1460
+ return pos ? [[qdif(a, b), true]] : [[qdif(b, a), false]];
1461
+ if (pos)
1462
+ return [[qdif(a, b), false], [qdif(b, a), false]];
1463
+ if (qdec(path, qdif(a, b)) === true)
1464
+ return [[qdif(a, b), true]];
1465
+ if (qdec(path, qdif(b, a)) === true)
1466
+ return [[qdif(b, a), true]];
1467
+ return [];
1468
+ }
1469
+ default: return unreachable(c);
1470
+ }
1471
+ }
1472
+ // A leaf's rows: the path's atoms (l <= 0, or −l < 0), then each hypothesis' facts; a row past 2^53 is left out.
1473
+ export function qLeafRows(goal, path) {
1474
+ const rows = [...[...path.values()].map(a => (a.holds ? [linRow(a.lin), false] : [rscale(-1n, linRow(a.lin)), true])),
1475
+ ...goal.hyps.flatMap(h => qfacts(h, path))];
1476
+ return rows.flatMap(([r, strict]) => { const lin = qLin(r); return lin ? [{ lin, label: '', strict }] : []; });
1477
+ }
1478
+ // A split on a row the path decides already (or a constant one) is refused, as Lean's checkT refuses it.
1479
+ export function checkQTree(goal, tree, path = new Map()) {
1480
+ if ('leaf' in tree)
1481
+ return !tree.products?.length && !tree.squares?.length && checkRefutation(qLeafRows(goal, path), tree.leaf, false);
1482
+ const row = linRow(tree.split), lin = row && qLin(row);
1483
+ if (!row || !lin || qdec(path, row) !== undefined)
1484
+ return false;
1485
+ const key = canon(lin);
1486
+ return checkQTree(goal, tree.yes, new Map(path).set(key, { lin, holds: true })) && checkQTree(goal, tree.no, new Map(path).set(key, { lin, holds: false }));
1487
+ }
1488
+ export const qTrue = { op: '<=', a: { op: 'const', q: { num: 0n, den: 1n } }, b: { op: 'const', q: { num: 0n, den: 1n } } };
1489
+ export function qSubstE(e, s) {
1490
+ switch (e.op) {
1491
+ case 'var': return Object.hasOwn(s, e.name) ? s[e.name] : e;
1492
+ case 'const': return e;
1493
+ case 'mul': return { ...e, a: qSubstE(e.a, s) };
1494
+ case 'if': return { op: 'if', c: qSubstC(e.c, s), then: qSubstE(e.then, s), else: qSubstE(e.else, s) };
1495
+ case 'add':
1496
+ case 'sub':
1497
+ case 'min':
1498
+ case 'max': return { ...e, a: qSubstE(e.a, s), b: qSubstE(e.b, s) };
1499
+ default: return unreachable(e);
1500
+ }
1501
+ }
1502
+ export function qSubstC(c, s) {
1503
+ switch (c.op) {
1504
+ case 'not': return { op: 'not', x: qSubstC(c.x, s) };
1505
+ case 'and':
1506
+ case 'or': return { op: c.op, a: qSubstC(c.a, s), b: qSubstC(c.b, s) };
1507
+ case '<=':
1508
+ case '<':
1509
+ case '=': return { op: c.op, a: qSubstE(c.a, s), b: qSubstE(c.b, s) };
1510
+ default: return unreachable(c);
1511
+ }
1512
+ }
1513
+ export function qOccurs(t, names) {
1514
+ switch (t.op) {
1515
+ case 'var': return names.includes(t.name);
1516
+ case 'const': return false;
1517
+ case 'mul': return qOccurs(t.a, names);
1518
+ case 'not': return qOccurs(t.x, names);
1519
+ case 'if': return qOccurs(t.c, names) || qOccurs(t.then, names) || qOccurs(t.else, names);
1520
+ case 'and':
1521
+ case 'or': return qOccurs(t.a, names) || qOccurs(t.b, names);
1522
+ case 'add':
1523
+ case 'sub':
1524
+ case 'min':
1525
+ case 'max':
1526
+ case '<=':
1527
+ case '<':
1528
+ case '=': return qOccurs(t.a, names) || qOccurs(t.b, names);
1529
+ default: return unreachable(t);
1530
+ }
1531
+ }
1532
+ // startGoal and stepGoal: the law refuted at the start, and after a step from where every law and the request's
1533
+ // assumption hold.
1534
+ export function qObligations(m, laws, law) {
1535
+ const pre = m.pre ?? qTrue, assume = m.assume ?? qTrue;
1536
+ return {
1537
+ start: { name: `${law.name} @start`, hyps: [pre, { op: 'not', x: qSubstC(law.holds, m.state) }] },
1538
+ step: { name: `${law.name} @step`, hyps: [pre, assume, ...laws.map(l => l.holds), { op: 'not', x: qSubstC(law.holds, m.step) }] },
1539
+ };
1540
+ }
1541
+ // checkMachine: the precondition reads no input and no state variable, no law reads an input, and each law's start
1542
+ // and step goals are refuted by its trees.
1543
+ export function checkQMachine(m, laws, trees) {
1544
+ const assigned = [...m.inputs, ...Object.keys(m.state), ...Object.keys(m.step)];
1545
+ if (m.pre && qOccurs(m.pre, assigned))
1546
+ return false;
1547
+ return laws.every(law => {
1548
+ const t = trees[law.name], goals = qObligations(m, laws, law);
1549
+ return !!t && !qOccurs(law.holds, m.inputs) && checkQTree(goals.start, t.start) && checkQTree(goals.step, t.step);
1550
+ });
1551
+ }
@@ -1,8 +1,13 @@
1
1
  import type { C, E, Law, Machine } from '../core/machine.js';
2
- import { type Goal, type Instances, type Liveness, type Path, type StepLaw, type Tree } from './kernel.js';
2
+ import { type Lin } from '../core/solver.js';
3
+ import type { Cyclic } from './cyclic.js';
4
+ import { type Goal, type Instances, type Liveness, type Loop, type Path, type StepLaw, type Tree, leafConstraintsReusing } from './kernel.js';
3
5
  export declare const pairedKeys: {
4
6
  skip: boolean;
5
7
  };
8
+ export declare function openCells(rows: {
9
+ lin: Lin;
10
+ }[], path: Path): Lin[];
6
11
  export declare const profile: {
7
12
  on: boolean;
8
13
  goals: {
@@ -47,7 +52,13 @@ export declare function grow(goal: Goal, path?: Path, budget?: {
47
52
  until?: number;
48
53
  units?: boolean;
49
54
  }): Outcome;
55
+ export declare function rowsAt(goal: Goal, path: Path): ReturnType<typeof leafConstraintsReusing>;
50
56
  export declare function widen(part: Goal, whole: Goal, tree: Tree, opaque?: Record<string, E>, pp?: Path, wp?: Path): Tree | undefined;
57
+ export declare function nearOf(goal: Goal): boolean[];
58
+ export declare const unitAtoms: (goal: Goal) => Lin[];
59
+ export declare function openAt(goal: Goal, path: Path, rows: {
60
+ lin: Lin;
61
+ }[]): Lin[];
51
62
  export declare const minimal: {
52
63
  on: boolean;
53
64
  };
@@ -109,6 +120,7 @@ export declare function proveStepLaws(given0: Machine, given: Law[], stepLaws: S
109
120
  machine?: Machine;
110
121
  stepLaws?: StepLaw[];
111
122
  proof?: StepProof;
123
+ uncovered?: string[];
112
124
  };
113
125
  export declare function proveProgress(m: Machine, laws: Law[], p: {
114
126
  name: string;
@@ -118,10 +130,17 @@ export declare function proveProgress(m: Machine, laws: Law[], p: {
118
130
  }): Report & {
119
131
  instances?: Instances;
120
132
  trees?: Record<string, Tree>;
133
+ uncovered?: string;
121
134
  };
122
135
  export declare function proveLiveness(m: Machine, laws: Law[], l: Liveness): Report & {
123
136
  steps?: ReturnType<typeof proveStepLaws>;
137
+ uncovered?: string[];
124
138
  };
139
+ export declare function certLoop(l: Loop, laws: Law[], rank: E | E[], trees: Record<string, Tree>, usualMs?: number): {
140
+ checked: boolean;
141
+ proof?: Cyclic;
142
+ why: string;
143
+ } | undefined;
125
144
  export declare const countLeaves: (t: Tree) => number;
126
145
  export declare function concretize(goal: Goal, bound?: number): Record<string, number> | undefined;
127
146
  export declare function factsFor(m: Machine, goal: Goal): C[];
@@ -1,8 +1,9 @@
1
1
  import { add, k, refuteFast, scale, solve, sub, v, work } from "../core/solver.js";
2
2
  import { checkRefutation } from "../core/check.js";
3
- import { allowNode, allowTranslated, certCyclic, certOn, certSearch, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
3
+ import { allowNode, allowTranslated, certCyclic, certOn, certSearch, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
4
4
  import { proveSome, someLaws } from "../core/exists.js";
5
- import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
5
+ import { growCdcl } from "./cdcl.js";
6
+ import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
6
7
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
7
8
  function openE(e, path, out) {
8
9
  switch (e.op) {
@@ -83,7 +84,7 @@ function openH(c, path, out, positive = true) {
83
84
  // keys a pairing builds ((a + b)² + b, keys whose difference has monomials) are left uncompared: that encoding states
84
85
  // their congruence as facts, and comparing their keys only brings products into leaves its linear rows decide.
85
86
  export const pairedKeys = { skip: false };
86
- function openCells(rows, path) {
87
+ export function openCells(rows, path) {
87
88
  const names = [...new Set(rows.flatMap(r => Object.keys(r.lin)))].filter(isCell);
88
89
  const out = [];
89
90
  const keyText = (n) => n.slice(n.indexOf('[') + 1, -1);
@@ -255,14 +256,25 @@ export function grow(goal, path = new Map(), budget = { nodes: 0, until: clock()
255
256
  profile.goals.push({ name: goal.name, ms: performance.now() - t, nodes: profile.nodes - n0, solves: profile.solves - s0, solveMs: profile.solveMs - m0, rowsMs: profile.rowsMs - r0, proven: 'tree' in out });
256
257
  return out;
257
258
  }
259
+ // The share of a root goal's budget the CDCL search gets (GDP_CDCL_SHARE; 0 turns it off), and the quick search's nodes
260
+ // before it (GDP_QUICK_CAP; 64 where the CDCL search isn't tried, as before it): research/step's comparisons.
261
+ const proveEnv = globalThis.process?.env ?? {};
262
+ const cdclShare = Number(proveEnv.GDP_CDCL_SHARE ?? 0.75), quickCap = Number(proveEnv.GDP_QUICK_CAP ?? 16);
258
263
  function growRoot(goal, path, budget) {
264
+ // Past a few cases, CDCL over the atoms (kernel/cdcl.ts), with most of the budget: a linear goal's refutation there
265
+ // is a resolution of short clauses, which the tree search would find again in every case that reaches one. Unknown
266
+ // there, the plain search, the cuts and the plain search again have the rest. Not for a law over k steps in a row
267
+ // (kernel.ts names its goals `@k steps`): the cuts make its tree a chain of one step's refutations, which the CDCL
268
+ // search's tree, unfolded, repeats (research/step: four times the Lean text of examples/steps.ts). Nor for products.
269
+ const root = path.size === 0 && budget.nodes === 0 ? leafConstraints(goal, path) : undefined;
270
+ const cdcl = !!root && cdclShare > 0 && !cellProducts.on && Number(/@(\d+) steps/.exec(goal.name)?.[1] ?? 1) <= 1 && !root.some(r => Object.keys(r.lin).some(isMonomial));
259
271
  // At the root: plainly first; where the cases multiply past a budget, through cuts. The plain budget halves with each
260
272
  // two open choices (what a plain search's cases grow by), so a long run's steps reach the cuts early.
261
- if (path.size === 0 && budget.nodes === 0 && unitFirst && unitsNow) {
273
+ if (root && unitFirst && unitsNow) {
262
274
  // A goal that a few cases settle needs no units (finding them costs a Farkas check per atom); the rest get them.
263
275
  unitsNow = false;
264
276
  try {
265
- const quick = growPlain(goal, path, { nodes: 0, until: budget.until, cap: 64 });
277
+ const quick = growPlain(goal, path, { nodes: 0, until: budget.until, cap: cdcl ? quickCap : 64 });
266
278
  if ('tree' in quick || quick.stuck === 'sat' || quick.why === undefined)
267
279
  return quick;
268
280
  }
@@ -270,8 +282,14 @@ function growRoot(goal, path, budget) {
270
282
  unitsNow = true;
271
283
  }
272
284
  }
273
- if (path.size === 0 && budget.nodes === 0) {
274
- const open = new Set(leafConstraints(goal, path).flatMap(r => Object.keys(r.lin)).filter(n => n.startsWith('⟦') && columnTerm(n)?.op === 'if')).size;
285
+ if (root) {
286
+ if (cdcl) {
287
+ const now = clock(), end = withinDeadline(budget.until ?? Infinity);
288
+ const out = growCdcl(goal, path, { nodes: 0, until: end === Infinity ? end : now + cdclShare * (end - now) });
289
+ if ('tree' in out || out.stuck === 'sat')
290
+ return out;
291
+ }
292
+ const open = new Set(root.flatMap(r => Object.keys(r.lin)).filter(n => n.startsWith('⟦') && columnTerm(n)?.op === 'if')).size;
275
293
  const plain = growPlain(goal, path, { nodes: 0, until: budget.until, cap: Math.max(32, Math.round(4_000 / 2 ** (open / 2))) });
276
294
  if ('tree' in plain || plain.stuck === 'sat' || plain.why === undefined)
277
295
  return plain;
@@ -299,30 +317,7 @@ function growPlain(goal, path, budget) {
299
317
  const { steps, products, squares } = products0 || squares0 ? trimmed(rows.length, steps0, products0 ?? [], squares0 ?? []) : { steps: steps0, products: undefined, squares: undefined };
300
318
  return { leaf: steps.map(st => (st.kind === 'input' ? { ...st, index: at(st.index) } : st)), ...(products?.length ? { products: products.map(([i, j]) => [at(i), at(j)]) } : {}), ...(squares?.length ? { squares } : {}) };
301
319
  };
302
- // The conclusion's own atoms first (the goal's last hypothesis is the law refuted): a case it doesn't read is often
303
- // one no refutation needs, and splitting it first multiplies every case after it.
304
- const open = [];
305
- const hyps = goal.hyps, last = hyps.length - 1;
306
- let byHyp = openSeen.get(goal);
307
- if (!byHyp)
308
- openSeen.set(goal, (byHyp = new Map()));
309
- const openOf = (h) => { let seen = byHyp.get(h); if (!seen)
310
- byHyp.set(h, (seen = {})); return reusing(seen, path, p => { const out = []; openH(h, p, out); return out; }); };
311
- // Then the hypotheses about only the names the conclusion reads (an assumption about another key, a witness, can
312
- // wait: a refutation seldom needs it), then the rest, each group in the goal's order.
313
- if (unitFirst && unitsNow)
314
- open.push(...unitsOf(goal));
315
- if (last >= 0)
316
- open.push(...openOf(hyps[last]));
317
- const near = nearOf(goal);
318
- for (const [i, h] of hyps.entries())
319
- if (i !== last && near[i])
320
- open.push(...openOf(h));
321
- for (const [i, h] of hyps.entries())
322
- if (i !== last && !near[i])
323
- open.push(...openOf(h));
324
- open.push(...openCells(rows, path));
325
- const next = open.find(lin => Object.keys(lin).some(key => key !== '1') && !path.has(canon(lin)) && !path.has(canonFlip(lin)));
320
+ const next = openAt(goal, path, rows).find(lin => Object.keys(lin).some(key => key !== '1') && !path.has(canon(lin)) && !path.has(canonFlip(lin)));
326
321
  // With a case still to split, only "refuted or not" matters (a witness here goes unused): a large system is tried by
327
322
  // its Farkas rows alone, and left to the split if they don't refute it. Elimination to the last variable, which a
328
323
  // satisfiable system needs to say so, is kept for small systems and for the leaves, where its answer is the outcome.
@@ -584,7 +579,7 @@ function squareForms(rows) {
584
579
  // A leaf's rows, by its path's decisions in order (what they are a function of): a lift reads every leaf of a subtree
585
580
  // at its own path, found when it was grown, and at the path without the split, which the next lift up reads again.
586
581
  const rowsSeen = new WeakMap();
587
- function rowsAt(goal, path) {
582
+ export function rowsAt(goal, path) {
588
583
  let byPath = rowsSeen.get(goal);
589
584
  if (!byPath)
590
585
  rowsSeen.set(goal, (byPath = new Map()));
@@ -722,7 +717,7 @@ export function widen(part, whole, tree, opaque = {}, pp = new Map(), wp = pp) {
722
717
  // Whether each hypothesis reads only names the goal's conclusion (its last hypothesis) reads.
723
718
  const nearSeen = new WeakMap();
724
719
  const namesOf = (t) => (t === undefined ? [] : [...JSON.stringify(t).matchAll(/"(?:name|map)":"([^"]+)"/g)].map(m => m[1]));
725
- function nearOf(goal) {
720
+ export function nearOf(goal) {
726
721
  let out = nearSeen.get(goal);
727
722
  if (!out) {
728
723
  const theirs = new Set(namesOf(goal.hyps.at(-1)));
@@ -736,6 +731,8 @@ function nearOf(goal) {
736
731
  // GDP_UNITS=0 leaves them in the goal's order (for comparing).
737
732
  const unitFirst = globalThis.process?.env?.GDP_UNITS !== '0';
738
733
  let unitsNow = true;
734
+ // The units growPlain splits first, where it does (kernel/cdcl.ts reads them too).
735
+ export const unitAtoms = (goal) => (unitFirst && unitsNow ? unitsOf(goal) : []);
739
736
  const unitSeen = new WeakMap();
740
737
  function unitsOf(goal) {
741
738
  let out = unitSeen.get(goal);
@@ -777,6 +774,36 @@ function unitsOf(goal) {
777
774
  }
778
775
  // Each hypothesis' open atoms, as at an earlier path that decided the same atoms it reads (kernel.ts's reusing).
779
776
  const openSeen = new WeakMap();
777
+ // The atoms a split may take at the path, in the order growPlain tries them (some may be decided already). The
778
+ // conclusion's own atoms first (the goal's last hypothesis is the law refuted): a case it doesn't read is often one no
779
+ // refutation needs, and splitting it first multiplies every case after it. Then the hypotheses about only the names
780
+ // the conclusion reads (an assumption about another key, a witness, can wait: a refutation seldom needs it), then the
781
+ // rest, each group in the goal's order, then pairs of cells.
782
+ export function openAt(goal, path, rows) {
783
+ const open = [];
784
+ const hyps = goal.hyps, last = hyps.length - 1;
785
+ let byHyp = openSeen.get(goal);
786
+ if (!byHyp)
787
+ openSeen.set(goal, (byHyp = new Map()));
788
+ const openOf = (h) => { let seen = byHyp.get(h); if (!seen)
789
+ byHyp.set(h, (seen = {})); return reusing(seen, path, p => { const out = []; openH(h, p, out); return out; }); };
790
+ // (pushed one by one: a k-step unrolling's lists outgrow a spread's argument limit)
791
+ const put = (xs) => { for (const x of xs)
792
+ open.push(x); };
793
+ if (unitFirst && unitsNow)
794
+ put(unitsOf(goal));
795
+ if (last >= 0)
796
+ put(openOf(hyps[last]));
797
+ const near = nearOf(goal);
798
+ for (const [i, h] of hyps.entries())
799
+ if (i !== last && near[i])
800
+ put(openOf(h));
801
+ for (const [i, h] of hyps.entries())
802
+ if (i !== last && !near[i])
803
+ put(openOf(h));
804
+ put(openCells(rows, path));
805
+ return open;
806
+ }
780
807
  // What ran out, for a goal left unknown: its size, how deep the case splits went, and the two shapes that usually cause it.
781
808
  function outOfBudget(goal, limit, depth) {
782
809
  const steps = Number(/@(\d+) steps/.exec(goal.name)?.[1] ?? 1);
@@ -1585,7 +1612,10 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1585
1612
  // trees are its input, as a machine's laws' are: checkStepLaws (the laws' usual trees again, then the step laws') runs
1586
1613
  // only where no certificate is made.
1587
1614
  const byCert = certOn() && !cyclicOn() && !why && one.length > 0 && base.checked;
1588
- const out = { proven: true, nodes, leaves, checked: byCert || checkStepLaws(m, laws, stepLaws, proof), proof };
1615
+ // (`uncovered`: why each step law left on the usual rule is, where the certificate is on: none, every step law has its
1616
+ // cyclic certificate; proveLiveness reads it)
1617
+ const left = [], miss = (sl, why) => { uncovered((sl.steps ?? 1) > 1 ? 'k-step law' : 'step law', m.name, why); left.push(why); };
1618
+ const out = { proven: true, nodes, leaves, checked: byCert || checkStepLaws(m, laws, stepLaws, proof), proof, ...(certOn() ? { uncovered: left } : {}) };
1589
1619
  if (!modes)
1590
1620
  return out;
1591
1621
  if (!why && one.length && out.checked) {
@@ -1603,7 +1633,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1603
1633
  for (const x of all) {
1604
1634
  const c = all.length > 1 ? certCyclic('step law', m.name, translatedOf([x]), undefined, usualMs) : together;
1605
1635
  if (!c.checked)
1606
- uncovered((x.sl.steps ?? 1) > 1 ? 'k-step law' : 'step law', m.name, c.why);
1636
+ miss(x.sl, c.why);
1607
1637
  }
1608
1638
  }
1609
1639
  }
@@ -1617,11 +1647,11 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1617
1647
  };
1618
1648
  const c = certCyclic('step law', m.name, undefined, searchedSteps, performance.now() - t0);
1619
1649
  for (const sl of c.checked ? [] : rest)
1620
- uncovered((sl.steps ?? 1) > 1 ? 'k-step law' : 'step law', m.name, `${restWhy(sl)}: ${c.why}`);
1650
+ miss(sl, `${restWhy(sl)}: ${c.why}`);
1621
1651
  }
1622
1652
  else if (cyclicOn() || certOn())
1623
1653
  for (const sl of rest)
1624
- uncovered((sl.steps ?? 1) > 1 ? 'k-step law' : 'step law', m.name, restWhy(sl));
1654
+ miss(sl, restWhy(sl));
1625
1655
  return out;
1626
1656
  }
1627
1657
  // Progress (kernel.ts's progressObligations): the laws proven first, then each goal, the every-key laws assumed at every
@@ -1671,25 +1701,39 @@ export function proveProgress(m, laws, p) {
1671
1701
  return found?.out ?? last;
1672
1702
  };
1673
1703
  const c = certCyclic('progress', m.name, translated, certSearch() ? allowed : undefined, performance.now() - t0);
1674
- if (!c.checked)
1675
- uncovered('progress', m.name, `a request allowed: ${c.why}`);
1704
+ if (!c.checked) {
1705
+ const why = `a request allowed: ${c.why}`;
1706
+ uncovered('progress', m.name, why);
1707
+ return { proven: true, nodes, leaves, checked, instances, trees, uncovered: why };
1708
+ }
1709
+ }
1710
+ else if (cyclicOn() || certOn()) {
1711
+ const why = alone ? 'a request allowed' : 'a request allowed and a claim after it';
1712
+ uncovered('progress', m.name, why);
1713
+ if (certOn())
1714
+ return { proven: true, nodes, leaves, checked, instances, trees, uncovered: why };
1676
1715
  }
1677
- else if (cyclicOn() || certOn())
1678
- uncovered('progress', m.name, alone ? 'a request allowed' : 'a request allowed and a claim after it');
1679
1716
  return { proven: true, nodes, leaves, checked, instances, trees };
1680
1717
  }
1681
1718
  // Liveness (kernel.ts's livenessParts): its step laws, proven together. The claim needs no more (a run takes the
1682
1719
  // request, so it is allowed); but a request never allowed would leave the claim about no run, so where a helpful request
1683
1720
  // names every input a client sends and carries no maps, it is proven allowed in its region too.
1721
+ // The certificate is its parts': the step laws' cyclic proof (translated, as any machine's step laws), and each helpful
1722
+ // request's allowed node. The claim about runs that never end is no certificate's, under either: the rank that can't
1723
+ // drop forever, the region that stays once it stops and the request that comes there are Live.lean's `leads_of_lex`,
1724
+ // read from the step laws' meaning (BridgeRules.lean's `sleads_of_holds`, of a cyclic proof's step laws through
1725
+ // `cyc_kstep_sound`) as from their usual trees (Live.lean's `sleads_sound`): one claim, its statement the same. So a
1726
+ // liveness is covered exactly where every part has its cyclic certificate (`cyclic: {kind: 'liveness', ...}`), and
1727
+ // uncovered, with the part's why, where one is on the usual rule.
1728
+ // (`uncovered`, where the certificate is on: why each part is on the usual rule; none, the liveness is covered)
1684
1729
  export function proveLiveness(m, laws, l) {
1685
- if (cyclicOn() || certOn())
1686
- uncovered('liveness', m.name, 'a claim about runs that never end');
1687
1730
  const { stay, cover, helps } = livenessParts(m, l);
1688
1731
  const a = proveStepLaws(m, laws, [stay, cover, ...helps]);
1689
1732
  if (!a.proven || !a.checked)
1690
1733
  return { proven: false, nodes: a.nodes, leaves: a.leaves, ...(a.failed ? { failed: a.failed } : {}), checked: false };
1691
1734
  const plain = m.history ? historyMachine(m).machine : m;
1692
1735
  let nodes = a.nodes, leaves = a.leaves;
1736
+ const left = [...(a.uncovered ?? []).map(why => `a step law: ${why}`)];
1693
1737
  for (const [i, h] of livenessHelpful(l).entries()) {
1694
1738
  if (m.history || plain.inputMaps?.length || !plain.assume || !plain.inputs.every(inp => inp in h.request))
1695
1739
  continue;
@@ -1698,8 +1742,39 @@ export function proveLiveness(m, laws, l) {
1698
1742
  leaves += b.leaves;
1699
1743
  if (!b.proven || !b.checked)
1700
1744
  return { proven: false, nodes, leaves, ...(b.failed ? { failed: b.failed } : {}), checked: false };
1745
+ if (b.uncovered)
1746
+ left.push(`helpful request ${i + 1} allowed: ${b.uncovered}`);
1747
+ }
1748
+ if (certOn()) {
1749
+ if (left.length)
1750
+ uncovered('liveness', m.name, left.join('; '));
1751
+ else
1752
+ cycLog({ kind: 'liveness', name: m.name, cert: true, usual: true, cyclic: true, route: 'its step laws', parts: 2 + helps.length });
1753
+ }
1754
+ else if (cyclicOn())
1755
+ uncovered('liveness', m.name, 'a claim about runs that never end');
1756
+ return { proven: true, checked: true, nodes, leaves, steps: a, ...(certOn() ? { uncovered: left } : {}) };
1757
+ }
1758
+ // A loop's halting (kernel.ts's loopObligations: its machine's laws, and its liveness's step laws, `while` failing later
1759
+ // from anywhere, every request helpful), its usual trees given: translated to one cyclic proof as proveStepLaws
1760
+ // translates a machine's step laws (core/cyclic.ts's machineNodes, the laws' nodes and the step laws' after them), the
1761
+ // proof Lean reads (lean-kernel/emit.ts's cycMachineToLean: Live.lean's loop_halts_of from BridgeRules.lean's
1762
+ // sleads_of_holds). The claim is the usual one: loop_halts_of reads the liveness's meaning, from either certificate.
1763
+ // Undefined where the cyclic certificate is off (GDP_CERT=usual; with GDP_CYCLIC=1 the cross-check runs); else checked,
1764
+ // the proof, and why not.
1765
+ export function certLoop(l, laws, rank, trees, usualMs) {
1766
+ if (!certOn() && !cyclicOn())
1767
+ return undefined;
1768
+ // (a proof made from the same loop, laws and rank before is that proof: it proves the same claim)
1769
+ const translated = (st) => translatedProof(() => JSON.stringify(['loop', loopMachine(l), laws, rank]), () => timedKind('instance', 0, () => loopNodes(l, laws, rank, trees, st)), st);
1770
+ if (!certOn()) {
1771
+ crossCyclic('loop', l.name, true, undefined, usualMs, translated);
1772
+ return undefined;
1701
1773
  }
1702
- return { proven: true, checked: true, nodes, leaves, steps: a };
1774
+ const c = certCyclic('loop', l.name, translated, undefined, usualMs);
1775
+ if (!c.checked)
1776
+ uncovered('loop', l.name, c.why);
1777
+ return c;
1703
1778
  }
1704
1779
  // The key terms a condition reads maps at; a primed map's key is a key of the map before the step too.
1705
1780
  function readKeysC(c) {