gdp-wired 0.28.0 → 0.30.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.
@@ -1,5 +1,5 @@
1
1
  import { argsKey, atMost as le, compileFunction, evalC as evalMC, evalE as evalME, fnValue, get, interpret, minus as sub, n as k, pairedArgs, plus as add, same as eqC, seeded, walk, x as v } from "./machine.js";
2
- import { check, livenessHelpful, livenessParts, loopLiveness, loopMachine, loopObligations, substC, substE } from "../kernel/kernel.js";
2
+ import { check, livenessHelpful, livenessParts, loopLiveness, loopMachine, loopObligations, strongly, substC, substE } from "../kernel/kernel.js";
3
3
  import { checkCyclic, factsAvoid, lexLt } from "../kernel/cyclic.js";
4
4
  import { and, proveCyclic, vars as vs } from "./cyclic.js";
5
5
  import { canon, env, gcd, konst, pivot, plus, ratioRow, refuteFast, solve, subst, times, vars, work } from "./solver.js";
@@ -1790,7 +1790,7 @@ export function findRank(l, laws = [], opts = {}) {
1790
1790
  }
1791
1791
  export function findLeadsTo(m, laws, l, sample, opts = {}) {
1792
1792
  const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(29), run = interpret(m);
1793
- const names = [...Object.keys(m.state), ...m.params].sort(), helpful = livenessHelpful(l);
1793
+ const names = [...Object.keys(m.state), ...m.params].sort(), helpful = livenessHelpful(l), fair = strongly(l);
1794
1794
  const node = { name: l.name, hyps: [], concl: yes, vars: names, level: 0, given: true };
1795
1795
  const env = (ps, st) => ({ ...ps, ...st.scalars });
1796
1796
  const holds = (c, ps, st) => { try {
@@ -1801,6 +1801,9 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
1801
1801
  } };
1802
1802
  const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
1803
1803
  const points = new Map(), strong = new Map(), weak = new Map();
1804
+ // (under strong fairness, the helpful steps that stay pending, by the regions they land in, and the regions whose
1805
+ // helpful step reached `to`)
1806
+ const handed = [], finishes = new Set();
1804
1807
  for (const bound of [2, 4, 8, 16])
1805
1808
  for (let trial = 0; trial < 20 && clock() < t0 + 1000; trial++) {
1806
1809
  let ps;
@@ -1840,11 +1843,35 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
1840
1843
  break;
1841
1844
  if (was && pending(ps, next)) {
1842
1845
  const e = { from: 0, to: 0, s: here, t: env(ps, next) };
1843
- (h ? strong : weak).set(id([e.s, e.t]), e);
1846
+ if (h && fair)
1847
+ handed.push({ e, from: helpful.indexOf(h), to: helpful.flatMap((g, j) => (g !== h && holds(g.when, ps, next) === true ? [j] : [])) });
1848
+ else
1849
+ (h ? strong : weak).set(id([e.s, e.t]), e);
1844
1850
  }
1851
+ else if (was && h && fair)
1852
+ finishes.add(helpful.indexOf(h));
1845
1853
  st = next;
1846
1854
  }
1847
1855
  }
1856
+ // Under strong fairness a helpful step may hand over to the region of a higher level instead of lowering the rank
1857
+ // (kernel.ts's livenessParts; the levels the kernel's search chooses, kernel/prove.ts's chooseLevels): the levels
1858
+ // read off the runs, a region's the fewer hand-overs from it to one whose helpful step reached `to`, so a step that
1859
+ // hands over closer only keeps the rank and every other must lower it (BullMQ's fetch, wait to active, and promote,
1860
+ // delayed to wait, keep it; a retry, active to wait, lowers it).
1861
+ if (fair) {
1862
+ const dist = helpful.map((_, i) => (finishes.has(i) ? 0 : Infinity));
1863
+ for (let changed = true; changed;) {
1864
+ changed = false;
1865
+ for (const x of handed)
1866
+ for (const j of x.to)
1867
+ if (dist[j] + 1 < dist[x.from]) {
1868
+ dist[x.from] = dist[j] + 1;
1869
+ changed = true;
1870
+ }
1871
+ }
1872
+ for (const x of handed)
1873
+ (x.to.some(j => dist[j] < dist[x.from]) ? weak : strong).set(id([x.e.s, x.e.t]), x.e);
1874
+ }
1848
1875
  // The trivial ranks first, where the runs allow them: the constant 0 (every helpful step in its region reaches `to` at
1849
1876
  // once: none sampled stays pending, which leaves the fit below nothing to fit), then each state variable alone (every
1850
1877
  // helpful step sampled that stays pending lowers it, and no other raises it), up to four of them. Rank 0 may take half
@@ -248,6 +248,10 @@ export type Measure = {
248
248
  comps: {
249
249
  coef: number[];
250
250
  c: number;
251
+ fold?: {
252
+ fn: string;
253
+ of: number;
254
+ };
251
255
  }[];
252
256
  };
