gdp-wired 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/core/c/reader.js +22 -7
  2. package/dist/core/check.js +3 -2
  3. package/dist/core/cli.d.ts +1 -0
  4. package/dist/core/cli.js +136 -6
  5. package/dist/core/counts.d.ts +1 -1
  6. package/dist/core/counts.js +30 -12
  7. package/dist/core/data.d.ts +6 -1
  8. package/dist/core/data.js +894 -152
  9. package/dist/core/dsl.d.ts +2 -0
  10. package/dist/core/dsl.js +88 -10
  11. package/dist/core/effect-prims.js +2 -2
  12. package/dist/core/ex/reader.exs +17 -1
  13. package/dist/core/exists.d.ts +15 -1
  14. package/dist/core/exists.js +263 -41
  15. package/dist/core/extract-c.js +19 -12
  16. package/dist/core/extract-check.d.ts +6 -0
  17. package/dist/core/extract-check.js +49 -3
  18. package/dist/core/extract-ex.js +3 -3
  19. package/dist/core/extract-go-check.js +19 -12
  20. package/dist/core/extract-go.js +20 -5
  21. package/dist/core/extract-jvm.js +63 -14
  22. package/dist/core/extract-print.js +3 -0
  23. package/dist/core/extract-py.js +3 -3
  24. package/dist/core/extract-rb.js +3 -3
  25. package/dist/core/extract-read.d.ts +8 -0
  26. package/dist/core/extract-read.js +55 -0
  27. package/dist/core/extract-rs.js +17 -19
  28. package/dist/core/extract-shapes.js +20 -0
  29. package/dist/core/extract-sol.js +19 -8
  30. package/dist/core/extract-step.d.ts +50 -3
  31. package/dist/core/extract-step.js +289 -58
  32. package/dist/core/extract-swift.js +20 -13
  33. package/dist/core/extract.d.ts +1 -0
  34. package/dist/core/extract.js +27 -2
  35. package/dist/core/fresh.d.ts +2 -2
  36. package/dist/core/fresh.js +7 -3
  37. package/dist/core/go/reader.go +7 -1
  38. package/dist/core/infer.js +115 -42
  39. package/dist/core/jvm/JavaReader.java +10 -2
  40. package/dist/core/jvm/Jvm.java +17 -1
  41. package/dist/core/jvm/KtReader.java +57 -5
  42. package/dist/core/machine.d.ts +1 -2
  43. package/dist/core/machine.js +27 -15
  44. package/dist/core/py/harness.py +77 -11
  45. package/dist/core/py/reader.py +50 -5
  46. package/dist/core/rb/reader.rb +52 -5
  47. package/dist/core/rs/src/main.rs +10 -0
  48. package/dist/core/sol/harness.py +6 -3
  49. package/dist/core/solver.js +5 -4
  50. package/dist/core/system.d.ts +62 -1
  51. package/dist/core/system.js +262 -3
  52. package/dist/core/transfer.js +17 -0
  53. package/dist/core/watch.js +1 -1
  54. package/dist/interchange/check.js +10 -10
  55. package/dist/interchange/format.d.ts +4 -0
  56. package/dist/interchange/format.js +13 -5
  57. package/dist/kernel/cdcl.js +33 -2
  58. package/dist/kernel/epr.js +35 -5
  59. package/dist/kernel/kernel.d.ts +2 -0
  60. package/dist/kernel/kernel.js +67 -40
  61. package/dist/kernel/prove.d.ts +22 -0
  62. package/dist/kernel/prove.js +156 -7
  63. package/dist/lean-kernel/emit.d.ts +9 -3
  64. package/dist/lean-kernel/emit.js +170 -29
  65. package/dist/lean-kernel/library.js +1 -1
  66. package/package.json +2 -2
@@ -61,6 +61,10 @@ impl Reader {
61
61
  }
