gdp-wired 0.27.0 → 0.28.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.
@@ -0,0 +1,317 @@
1
+ // "From leads to to" with no rank stated, where the rank fitted to the runs (core/cycles.ts's findLeadsTo) is not the
2
+ // one: a rank made of the rule's own terms, chosen by the steps it must lower. Its components are drawn from
3
+ // - the control: a variable its kind bounds (a chart's state, a status, a flag), ranked by the steps between its
4
+ // values (each strongly connected set of values one level, the levels in the order the steps go);
5
+ // - the distances the rule compares: for each comparison a < b or a <= b of its guards, its steps, the law and the
6
+ // helpful requests (the request's own inputs replaced by what it sends), over the state, the params and the cells
7
+ // they read, the distance until it changes (b ∸ a, a + 1 ∸ b and the like): a counter up to a limit, a clock up to a
8
+ // deadline, a timestamp's distance from the time;
9
+ // - a state variable alone, and the constant 0.
10
+ // The steps are taken from runs from the start and from random states the laws allow, where `from` holds and `to`
11
+ // doesn't (the kernel's goals are about every such state, reached or not): a helpful request's in its region must
12
+ // lower the rank, and so must any other that leaves a region it was in; the rest must not raise it. Components are
13
+ // chosen in order, each one no step raises that lowers the most of those left. The rank is then the kernel's
14
+ // (proveLiveness), with the invariants inferLaws finds where its goals need some. Nothing new is trusted.
15
+ import { evalC, evalE, interpret, seeded, walk } from "./machine.js";
16
+ import { livenessHelpful, livenessParts, substE } from "../kernel/kernel.js";
17
+ import { clock, proveLiveness, withDeadline } from "../kernel/prove.js";
18
+ import { allowed, watch } from "./watch.js";
19
+ import { showE } from "./cycles.js";
20
+ import { inferLaws } from "./infer.js";
21
+ const id = (t) => JSON.stringify(t);
22
+ const k = (value) => ({ op: 'const', value }), v = (name) => ({ op: 'var', name });
23
+ const sub = (a, b) => ({ op: 'sub', a, b }), plus1 = (a) => ({ op: 'add', a, b: k(1) });
24
+ // The comparisons a condition or term makes, each side a term.
25
+ function comparisons(t) {
26
+ const out = [];
27
+ walk(t, o => { if ((o.op === '<' || o.op === '<=' || o.op === '=') && typeof o.a === 'object' && typeof o.b === 'object')
28
+ out.push([o.a, o.b]); });
29
+ // (a side that decides a flag or a quantifier is no term of the state)
30
+ return out.filter(p => { let plain = true; walk(p, o => { if (o.op === 'flag' || o.op === 'all')
31
+ plain = false; }); return plain; });
32
+ }
33
+ const reads = (e, names) => { let hit = false; walk(e, o => { if (o.op === 'var' && names.includes(o.name))
34
+ hit = true; }); return hit; };
35
+ const constant = (e) => { let c = true; walk(e, o => { if (o.op === 'var' || o.op === 'get')
36
+ c = false; }); return c; };
37
+ // The candidate components that don't depend on the steps: the distances, each variable alone.
38
+ function distances(m, l) {
39
+ const helpful = livenessHelpful(l), atoms = [...comparisons([m.step, m.assume, l.from, l.to, helpful.map(h => h.when)])];
40
+ // a guard as the helpful request meets it: its inputs replaced by the terms it sends
41
+ for (const h of helpful) {
42
+ const s = { vars: h.request, maps: {}, flags: {} };
43
+ for (const [a, b] of comparisons([m.step, m.assume]))
44
+ atoms.push([substE(a, s), substE(b, s)]);
45
+ }
46
+ const out = new Map();
47
+ const add = (e) => { if (!constant(e) && !reads(e, m.inputs))
48
+ out.set(id(e), e); };
49
+ for (const [a, b] of atoms) {
50
+ if (reads(a, m.inputs) || reads(b, m.inputs) || constant(a) && constant(b))
51
+ continue;
52
+ for (const e of [sub(b, a), sub(a, b), sub(plus1(a), b), sub(plus1(b), a)])
53
+ add(e);
54
+ }
55
+ for (const x of Object.keys(m.state))
56
+ add(v(x));
57
+ return [...out.values()];
58
+ }
59
+ // A variable's values ranked by the steps between them: each strongly connected set one level, a level above every one
60
+ // a step goes to from it (Tarjan's components, then the longest path down).
61
+ function controlRank(x, steps) {
62
+ const graph = new Map();
63
+ const node = (a) => graph.get(a) ?? (graph.set(a, new Set()), graph.get(a));
64
+ for (const st of steps) {
65
+ const a = st.s.scalars[x], b = st.t.scalars[x];
66
+ node(b);
67
+ if (a !== b)
68
+ node(a).add(b);
69
+ }
70
+ if (graph.size < 2)
71
+ return undefined;
72
+ const index = new Map(), low = new Map(), comp = new Map(), stack = [];
73
+ let n = 0, c = 0;
74
+ const visit = (a) => {
75
+ index.set(a, n);
76
+ low.set(a, n++);
77
+ stack.push(a);
78
+ for (const b of graph.get(a)) {
79
+ if (!index.has(b)) {
80
+ visit(b);
81
+ low.set(a, Math.min(low.get(a), low.get(b)));
82
+ }
83
+ else if (!comp.has(b))
84
+ low.set(a, Math.min(low.get(a), index.get(b)));
85
+ }
86
+ if (low.get(a) === index.get(a)) {
87
+ let b;
88
+ do {
89
+ b = stack.pop();
90
+ comp.set(b, c);
91
+ } while (b !== a);
92
+ c++;
93
+ }
94
+ };
95
+ for (const a of graph.keys())
96
+ if (!index.has(a))
97
+ visit(a);
98
+ const level = new Map();
99
+ // (Tarjan numbers a component after every one it reaches: so in that order each level is known before it is needed)
100
+ const members = Array.from({ length: c }, (_, i) => [...graph.keys()].filter(a => comp.get(a) === i));
101
+ for (const ms of members) {
102
+ let lv = 0;
103
+ for (const a of ms)
104
+ for (const b of graph.get(a))
105
+ if (comp.get(b) !== comp.get(a))
106
+ lv = Math.max(lv, level.get(comp.get(b)) + 1);
107
+ level.set(comp.get(ms[0]), lv);
108
+ }
109
+ const values = [...graph.keys()].sort((p, q) => p - q).map(a => [a, level.get(comp.get(a))]);
110
+ if (values.every(([, lv]) => lv === 0))
111
+ return undefined;
112
+ return values.slice(0, -1).reduceRight((rest, [a, lv]) => ({ op: 'if', c: { op: '=', a: v(x), b: k(a) }, then: k(lv), else: rest }), k(values.at(-1)[1]));
113
+ }
114
+ // The variables a kind law bounds by a small constant (x < c, x <= c).
115
+ const bounded = (m, laws) => {
116
+ const out = new Set();
117
+ for (const law of laws)
118
+ if (!law.forall)
119
+ walk(law.holds, o => {
120
+ const a = o.a, b = o.b;
121
+ if ((o.op === '<' || o.op === '<=') && a?.op === 'var' && a.name in m.state && b?.op === 'const' && b.value <= 32)
122
+ out.add(a.name);
123
+ });
124
+ return [...out];
125
+ };
126
+ export function leadsByTerms(m, laws, l, draws, opts = {}) {
127
+ const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(31), run = interpret(m), helpful = livenessHelpful(l);
128
+ const env = (ps, st) => ({ ...ps, ...st.scalars });
129
+ const holds = (c, ps, st) => { try {
130
+ return evalC(c, env(ps, st), st, m);
131
+ }
132
+ catch {
133
+ return undefined;
134
+ } };
135
+ const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
136
+ const regions = (ps, st) => helpful.map(h => holds(h.when, ps, st) === true);
137
+ const steps = [];
138
+ // One step from a pending state: a helpful request in its region (its named inputs at the state, the rest drawn), or
139
+ // any request; kept where it stays pending.
140
+ const take = (ps, st, bound, h) => {
141
+ for (let tries = 0; tries < 20; tries++) {
142
+ try {
143
+ const input = draws.input(rand, bound, ps);
144
+ if (h !== undefined)
145
+ for (const [x, t] of Object.entries(helpful[h].request))
146
+ input[x] = evalE(t, env(ps, st), st, m);
147
+ if (!allowed(m, run, ps, st, input))
148
+ continue;
149
+ const next = run.step(ps, st, input);
150
+ if (pending(ps, st) && pending(ps, next)) {
151
+ const was = regions(ps, st), now = regions(ps, next);
152
+ steps.push({ ps, s: st, t: next, lower: h !== undefined || was.some((r, i) => r && !now[i]) });
153
+ }
154
+ return next;
155
+ }
156
+ catch { /* refused: another */ }
157
+ }
158
+ return undefined;
159
+ };
160
+ const pick = (ps, st) => { const rs = regions(ps, st).flatMap((r, i) => (r ? [i] : [])); return rs.length && rand(2) ? rs[rand(rs.length)] : undefined; };
161
+ const sampleUntil = t0 + Math.min(1500, (until - t0) / 8);
162
+ // runs from the start
163
+ for (const bound of [2, 4, 8])
164
+ for (let trial = 0; trial < 20 && clock() < sampleUntil; trial++) {
165
+ let ps, st;
166
+ try {
167
+ ps = draws.params(rand, bound);
168
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
169
+ continue;
170
+ st = run.init(ps);
171
+ }
172
+ catch {
173
+ continue;
174
+ }
175
+ for (let turn = 0; turn < 80 && st; turn++)
176
+ st = pending(ps, st) ? take(ps, st, bound, pick(ps, st)) : take(ps, st, bound);
177
+ }
178
+ // random states the laws allow
179
+ if (!m.history)
180
+ for (let trial = 0, found = 0; trial < 4000 && found < 300 && clock() < sampleUntil; trial++) {
181
+ const bound = 4;
182
+ let ps;
183
+ try {
184
+ ps = draws.params(rand, bound);
185
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
186
+ continue;
187
+ }
188
+ catch {
189
+ continue;
190
+ }
191
+ const scalars = { ...Object.fromEntries(Object.keys(m.state).map(n => [n, rand(8)])), ...(draws.state?.(rand, bound) ?? {}) };
192
+ const st = { scalars, maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(n => [n, new Map(Array.from({ length: rand(3) }, () => [rand(bound + 1), rand(bound + 1)]))])) };
193
+ try {
194
+ if (!pending(ps, st) || !laws.every(law => watch(m, run, law, ps, bound).start(st)))
195
+ continue;
196
+ }
197
+ catch {
198
+ continue;
199
+ }
200
+ found++;
201
+ take(ps, st, bound, pick(ps, st));
202
+ }
203
+ // A goal's counterexample as a step (the kernel names a cell by its map and its key's linear form, `M[d:1,1:2]`): the
204
+ // state, params and request it gives (0 where it gives none), stepped by the interpreter. The step a goal fails at
205
+ // is one the rank must allow; so the ranks are chosen again with it, a few rounds.
206
+ const fromWitness = (w, goal) => {
207
+ const ps = Object.fromEntries(m.params.map(p => [p, w[p] ?? 0])), maps = Object.fromEntries(Object.keys(m.maps ?? {}).map(n => [n, new Map()]));
208
+ for (const [name, x] of Object.entries(w)) {
209
+ const at = name.indexOf('[');
210
+ if (at < 0 || !name.endsWith(']') || !maps[name.slice(0, at)])
211
+ continue;
212
+ let key = 0;
213
+ for (const part of name.slice(at + 1, -1).split(',')) {
214
+ const c = part.lastIndexOf(':'), n = part.slice(0, c);
215
+ key += Number(part.slice(c + 1)) * (n === '1' ? 1 : w[n] ?? 0);
216
+ }
217
+ if (Number.isInteger(key) && key >= 0)
218
+ maps[name.slice(0, at)].set(key, x);
219
+ }
220
+ const st = { scalars: Object.fromEntries(Object.keys(m.state).map(x => [x, w[x] ?? 0])), maps };
221
+ const input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
222
+ try {
223
+ if (!pending(ps, st) || !allowed(m, run, ps, st, input))
224
+ return false;
225
+ const next = run.step(ps, st, input);
226
+ if (!pending(ps, next))
227
+ return false;
228
+ const was = regions(ps, st), now = regions(ps, next), h = /helpful request (\d+)/.exec(goal);
229
+ steps.push({ ps, s: st, t: next, lower: !!h || was.some((r, i) => r && !now[i]) });
230
+ return true;
231
+ }
232
+ catch {
233
+ return false;
234
+ }
235
+ };
236
+ if (!steps.length)
237
+ return { proven: false, checked: false, why: 'no step sampled from a state where it is pending' };
238
+ // The components, then the ranks: each component the one no step raises that lowers the most steps left to lower.
239
+ const value = (e, ps, st) => { try {
240
+ return evalE(e, env(ps, st), st, m);
241
+ }
242
+ catch {
243
+ return NaN;
244
+ } };
245
+ const fixed = distances(m, l), text = (rank) => `(${rank.map(showE).join(', ')})`, tried = new Set();
246
+ let last, best;
247
+ for (let round = 0; round < 6 && until - clock() > 200; round++) {
248
+ const cands = [...bounded(m, laws).map(x => controlRank(x, steps)).filter((e) => !!e), ...fixed];
249
+ const vals = cands.map(e => steps.map(st => [value(e, st.ps, st.s), value(e, st.ps, st.t)]));
250
+ const build = (banned) => {
251
+ let left = steps.map((_, i) => i);
252
+ const rank = [];
253
+ for (let turn = 0; turn < 3 && left.some(i => steps[i].lower); turn++) {
254
+ let pick = -1, most = 0;
255
+ for (let c = 0; c < cands.length; c++) {
256
+ if (banned.has(c) || rank.includes(c))
257
+ continue;
258
+ const vs = vals[c];
259
+ if (!left.every(i => vs[i][1] <= vs[i][0]))
260
+ continue;
261
+ const n = left.filter(i => steps[i].lower && vs[i][1] < vs[i][0]).length;
262
+ if (n > most)
263
+ (pick = c, most = n);
264
+ }
265
+ if (pick < 0)
266
+ return undefined;
267
+ rank.push(pick);
268
+ left = left.filter(i => !(vals[pick][i][1] < vals[pick][i][0]));
269
+ }
270
+ return left.some(i => steps[i].lower) ? undefined : (rank.length ? rank.map(c => cands[c]) : [k(0)]);
271
+ };
272
+ // the first rank, then those without its first component
273
+ const ranks = [], first = build(new Set());
274
+ if (first)
275
+ ranks.push(first);
276
+ for (let c = 0; c < cands.length && ranks.length < 3 && first; c++) {
277
+ if (id(cands[c]) !== id(first[0]))
278
+ continue;
279
+ const r = build(new Set([c]));
280
+ if (r && !ranks.some(x => id(x) === id(r)))
281
+ ranks.push(r);
282
+ }
283
+ const fresh = ranks.filter(r => !tried.has(id(r)));
284
+ if (!fresh.length)
285
+ break;
286
+ let learnt = false;
287
+ for (const rank of fresh) {
288
+ const ms = until - clock();
289
+ if (ms < 200)
290
+ break;
291
+ tried.add(id(rank));
292
+ best ??= rank;
293
+ last = withDeadline(clock() + ms / 3, () => proveLiveness(m, laws, { ...l, rank }));
294
+ if (last.proven && last.checked)
295
+ return { proven: true, checked: true, rank, laws: [], found: { rank: text(rank), laws: [] } };
296
+ if (last.failed?.witness && fromWitness(last.failed.witness, last.failed.goal))
297
+ learnt = true;
298
+ }
299
+ if (!learnt)
300
+ break;
301
+ }
302
+ if (!best)
303
+ return { proven: false, checked: false, why: `no rank of the rule's terms that the ${steps.length} steps sampled allow` };
304
+ // the first rank with the invariants its goals need
305
+ const rank = best, lv = { ...l, rank }, ms = until - clock();
306
+ if (ms > 300) {
307
+ const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(draws.rule ?? m, laws, [stay, cover, ...helps], { ms });
308
+ const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
309
+ if (inf.proven && more.length) {
310
+ const again = withDeadline(until + 5000, () => proveLiveness(m, [...laws, ...more], lv));
311
+ if (again.proven && again.checked)
312
+ return { proven: true, checked: true, rank, laws: more, found: { rank: text(rank), laws: kept.map(f => f.text) } };
313
+ }
314
+ }
315
+ const failed = last?.failed ? { goal: last.failed.goal, stuck: last.failed.stuck, ...(last.failed.witness ? { witness: last.failed.witness } : {}) } : {};
316
+ return { proven: false, checked: false, rank, found: { rank: text(rank), laws: [] }, ...failed, why: `rank ${text(rank)} of the rule's terms, from ${steps.length} steps sampled; the kernel's goals not proven with it` };
317
+ }
@@ -1,5 +1,5 @@
1
1
  import { type C, type E } from './machine.js';