253
257
  export type Termination = {
package/dist/core/data.js CHANGED
@@ -447,7 +447,7 @@ function measureOf(name, ps, m) {
447
447
  export const showMeasure = (f, m) => {
448
448
  const comp = (c) => {
449
449
  const parts = c.coef.flatMap((k, i) => (k ? [`${k < 0 ? '−' : ''}${Math.abs(k) === 1 ? '' : `${Math.abs(k)}·`}${f.params[i].sort === 'nat' ? f.params[i].name : `size(${f.params[i].name})`}`] : []));
450
- const t = [...parts, ...(c.c ? [String(c.c)] : [])].join(' + ').replace(/\+ −/g, '− ');
450
+ const t = [...parts, ...(c.fold ? [`${c.fold.fn}(${f.params[c.fold.of].name})`] : []), ...(c.c ? [String(c.c)] : [])].join(' + ').replace(/\+ −/g, '− ');
451
451
  return t || '0';
452
452
  };
453
453
  return m.comps.length === 1 ? comp(m.comps[0]) : `(${m.comps.map(comp).join(', ')})`;
@@ -458,6 +458,8 @@ export function measureX(f, c, args) {
458
458
  const pos = [], neg = [];
459
459
  c.coef.forEach((k, i) => { if (!k)
460
460
  return; const t = sizeX(f.params[i].sort, args[i]); (k > 0 ? pos : neg).push(Math.abs(k) === 1 ? t : { op: 'mul', k: Math.abs(k), a: t }); });
461
+ if (c.fold)
462
+ pos.push({ op: 'call', fn: c.fold.fn, args: [args[c.fold.of]] });
461
463
  if (c.c > 0)
462
464
  pos.push({ op: 'nat', value: c.c });
463
465
  if (c.c < 0)
@@ -608,7 +610,7 @@ function runEdges(ring) {
608
610
  const params = new Proxy({}, { get: (_, key) => tables.get(key) ?? (tables.set(key, randomFn(rand)), tables.get(key)) });
609
611
  for (let i = 0; i < 120 * ring.length && edges.size < 400 * ring.length; i++) {
610
612
  const fn = ring[i % ring.length], vals = fn.params.map(p => randomValue(p.sort, rand, 1 + (Math.floor(i / ring.length) % 7)));
611
- tracing = { fns: new Map(ring.map((g, j) => [g.name, j])), stack: [], fuel: 2000, edge: (a, b) => { const e = { from: a.at, to: b.at, s: featOf(ring[a.at], a.vals), t: featOf(ring[b.at], b.vals) }; edges.set(JSON.stringify(e), e); } };
613
+ tracing = { fns: new Map(ring.map((g, j) => [g.name, j])), stack: [], fuel: 2000, edge: (a, b) => { const e = { from: a.at, to: b.at, s: featOf(ring[a.at], a.vals), t: featOf(ring[b.at], b.vals), sv: a.vals, tv: b.vals }; edges.set(JSON.stringify(e), e); } };
612
614
  try {
613
615
  evalX({ op: 'call', fn: fn.name, args: vals.map((_, j) => ({ op: 'var', name: `$a${j}` })) }, new Map(vals.map((v, j) => [`$a${j}`, v])), params);
614
616
  }
@@ -619,11 +621,12 @@ function runEdges(ring) {
619
621
  }
620
622
  return [...edges.values()];
621
623
  }
622
- const valueOf = (c, xs) => Math.max(0, c.coef.reduce((a, k, i) => a + k * xs[i], c.c));
624
+ const foldAt = (fn, v) => evalX({ op: 'call', fn, args: [{ op: 'var', name: '$v' }] }, new Map([['$v', v]]), {});
625
+ const valueOf = (c, xs, vs) => Math.max(0, c.coef.reduce((a, k, i) => a + k * xs[i], c.c) + (c.fold ? foldAt(c.fold.fn, vs[c.fold.of]) : 0));
623
626
  const lowers = (ms, e) => {
624
627
  const a = ms[e.to], b = ms[e.from];
625
628
  for (const [j, c] of a.comps.entries()) {
626
- const x = valueOf(c, e.t), y = valueOf(b.comps[j], e.s);
629
+ const x = valueOf(c, e.t, e.tv), y = valueOf(b.comps[j], e.s, e.sv);
627
630
  if (x < y)
628
631
  return true;
629
632
  if (x > y)
@@ -803,8 +806,65 @@ function candidates(ring, edges, sites, until) {
803
806
  // (a ring's last: each function the sum of its parameters' sizes)
804
807
  if (ring.length > 1)
805
808
  out.push(ring.map(f => ({ comps: [{ coef: f.params.map(q => (measurable(q.sort) ? 1 : 0)), c: 0 }] })));
809
+ // (a function's last: a weighted size of a parameter, the runs lowering it: below)
810
+ if (ring.length === 1)
811
+ for (const m of foldMeasures(ring[0], edges))
812
+ out.push([m]);
806
813
  return out.map(ms => padded(ring, ms));
807
814
  }
815
+ // A weighted size of a parameter, where no size of the parameters falls (a call on a value of the same size: a tree
816
+ // turned, flatten3's Node(Node(p, x, q), y, r) to Node(p, x, Node(q, y, r)); a list of lists whose first shrinks,
817
+ // weird_concat's): a structural fold of the parameter's datatype, each constructor 1 plus each field's weight times its
818
+ // own fold (a field of the datatype, 1 or 2) or its size (another datatype's, 0 or 1), the first few the runs' calls
819
+ // all lower, the lightest first (at most two). Each is a function defined for it (`fold<datatype>_<weights>`), taken
820
+ // structurally, so the obligations read it as any function: the kernel proves each call lowers it, and Lean's
821
+ // `wf_fix_unique` is about any measure into the naturals.
822
+ function foldMeasures(fn, edges) {
823
+ const out = [];
824
+ if (!edges.length)
825
+ return out;
826
+ for (const [i, q] of fn.params.entries()) {
827
+ const d = q.sort;
828
+ if (!(d instanceof Data) || d.group.length > 1 || d.abstract)
829
+ continue;
830
+ // each field's choices: of the datatype 1 or 2, of another datatype 0 or 1, else 0
831
+ const fields = d.ctors.flatMap((c, j) => c.fields.map((f, k) => ({ j, k, sort: fieldSort(f) })));
832
+ const choices = fields.map(f => (f.sort === d ? [1, 2] : f.sort instanceof Data ? [0, 1] : [0]));
833
+ if (choices.reduce((n, c) => n * c.length, 1) > 64)
834
+ continue;
835
+ let combos = [[]];
836
+ for (const c of choices)
837
+ combos = combos.flatMap(a => c.map(w => [...a, w]));
838
+ // (the plain size is tried before: its weights are 1 on the datatype's fields, 0 on the others')
839
+ const size = fields.map(f => (f.sort === d ? 1 : 0));
840
+ combos = combos.filter(ws => ws.some((w, n) => w !== size[n])).sort((a, b) => a.reduce((x, y) => x + y, 0) - b.reduce((x, y) => x + y, 0));
841
+ const weight = (ws) => { const at = new Map(fields.map((f, n) => [`${f.j}.${f.k}`, ws[n]])); const go = (v) => { const o = v; return 1 + d.ctors[o.c].fields.reduce((t, f, k) => { const w = at.get(`${o.c}.${k}`), fs = fieldSort(f); return t + (!w ? 0 : fs === d ? w * go(o.f[k]) : fs instanceof Data ? w * sizeOf(fs, o.f[k]) : 0); }, 0); }; return go; };
842
+ for (const ws of combos) {
843
+ const w = weight(ws);
844
+ if (!edges.every(e => w(e.tv[i]) < w(e.sv[i])))
845
+ continue;
846
+ out.push({ comps: [{ coef: fn.params.map(() => 0), c: 0, fold: { fn: foldFn(d, fields, ws), of: i } }] });
847
+ if (out.length >= 2)
848
+ return out;
849
+ }
850
+ }
851
+ return out;
852
+ }
853
+ // The fold of those weights, defined once.
854
+ function foldFn(d, fields, ws) {
855
+ const name = `fold${d.name}_${ws.join('')}`;
856
+ if (fns.has(name))
857
+ return name;
858
+ const at = new Map(fields.map((f, n) => [`${f.j}.${f.k}`, ws[n]]));
859
+ const self = define(name, { x: d }, natural, ({ x }) => x.match(Object.fromEntries(d.ctors.map((c, j) => [c.name, (fs) => c.fields.reduce((t, f, k) => {
860
+ const w = at.get(`${j}.${k}`), s2 = fieldSort(f);
861
+ if (!w)
862
+ return t;
863
+ const part = s2 === d ? self(fs[f.name]) : fs[f.name].size();
864
+ return w === 1 ? t.plus(part) : t.plus(part.times(w));
865
+ }, new Nat({ op: 'nat', value: 1 }))]))));
866
+ return name;
867
+ }
808
868
  // An obligation as one node of a cyclic proof (no use, no models): its conclusion, each definition it reads unfolded
809
869
  // once, the constructors' facts at the values built, the shape at each size it reads and at its variables of a
810
870
  // datatype, the congruences 16 random models' explanations use. The kernel checks it as any cyclic proof; undefined where it isn't proven.
@@ -812,7 +872,12 @@ function directly(law, ms) {
812
872
  const p = programOf([law]), fs = factsOf(p), concl = encY(p, law.holds, new Map());
813
873
  varSorts = new Map(law.vars.flatMap(v => (v.sort instanceof Data ? [[v.name, v.sort]] : [])));
814
874
  const until = clock() + ms;
815
- const insts = instancesOf(p, fs, { roots: [concl], others: [], depth: 1, shapesAt: [...varSorts.keys()].map(ev), etaAt: [], models: modelsFor(p, law, 16, 3), until });
875
+ // (and at each value of a datatype the conclusion builds: a fold reads its fields' sizes, size(x :: xs) = 1 + size(xs))
876
+ const ctors = new Set(p.datas.flatMap(d => d.ctors.flatMap((c, j) => (c.fields.length ? [ctorMap(d, j)] : []))));
877
+ const built = new Map();
878
+ walk(concl, o => { if (o.op === 'get' && ctors.has(o.map))
879
+ built.set(tid(o), o); });
880
+ const insts = instancesOf(p, fs, { roots: [concl], others: [], depth: 1, shapesAt: [...[...varSorts.keys()].map(ev), ...built.values()], etaAt: [], models: modelsFor(p, law, 16, 3), until });
816
881
  if (clock() > until)
817
882
  return undefined;
818
883
  const was = pairedKeys.skip;
@@ -838,7 +903,8 @@ function proveMeasures(ring, sites, ms, until) {
838
903
  // First one node, the definitions unfolded once (most calls lower the measure by their cases alone); then, where its
839
904
  // call is on a function of the argument, size laws about those functions proven by induction and used; else, or
840
905
  // then, proveData: by induction where the obligation has a scheme (a call on a filter of the tail: the filter's own
841
- // recursion), else, or then, the definitions unfolded alone.
906
+ // recursion), and through the built-ins where its functions compute them (mod2's call: ¬lt(x, y) ⇒ minus(x, y) < x),
907
+ // else, or then, the definitions unfolded alone.
842
908
  const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
843
909
  if (cex)
844
910
  return { failed: `${text}: its ${call} doesn't lower it at ${JSON.stringify(cex)}` };
@@ -848,12 +914,13 @@ function proveMeasures(ring, sites, ms, until) {
848
914
  continue;
849
915
  }
850
916
  // (the size laws first, each proven once and used, within 60% of the time left; then proveData without conjectured
851
- // lemmas, whose making isn't counted in the budget: by induction, then the definitions unfolded alone)
852
- const inductive = schemes(programOf([law]), law).length > 0, lemmas = sizeLaws(law, names);
917
+ // lemmas, whose making isn't counted in the budget: by induction and the built-ins, then the definitions unfolded
918
+ // alone)
919
+ const lemmas = sizeLaws(law, names);
853
920
  if (dataTrace && lemmas.length)
854
921
  console.error(`[data] ${law.name}: ${lemmas.map(c => c.name).join('; ')}`);
855
922
  let v = lemmas.length ? proveData(law, { lemmas, lemmasFirst: true, ms: Math.min(8000, 0.6 * left()) }) : undefined;
856
- if (!v?.proven && !v?.counterexample && inductive && clock() < until)
923
+ if (!v?.proven && !v?.counterexample && clock() < until)
857
924
  v = proveData(law, { ms: Math.min(12_000, left()), lemmas: false });
858
925
  if (!v?.proven && !v?.counterexample && clock() < until)
859
926
  v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
@@ -1134,9 +1201,16 @@ export function programOf(laws, extra = []) {
1134
1201
  place(fnOf(o.fn)); }); order.push(f); };
1135
1202
  for (const f of fs.values())
1136
1203
  place(f);
1137
- // (the recursion of each checked)
1204
+ // (the recursion of each checked; a measure's folds, which its rank reads, with them)
1138
1205
  for (const f of order)
1139
1206
  void f.decreases;
1207
+ const folds = order.flatMap(f => (f.decreases === undefined && f.measure ? f.measure.comps.flatMap(c => (c.fold && !fs.has(c.fold.fn) ? [c.fold.fn] : [])) : []));
1208
+ if (folds.length) {
1209
+ for (const n of folds)
1210
+ visit({ op: 'call', fn: n, args: [] });
1211
+ for (const f of fs.values())
1212
+ place(f);
1213
+ }
1140
1214
  const divs = new Set();
1141
1215
  let ints = false;
1142
1216
  const scan = (t) => walk(t, o => { if (o.op === 'mod' || o.op === 'div' || o.op === 'imod' || o.op === 'idiv')
@@ -1916,6 +1990,21 @@ function instancesOf(p, fs, w) {
1916
1990
  note(frontier);
1917
1991
  note(reads(w.others));
1918
1992
  ctors(all);
1993
+ // (`once`: reads unfolded one round whatever the depth, a fold's rank at the node and its uses)
1994
+ // (`decided`: those of its reads whose decreasing argument is a constructor's value or a successor, the definition's
1995
+ // case decided there: drop(v + 1 + w + x, y :: z))
1996
+ const succ = (t) => t.op === 'add' && ((t.b.op === 'const' && t.b.value > 0) || (t.a.op === 'const' && t.a.value > 0) || succ(t.a) || succ(t.b));
1997
+ const decidedAt = (r) => { const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), a = f?.decreases === undefined ? undefined : as?.[f.decreases]; return !!a && ((a.op === 'get' && ctorOf(a.map) !== undefined) || succ(a)); };
1998
+ const onceReads = [...(w.once ? reads(w.once) : []), ...(w.decided ? reads(w.decided).filter(decidedAt) : [])];
1999
+ note(onceReads);
2000
+ for (const r of onceReads) {
2001
+ const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid = sid(r);
2002
+ if (!f || !as || unfolded.has(rid))
2003
+ continue;
2004
+ unfolded.add(rid);
2005
+ inst(`fn ${f.name}`, as);
2006
+ ctors(note(reads(holdsAt(`fn ${f.name}`, as))));
2007
+ }
1919
2008
  for (let round = 0; round < w.depth && frontier.length; round++) {
1920
2009
  const next = [];
1921
2010
  for (const r of frontier) {
@@ -2749,7 +2838,12 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2749
2838
  if (d && d.ctors[j] && !d.ctors[j].fields.length)
2750
2839
  out.set(sid(t.key), t.key);
2751
2840
  } return [...out.values()]; };
2752
- const instsFor = (ms, us, every = false, hyps) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law), ...tagged(hyps)], models: ms, every, until: t0 + attemptMs.ms, hyps });
2841
+ // (a rank that reads a function, a fold's measure, read at the node and at each use, unfolded once: its descent
2842
+ // reads it; and the uses' conclusions, at the values built of constructors the fold's calls take: weird_concat's
2843
+ // hypothesis at x :: xss, its definition decided there; a fusion chain's last links', drop(v + 1 + w + x, y :: z))
2844
+ const rankReads = mb.rank && JSON.stringify(mb.rank).includes('"op":"get"') && mb.rank.some(e => { let yes = false; walk(e, o => { if (o.op === 'get' && p.fns.some(f => f.name === o.map))
2845
+ yes = true; }); return yes; }) ? [mb.rank, mb.uses.map(u => mb.rank.map(e => substE(e, { vars: u.subst, maps: {}, flags: {} })))] : [];
2846
+ const instsFor = (ms, us, every = false, hyps) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), once: [rankReads, rankReads.length ? us.map(useConcl) : []], decided: us.filter(u => chained.has(u)).map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law), ...tagged(hyps)], models: ms, every, until: t0 + attemptMs.ms, hyps });
2753
2847
  const cases = scheme ? casesOf(p, pre.filter(q => fs.facts[q.fact].name.startsWith('fn ')).map(q => holdsAt(fs, q)), new Set(mb.law.vars.map(v => v.name)), mb.pool) : [];