62
62
  fn load_file(root: &Path, rel: &Path, module: &str, out: &mut Vec<File>) -> Result<(), String> {
63
63
  let src = std::fs::read_to_string(root.join(rel)).map_err(|e| format!("{}: {e}", rel.display()))?;
64
+ // (syn's parser and the lowering recurse on each level of nesting: past MAX_DEPTH brackets the source is refused, said
65
+ // so as core/extract-read.ts's statedRefusal reads it, before any recursion could pass the reader's stack)
66
+ let deep = src.chars().fold((0i64, 0i64), |(d, m), c| match c { '(' | '[' | '{' => (d + 1, m.max(d + 1)), ')' | ']' | '}' => (d - 1, m), _ => (d, m) }).1;
67
+ if deep > MAX_DEPTH { eprintln!("gdp: refused: {}: the source nests {deep} brackets deep (past {MAX_DEPTH})", rel.display()); std::process::exit(3) }
64
68
  let f = syn::parse_file(&src).map_err(|e| format!("{}: {e}", rel.display()))?;
65
69
  let dir: PathBuf = if rel.file_name().map(|n| n == "lib.rs" || n == "main.rs" || n == "mod.rs").unwrap_or(false) { rel.parent().unwrap().to_path_buf() } else { rel.with_extension("") };
66
70
  let mut items = vec![];
@@ -654,7 +658,13 @@ fn assigns(e: &Expr, n: &str) -> bool {
654
658
  false
655
659
  }
656
660
 
661
+ const MAX_DEPTH: i64 = 1000;
662
+ // The reader on a thread of 1 GiB of stack (reserved, not used): MAX_DEPTH levels of syn's recursion fit in it.
657
663
  fn main() {
664
+ let t = std::thread::Builder::new().stack_size(1 << 30).spawn(run).expect("a thread");
665
+ if t.join().is_err() { std::process::exit(101) }
666
+ }
667
+ fn run() {
658
668
  let req: Value = serde_json::from_str(&std::env::args().nth(1).expect("a request")).expect("JSON");
659
669
  let root = PathBuf::from(req["root"].as_str().unwrap());
660
670
  let files = match Reader::load(&root) { Ok(f) => f, Err(e) => { println!("{}", json!({"error": e})); return } };
@@ -233,7 +233,7 @@ def send(frm, to, data, value, deploy=False):
233
233
  r = rpc('eth_getTransactionReceipt', [h])
234
234
  if r is not None: break
235
235
  time.sleep(0.002 * (i + 1))
236
- if r is None: return None, 'no receipt'
236
+ if r is None: raise TimeoutError('no receipt for a transaction anvil was sent')
237
237
  if int(r['status'], 16) != 1: return None, 'reverted'
238
238
  return r, None
239
239
 
@@ -475,7 +475,7 @@ def main():
475
475
  if sys.argv[1] == '--replay':
476
476
  req = json.load(open(sys.argv[2]))
477
477
  try: res = replay(req)
478
- except Exception as e: res = {'error': f'{type(e).__name__}: {e}'[:500]}
478
+ except Exception as e: res = {'error': f'{type(e).__name__}: {e}'[:500], **({'transport': True} if isinstance(e, OSError) else {})}
479
479
  finally:
480
480
  if S.get('anvil'): S['anvil'].kill()
481
481
  print(json.dumps(res))
@@ -489,16 +489,19 @@ def main():
489
489
  if op == 'hello': res = hello(req)
490
490
  elif op == 'new':
491
491
  try: res = {'id': make(req['a'])}
492
+ except OSError: raise
492
493
  except Exception as e: res = {'err': f'{type(e).__name__}: {e}'[:300]}
493
494
  elif op == 'at':
494
495
  try: res = {'id': at(req['a'], req['state'])}
496
+ except OSError: raise
495
497
  except Exception as e: res = {'bad': f'{type(e).__name__}: {e}'[:300]}
496
498
  elif op == 'get': res = {'state': state_of(req['id'])}
497
499
  elif op == 'call': res = call(req)
498
500
  elif op == 'coverage': res = {'hit': []}
499
501
  else: res = {'error': f'no op {op}'}
500
502
  except Exception as e:
501
- res = {'error': f'{type(e).__name__}: {e}'[:500]}
503
+ # (anvil's transport failing, a request past its time: the check's failure, never the code's)
504
+ res = {'error': f'{type(e).__name__}: {e}'[:500], **({'transport': True} if isinstance(e, OSError) else {})}
502
505
  fout.write(json.dumps(res) + '\n'); fout.flush()
503
506
  finally:
504
507
  if S.get('anvil'): S['anvil'].kill()
@@ -16,9 +16,10 @@ export const env = globalThis.process?.env ?? {};
16
16
  export const v = (name) => ({ [name]: 1 });
17
17
  export const k = (value) => (value === 0 ? {} : { 1: value });
18
18
  // (Plain loops, no intermediate arrays: these run millions of times in a proof. Each keeps the keys in the order they
19
- // first appear, as a sum over the entries would.)
19
+ // first appear, as a sum over the entries would. Each builds on an object with no prototype, so a variable
20
+ // named __proto__ is a key like any other and one named constructor or toString reads 0 until set.)
20
21
  export function add(...xs) {
21
- const out = {};
22
+ const out = Object.create(null);
22
23
  for (const x of xs)
23
24
  for (const key in x)
24
25
  out[key] = (out[key] ?? 0) + x[key];
@@ -28,7 +29,7 @@ export function add(...xs) {
28
29
  return out;
29
30
  }
30
31
  export const scale = (x, f) => {
31
- const out = {};
32
+ const out = Object.create(null);
32
33
  for (const key in x) {
33
34
  const value = x[key] * f;
34
35
  if (value !== 0)
@@ -37,7 +38,7 @@ export const scale = (x, f) => {
37
38
  return out;
38
39
  };
39
40
  export const sub = (a, b) => {
40
- const out = {};
41
+ const out = Object.create(null);
41
42
  for (const key in a)
42
43
  out[key] = a[key];
43
44
  for (const key in b)
@@ -1,4 +1,5 @@
1
- import { type Machine } from './machine.js';
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type StepLaw } from '../kernel/kernel.js';
2
3
  import { type Kind, type Rule } from './dsl.js';
3
4
  export type Model = {
4
5
  name: string;
@@ -21,6 +22,7 @@ export declare function asRule(m: Machine, kinds?: Record<string, Kind<unknown>>
21
22
  export type Level = 'atomic' | 'read committed' | 'snapshot';
22
23
  export declare const ISOLATION: Record<Level, Model>;
23
24
  export declare function isolation(m: Machine, level: Level): Machine;
25
+ export declare const readsOf: WeakMap<Machine, string[]>;
24
26
  export type Delivery = 'exactly-once' | 'at-least-once';
25
27
  export declare const DELIVERY: Record<Delivery, Model>;
26
28
  export declare function delivery(m: Machine, pool: string, fields: string[], mode: Delivery, opts?: {
@@ -42,3 +44,62 @@ export declare function expires(cells: Record<string, number>, at: string, opts?
42
44
  key?: string;
43
45
  now?: string;
44
46
  }): Machine;
47
+ export type Env = {
48
+ isolation?: Level;
49
+ expiry?: boolean;
50
+ retries?: boolean;
51
+ flow?: string[];
52
+ apart?: boolean;
53
+ };
54
+ export declare function envOf(text: string | string[]): Env;
55
+ export declare const envText: (e: Env) => string;
56
+ export type InEnv = {
57
+ rule: Rule;
58
+ models: Model[];
59
+ reads: string[];
60
+ part: string;
61
+ act: string;
62
+ id?: string;
63
+ commit?: number;
64
+ level: Level;
65
+ flow?: string[];
66
+ method?: string;
67
+ methods?: number;
68
+ law: (l: Law) => Law;
69
+ step: (s: StepLaw) => StepLaw;
70
+ between: (name: string, a: string, b: string) => Law;
71
+ };
72
+ export type EnvOpts = {
73
+ stores?: string[][];
74
+ own?: string[];
75
+ method?: {
76
+ name: string;
77
+ values: string[];
78
+ };
79
+ failed?: string;
80
+ args?: {
81
+ method: string;
82
+ code: string;
83
+ rule: string;
84
+ }[];
85
+ oks?: {
86
+ method: string;
87
+ rule: string;
88
+ }[];
89
+ };
90
+ export declare function inEnv(r: Rule | Machine, env: Env, o?: EnvOpts): InEnv;
91
+ export declare function shrinkRun<T extends {
92
+ params: Record<string, number>;
93
+ trace: Record<string, unknown>[];
94
+ }>(r: Rule | Machine, w: Law | StepLaw, run: T): T;
95
+ export declare function contend(e: InEnv, w: Law | StepLaw, opts?: {
96
+ bases?: number;
97
+ depth?: number;
98
+ bound?: number;
99
+ seed?: number;
100
+ ms?: number;
101
+ calls?: number;
102
+ }): {
103
+ params: Record<string, number>;
104
+ trace: Record<string, unknown>[];
105
+ } | undefined;
@@ -19,6 +19,8 @@
19
19
  import { all, any, atMost, get, ite, n, not, plus, same, x } from "./machine.js";
20
20
  import { substC, substE } from "../kernel/kernel.js";
21
21
  import { Cond, Term, nat, oneOf, rule } from "./dsl.js";
22
+ import { interpret } from "./machine.js";
23
+ import { allowed, watch } from "./watch.js";
22
24
  const models = new WeakMap();
23
25
  const modelled = (m, ...ms) => { models.set(m, [...(models.get(m) ?? []), ...ms]); return m; };
24
26
  // m made from `from`: the models it assumes, and the scalars it keeps shared (`sharedOf`), carried over.
@@ -198,7 +200,7 @@ function writesWhen(v, cell) {
198
200
  return xs.length ? any(...xs) : false;
199
201
  }
200
202
  // m's one step (a request's) as a transaction of several: `pc$` 0 begins it (the request's inputs kept as in$<input>),
201
- // then the reads (read committed: each store read site at its own step, inner ones first, as rd$<i>; snapshot: all at
203
+ // then the reads (read committed: each store read site at its own step, inner ones first, as rd$<i>, a record's parts at one key one step; snapshot: all at
202
204
  // the begin), then the commit, which computes m's step from what was read and writes it (snapshot: unless a cell it
203
205
  // writes moved since the begin, aborted$ then 1), then done. m's scalars are the request's own (a result, a flag); its
204
206
  // maps are the stores. 'atomic' is m itself. Each step reads only its own process's state and the stores, so
@@ -291,7 +293,9 @@ export function isolation(m, level) {
291
293
  return c;
292
294
  return { ...c, a: sigma(c.a), b: sigma(c.b) };
293
295
  };
294
- const r = sites.length, snap = level === 'snapshot';
296
+ // (a record's parts at one key are one read: one GET returns the record)
297
+ const groupOf = (st) => `${st.map.replace(/\.[^.]*$/, '')}|${JSON.stringify(st.key)}`, groups = [...new Set(sites.map(groupOf))], gi = (j) => groups.indexOf(groupOf(sites[j]));
298
+ const r = groups.length, snap = level === 'snapshot';
295
299
  const commit = snap ? 1 : r + 1, done = commit + 1;
296
300
  const at = (k) => same(x('pc$'), n(k));
297
301
  const valid = snap ? all(...pointWrites.map(w => { const on = writesWhen(w.value, get(w.map, w.key)); const cell = get(w.map, sigma(w.key)), was = sigma(get(w.map, w.key)); return on === false ? same(n(0), n(0)) : any(...(on === true ? [] : [not(sigmaC(on))]), same(cell, was)); })) : undefined;
@@ -300,7 +304,7 @@ export function isolation(m, level) {
300
304
  const state = {
301
305
  'pc$': ite(at(0), n(snap || !r ? commit : 1), ite(at(commit), n(done), reads)),
302
306
  ...Object.fromEntries(m.inputs.map(i => [inp(i), ite(at(0), x(i), x(inp(i)))])),
303
- ...Object.fromEntries(sites.map((s, j) => [rd(j), ite(at(snap ? 0 : j + 1), snap ? s.e : get(s.map, sigma(s.key)), x(rd(j)))])),
307
+ ...Object.fromEntries(sites.map((s, j) => [rd(j), ite(at(snap ? 0 : gi(j) + 1), snap ? s.e : get(s.map, sigma(s.key)), x(rd(j)))])),
304
308
  ...mapValues(m.step.state, (e, s) => ite(commits, sigma(e), x(s))),
305
309
  ...(snap ? { 'aborted$': ite(at(commit), valid.op === 'and' && !valid.xs.length ? n(0) : ite(valid, n(0), n(1)), x('aborted$')) } : {}),
306
310
  };
@@ -318,8 +322,11 @@ export function isolation(m, level) {
318
322
  ...(m.assume ? { assume: any(not(at(0)), m.assume) } : {}),
319
323
  ...(m.pre ? { pre: m.pre } : {}),
320
324
  };
325
+ readsOf.set(out, groups.map(g => g.slice(0, g.indexOf('|'))));
321
326
  return from(out, m, ISOLATION[level]);
322
327
  }
328
+ // The stores a transaction reads, one per read step (read committed's; snapshot's are all at its begin).
329
+ export const readsOf = new WeakMap();
323
330
  export const DELIVERY = {
324
331
  'exactly-once': { name: 'exactly-once delivery', assumes: 'a message is taken by one handler step, once, and the take commits with the handler\'s writes (a transactional consume, an inbox row in the same transaction)',
325
332
  checked: 'a transactional consume (Kafka transactions, an inbox row in the handler\'s transaction)' },
@@ -433,3 +440,255 @@ export function expires(cells, at, opts = {}) {
433
440
  sharedOf.set(m, [now]);
434
441
  return modelled(m, TTL);
435
442
  }
443
+ const WORDS = [
444
+ [/^(atomic|serializable|lua|one step|locked|for update)$/, e => { e.isolation = 'atomic'; }],
445
+ [/^read committed$/, e => { e.isolation = 'read committed'; }],
446
+ [/^(snapshot|repeatable read)$/, e => { e.isolation = 'snapshot'; }],
447
+ [/^(keys expire|expiry|ttl|eviction|keys evicted)$/, e => { e.expiry = true; }],
448
+ [/^(retries|retried|at-least-once|at least once|redelivery|duplicates)$/, e => { e.retries = true; }],
449
+ [/^(an object per call|objects apart|a process per call|one object per call)$/, e => { e.apart = true; }],
450
+ ];
451
+ export function envOf(text) {
452
+ const e = {};
453
+ for (const w of (Array.isArray(text) ? text : [text]).flatMap(t => t.split(/\s*[,;]\s*|\s+and\s+/)).map(w => w.trim().replace(/\s+/g, ' ')).filter(Boolean)) {
454
+ // (a call's flow: its methods in order, `acquire then release`)
455
+ if (/^[\w.]+( then [\w.]+)+$/.test(w)) {
456
+ e.flow = w.split(' then ');
457
+ continue;
458
+ }
459
+ const f = WORDS.find(([re]) => re.test(w.toLowerCase()));
460
+ if (!f)
461
+ throw new Error(`env: ${JSON.stringify(w)} is not an environment gdp-wired models (atomic, read committed, snapshot, keys expire, retries, a flow: <method> then <method>)`);
462
+ f[1](e);
463
+ }
464
+ return e;
465
+ }
466
+ export const envText = (e) => [e.isolation, e.expiry && 'keys expire', e.retries && 'retries', e.apart && 'an object per call', e.flow?.join(' then ')].filter(Boolean).join(', ');
467
+ export function inEnv(r, env, o = {}) {
468
+ let m = machineOf(r);
469
+ const level = env.isolation ?? 'atomic', split = level !== 'atomic', flow = env.flow, lifted = split || !!flow, P = 'calls', act = 'act$', id = 'p$';
470
+ const stores = o.stores ?? [], own = [...(o.own ?? [])], hk = {};
471
+ if (flow) {
472
+ const k = flow.length;
473
+ const is = (f) => {
474
+ if (!o.method) {
475
+ if (k > 1)
476
+ throw new Error(`a flow of ${k} methods, and the rule has one`);
477
+ return same(n(0), n(0));
478
+ }
479
+ const i = o.method.values.indexOf(f);
480
+ if (i < 0)
481
+ throw new Error(`${f} is no method of ${m.name} (${o.method.values.join(', ')})`);
482
+ return same(x(o.method.name), n(i));
483
+ };
484
+ // (a method done: not failed, and where its result says whether it did it, that result true)
485
+ const failedOk = o.failed && m.step.state?.[o.failed] ? [same(m.step.state[o.failed], n(0))] : [];
486
+ const oks = (o.oks ?? []).filter(r => flow.includes(r.method) && m.step.state?.[r.rule]).map(r => any(not(is(r.method)), not(same(m.step.state[r.rule], n(0)))));
487
+ const done = failedOk.length || oks.length ? all(...failedOk, ...oks) : undefined, stage = x('stage$');
488
+ for (const [map, w] of Object.entries(m.step.maps ?? {}))
489
+ if ('key' in w)
490
+ hk[map] = `hk$${map}`;
491
+ m = { ...m, state: { ...m.state, 'stage$': n(0), 'held$': n(0), ...Object.fromEntries(Object.values(hk).map(h => [h, n(0)])) },
492
+ step: { ...m.step, state: { ...m.step.state,
493
+ 'stage$': done ? ite(done, plus(stage, n(1)), n(k)) : plus(stage, n(1)),
494
+ 'held$': ite(all(is(flow[0]), ...(done ? [done] : [])), n(1), ite(is(flow[k - 1]), n(0), x('held$'))),
495
+ ...Object.fromEntries(Object.entries(hk).map(([map, h]) => [h, ite(is(flow[0]), m.step.maps[map].key, x(h))])) } },
496
+ assume: all(...(m.assume ? [m.assume] : []), atMost(plus(stage, n(1)), n(k)), any(...flow.map((f, j) => all(same(stage, n(j)), is(f))))) };
497
+ // (an argument of one name, kept from the first method of the flow that takes it, its later methods given the same)
498
+ const named = new Map();
499
+ for (const a of o.args ?? [])
500
+ if (flow.includes(a.method) && m.inputs.includes(a.rule))
501
+ named.set(a.code, [...(named.get(a.code) ?? []), a]);
502
+ const keeps = [];
503
+ for (const [code, as] of named) {
504
+ const sorted = [...as].sort((a, b) => flow.indexOf(a.method) - flow.indexOf(b.method)), first = sorted[0], kept = `arg$${code}`;
505
+ if (sorted.length < 2 || kept in m.state)
506
+ continue;
507
+ keeps.push(kept);
508
+ m = { ...m, state: { ...m.state, [kept]: n(0) }, step: { ...m.step, state: { ...m.step.state, [kept]: ite(is(first.method), x(first.rule), x(kept)) } },
509
+ assume: all(m.assume, ...sorted.slice(1).map(a => any(not(is(a.method)), same(x(a.rule), x(kept))))) };
510
+ }
511
+ own.push('stage$', 'held$', ...Object.values(hk), ...keeps);
512
+ // (atomic: the calls holding each key, counted in the step that takes or gives it up, so the law is about every key)
513
+ const rk = Object.values(m.step.maps ?? {}).find((w) => 'key' in w)?.key;
514
+ if (!split && rk) {
515
+ const d = get('done$', rk), took = all(is(flow[0]), ...(done ? [done] : [])), gave = k > 1 ? all(is(flow[k - 1]), same(x('held$'), n(1))) : same(n(0), n(1));
516
+ m = { ...m, maps: { ...m.maps, 'done$': 0 }, step: { ...m.step, maps: { ...m.step.maps, 'done$': { key: rk, value: ite(took, plus(d, n(1)), ite(gave, { op: 'sub', a: d, b: n(1) }, d)) } } } };
517
+ }
518
+ }
519
+ // (an object per call: the fields its methods write are the call's own, those it only reads the object's as made)
520
+ if (env.apart)
521
+ own.push(...Object.keys(m.state).filter(s => !own.includes(s) && m.step.state?.[s] && JSON.stringify(m.step.state[s]) !== JSON.stringify(x(s))));
522
+ // (a field a call writes is read where the call commits, not where the code reads it: refused at a split level)
523
+ const fields = Object.keys(m.state).filter(s => !own.includes(s)), written = fields.filter(s => m.step.state?.[s] && JSON.stringify(m.step.state[s]) !== JSON.stringify(x(s)));
524
+ if (split && written.length)
525
+ throw new Error(`a call writes the object's ${written.join(', ')}, which it reads at its commit only here: not modelled at ${level}`);
526
+ const h = isolation(m, level);
527
+ const commit = split ? (level === 'snapshot' ? 1 : readsOf.get(h).length + 1) : undefined;
528
+ // (a flow's call begins its next method after a commit)
529
+ if (flow && split)
530
+ h.step.state['pc$'] = ite(same(x('pc$'), n(commit)), n(0), h.step.state['pc$']);
531
+ const parts = { [P]: lifted ? { rule: h, id, shared: fields } : h };
532
+ if (env.expiry)
533
+ stores.forEach((cells, i) => {
534
+ const e = expiry(Object.fromEntries(cells.map(c => [c, m.maps[c]])), 'key$'), mine = cells.filter(c => hk[c]);
535
+ // (a lease runs out: the calls holding by the key expired hold no longer; a call's done work, a flow of one method, stays done)
536
+ if (mine.length && flow.length > 1) {
537
+ e.maps = { ...e.maps, 'held$': 0, ...Object.fromEntries(mine.map(c => [hk[c], 0])) };
538
+ e.step.maps['held$'] = { each: 'q$', value: ite(any(...mine.map(c => same(get(hk[c], x('q$')), x('key$')))), n(0), get('held$', x('q$'))) };
539
+ if ('done$' in (m.maps ?? {})) {
540
+ e.maps['done$'] = 0;
541
+ e.step.maps['done$'] = { key: x('key$'), value: n(0) };
542
+ }
543
+ }
544
+ parts[`expiry${stores.length > 1 ? i : ''}`] = e;
545
+ });
546
+ const sys = system(`${machineOf(r).name} (${envText(env) || 'atomic'})`, parts, { act });
547
+ const ms = [...modelsOf(sys), ...(env.retries ? [RETRIES] : [])];
548
+ models.set(sys, ms);
549
+ const locals = Object.keys(m.state).filter(s => own.includes(s)), on = same(x(act), n(0));
550
+ const flags = () => Object.fromEntries(Object.keys(m.step.flags ?? {}).map(g => [g, { op: 'flag', name: `${P}$${g}` }]));
551
+ // (a call's own: its locals at its process `at`, before and after; its request as the call kept it)
552
+ const mine = (at, before) => {
553
+ const vs = [...locals.flatMap((s) => [[s, get(s, at)], [`${s}'`, get(`${s}'`, at)]]), ...(before && split ? m.inputs.map((i) => [i, get(`in$${i}`, at)]) : [])];
554
+ return { vars: lifted ? Object.fromEntries(vs) : {}, maps: {}, flags: flags() };
555
+ };
556
+ const law = (l) => {
557
+ if (!lifted || !locals.some(s => JSON.stringify(l.holds).includes(`"name":"${s}"`)))
558
+ return l;
559
+ const k = 'p$k', holds = substC(l.holds, mine(x(k), false));
560
+ return l.forall ? { ...l, holds, keys: [...(l.keys ?? []), k] } : { ...l, holds, forall: k };
561
+ };
562
+ const step = (s) => {
563
+ if ((s.steps ?? 1) !== 1)
564
+ throw new Error(`env: a law of ${s.steps} steps is not lifted to every call at once`);
565
+ const sub = mine(x(id), true), whens = s.when === undefined ? [] : Array.isArray(s.when) ? s.when : [s.when];
566
+ const then = substC(s.then, sub);
567
+ return { ...s, then: level === 'snapshot' ? any(same(get("aborted$'", x(id)), n(1)), then) : then,
568
+ when: all(on, ...(split ? [same(get('pc$', x(id)), n(commit))] : []), ...whens.map(w => substC(w, sub))) };
569
+ };
570
+ const between = (name, a, b) => {
571
+ if (!flow || flow[0] !== a || flow.at(-1) !== b)
572
+ throw new Error(`between ${a} and ${b}: the call's flow is ${flow ? flow.join(' then ') : 'not stated'} (env: ${a} then ${b})`);
573
+ if (!split && 'done$' in (m.maps ?? {}))
574
+ return { name, holds: atMost(get('done$', x('k$d')), n(1)), forall: 'k$d' };
575
+ const held = (p) => same(get('held$', x(p)), n(1));
576
+ // (per lock: two calls holding by different keys hold different things)
577
+ return { name, holds: any(not(held('p$a')), not(held('p$b')), same(x('p$a'), x('p$b')), ...Object.values(hk).map(k => not(same(get(k, x('p$a')), get(k, x('p$b')))))), forall: 'p$a', keys: ['p$b'] };
578
+ };
579
+ return { rule: sys, models: ms, reads: split && level !== 'snapshot' ? readsOf.get(h) : [], part: P, act, ...(lifted ? { id } : {}), ...(split ? { commit } : {}), level, ...(flow ? { flow } : {}), ...(o.method ? { method: o.method.name, methods: o.method.values.length } : {}), law, step, between };
580
+ }
581
+ // A run that breaks a law, shortened: steps dropped one at a time while the rest still breaks it (replayed on the
582
+ // interpreter, each request allowed where it is taken, the law read as the search reads it), cut at the first break.
583
+ export function shrinkRun(r, w, run) {
584
+ const m = machineOf(r), rt = interpret(m), params = run.params;
585
+ const bound = 2 + Math.max(0, ...[...Object.values(params), ...run.trace.flatMap(q => Object.values(q))].filter((v) => typeof v === 'number'));
586
+ // (the length of the prefix that breaks it, or 0)
587
+ const breaks = (trace) => {
588
+ try {
589
+ const on = watch(m, rt, w, params, bound);
590
+ let st = rt.init(params);
591
+ if (!on.start(st))
592
+ return 0;
593
+ for (const [i, q] of trace.entries()) {
594
+ if (!allowed(m, rt, params, st, q))
595
+ return 0;
596
+ const nx = rt.step(params, st, q);
597
+ if (!on.step(st, q, nx))
598
+ return i + 1;
599
+ st = nx;
600
+ }
601
+ }
602
+ catch {
603
+ return 0;
604
+ }
605
+ return 0;
606
+ };
607
+ let trace = run.trace, at = breaks(trace);
608
+ if (!at)
609
+ return run;
610
+ trace = trace.slice(0, at);
611
+ for (let changed = true; changed;) {
612
+ changed = false;
613
+ for (let i = 0; i < trace.length; i++) {
614
+ const t = [...trace.slice(0, i), ...trace.slice(i + 1)], b = breaks(t);
615
+ if (b) {
616
+ trace = t.slice(0, b);
617
+ changed = true;
618
+ i--;
619
+ }
620
+ }
621
+ }
622
+ return { ...run, trace };
623
+ }
624
+ // Contention: runs of a system where every call passes one request, so the calls contend for one key; only which
625
+ // part steps, which of three calls, its method and the expiring key vary, searched breadth first (states seen once) to
626
+ // a depth, for each of a few requests drawn. A run found breaks the law on the interpreter, as the search's do. (The
627
+ // search's own runs draw each request apart: three calls on one lock are rare among them.)
628
+ export function contend(e, w, opts = {}) {
629
+ const m = e.rule.machine, rt = interpret(m), bound = opts.bound ?? 2, until = performance.now() + (opts.ms ?? 3000), calls = opts.calls ?? 3;
630
+ let seed = opts.seed ?? 7;
631
+ const rand = (k) => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed % k; };
632
+ const free = new Set([e.act, ...(e.id ? [e.id] : []), ...(e.method ? [e.method] : []), 'key$']);
633
+ const acts = (e.rule.parts?.inputs.find(([i]) => i === e.act)?.[1].values ?? ['calls']).length;
634
+ const choices = [];
635
+ for (let a = 0; a < acts; a++) {
636
+ if (a > 0) {
637
+ for (let k = 0; k <= bound; k++)
638
+ choices.push({ [e.act]: a, 'key$': k });
639
+ continue;
640
+ }
641
+ for (let p = 1; p <= (e.id ? calls : 1); p++)
642
+ for (let mt = 0; mt < (e.method ? e.methods ?? 1 : 1); mt++)
643
+ choices.push({ [e.act]: 0, ...(e.id ? { [e.id]: p } : {}), ...(e.method ? { [e.method]: mt } : {}) });
644
+ }
645
+ const key = (st) => JSON.stringify([st.scalars, Object.entries(st.maps).map(([k, v]) => [k, [...v].filter(([, x]) => x !== 0).sort((a, b) => a[0] - b[0])])]);
646
+ for (let b = 0, tried = 0; b < (opts.bases ?? 12) && tried < 400 && performance.now() < until; tried++) {
647
+ const params = Object.fromEntries(m.params.map(p => [p, rand(bound + 1)]));
648
+ // (the request's values from 0 and 1: two arguments a flow keeps equal, two strings of one length, agree often)
649
+ const base = Object.fromEntries(m.inputs.filter(i => !free.has(i)).map(i => [i, rand(2)]));
650
+ let st0;
651
+ try {
652
+ st0 = rt.init(params);
653
+ }
654
+ catch {
655
+ continue;
656
+ }
657
+ const req = (c) => ({ ...base, ...Object.fromEntries(m.inputs.filter(i => !(i in base)).map(i => [i, 0])), ...c });
658
+ if (!choices.some(c => { try {
659
+ return allowed(m, rt, params, st0, req(c));
660
+ }
661
+ catch {
662
+ return false;
663
+ } }))
664
+ continue;
665
+ b++;
666
+ const seen = new Set([key(st0)]);
667
+ let frontier = [{ st: st0, trace: [] }];
668
+ for (let d = 0; d < (opts.depth ?? 7) && frontier.length && performance.now() < until; d++) {
669
+ const next = [];
670
+ for (const { st, trace } of frontier)
671
+ for (const c of choices) {
672
+ const q = req(c);
673
+ let nx;
674
+ try {
675
+ if (!allowed(m, rt, params, st, q))
676
+ continue;
677
+ nx = rt.step(params, st, q);
678
+ }
679
+ catch {
680
+ continue;
681
+ }
682
+ if (!watch(m, rt, w, params, bound + 2).step(st, q, nx))
683
+ return { params, trace: [...trace, q] };
684
+ const k = key(nx);
685
+ if (seen.has(k) || seen.size > 200_000)
686
+ continue;
687
+ seen.add(k);
688
+ next.push({ st: nx, trace: [...trace, q] });
689
+ }
690
+ frontier = next;
691
+ }
692
+ }
693
+ return undefined;
694
+ }
@@ -225,6 +225,7 @@ function rewriter(bridges, copies, unfold, ren = new Map()) {
225
225
  const valueOf = (s, x) => (s === 'nat' ? new Nat(x) : s === 'bool' ? new Bool(x.op === 'bool' ? x.c : { op: 'holds', x }) : s === 'int' ? new Integer(x) : new Val(s, x));
226
226
  // The copies made, by function and bridges (a law proven again reads the same copies).
227
227
  const made = new WeakMap();
228
+ const refused = new Set();
228
229
  const freshName = (base) => { let n = base; for (let i = 2; fnNamed(n); i++)
229
230
  n = `${base}${i}`; return n; };
230
231
  // The law through the bridges `bridged`: the copies (made once), the law said with them, the bridge and copy laws, and
@@ -246,6 +247,8 @@ function build(l, bridged, unfold) {
246
247
  const key = `${unfold}|${[...bridged].map(([f, op]) => `${f}:${op.name}`).sort().join(',')}`, copies = new Map();
247
248
  for (const n of reach) {
248
249
  const f = fnOf(n), had = made.get(f)?.get(key);
250
+ if (had && refused.has(had))
251
+ return undefined;
249
252
  if (had && fnNamed(had))
250
253
  copies.set(n, had);
251
254
  }
@@ -274,6 +277,20 @@ function build(l, bridged, unfold) {
274
277
  }
275
278
  define(name, Object.fromEntries(f.params.map(q => [q.name, q.sort])), f.ret, () => valueOf(f.ret, body));
276
279
  }
280
+ // (a copy whose recursion isn't taken where the original's is, a well-founded call left nested in the match of an
281
+ // unfolded definition, bmerge's in stitch's: no copies of these)
282
+ for (const n of reach) {
283
+ const name = copies.get(n);
284
+ try {
285
+ void fnOf(name).ring;
286
+ }
287
+ catch (e) {
288
+ if (!/not structural recursion/.test(e.message))
289
+ throw e;
290
+ refused.add(name);
291
+ return undefined;
292
+ }
293
+ }
277
294
  let holds;
278
295
  try {
279
296
  holds = rewriter(bridged, copies, unfold).ry(l.holds);
@@ -102,7 +102,7 @@ export function watch(m, run, w, params, bound) {
102
102
  if (!isStepLaw(w)) {
103
103
  // A law with "there exists" (core/exists.ts): broken only where no value can be a witness, as far as that is decided
104
104
  // (one natural or integer read linearly); undecided, it is kept.
105
- const at = (env, st) => (w.some?.length ? someHolds(w.holds, w.some, { ...env }, st, m)?.holds ?? true : evalC(w.holds, env, st, m));
105
+ const at = (env, st) => (w.some?.length ? someHolds(w.holds, w.some, { ...env }, st, m, true)?.holds ?? true : evalC(w.holds, env, st, m));
106
106
  const holds = (st) => atKeys(per(bound, st, () => keysOf(bound, st)), { ...params }, env => at(env, st));
107
107
  return { start: holds, step: (_before, _input, after) => holds(after) };
108
108
  }
@@ -5,7 +5,7 @@
5
5
  // loops (loopObligations), folds (foldObligations), progress (progressObligations), liveness (livenessParts, then
6
6
  // checkStepLaws). Around them, untrusted: reading the document (format.ts) and the guard that it was read faithfully
7
7
  // (written again, it must be the document read).
8
- import { check, checkKInduction, checkLaws, checkQMachine, checkQTree, checkRecur, checkStepLaws, foldObligations, kInductionStart, kInductionSteps, livenessParts, loopObligations, obligations, progressObligations, qObligations, recurGoal, stepLawObligations } from "../kernel/kernel.js";
8
+ import { check, checkKInduction, checkLaws, checkQMachine, checkQTree, checkRecur, checkStepLaws, foldObligations, kInductionStart, kInductionSteps, livenessParts, loopObligations, obligations, own, progressObligations, qObligations, recurGoal, stepLawObligations } from "../kernel/kernel.js";
9
9
  import { descentGoal, mainGoal, premiseGoal, refuseCyclic } from "../kernel/cyclic.js";
10
10
  import { FormatError, fromInterchange, resolved, sameJson, toInterchange } from "./format.js";
11
11
  const attempt = (f) => { try {
@@ -14,11 +14,11 @@ const attempt = (f) => { try {
14
14
  catch (e) {
15
15
  return { ok: false, why: e instanceof Error ? e.message : String(e) };
16
16
  } };
17
- const treeOk = (g, trees) => trees[g.name] !== undefined && check(g, trees[g.name]);
17
+ const treeOk = (g, trees) => { const t = own(trees, g.name); return t !== undefined && check(g, t); };
18
18
  // Each goal's own answer, for a refusal's why (never the verdict: that is the kernel's entry point's).
19
19
  const failing = (goals, trees) => {
20
20
  try {
21
- const bad = goals().filter(g => !treeOk(g, trees)).map(g => (trees[g.name] ? `${g.name}: its tree doesn't refute it` : `${g.name}: no tree`));
21
+ const bad = goals().filter(g => !treeOk(g, trees)).map(g => (own(trees, g.name) ? `${g.name}: its tree doesn't refute it` : `${g.name}: no tree`));
22
22
  return bad.length ? bad.slice(0, 3).join('; ') + (bad.length > 3 ? `; and ${bad.length - 3} more` : '') : undefined;
23
23
  }
24
24
  catch (e) {
@@ -38,13 +38,13 @@ export function checkCertificate(c) {
38
38
  case 'qgoals': return c.goals.map(g => { const r = attempt(() => checkQTree(g.goal, g.tree)); return { name: g.goal.name, accepted: r.ok, ...(r.ok ? {} : { why: r.why ?? 'the tree doesn\'t refute the goal' }) }; });
39
39
  // A set of laws is proven together (each step assumes them all), so each is accepted exactly when the set is.
40
40
  case 'laws': return all(c.laws.map(l => l.name), attempt(() => checkLaws(c.machine, c.laws, c.proof)), () => failing(() => obligations(c.machine, c.laws, c.proof.instances), c.proof.trees));
41
- case 'stepLaws': return all([...c.laws.map(l => l.name), ...c.stepLaws.map(s => s.name)], attempt(() => checkStepLaws(c.machine, c.laws, c.stepLaws, c.proof)), () => failing(() => [...obligations(c.machine, c.laws, c.proof.laws.instances), ...c.stepLaws.flatMap(s => stepLawObligations(c.machine, c.laws, c.proof.perStep?.[s.name] ?? c.proof.instances, s))], { ...c.proof.laws.trees, ...c.proof.trees })
41
+ case 'stepLaws': return all([...c.laws.map(l => l.name), ...c.stepLaws.map(s => s.name)], attempt(() => checkStepLaws(c.machine, c.laws, c.stepLaws, c.proof)), () => failing(() => [...obligations(c.machine, c.laws, c.proof.laws.instances), ...c.stepLaws.flatMap(s => stepLawObligations(c.machine, c.laws, own(c.proof.perStep ?? {}, s.name) ?? c.proof.instances, s))], { ...c.proof.laws.trees, ...c.proof.trees })
42
42
  ?? 'a later step\'s names read before it (the zone condition)');
43
- case 'kInduction': return all([c.kInduction.law.name], attempt(() => checkKInduction(c.machine, c.laws, c.kInduction, c.proof)), () => failing(() => [kInductionStart(c.machine, c.kInduction, c.proof.perStep?.[`${c.kInduction.law.name} @start`] ?? c.proof.instances), ...kInductionSteps(c.machine, c.kInduction).flatMap(s => stepLawObligations(c.machine, c.laws, c.proof.perStep?.[s.name] ?? c.proof.instances, s))], c.proof.trees)
43
+ case 'kInduction': return all([c.kInduction.law.name], attempt(() => checkKInduction(c.machine, c.laws, c.kInduction, c.proof)), () => failing(() => [kInductionStart(c.machine, c.kInduction, own(c.proof.perStep ?? {}, `${c.kInduction.law.name} @start`) ?? c.proof.instances), ...kInductionSteps(c.machine, c.kInduction).flatMap(s => stepLawObligations(c.machine, c.laws, own(c.proof.perStep ?? {}, s.name) ?? c.proof.instances, s))], c.proof.trees)
44
44
  ?? failing(() => obligations(c.machine, c.laws, c.proof.laws.instances), c.proof.laws.trees));
45
45
  case 'liveness': {
46
46
  const r = attempt(() => { const { stay, cover, helps } = livenessParts(c.machine, c.liveness); return checkStepLaws(c.machine, c.laws, [stay, cover, ...helps], c.proof); });
47
- return all([c.liveness.name], r, () => failing(() => { const { stay, cover, helps } = livenessParts(c.machine, c.liveness); return [stay, cover, ...helps].flatMap(s => stepLawObligations(c.machine, c.laws, c.proof.perStep?.[s.name] ?? c.proof.instances, s)); }, c.proof.trees));
47
+ return all([c.liveness.name], r, () => failing(() => { const { stay, cover, helps } = livenessParts(c.machine, c.liveness); return [stay, cover, ...helps].flatMap(s => stepLawObligations(c.machine, c.laws, own(c.proof.perStep ?? {}, s.name) ?? c.proof.instances, s)); }, c.proof.trees));
48
48
  }
49
49
  // Progress assumes the laws: proven here by their own trees where the document has them, else not accepted.
50
50
  case 'progress': {
@@ -86,16 +86,16 @@ export function checkDocument(doc) {
86
86
  // check, as a `goals` (or `qgoals`) certificate a second checker reads (interchange/py/check.py checks trees alone).
87
87
  // (The checks past trees stay the kernel's: a stem evaluated, a cyclic proof's ranks of one length, the step laws' zone.)
88
88
  export function goalsOf(c) {
89
- const pick = (goals, trees) => goals.flatMap(goal => (trees[goal.name] ? [{ goal, tree: trees[goal.name] }] : []));
89
+ const pick = (goals, trees) => goals.flatMap(goal => { const tree = own(trees, goal.name); return tree ? [{ goal, tree }] : []; });
90
90
  const cyclic = (p) => p.nodes.flatMap(n => [{ goal: mainGoal(p.facts, p.nodes, n), tree: n.main }, ...n.uses.flatMap(u => {
91
91
  const m = p.nodes[u.node];
92
92
  return m ? [...m.hyps.flatMap((h, i) => (u.premises[i] ? [{ goal: premiseGoal(p.facts, n, u, h, i), tree: u.premises[i] }] : [])), ...(m.rank.length === n.rank.length ? [{ goal: descentGoal(p.facts, n, u, m), tree: u.descent }] : [])] : [];
93
93
  })]);
94
- const steps = (m, sls) => [...pick(obligations(m.machine, m.laws, m.proof.laws.instances), m.proof.laws.trees), ...pick(sls.flatMap(s => stepLawObligations(m.machine, m.laws, m.proof.perStep?.[s.name] ?? m.proof.instances, s)), m.proof.trees)];
94
+ const steps = (m, sls) => [...pick(obligations(m.machine, m.laws, m.proof.laws.instances), m.proof.laws.trees), ...pick(sls.flatMap(s => stepLawObligations(m.machine, m.laws, own(m.proof.perStep ?? {}, s.name) ?? m.proof.instances, s)), m.proof.trees)];
95
95
  switch (c.kind) {
96
96
  case 'goals':
97
97
  case 'qgoals': return c;
98
- case 'qmachine': return { kind: 'qgoals', goals: c.laws.flatMap(l => { const g = qObligations(c.machine, c.laws, l), t = c.trees[l.name]; return t ? [{ goal: g.start, tree: t.start }, { goal: g.step, tree: t.step }] : []; }) };
98
+ case 'qmachine': return { kind: 'qgoals', goals: c.laws.flatMap(l => { const g = qObligations(c.machine, c.laws, l), t = own(c.trees, l.name); return t ? [{ goal: g.start, tree: t.start }, { goal: g.step, tree: t.step }] : []; }) };
99
99
  case 'laws': return { kind: 'goals', goals: pick(obligations(c.machine, c.laws, c.proof.instances), c.proof.trees) };
100
100
  case 'stepLaws': return { kind: 'goals', goals: steps(c, c.stepLaws) };
101
101
  case 'liveness': {
@@ -103,7 +103,7 @@ export function goalsOf(c) {
103
103
  return { kind: 'goals', goals: steps(c, [stay, cover, ...helps]) };
104
104
  }
105
105
  case 'kInduction': {
106
- const start = kInductionStart(c.machine, c.kInduction, c.proof.perStep?.[`${c.kInduction.law.name} @start`] ?? c.proof.instances);
106
+ const start = kInductionStart(c.machine, c.kInduction, own(c.proof.perStep ?? {}, `${c.kInduction.law.name} @start`) ?? c.proof.instances);
107
107
  return { kind: 'goals', goals: [...pick([start], c.proof.trees), ...steps(c, kInductionSteps(c.machine, c.kInduction))] };
108
108
  }
109
109
  case 'progress': return { kind: 'goals', goals: [...(c.lawsProof ? pick(obligations(c.machine, c.laws, c.lawsProof.instances), c.lawsProof.trees) : []), ...pick(progressObligations(c.machine, c.laws, c.instances, c.progress), c.trees)] };
@@ -23,6 +23,10 @@ export type Measure = {
23
23
  comps: {
24
24
  coef: number[];
25
25
  c: number;
26
+ fold?: {
27
+ fn: string;
28
+ of: number;
29
+ };
26
30
  }[];
27
31
  };
28
32
  export type Obligation = {