gdp-wired 0.33.1 → 0.35.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.
package/dist/core/laws.js CHANGED
@@ -22,6 +22,9 @@
22
22
  // counts[user] < limit, user in m a map at a key as the code reads it (m.get(k), k in m, m[k] is None)
23
23
  // cache["hits:" + s] <= limit a store at its key's template ("hits:" + s, f"hits:{s}")
24
24
  // forall k in budgets: budgets[k].spent <= budgets[k].limit every key the map holds (at the top of the law)
25
+ // forall o in old(asks): forall j in old(asks): o in asks or o.price <= j.price
26
+ // every item of a list (o.price its field; `o in asks` whether that item is still
27
+ // in it, the same item, not an equal one), at every two (or three) at once
25
28
  // mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
26
29
  import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
27
30
  import { agreement, isolation, noninterference } from "./relational.js";
@@ -262,14 +265,38 @@ export function buildLaw(x, l, opts = {}) {
262
265
  // The expression read: its value (`dry`: only which names it reads, nothing built).
263
266
  function read(e, c, names, dry) {
264
267
  if (e.k === 'forall') {
265
- const over = val(e.over, c, names, dry);
266
- if (over.t !== 'map')
267
- throw new LawError(`forall ${e.v} in ...: over a map (a dict, a Map, a hash)`);
268
+ // (forall a in X: forall b in Y: ...: at every two keys at once, each held by its map)
269
+ const chain = [];
270
+ let body = e;
271
+ while (body.k === 'forall') {
272
+ chain.push(body);
273
+ body = body.body;
274
+ }
275
+ if (chain.length > 3)
276
+ throw new LawError('forall ... in ...: at most three at once');
277
+ c.items ??= new Map();
278
+ const overs = chain.map(f => {
279
+ const over = val(f.over, c, names, dry);
280
+ if (over.t !== 'map')
281
+ throw new LawError(`forall ${f.v} in ...: over a map (a dict, a Map, a hash) or a list`);
282
+ return { over, env: f.over.k === 'old' || !c.step ? c.b : c.a };
283
+ });
268
284
  if (dry) {
269
- c.keys.set(e.v, new Term({ op: 'const', value: 0 }));
270
- return cond(val(e.body, c, names, true));
285
+ for (const f of chain)
286
+ c.keys.set(f.v, new Term({ op: 'const', value: 0 }));
287
+ return cond(val(body, c, names, true));
271
288
  }
272
- return forall(k => { c.keys.set(e.v, k); const m = (c.step ? c.a : c.b)[over.n.rule]; return m.at(k).has.implies(cond(val(e.body, c, names, false))); });
289
+ const at = (ks) => {
290
+ const held = overs.map((o, i) => {
291
+ const m = o.env[o.over.n.rule];
292
+ c.keys.set(chain[i].v, ks[i]);
293
+ if (o.over.n.map?.ordered)
294
+ c.items.set(chain[i].v, { map: m.at(ks[i]), fields: o.over.n.map.fields });
295
+ return m.at(ks[i]).has;
296
+ });
297
+ return all(...held).implies(cond(val(body, c, names, false)));
298
+ };
299
+ return chain.length === 1 ? forall(k => at([k])) : chain.length === 2 ? forall((k, j) => at([k, j])) : forall((k, j, i) => at([k, j, i]));
273
300
  }
274
301
  return cond(val(e, c, names, dry));
275
302
  }
@@ -422,6 +449,12 @@ function cellOf(m, k, c) {
422
449
  function path(e, c, names, dry) {
423
450
  if (c.keys.has(e.head) && !e.segs.length)
424
451
  return { t: 'key', v: c.keys.get(e.head) };
452
+ // (an item of a list a forall is over: its fields)
453
+ const item = c.items?.get(e.head);
454
+ if (item && e.segs.length)
455
+ return dry ? DRY : rest(e.segs, { t: 'cell', rec: item.map, fields: item.fields }, c, names, dry, e);
456
+ if (c.keys.has(e.head) && dry)
457
+ return DRY;
425
458
  if (e.head === 'result' || e.head === 'failed') {
426
459
  const n = e.head === 'failed' ? names.find(x => x.role === 'failed') : results(names, c);
427
460
  if (!n)
@@ -1,4 +1,4 @@
1
- import { type Law, type Machine, type Rand, type Request } from './machine.js';
1
+ import { type C, type E, type Law, type Machine, type Rand, type Request } from './machine.js';
2
2
  import { type Liveness } from '../kernel/kernel.js';
3
3
  import { type LeadsVerdict } from './cycles.js';
4
4
  import { inferLaws } from './infer.js';
@@ -12,4 +12,25 @@ export type Draws = {
12
12
  export declare function leadsByTerms(m: Machine, laws: Law[], l: Liveness, draws: Draws, opts?: {
13
13
  ms?: number;
14
14
  }): LeadsVerdict;
15
+ export type Ring = {
16
+ params: Env;
17
+ stem: Request[];
18
+ sets: {
19
+ holds: C;
20
+ request: Record<string, E>;
21
+ }[];
22
+ };
23
+ export type Fairness = 'taken' | 'weak' | 'strong';
24
+ export type RingVerdict = {
25
+ refuted: boolean;
26
+ fair?: Fairness[];
27
+ why?: string;
28
+ };
29
+ export declare function refutedBy(m: Machine, laws: Law[], l: Liveness, ring: Ring): RingVerdict;
30
+ export declare function findRing(m: Machine, laws: Law[], l: Liveness, draws: Draws, opts?: {
31
+ ms?: number;
32
+ }): {
33
+ ring: Ring;
34
+ verdict: RingVerdict;
35
+ } | undefined;
15
36
  export {};
package/dist/core/live.js CHANGED
@@ -13,8 +13,8 @@
13
13
  // chosen in order, each one no step raises that lowers the most of those left. The rank is then the kernel's
14
14
  // (proveLiveness), with the invariants inferLaws finds where its goals need some. Nothing new is trusted.
15
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";
16
+ import { falseC, livenessHelpful, livenessParts, substC, substE } from "../kernel/kernel.js";
17
+ import { clock, proveLiveness, proveProgress, proveStepLaws, withDeadline } from "../kernel/prove.js";
18
18
  import { allowed, watch } from "./watch.js";
19
19
  import { showE } from "./cycles.js";
20
20
  import { inferLaws } from "./infer.js";
@@ -58,16 +58,18 @@ function distances(m, l) {
58
58
  }
59
59
  // A variable's values ranked by the steps between them: each strongly connected set one level, a level above every one
60
60
  // a step goes to from it (Tarjan's components, then the longest path down).
61
- function controlRank(x, steps) {
61
+ function controlRank(x, value, steps) {
62
62
  const graph = new Map();
63
63
  const node = (a) => graph.get(a) ?? (graph.set(a, new Set()), graph.get(a));
64
64
  for (const st of steps) {
65
- const a = st.s.scalars[x], b = st.t.scalars[x];
65
+ const a = value(x, st, false), b = value(x, st, true);
66
+ if (Number.isNaN(a) || Number.isNaN(b))
67
+ return undefined;
66
68
  node(b);
67
69
  if (a !== b)
68
70
  node(a).add(b);
69
71
  }
70
- if (graph.size < 2)
72
+ if (graph.size < 2 || graph.size > 16)
71
73
  return undefined;
72
74
  const index = new Map(), low = new Map(), comp = new Map(), stack = [];
73
75
  let n = 0, c = 0;
@@ -109,7 +111,7 @@ function controlRank(x, steps) {
109
111
  const values = [...graph.keys()].sort((p, q) => p - q).map(a => [a, level.get(comp.get(a))]);
110
112
  if (values.every(([, lv]) => lv === 0))
111
113
  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]));
114
+ return values.slice(0, -1).reduceRight((rest, [a, lv]) => ({ op: 'if', c: { op: '=', a: x, b: k(a) }, then: k(lv), else: rest }), k(values.at(-1)[1]));
113
115
  }
114
116
  // The variables a kind law bounds by a small constant (x < c, x <= c).
115
117
  const bounded = (m, laws) => {
@@ -243,14 +245,22 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
243
245
  return NaN;
244
246
  } };
245
247
  const fixed = distances(m, l), text = (rank) => `(${rank.map(showE).join(', ')})`, tried = new Set();
248
+ // the control: the variables a kind law bounds, and the cells `from` and `to` read at a key of the params (a liveness
249
+ // about every key reads its key's cells: a status per key)
250
+ const cells = new Map();
251
+ walk([l.from, l.to], o => { if (o.op === 'get' && !reads(o.key, [...m.inputs, ...Object.keys(m.state)]) && !id(o.key).includes('"op":"get"'))
252
+ cells.set(id(o), o); });
253
+ const controls = [...bounded(m, laws).map(v), ...cells.values()];
246
254
  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];
255
+ // (the ranks alone until two thirds of the time are spent: the rest for the invariants the first one needs)
256
+ const ranksUntil = until - (until - clock()) / 3;
257
+ for (let round = 0; round < 6 && ranksUntil - clock() > 200; round++) {
258
+ const cands = [...controls.map(x => controlRank(x, (e, st, after) => value(e, st.ps, after ? st.t : st.s), steps)).filter((e) => !!e), ...fixed];
249
259
  const vals = cands.map(e => steps.map(st => [value(e, st.ps, st.s), value(e, st.ps, st.t)]));
250
260
  const build = (banned) => {
251
261
  let left = steps.map((_, i) => i);
252
262
  const rank = [];
253
- for (let turn = 0; turn < 3 && left.some(i => steps[i].lower); turn++) {
263
+ for (let turn = 0; turn < 4 && left.some(i => steps[i].lower); turn++) {
254
264
  let pick = -1, most = 0;
255
265
  for (let c = 0; c < cands.length; c++) {
256
266
  if (banned.has(c) || rank.includes(c))
@@ -285,7 +295,7 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
285
295
  break;
286
296
  let learnt = false;
287
297
  for (const rank of fresh) {
288
- const ms = until - clock();
298
+ const ms = ranksUntil - clock();
289
299
  if (ms < 200)
290
300
  break;
291
301
  tried.add(id(rank));
@@ -305,7 +315,7 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
305
315
  const rank = best, lv = { ...l, rank }, ms = until - clock();
306
316
  if (ms > 300) {
307
317
  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);
318
+ const kept = inf.found.filter(f => !f.law.some?.length), more = kept.map(f => f.law);
309
319
  if (inf.proven && more.length) {
310
320
  const again = withDeadline(until + 5000, () => proveLiveness(m, [...laws, ...more], lv));
311
321
  if (again.proven && again.checked)
@@ -315,3 +325,146 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
315
325
  const failed = last?.failed ? { goal: last.failed.goal, stuck: last.failed.stuck, ...(last.failed.witness ? { witness: last.failed.witness } : {}) } : {};
316
326
  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
327
  }
328
+ export function refutedBy(m, laws, l, ring) {
329
+ const run = interpret(m), helpful = livenessHelpful(l), n = ring.sets.length;
330
+ if (!n)
331
+ return { refuted: false, why: 'no set' };
332
+ if (m.pre && !evalC(m.pre, ring.params, { scalars: {}, maps: {} }, m))
333
+ return { refuted: false, why: 'the params break the precondition' };
334
+ let st = run.init(ring.params);
335
+ for (const [i, req] of ring.stem.entries()) {
336
+ if (!allowed(m, run, ring.params, st, req))
337
+ return { refuted: false, why: `the stem's request ${i + 1} is not allowed` };
338
+ st = run.step(ring.params, st, req);
339
+ }
340
+ const at = (c) => evalC(c, { ...ring.params, ...st.scalars }, st, m);
341
+ if (!at(l.from) || at(l.to) || !at(ring.sets[0].holds))
342
+ return { refuted: false, why: 'the stem ends where `from` doesn\'t hold, `to` does, or outside the first set' };
343
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(x => [x, v(`${x}'`)])), maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(map => [map, (key) => ({ op: 'get', map: `${map}'`, key })])), flags: {} };
344
+ const full = (r) => Object.fromEntries(m.inputs.map(i => [i, r[i] ?? k(0)]));
345
+ for (const [j, set] of ring.sets.entries()) {
346
+ const next = ring.sets[(j + 1) % n].holds, then = { op: 'and', xs: [substC(next, after), substC(l.from, after), { op: 'not', x: substC(l.to, after) }] };
347
+ const p = proveProgress(m, laws, { name: `${l.name}: ring ${j + 1}`, when: set.holds, then, request: full(set.request) });
348
+ if (!p.proven || !p.checked)
349
+ return { refuted: false, why: `ring ${j + 1}: its request not proven allowed and into the next set${p.failed ? ` (${p.failed.goal})` : ''}` };
350
+ }
351
+ // "no allowed request from a state of R_j meets these": a step law whose `then` is false
352
+ const never = (what, ...cs) => { const r = proveStepLaws(m, laws, [{ name: `${l.name}: ${what}`, when: { op: 'and', xs: cs }, then: falseC }]); return r.proven && r.checked; };
353
+ const named = (req) => Object.entries(req).map(([x, t]) => ({ op: '=', a: v(x), b: t }));
354
+ const fair = new Set(['taken', 'weak', 'strong']);
355
+ for (const [i, h] of helpful.entries()) {
356
+ const takes = ring.sets.map(set => Object.entries(h.request).every(([x, t]) => id(full(set.request)[x]) === id(t)));
357
+ if (!takes.some(Boolean))
358
+ fair.delete('taken');
359
+ if (!takes.some(Boolean) && !ring.sets.some(set => never(`helpful request ${i + 1} not allowed`, set.holds, ...named(h.request))))
360
+ fair.delete('weak');
361
+ if (!ring.sets.some((set, j) => takes[j] && never(`helpful request ${i + 1} taken in its region`, set.holds, { op: 'not', x: h.when }, ...named(full(set.request))))
362
+ && !ring.sets.every(set => never(`helpful request ${i + 1} not allowed in its region`, set.holds, h.when, ...named(h.request))))
363
+ fair.delete('strong');
364
+ if (!fair.size)
365
+ return { refuted: false, fair: [], why: `helpful request ${i + 1}: the run is fair to it under no notion` };
366
+ }
367
+ const want = l.fairness === 'strong' ? 'strong' : 'weak', out = [...fair];
368
+ return { refuted: fair.has(want), fair: out, ...(fair.has(want) ? {} : { why: `the run is not ${want}ly fair` }) };
369
+ }
370
+ // A ring of one set, found: a state the runs reach where `from` holds and `to` doesn't and the helpful requests taken in
371
+ // turn keep it so; the set, the literals of the rule's comparisons (its guards and steps, also as each helpful request
372
+ // meets them, `from`, `to`, the regions) true there, the ring's requests the helpful requests allowed there. Literals a
373
+ // request doesn't keep are dropped (each kept literal proven by the kernel after each request, as Houdini drops them)
374
+ // until the rest are kept; then refutedBy checks the ring. Undefined where none is found.
375
+ export function findRing(m, laws, l, draws, opts = {}) {
376
+ const until = clock() + (opts.ms ?? 10_000), rand = seeded(17), run = interpret(m), helpful = livenessHelpful(l);
377
+ const env = (ps, st) => ({ ...ps, ...st.scalars });
378
+ const holds = (c, ps, st) => { try {
379
+ return evalC(c, env(ps, st), st, m);
380
+ }
381
+ catch {
382
+ return undefined;
383
+ } };
384
+ const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
385
+ const full = (r) => Object.fromEntries(m.inputs.map(i => [i, r[i] ?? k(0)]));
386
+ const concrete = (r, ps, st) => Object.fromEntries(Object.entries(full(r)).map(([i, t]) => [i, evalE(t, env(ps, st), st, m)]));
387
+ // A state where `from` holds and `to` doesn't, then the helpful requests allowed taken in turn, up to 3,000 steps (the
388
+ // time passing in them, every deadline small params allow passed), never reaching `to`: the state they end at.
389
+ let found;
390
+ const allowedAt = (ps, st) => helpful.flatMap((h, i) => { try {
391
+ return allowed(m, run, ps, st, concrete(h.request, ps, st)) ? [i] : [];
392
+ }
393
+ catch {
394
+ return [];
395
+ } });
396
+ for (let trial = 0; trial < 400 && !found && clock() < until; trial++) {
397
+ let ps, st;
398
+ try {
399
+ ps = draws.params(rand, 2 + (trial % 3) * 2);
400
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
401
+ continue;
402
+ st = run.init(ps);
403
+ }
404
+ catch {
405
+ continue;
406
+ }
407
+ const stem = [];
408
+ for (let turn = 0; turn < 40; turn++) {
409
+ if (turn > 0 && pending(ps, st)) {
410
+ let s2 = st;
411
+ const laps = [];
412
+ for (let lap = 0; lap < 1000 && s2 && laps.length < 3000; lap++)
413
+ for (const i of allowedAt(ps, s2)) {
414
+ if (!s2)
415
+ break;
416
+ const req = concrete(helpful[i].request, ps, s2);
417
+ if (!allowed(m, run, ps, s2, req))
418
+ continue;
419
+ s2 = run.step(ps, s2, req);
420
+ laps.push(req);
421
+ if (!pending(ps, s2))
422
+ s2 = undefined;
423
+ }
424
+ const hs = s2 ? allowedAt(ps, s2) : [];
425
+ if (s2 && hs.length) {
426
+ found = { ps, stem: [...stem, ...laps], st: s2, hs };
427
+ break;
428
+ }
429
+ }
430
+ try {
431
+ const req = draws.input(rand, 4, ps);
432
+ if (!allowed(m, run, ps, st, req))
433
+ continue;
434
+ st = run.step(ps, st, req);
435
+ stem.push(req);
436
+ }
437
+ catch { /* refused: another */ }
438
+ }
439
+ }
440
+ if (!found)
441
+ return undefined;
442
+ // the literals there
443
+ const atoms = new Map();
444
+ const add = (t) => walk(t, o => { if ((o.op === '<' || o.op === '<=' || o.op === '=') && typeof o.a === 'object' && typeof o.b === 'object') {
445
+ const c = o;
446
+ if (!readsC(c, m.inputs) && !id(c).includes('"op":"flag"'))
447
+ atoms.set(id(c), c);
448
+ } });
449
+ add([l.from, l.to, helpful.map(h => h.when), m.assume, m.step]);
450
+ for (const h of helpful) {
451
+ const sb = { vars: full(h.request), maps: {}, flags: {} };
452
+ if (m.assume)
453
+ add(substC(m.assume, sb));
454
+ for (const e of Object.values(m.step.state ?? {}))
455
+ add(substE(e, sb));
456
+ }
457
+ let lits = [...atoms.values()].flatMap(c => { const b = holds(c, found.ps, found.st); return b === undefined ? [] : [b ? c : { op: 'not', x: c }]; });
458
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(x => [x, v(`${x}'`)])), maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(map => [map, (key) => ({ op: 'get', map: `${map}'`, key })])), flags: {} };
459
+ for (let round = 0; round < 8 && clock() < until; round++) {
460
+ const R = { op: 'and', xs: lits };
461
+ const kept = lits.filter(c => found.hs.every(i => { const p = withDeadline(Math.min(until, clock() + 2000), () => proveProgress(m, laws, { name: 'kept', when: R, then: substC(c, after), request: full(helpful[i].request) })); return p.proven && p.checked; }));
462
+ if (kept.length === lits.length)
463
+ break;
464
+ lits = kept;
465
+ }
466
+ const ring = { params: found.ps, stem: found.stem, sets: found.hs.map(i => ({ holds: { op: 'and', xs: lits }, request: helpful[i].request })) };
467
+ return { ring, verdict: refutedBy(m, laws, l, ring) };
468
+ }
469
+ const readsC = (c, names) => { let hit = false; walk(c, o => { if (o.op === 'var' && names.includes(o.name))
470
+ hit = true; }); return hit; };
@@ -70,8 +70,20 @@ export type Machine = {
70
70
  assume?: C;
71
71
  history?: History;
72
72
  sums?: Record<string, Sum>;
73
+ counts?: Record<string, Counted>;
73
74
  fns?: Record<string, Fn>;
74
75
  facts?: Law[];
76
+ leasts?: Record<string, Least>;
77
+ };
78
+ export type Least = {
79
+ some: string;
80
+ key: string;
81
+ where: C;
82
+ by: {
83
+ e: E;
84
+ neg?: E;
85
+ desc?: boolean;
86
+ }[];
75
87
  };
76
88
  export type Fn = {
77
89
  js: string;
@@ -125,6 +137,12 @@ export type Sum = {
125
137
  key: string;
126
138
  term: E;
127
139
  };
140
+ export type Counted = {
141
+ j: string;
142
+ key: string;
143
+ below: E;
144
+ body: E;
145
+ };
128
146
  export type MapUpdate = {
129
147
  key: E;
130
148
  value: E;
@@ -207,7 +225,8 @@ export declare function pairedArgs(key: E, n: number): E[] | undefined;
207
225
  export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
208
226
  export declare function compileE(e: E, m: Machine): (env: Env, st: State) => number;
209
227
  export declare function compileC(c: C, m: Machine): (env: Env, st: State) => boolean;
210
- export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;
228
+ export declare function leastsIn(m: Machine, env: Env, st: State): Env;
229
+ export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string, params?: Env): State;
211
230
  export declare const numbersOf: (input: Request) => Record<string, number>;
212
231
  export declare function interpret(m: Machine): {
213
232
  init: (params: Env) => State;
@@ -420,16 +420,54 @@ function runnable(m) {
420
420
  const plain = h ? historyMachine(m).machine : sumRuntime(m);
421
421
  if (!h)
422
422
  scope(plain);
423
- const queries = h ? Object.keys(h.queries) : [];
424
- return { h, plain, queries, carried: m.inputs.filter(i => !queries.includes(i)) };
423
+ const queries = h ? Object.keys(h.queries) : [], found = Object.entries(m.leasts ?? {}).flatMap(([n, l]) => [n, l.some]);
424
+ return { h, plain, queries, carried: m.inputs.filter(i => !queries.includes(i) && !found.includes(i)) };
425
+ }
426
+ // The least keys (Machine.leasts) in a state: the candidates are the keys the maps `where` and `by` read hold a cell at;
427
+ // where `where` holds past them all too (at every key no map holds), there is no least, and the request is refused.
428
+ export function leastsIn(m, env, st) {
429
+ const out = {};
430
+ for (const [name, l] of Object.entries(m.leasts ?? {})) {
431
+ const keys = keysAt(st, mapsIn({ op: 'and', xs: [l.where, ...l.by.flatMap(b => [b.e, ...(b.neg ? [b.neg] : [])].map(e => ({ op: '=', a: e, b: e })))] }).filter(mp => !m.fns?.[mp])), past = keys.pop();
432
+ const at = (key) => ({ ...env, ...out, [l.key]: key });
433
+ if (evalC(l.where, at(past), st, m))
434
+ throw new RangeError(`${m.name}: ${name} has no least (its condition holds at every key past the cells)`);
435
+ let best;
436
+ for (const key of keys.sort((a, b) => a - b)) {
437
+ if (!evalC(l.where, at(key), st, m))
438
+ continue;
439
+ const by = l.by.map(b => evalE(b.e, at(key), st, m) - (b.neg ? evalE(b.neg, at(key), st, m) : 0));
440
+ const first = best && by.findIndex((x, i) => x !== best.by[i]);
441
+ if (!best || (first !== -1 && (l.by[first].desc ? by[first] > best.by[first] : by[first] < best.by[first])))
442
+ best = { key, by };
443
+ }
444
+ out[name] = best?.key ?? 0;
445
+ out[l.some] = best ? 1 : 0;
446
+ }
447
+ return out;
425
448
  }
426
449
  const empty = { scalars: {}, maps: {} };
427
450
  // The state as a step reads it: with the maps the request carries (cells past them read 0), each checked natural.
428
- export function carriedView(m, st, input, rename = map => map) {
429
- if (!m.inputMaps?.length)
451
+ // A request's counts (Machine.counts) are read at this view too: each count map's cell at x, computed when read, the sum
452
+ // of its body over the keys below its bound, j at x (CountMachine.lean's cntOf at CReach's view: the params, the request's
453
+ // numbers, the state, the maps it carries).
454
+ class CountCells extends Map {
455
+ at;
456
+ constructor(at) {
457
+ super();
458
+ this.at = at;
459
+ }
460
+ get(x) { let v = super.get(x); if (v === undefined) {
461
+ v = this.at(x);
462
+ super.set(x, v);
463
+ } return v; }
464
+ }
465
+ export function carriedView(m, st, input, rename = map => map, params) {
466
+ const counts = Object.entries(m.counts ?? {});
467
+ if (!m.inputMaps?.length && !counts.length)
430
468
  return st;
431
469
  const maps = { ...st.maps }, defaults = { ...st.defaults };
432
- for (const map of m.inputMaps) {
470
+ for (const map of m.inputMaps ?? []) {
433
471
  const cells = input[map];
434
472
  if (!(cells instanceof Map))
435
473
  throw new RangeError(`input ${map} must be a Map of naturals`);
@@ -440,6 +478,21 @@ export function carriedView(m, st, input, rename = map => map) {
440
478
  maps[rename(map)] = cells;
441
479
  defaults[rename(map)] = 0;
442
480
  }
481
+ if (counts.length) {
482
+ if (!params)
483
+ throw new Error(`${m.name}: a request's counts read the params`);
484
+ const view = { ...st, maps, defaults }, env0 = { ...params, ...numbersOf(input) };
485
+ for (const [c, d] of counts) {
486
+ maps[rename(c)] = new CountCells(x => {
487
+ const e1 = { ...env0, [d.j]: x }, n = evalE(d.below, e1, view, m);
488
+ let sum = 0;
489
+ for (let k = 0; k < n; k++)
490
+ sum = exact(sum + evalE(d.body, { ...e1, [d.key]: k }, view, m));
491
+ return sum;
492
+ });
493
+ defaults[rename(c)] = 0;
494
+ }
495
+ }
443
496
  return { ...st, maps, defaults };
444
497
  }
445
498
  // A request's numbers (its inputs), without the maps it carries.
@@ -459,7 +512,7 @@ export function interpret(m) {
459
512
  env[i] = naturalIn(input[i], `input ${i}`);
460
513
  return env;
461
514
  };
462
- const viewed = (st, input) => carriedView(m, st, input);
515
+ const viewed = (st, input, params) => carriedView(m, st, input, undefined, params);
463
516
  // The records a request's queries read: with pruning, those not yet spent at its order.
464
517
  const live = (env, st) => {
465
518
  const records = st.history;
@@ -499,20 +552,23 @@ export function interpret(m) {
499
552
  },
500
553
  // The queries a request would read (none without a history).
501
554
  queries: (params, st, input) => {
502
- if (!h)
503
- return {};
504
555
  const env = args(params, input);
556
+ if (!h)
557
+ return m.leasts ? leastsIn(m, env, viewed(st, input)) : {};
505
558
  ordered(env, st);
506
- return queriesOf(env, live(env, st));
559
+ const qs = queriesOf(env, live(env, st));
560
+ return m.leasts ? { ...qs, ...leastsIn(m, { ...env, ...qs }, viewed(st, input)) } : qs;
507
561
  },
508
562
  step: (params, given, input) => {
509
- const env = args(params, input), st = viewed(given, input);
563
+ const env = args(params, input), st = viewed(given, input, params);
510
564
  let records = [];
511
565
  if (h) {
512
566
  ordered(env, st);
513
567
  records = live(env, st);
514
568
  Object.assign(env, queriesOf(env, records));
515
569
  }
570
+ if (m.leasts)
571
+ Object.assign(env, leastsIn(m, env, st));
516
572
  for (const [name, c] of Object.entries(plain.step.flags ?? {}))
517
573
  env[`?${name}`] = evalC(c, env, st, plain) ? 1 : 0;
518
574
  if (m.assume && !evalC(m.assume, env, st, plain))
@@ -669,6 +725,16 @@ export function compileJs(m) {
669
725
  }
670
726
  lines.push(`let ${queries.map((_, i) => `q${i} = 0`).join(', ')};`, `for (let i = head; i < records.length; i++) { const r = records[i]; ${queries.map((q, i) => `q${i} = $x(q${i} + ${ex(h.queries[q])});`).join(' ')} }`, ...queries.map((q, i) => `env[${id(q)}] = q${i};`));
671
727
  }
728
+ // The least keys (leastsIn): a scan of the keys the maps read hold, smaller keys first.
729
+ for (const [name, l] of Object.entries(m.leasts ?? {})) {
730
+ const outer = bound;
731
+ bound = { ...bound, [l.key]: 'lk' };
732
+ const where = cx(l.where), by = l.by.map(b => (b.neg ? `(${ex(b.e)} - ${ex(b.neg)})` : ex(b.e)));
733
+ bound = outer;
734
+ const ms = mapsIn({ op: 'and', xs: [l.where, ...l.by.flatMap(b => [b.e, ...(b.neg ? [b.neg] : [])].map(e => ({ op: '=', a: e, b: e })))] }).filter(mp => !fns.includes(mp));
735
+ const better = l.by.map((b, i) => `by[${i}] !== bb[${i}] ? by[${i}] ${b.desc ? '>' : '<'} bb[${i}] : `).join('') + 'false';
736
+ lines.push(`{ const ks = $keys(maps, ${JSON.stringify(ms)}), past = ks.pop(); let lk = past; if (${where}) throw new RangeError(${id(`${m.name}: ${name} has no least (its condition holds at every key past the cells)`)}); let bk, bb; for (lk of ks.sort((a, b) => a - b)) { if (!(${where})) continue; const by = [${by.join(', ')}]; if (bk === undefined || (${better})) { bk = lk; bb = by; } } env[${id(name)}] = bk ?? 0; env[${id(l.some)}] = bk === undefined ? 0 : 1; }`);
737
+ }
672
738
  lines.push(...flags.map((name, i) => `const flag${i} = ${cx(plain.step.flags[name])};`),
673
739
  // The rule's own assumption, as `allowed` (core/watch.ts) reads it (a history's machine assumes more: its relations).
674
740
  ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), `const scalars = {...s, ${Object.entries(plain.step.state ?? {}).map(([name, e]) => `${id(name)}: ${ex(e)}`).join(', ')}};`, ...writes.map(([, w], i) => ('each' in w ? `const write${i} = ${every(w)};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
@@ -149,8 +149,9 @@ def state_of(obj, stores):
149
149
  elif k == 'bool': s[l['name']] = False if v is None else v
150
150
  elif k == 'map':
151
151
  cells = {}
152
- for key, x in (v or {}).items():
153
- if l.get('fields'): cells[str(key)] = {f['name']: (enc_num(x[f['name']] if isinstance(x, dict) else getattr(x, f['name']))) for f in l['fields']}
152
+ # (a list: its items by their places, 0 first)
153
+ for key, x in (enumerate(v or []) if l.get('ordered') else (v or {}).items()):
154
+ if l.get('fields'): cells[str(key)] = {f['name']: (lambda y: y if f.get('choice') else enc_num(y))(x[f['name']] if isinstance(x, dict) else getattr(x, f['name'])) for f in l['fields']}
154
155
  else: cells[str(key)] = {'value': enc_num(x)}
155
156
  s[l['name']] = cells
156
157
  # A store's key no template names: the code keeps state the rule has no place for.
@@ -181,9 +182,9 @@ def set_state(obj, stores, state):
181
182
  for key, c in (v or {}).items():
182
183
  kk = int(key) if l.get('key') == 'num' else key
183
184
  if l.get('fields'):
184
- d[kk] = make_rec(resolve(l['cls']), {f['name']: (num_in(c[f['name']], f.get('float')) if isinstance(c[f['name']], str) else c[f['name']]) for f in l['fields']})
185
+ d[kk] = make_rec(resolve(l['cls']), {f['name']: (num_in(c[f['name']], f.get('float')) if isinstance(c[f['name']], str) and not f.get('choice') else c[f['name']]) for f in l['fields']})
185
186
  else: d[kk] = num_in(c['value'], l.get('float')) if isinstance(c['value'], str) else c['value']
186
- put(obj, l['path'], d)
187
+ put(obj, l['path'], [d[kk] for kk in sorted(d)] if l.get('ordered') else d)
187
188
  for l in S['leaves']:
188
189
  if l['kind'] == 'none' and state.get(l['name']) is True: put(obj, l['path'], None)
189
190
 
@@ -147,6 +147,8 @@ class Reader:
147
147
  elif bn: kinds.add('outside-base:' + bn)
148
148
  dataclass = any((dotted(d.func if isinstance(d, ast.Call) else d) or '').split('.')[-1] == 'dataclass' for d in cdef.decorator_list)
149
149
  frozen = any(isinstance(d, ast.Call) and any(k.arg == 'frozen' and isinstance(k.value, ast.Constant) and k.value.value for k in d.keywords) for d in cdef.decorator_list)
150
+ # (a dataclass whose == is its fields' unless eq=False says it is identity)
151
+ if any(isinstance(d, ast.Call) and any(k.arg == 'eq' and not (isinstance(k.value, ast.Constant) and k.value.value is True) for k in d.keywords) for d in cdef.decorator_list): kinds.add('eq-identity')
150
152
  total = not any(k.arg == 'total' and isinstance(k.value, ast.Constant) and k.value.value is False for k in cdef.keywords)
151
153
  # The fields its __init__ sets: annotated there, or set from an annotated argument (a class of another module whose
152
154
  # fields aren't declared on the class).
@@ -419,7 +421,15 @@ class Reader:
419
421
  return {'e': 'fstr', 'parts': parts, 'p': p, 'text': text(x)}
420
422
  if isinstance(x, ast.List): return {'e': 'list', 'xs': [E(v) for v in x.elts], 'p': p}
421
423
  if isinstance(x, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): return {'e': 'no', 'why': f"{text(x)}: a comprehension (a loop)", 'p': p}
422
- if isinstance(x, ast.Lambda): return {'e': 'no', 'why': f"{text(x)}: a lambda (a closure)", 'p': p}
424
+ if isinstance(x, ast.Lambda):
425
+ # (read as a key function where one is taken, min/max(xs, key=lambda o: ...); anywhere else refused, a closure)
426
+ a = x.args
427
+ if a.vararg or a.kwarg or a.kwonlyargs or a.defaults or a.posonlyargs or len(a.args) != 1: return {'e': 'no', 'why': f"{text(x)}: a lambda (a closure)", 'p': p}
428
+ ps = [y.arg for y in a.args]
429
+ self.local_stack.append((self.local_stack[-1] if self.local_stack else set()) | set(ps))
430
+ try: body = E(x.body)
431
+ finally: self.local_stack.pop()
432
+ return {'e': 'lambda', 'params': ps, 'x': body, 'p': p, 'text': text(x)}
423
433
  return {'e': 'no', 'why': f"{text(x)}: {type(x).__name__} (outside the subset)", 'p': p}
424
434
 
425
435
  def main():
@@ -23,7 +23,7 @@ export const allowed = (m, run, params, st, input) => {
23
23
  const order = m.history?.prune?.order;
24
24
  if (order !== undefined && st.last !== undefined && input[order] < st.last)
25
25
  return false;
26
- return !m.assume || evalC(m.assume, requestEnv(m, run, params, st, input), carriedView(m, st, input), m);
26
+ return !m.assume || evalC(m.assume, requestEnv(m, run, params, st, input), carriedView(m, st, input, undefined, params), m);
27
27
  };
28
28
  // The keys a law about every key is read at: 0 to bound + 1, and every key a map holds.
29
29
  export const keysOf = (bound, ...states) => {
@@ -313,6 +313,31 @@ export declare function checkCounted(g: CountedGoal, cert: {
313
313
  tree: Tree;
314
314
  }): boolean;
315
315
  export declare function countedGoal(g: CountedGoal, insts: CountInst[]): Goal | undefined;
316
+ export type CountDecl = {
317
+ map: string;
318
+ j: string;
319
+ key: string;
320
+ below: E;
321
+ body: E;
322
+ };
323
+ export type MapRead = [string, string, E];
324
+ export type CountCert = {
325
+ reads: MapRead[];
326
+ insts: CountInst[];
327
+ tree: Tree;
328
+ };
329
+ export declare const postName: (map: string) => string;
330
+ export declare const stateCounts: (m: Machine) => string[];
331
+ export declare function checkMC(hyps: C[], ds: CountDecl[], k: CountCert): boolean;
332
+ export declare function mcGoal(hyps: C[], ds: CountDecl[], k: Pick<CountCert, 'reads' | 'insts'>): Goal | undefined;
333
+ export declare function countedObligations(m: Machine, laws: Law[], instances?: Record<string, Instances>, only?: number): {
334
+ goal: Goal;
335
+ decls: CountDecl[];
336
+ }[];
337
+ export declare function checkCountedLaws(m: Machine, laws: Law[], proof: {
338
+ instances: Record<string, Instances>;
339
+ certs: Record<string, CountCert>;
340
+ }): boolean;
316
341
  export type GhostMap = {
317
342
  start: number;
318
343
  write: MapUpdate;