2754
2848
  if (cases.length <= 1) {
2755
2849
  // One node: four uses of a lemma, twelve in all, the best first (as lemmaUsesFor ranks them).
@@ -2779,7 +2873,7 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2779
2873
  const rest = fit.filter(u => u.node >= 0 && !kept.includes(u)), joins = rest.length && c.models ? caseJoins(fs, [concl, ihConcls], pre, ihConcls, few(c.models)) : undefined;
2780
2874
  const us = [...kept, ...capUses(joins ? rest.filter(u => joins(useConcl(u))) : [], lemmaCaps.joined)];
2781
2875
  const ms = few(first(c.models ?? c.near ?? models));
2782
- plan.push({ name: `${name}, case ${i + 1}`, hyps: c.lits, concl, sub: 0, insts: reached(p, fs, instsFor(ms, us, false, c.lits), [c.lits, concl, us.map(u => [u.guard, useConcl(u)]), shapesAt], ms), uses: us });
2876
+ plan.push({ name: `${name}, case ${i + 1}`, hyps: c.lits, concl, sub: 0, insts: reached(p, fs, instsFor(ms, us, false, c.lits), [c.lits, concl, us.map(u => [u.guard, useConcl(u)]), shapesAt, rankReads], ms), uses: us });
2783
2877
  }