2
- import { type Loop, type Recur } from '../kernel/kernel.js';
2
+ import { type Loop, type Recur, type RecurCases } from '../kernel/kernel.js';
3
3
  export type NeverEndsOptions = {
4
4
  ms?: number;
5
5
  seed?: number;
@@ -8,11 +8,13 @@ export type NeverEndsOptions = {
8
8
  counted?: number;
9
9
  accel?: number;
10
10
  extend?: number;
11
+ cases?: boolean;
11
12
  };
12
13
  export type NeverEndsVerdict = {
13
14
  proven: boolean;
14
15
  checked: boolean;
15
16
  recur?: Recur;
17
+ cases?: RecurCases;
16
18
  by?: 'lasso' | 'policy lasso' | 'recurrent set' | 'accelerated';
17
19
  why?: string;
18
20
  lasso?: {
@@ -20,12 +20,14 @@
20
20
  // among these sets: their bounds and differences grow along the run.
21
21
  // - Accelerated cycles, between the runs and the policies (core/accel.ts): a set from a cycle of the loop's relation,
22
22
  // the cycle's n-fold run read in closed form (an atom's differences along it), and a stem from a reached state or a
23
- // run with its loops accelerated, checked as the rest are.
23
+ // run with its loops accelerated, checked as the rest are. A large closure goal (a program of many locations, whose
24
+ // body reads every rule) is closed by the set's parts (`cases`): each part's goal at its location, the location
25
+ // substituted and the constants folded, which leaves only that location's rules (kernel.ts's checkRecurCases).
24
26
  import { n as K, same as eq, seeded, walkOnce, x as V } from "./machine.js";
25
- import { checkRecur, loopMachine, recurGoal, substC, trueC } from "../kernel/kernel.js";
27
+ import { caseGoals, checkRecur, checkRecurCases, coverGoal, loopMachine, recurGoal, substC, trueC } from "../kernel/kernel.js";
26
28
  import { clock, counted, grow, realModels } from "../kernel/prove.js";
27
29
  import { work } from "./solver.js";
28
- import { accelerated, stemsTo } from "./accel.js";
30
+ import { accelerated, relationBuilt, stemsTo } from "./accel.js";
29
31
  import { findBoundedRun } from "./bmc.js";
30
32
  const T = trueC, F = { op: '<', a: K(0), b: K(0) };
31
33
  export const isT = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
@@ -107,6 +109,9 @@ const GOAL_MAX = 300_000;
107
109
  // 11 s; tqli: 720,729 written out, proven in 22 s).
108
110
  export const dagSize = (x) => { let n = 0; walkOnce(x, () => { n++; }); return n; };
109
111
  const ACCEL_DAG_MAX = 1_500_000;
112
+ // (a goal past this many distinct terms is closed by cases, where `cases` asks for it: pgarch's sets, 537,164, each
113
+ // location's case under 300)
114
+ const CASES_FROM = 20_000;
110
115
  // --- running the loop ---------------------------------------------------------------------------------------------------
111
116
  class Overflow extends Error {
112
117
  }
@@ -425,15 +430,31 @@ function search(l, opts) {
425
430
  // (a model of the CDCL search whose products don't multiply out goes on to the plain search, which multiplies rows)
426
431
  const was = realModels.on;
427
432
  realModels.on = true;
428
- let out;
433
+ // (a large goal by its cases, where the set's parts are at locations: each part's goal its location substituted
434
+ // and its constants folded, which leaves the rules at that location, and the cover)
435
+ const byCases = opts.cases && a.cases && dagSize(goal.hyps) > CASES_FROM ? a.cases : undefined;
436
+ let closed, late = false;
429
437
  try {
430
- out = grow(goal, new Map(), { nodes: 0, until: budget });
438
+ for (const g of byCases ? [coverGoal({ set: a.set, cases: byCases }), ...caseGoals(l, a, byCases)] : [goal]) {
439
+ const out = grow(g, new Map(), { nodes: 0, until: budget });
440
+ if (!('tree' in out)) {
441
+ late = out.stuck === 'unknown' && out.why !== undefined;
442
+ closed = undefined;
443
+ break;
444
+ }
445
+ if (!byCases)
446
+ closed = { tree: out.tree };
447
+ else if (!closed)
448
+ closed = { cover: out.tree, cases: [] };
449
+ else if ('cases' in closed)
450
+ closed.cases.push({ ...byCases[closed.cases.length], tree: out.tree });
451
+ }
431
452
  }
432
453
  finally {
433
454
  realModels.on = was;
434
455
  }
435
- if (!('tree' in out))
436
- return out.stuck === 'unknown' && out.why !== undefined ? 'late' : undefined;
456
+ if (!closed)
457
+ return late ? 'late' : undefined;
437
458
  stats.accelClosed++;
438
459
  // (the accelerated runs' search again, deeper: fun9's stem of 30 turns)
439
460
  if (!stems.length && now() < until)
@@ -452,7 +473,21 @@ function search(l, opts) {
452
473
  stems.push(c);
453
474
  }
454
475
  for (const t of stems) {
455
- const recur = { start: params(t.params), stem: asStem(t.stem), set: a.set, wit: a.wit, tree: out.tree };
476
+ const base = { start: params(t.params), stem: asStem(t.stem), set: a.set, wit: a.wit };
477
+ if ('cases' in closed) {
478
+ const cases = { ...base, ...closed };
479
+ let ok = false;
480
+ try {
481
+ ok = checkRecurCases(l, cases);
482
+ }
483
+ catch {
484
+ ok = false;
485
+ }
486
+ if (ok)
487
+ return done({ proven: true, checked: true, cases, by: 'accelerated' });
488
+ continue;
489
+ }
490
+ const recur = { ...base, tree: closed.tree };
456
491
  let ok = false;
457
492
  try {
458
493
  ok = checkRecur(l, recur);
@@ -470,11 +505,19 @@ function search(l, opts) {
470
505
  const later = [];
471
506
  let deepened = 0;
472
507
  const again = [];
473
- for (const a of accelerated(l, { now, until: accelUntil, runs, io: { start, turn } })) {
508
+ // (the search for the next candidate has its own time: a closure tried on a set a stem reaches doesn't count
509
+ // against it, up to `extend`; so a set whose closure runs out of time leaves the time to look for a smaller one)
510
+ // (a large loop's relation takes seconds to build, once: the search for candidates starts when it is built, up to
511
+ // 10 s later; pgarch's 203 locations, 4 s to build its loop and 13 s its relation on a laptop)
512
+ const built = now();
513
+ relationBuilt(l);
514
+ let genUntil = accelUntil + Math.min(10_000, now() - built);
515
+ for (const a of accelerated(l, { now, get until() { return genUntil; }, runs, io: { start, turn } })) {
474
516
  stats.accel++;
475
517
  const goal = recurGoal(l, a);
476
518
  stats.goalSize = Math.max(stats.goalSize, goalSize(goal.hyps));
477
- if (dagSize(goal.hyps) > ACCEL_DAG_MAX)
519
+ // (past the cap a goal is closed only by its cases, each at one location)
520
+ if (dagSize(goal.hyps) > ACCEL_DAG_MAX && !(opts.cases && a.cases))
478
521
  continue;
479
522
  const inSet = cC(a.set);
480
523
  // A stem into the set, cut where it first enters it (every turn allowed): from a state a random run reached (the
@@ -499,8 +542,19 @@ function search(l, opts) {
499
542
  for (const v of visits)
500
543
  if ((!best || v.at < best.at) && inSet(v.st))
501
544
  best = v;
502
- if (best)
503
- stems.push({ params: best.params, stem: stemOf(best) });
545
+ if (best) {
546
+ stems.push(cut({ params: best.params, stem: stemOf(best) }) ?? { params: best.params, stem: stemOf(best) });
547
+ // (a run's stem past 64 turns, which Lean replays turn by turn over the whole loop: a shorter one of the
548
+ // accelerated runs' search first, where it finds one within 500 ms)
549
+ if (stems[0].stem.length > 64)
550
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(longUntil, now() + 500) })) {
551
+ const c = cut(t);
552
+ if (c && c.stem.length < stems[0].stem.length) {
553
+ stems.unshift(c);
554
+ break;
555
+ }
556
+ }
557
+ }
504
558
  else {
505
559
  // (a set's stem has time of its own, past the stage's if need be, within the search's)
506
560
  let n = 0;
@@ -532,10 +586,13 @@ function search(l, opts) {
532
586
  }
533
587
  // (a set with a stem is likely: its closure may take most of what is left, past the stage's share; one without,
534
588
  // the stage's share and at most 4 s)
589
+ const tried = now();
535
590
  const v = attempt(a, goal, stems, cut, stems.length ? Math.min(until, now() + Math.max(4000, (until - now()) * 0.6)) : Math.min(accelUntil, now() + 4000));
536
591
  if (v && v !== 'late')
537
592
  return v;
538
- if (v === 'late' && stems.length && longUntil > until && again.length < 3)
593
+ if (stems.length)
594
+ genUntil = Math.max(genUntil, Math.min(longUntil - 1000, genUntil + now() - tried));
595
+ if (v === 'late' && stems.length && longUntil > until)
539
596
  again.push({ a, goal, stems, cut });
540
597
  }
541
598
  // (the small sets no stem reaches: a closure and a bounded run each, in what is left of the search's time)
@@ -546,13 +603,14 @@ function search(l, opts) {
546
603
  if (v && v !== 'late')
547
604
  return v;
548
605
  }
549
- // (a set with a stem whose closure ran out of time: again, with the time `extend` gives, shared, the smaller goal
550
- // first)
551
- again.sort((x, y) => dagSize(x.goal.hyps) - dagSize(y.goal.hyps));
552
- for (const [k, { a, goal, stems, cut }] of again.entries()) {
606
+ // (a set with a stem whose closure ran out of time: again, with the time `extend` gives, the smaller goal first,
607
+ // each its share of what is left by its goal's size, the closure's work growing with it)
608
+ const sized = again.map(x => ({ ...x, size: dagSize(x.goal.hyps) })).sort((x, y) => x.size - y.size).slice(0, 6);
609
+ for (const [k, { a, goal, stems, cut, size }] of sized.entries()) {
553
610
  if (now() >= longUntil - 1000)
554
611
  break;
555
- const v = attempt(a, goal, stems, cut, Math.min(longUntil, now() + Math.max(4000, (longUntil - now()) * 0.9 / (again.length - k))));
612
+ const share = size / sized.slice(k).reduce((s, x) => s + x.size, 0);
613
+ const v = attempt(a, goal, stems, cut, Math.min(longUntil, now() + Math.max(2000, (longUntil - now()) * 0.9 * share)));
556
614
  if (v && v !== 'late')
557
615
  return v;
558
616
  }
@@ -99,7 +99,23 @@ export type Recur = {
99
99
  tree: Tree;
100
100
  };
101
101
  export declare function recurGoal(l: Loop, r: Pick<Recur, 'set' | 'wit'>): Goal;
102
- export declare function checkRecur(l: Loop, r: Recur): boolean;
102
+ export declare function checkRecur(l: Loop, r: Recur | RecurCases): boolean;
103
+ export type RecurCases = Omit<Recur, 'tree'> & {
104
+ cover: Tree;
105
+ cases: {
106
+ pins: [string, number][];
107
+ cond: C;
108
+ tree: Tree;
109
+ }[];
110
+ };
111
+ export declare const foldPinned: (c: C, pins: [string, number][]) => C;
112
+ export declare const pinC: (pins: [string, number][]) => C;
113
+ export declare const coverGoal: (r: {
114
+ set: C;
115
+ cases: Pick<RecurCases["cases"][number], "pins" | "cond">[];
116
+ }) => Goal;
117
+ export declare function caseGoals(l: Loop, r: Pick<Recur, 'set' | 'wit'>, cases: Pick<RecurCases['cases'][number], 'pins' | 'cond'>[]): Goal[];
118
+ export declare function checkRecurCases(l: Loop, r: RecurCases): boolean;
103
119
  export declare function progressObligations(m: Machine, laws: Law[], instances: Instances, p: {
104
120
  name: string;
105
121
  when: C;