2784
2878
  plans.push(plan);
2785
2879
  }
@@ -2974,12 +3068,19 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2974
3068
  const out = [], seen = new Set();
2975
3069
  const goalReads = readsOnce([from, insts.map(q => holdsAt(fs, q))]);
2976
3070
  let reads = goalReads;
3071
+ // (each lemma's first-round conclusions' reads: a fusion's chain goes on at its own)
3072
+ const ownFresh = new Map();
3073
+ const links = new Map();
2977
3074
  for (let round = 0; round < 2; round++) {
2978
3075
  const fresh = [];
2979
3076
  const cands = [];
2980
3077
  // The newest lemma first (the one the law is tried again for).
3078
+ let lemmaOrd = 0;
2981
3079
  for (const lm of [...lemmas].reverse()) {
2982
- if (round > 0 && out.some(u => u.node === lm.node))
3080
+ lemmaOrd++;
3081
+ // (a fusion again in the second round: drop(w, drop(x, drop(y, z))) takes it twice, the second at the term the
3082
+ // first makes)
3083
+ if (round > 0 && out.some(u => u.node === lm.node) && !fusion(lm.law.holds))
2983
3084
  continue;
2984
3085
  const vars = new Set(lm.law.vars.map(v => v.name)), sides = [];
2985
3086
  walk(lm.pat ?? encY(p, lm.law.holds, new Map()), o => { if (o.op === 'get')
@@ -2990,6 +3091,17 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2990
3091
  const callsFn = (t) => { let yes = false; walk(t, o => { if (o.op === 'get' && fs.arity.has(o.map) && p.fns.some(f => f.name === o.map))
2991
3092
  yes = true; }); return yes; };
2992
3093
  const tops = tops0.some(callsFn) ? tops0.filter(callsFn) : tops0;
3094
+ // (a fusion first at reads as they stand: the goal's, those taken first; then in the next round, used already,
3095
+ // only at the terms its own first uses made, the chain's next links, drop(w, drop(x, drop(y, z))) =
3096
+ // drop(w + x, drop(y, z)) = drop(w + x + y, z), `perCase` past the lemma's caps; the matches through every
3097
+ // branch's classes, drop(w + w, ..), would fill those)
3098
+ const fused = fusion(lm.law.holds);
3099
+ const fnDepth = (t) => { if (!t || typeof t !== 'object')
3100
+ return 0; if (Array.isArray(t))
3101
+ return Math.max(0, ...t.map(fnDepth)); const o = t, inner = Math.max(0, ...Object.values(o).map(fnDepth)); return o.op === 'get' && p.fns.some(f => f.name === o.map) ? 1 + inner : inner; };
3102
+ const composite = (t) => fnDepth(t) >= 2;
3103
+ const again = round > 0 && out.some(u => u.node === lm.node);
3104
+ const mine = [...(fused ? (round > 0 ? readsOnce(ownFresh.get(lm.node) ?? []) : reads).map((t) => [t, true]) : []), ...(again ? [] : reads.map((t) => [t, false]))];
2993
3105
  // (a constructor matched by its fields only for a lemma no read matches as it stands, the uses would multiply; always
2994
3106
  // for the hypothesis, whose step names a value by its fields: y :: zs at the tail of a cons)
2995
3107
  for (const byFields of [false, true]) {
@@ -3019,9 +3131,13 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
3019
3131
  }
3020
3132
  return out;
3021
3133
  };
3022
- for (const t of reads) {
3134
+ for (const [t, exact] of mine) {
3023
3135
  if (t.op !== 'get' || t.map !== top.map)
3024
3136
  continue;
3137
+ // (as it stands, its composition only: len(xs ++ []) = len(xs) read at len(xs ++ []), not at every length,
3138
+ // whose conclusions would grow the chain without end)
3139
+ if (exact && !composite(top))
3140
+ continue;
3025
3141
  // (one use is all `hits` asks of a lemma)
3026
3142
  if (hits?.has(lm.node))
3027
3143
  break;
@@ -3031,7 +3147,7 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
3031
3147
  continue;
3032
3148
  let subs = [{}];
3033
3149
  for (const q of pats.keys()) {
3034
- const ms = members(args[q]).slice(0, 256);
3150
+ const ms = (exact ? [args[q]] : members(args[q])).slice(0, 256);
3035
3151
  subs = subs.flatMap(sb => ms.flatMap(m => { const r = matchAt(q, m, sb); return r ? [r] : []; })).slice(0, 512);
3036
3152
  }
3037
3153
  for (const sub of subs) {
@@ -3063,7 +3179,7 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
3063
3179
  hits.add(lm.node);
3064
3180
  break;
3065
3181
  }
3066
- cands.push({ use, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size: textLength([lm.node, sub]), concl: lm.concl });
3182
+ cands.push({ use, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size: textLength([lm.node, sub]), concl: lm.concl, exact: exact && round > 0, first: exact, ord: lemmaOrd });
3067
3183
  }
3068
3184
  }
3069
3185
  }
@@ -3079,19 +3195,31 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
3079
3195
  // (the most models, then the smallest terms), one of each set of values, up to `perLemma` of a lemma and `total` in
3080
3196
  // all: a case node keeps those its models meet, `perCase` of a lemma (attempt's `applies`), so a use that holds in
3081
3197
  // one case only (the insertion's other side) isn't crowded out by those found first.
3198
+ // (within each lemma's: the others' as found)
3199
+ cands.sort((a, b) => a.ord - b.ord || +b.first - +a.first);
3082
3200
  const fps = new Set(), first = new Set();
3083
- const take = (c) => { fps.add(c.fp); out.push(c.use); matchedAt.set(c.use, c.at); };
3201
+ const take = (c) => { fps.add(c.fp); out.push(c.use); matchedAt.set(c.use, c.at); if (c.exact)
3202
+ chained.add(c.use); };
3084
3203
  for (const c of cands) {
3085
3204
  if (out.length >= 12 || out.filter(u => u.node === c.use.node).length >= 4)
3086
3205
  continue;
3087
3206
  take(c);
3088
3207
  first.add(c);
3089
3208
  fresh.push(substC(c.concl, { vars: c.use.subst, maps: {}, flags: {} }));
3209
+ (ownFresh.get(c.use.node) ?? ownFresh.set(c.use.node, []).get(c.use.node)).push(fresh.at(-1));
3090
3210
  }
3091
- const rest = cands.filter(c => !first.has(c)).sort((a, b) => b.score - a.score || a.size - b.size);
3211
+ const rest = cands.filter(c => !first.has(c)).sort((a, b) => +b.exact - +a.exact || b.score - a.score || a.size - b.size);
3092
3212
  for (const c of rest) {
3093
3213
  if (fps.has(c.fp))
3094
3214
  continue;
3215
+ if (c.exact) {
3216
+ const n = links.get(c.use.node) ?? 0;
3217
+ if (n < lemmaCaps.perCase) {
3218
+ links.set(c.use.node, n + 1);
3219
+ take(c);
3220
+ }
3221
+ continue;
3222
+ }
3095
3223
  if (out.length < lemmaCaps.total && out.filter(u => u.node === c.use.node).length < lemmaCaps.perLemma)
3096
3224
  take(c);
3097
3225
  // (past the node's caps, kept for the cases: one case's models may meet a use the node's rank puts below them)
@@ -3118,12 +3246,21 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
3118
3246
  export const lemmaCaps = { perLemma: 8, total: 24, perCase: 4, spare: 96, joined: 2, self: 4 };
3119
3247
  // A node's uses: the scheme's (the cycle's, read at nodes not yet placed) all, `perCase` of each lemma, `total` lemma
3120
3248
  // uses in all, in the order given.
3249
+ // (a fusion's use at a term another of its uses made, the chain's next link, past them: `perCase` more of a lemma)
3250
+ const chained = new WeakSet();
3121
3251
  function capUses(uses, total = Infinity) {
3122
- const per = new Map();
3252
+ const per = new Map(), links = new Map();
3123
3253
  let all = 0;
3124
3254
  return uses.filter(u => {
3125
3255
  if (u.node < 0)
3126
3256
  return true;
3257
+ if (chained.has(u)) {
3258
+ const m = links.get(u.node) ?? 0;
3259
+ if (m < lemmaCaps.perCase) {
3260
+ links.set(u.node, m + 1);
3261
+ return true;
3262
+ }
3263
+ }
3127
3264
  const n = per.get(u.node) ?? 0;
3128
3265
  if (n >= lemmaCaps.perCase || all >= total)
3129
3266
  return false;
@@ -3260,7 +3397,17 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without, m
3260
3397
  tried++;
3261
3398
  const t1 = clock();
3262
3399
  // (and within a third of an attempt's time: a merged scheme's proof, where there is one, is short)
3263
- const { verdict, specs, main } = (attemptMs.ms = Math.min(per * (opts.patience ?? 1) / (s?.merged ? 3 : 1), until - clock()), attempt(p, fs, l, s, depth, lemmas, level, models));
3400
+ const run = (part = 1) => (attemptMs.ms = Math.min(part * per * (opts.patience ?? 1) / (s?.merged ? 3 : 1), until - clock()), attempt(p, fs, l, s, depth, lemmas, level, models));
3401
+ let { verdict, specs, main } = run(), t2 = t1;
3402
+ // Out of its time past half its own nodes (those before proven, their trees kept by cyclic.ts's `searched`): a
3403
+ // quarter of its time more, spent on the nodes left, once (insertion keeps a list sorted at two unfoldings, its last
3404
+ // case at the edge of its time: 3.7 million units of work in place of the conjectures' 26 to 60 million).
3405
+ if (!verdict.proven && verdict.stuck === 'unknown' && clock() > t1 + attemptMs.ms && clock() < until && (at => at > main && (at - main) * 2 >= specs.length - main)(specs.findIndex(n => n.name === verdict.goal))) {
3406
+ if (dataTrace)
3407
+ console.error(`[data] resumed past ${verdict.goal}`);
3408
+ t2 = clock();
3409
+ ({ verdict, specs, main } = run(0.25));
3410
+ }
3264
3411
  last = verdict;
3265
3412
  if (nodeTrace && !verdict.proven && new RegExp(nodeTrace).test(verdict.goal)) {
3266
3413
  const n = specs.find(x => x.name === verdict.goal);
@@ -3269,7 +3416,7 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without, m
3269
3416
  }
3270
3417
  if (dataTrace)
3271
3418
  console.error(`[data] -> ${verdict.proven ? (verdict.checked ? 'proven' : `not checked: ${verdict.why}`) : `${verdict.goal}: ${verdict.stuck}`}`);
3272
- if (!(verdict.proven && verdict.checked) && clock() <= t1 + attemptMs.ms)
3419
+ if (!(verdict.proven && verdict.checked) && clock() <= t2 + attemptMs.ms)
3273
3420
  done.add(key);
3274
3421
  if (verdict.proven && verdict.checked)
3275
3422
  return { out: { law: l, spec: specs[main], nodes: specs }, verdict, scheme: s?.name ?? (without ? 'no induction' : undefined), tried };
@@ -4152,14 +4299,18 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4152
4299
  for (const g of goals)
4153
4300
  lemmaUsesFor(p2, fs2, others.map((c, i) => ({ law: c, node: i, concl: encY(p2, c.holds, new Map()) })), g.from, g.insts, [], undefined, goalHits);
4154
4301
  const matchesGoal = (c) => goalHits.has(others.indexOf(c));
4155
- // Those the goal matches first, of those the ones of the law's shape (an implication for an implication) first.
4302
+ // Those the goal matches first, of those the ones of the law's shape (an implication for an implication) first, then
4303
+ // the fusions.
4156
4304
  const implication = (y) => y.op === 'or' && y.xs.length === 2 && y.xs[0].op === 'not';
4157
- const score = (c, hit) => (hit ? 2 : 0) + (implication(c.holds) === implication(l.holds) ? 1 : 0);
4305
+ const score = (c, hit) => (hit ? 4 : 0) + (implication(c.holds) === implication(l.holds) ? 2 : 0) + (fusion(c.holds) ? 1 : 0);
4158
4306
  if (dataTrace)
4159
4307
  console.error(`[data] ${l.name}: ${cands.length} conjectures at ${Math.round(clock())} of ${Math.round(until)}${cands.map(c => `\n[data] conjecture ${c.name.slice(0, 160)}`).join('')}`);
4160
4308
  // (the calculated steps first, in their order: each before the one it was calculated from)
4161
4309
  const calcSet = new Set(calc);
4162
4310
  const ranked = [...calc.map(c => ({ c, hit: true })), ...cands.slice(calc.length).map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit))];
4311
+ if (dataTrace)
4312
+ for (const r of ranked)
4313
+ console.error(`[data] ranked ${r.hit ? "hit" : " "} ${r.c.name.slice(0, 150)}`);
4163
4314
  // The lemmas proven: those given (`base`) and those found, each found one a level above the last.
4164
4315
  const proven = [...base], failed = new Set(), level = () => lv + 1 + proven.length - base.length;
4165
4316
  // A pass of lemmas: of those the goal reads (`hits`) or the others, each proven at one unfolding (8 s of counted work
@@ -4197,7 +4348,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4197
4348
  else
4198
4349
  tries++;
4199
4350
  // (a calculated step half a conjecture's time: there are few, and one past its time is seldom the one)
4200
- const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(end, clock() + (calcSet.has(c) ? 3000 : 8000) * (opts.patience ?? 1)), 5000, [1]);
4351
+ const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(end, clock() + (calcSet.has(c) ? 3000 : 8000) * (opts.patience ?? 1)), 5000, fusion(c.holds) ? [1, 2] : [1]);
4201
4352
  tried += r.tried;
4202
4353
  if (!r.out) {
4203
4354
  failed.add(c);
@@ -4278,6 +4429,19 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4278
4429
  }
4279
4430
  return done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first?.last) });
4280
4431
  }
4432
+ // A fusion: an equation one side of which nests a call of the program's functions in another's argument, the other side
4433
+ // calls on its variables alone (length(x ++ y) = length(x) + length(y), drop(n + m, xs) = drop(n, drop(m, xs)),
4434
+ // rev(xs ++ [x]) = x :: rev(xs)): the rewrite that takes a composition the goal reads apart. Its proof unfolds both
4435
+ // functions: two unfoldings.
4436
+ const callDepth = (x) => {
4437
+ if (!x || typeof x !== 'object')
4438
+ return 0;
4439
+ if (Array.isArray(x))
4440
+ return Math.max(0, ...x.map(callDepth));
4441
+ const o = x, inner = Math.max(0, ...Object.values(o).map(callDepth));
4442
+ return o.op === 'call' ? 1 + inner : inner;
4443
+ };
4444
+ const fusion = (y) => y.op === '=' && Math.max(callDepth(y.a), callDepth(y.b)) === 2 && Math.min(callDepth(y.a), callDepth(y.b)) === 1;
4281
4445
  const stuckOf = (v) => (v && !v.proven ? { goal: v.goal, stuck: v.stuck } : v && !v.checked ? { goal: 'check', stuck: v.why } : {});
4282
4446
  // The law with no cycle: its definitions unfolded, the kernel's prover alone (what the library proves without the search).
4283
4447
  export const proveDataToday = (l) => proveData(l, { induction: false });
@@ -1,4 +1,4 @@
1
- import { type C, type E, type Law, type Recurrence, type Machine, type Rand, type Request, type State } from './machine.js';
1
+ import { type C, type E, type Law, type Recurrence, type Machine, type Rand, type Request, type State, type Sum } from './machine.js';
2
2
  import { type Fold, type Goal, type Liveness, type Loop, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
3
3
  import { type Report } from '../kernel/prove.js';
4
4
  export type TermLike = Term | number;
@@ -282,6 +282,8 @@ type Bound = {
282
282
  };
283
283
  export declare function exists(f: (x: Term) => Cond, witness?: ExistsWitness<Term>): Cond;
284
284
  export declare function exists<V>(kind: Kind<V>, f: (x: V) => Cond, witness?: ExistsWitness<V>): Cond;
285
+ export declare const declaredSum: (name: string) => Sum | undefined;
286
+ export declare const sumsIn: (ts: unknown[], more?: Iterable<string>) => Record<string, Sum> | undefined;
285
287
  export declare class MapRef {
286
288
  readonly name: string;
287
289
  readonly init: number;
@@ -297,6 +299,7 @@ export declare class MapRef {
297
299
  sameAs(other: MapRef): Cond;
298
300
  within(n: number): Cond;
299
301
  sizeBelow(n: number): Term;
302
+ sum(of?: (cell: Term) => TermLike): Term;
300
303
  }
301
304
  export type ListOp = {
302
305
  readonly when: Cond;
@@ -351,6 +354,7 @@ export declare class CellsRef<V> {
351
354
  at(key: TermLike): V;
352
355
  set(key: TermLike, value: Writes<V>): PartsWrite;
353
356
  each(f: (key: Term) => Writes<V>): PartsWrite;
357
+ sum(of: (value: V) => TermLike): Term;
354
358
  }
355
359
  export type ItemsOp = {
356
360
  readonly when: Cond;
@@ -520,6 +524,7 @@ type Spec = {
520
524
  fns?: [string, FnDef][];
521
525
  facts?: ((env: never) => Record<string, Cond | Forall>)[];
522
526
  arith?: Set<number>;
527
+ sumsRead?: Set<string>;
523
528
  flags: ((env: never) => Record<string, Cond>)[];
524
529
  step?: (env: never) => Record<string, TermLike | MapWrite | undefined>;
525
530
  pre: ((p: never) => Cond)[];
@@ -545,6 +550,7 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
545
550
  lists: [string, Kind<unknown>, Record<string, ListFold<unknown>>, Record<string, ListLemma>][];
546
551
  };
547
552
  withParts(fns: Record<string, FnDef>, listLemmas?: Record<string, Record<string, ListLemma>>): this;
553
+ withMapSums(): this | undefined;
548
554
  params<K extends Kinds>(kinds: K): Rule<P & ValuesOf<K>, I, S, M, F, R, Su, Q>;
549
555
  inputs<K extends Kinds>(kinds: K): Rule<P, I & ValuesOf<K>, S, M, F, R, Su, Q>;
550
556
  state<T extends Record<string, number | ((p: P) => TermLike) | Init<unknown>>>(init: T): Rule<P, I, S & {
@@ -614,7 +620,9 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
614
620
  private divides;
615
621
  dividesBy(...ks: number[]): this;
616
622
  withDivisors(...ks: number[]): this;
623
+ private kinds?;
617
624
  kindLaws(): Law[];
625
+ private kindLawsOf;
618
626
  stepLaw(name: string, then: (before: P & I & S & M & F & Su & Q, after: S & M & Su) => Cond | Forall, when?: (before: P & I & S & M & F & Su & Q) => Cond): StepLaw;
619
627
  stepsLaw(name: string, k: number, then: (first: P & I & S & M & F & Su & Q, last: S & M & Su, requests: (I & Q)[]) => Cond | Forall, when?: (before: P & I & S & M & F & Su & Q, j: number) => Cond | undefined): StepLaw;
620
628
  leadsTo(name: string, spec: {
@@ -625,6 +633,8 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
625
633
  when?: (env: P & S & M & Su) => Cond;
626
634
  request: (env: P & S & M & Su) => Record<string, TermLike>;
627
635
  }[];
636
+ fairness?: 'weak' | 'strong';
637
+ levels?: number[];
628
638
  }): Liveness;
629
639
  decide(name: string, given: (env: P & I) => Cond | Cond[], then: (env: P & I) => Cond): Decision;
630
640
  relate(name: string, given: (a: P & I, b: P & I) => Cond | Cond[], then: (a: P & I, b: P & I) => Cond): Decision;