gdp-wired 0.42.0 → 0.43.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,426 @@
1
+ // Systems (research/distributed/DESIGN.md): handlers, their stores and message pools, and the environment, as one rule,
2
+ // so every prover takes a distributed system as it takes one process. Each combinator returns a plain Machine (or, from
3
+ // `system`, a Rule over it), and nothing here is trusted: a proof is about the rule built, and what it assumes of the
4
+ // network and the stores is the environment models named in it (`models`), each stating what it assumes.
5
+ // system(name, parts) one part steps per request (`act` picks which); maps of one name are one store, shared;
6
+ // a part with an `id` is every process of it at once: each scalar a map keyed by the
7
+ // process (a request's own locals), the request's process its input `id`
8
+ // isolation(m, level) a handler's one atomic step run as a transaction at an isolation level
9
+ // delivery(m, pool, ...) a handler's request taken from a message pool, exactly once or at least once
10
+ // client(pool, fields) the environment's sends: any message, at a fresh id
11
+ // expiry(cells) a store's key vanishes at any step: a TTL lapsed, an eviction
12
+ // time() the true time `now`, rising by any amount at a step of the environment's
13
+ // clocked(m, at, skew) m reads its node's clock as the input `at`, within `skew` of the true time
14
+ // expires(cells, at) a store's key vanishes once the time has passed its expiry `at`, never before
15
+ // asRule(m) a Machine as a Rule, for the provers' entries (proveRule, proveSteps)
16
+ // The handlers are any rules: extracted by the readers (a step of one process, its maps the stores it reads and writes)
17
+ // or written; a handler that awaits other services between its reads and writes is several steps (a `pc` scalar), the
18
+ // form `isolation` gives an atomic one.
19
+ import { all, any, atMost, get, ite, n, not, plus, same, x } from "./machine.js";
20
+ import { substC, substE } from "../kernel/kernel.js";
21
+ import { Cond, Term, nat, oneOf, rule } from "./dsl.js";
22
+ const models = new WeakMap();
23
+ const modelled = (m, ...ms) => { models.set(m, [...(models.get(m) ?? []), ...ms]); return m; };
24
+ // m made from `from`: the models it assumes, and the scalars it keeps shared (`sharedOf`), carried over.
25
+ const from = (m, src, ...ms) => { const sh = sharedOf.get(machineOf(src)); if (sh)
26
+ sharedOf.set(m, sh); return modelled(m, ...(models.get(src) ?? []), ...ms); };
27
+ // m, stated to assume these models (a copy: what a written rule's inputs or steps assume of its environment).
28
+ export const assuming = (m, ...ms) => from({ ...machineOf(m) }, m, ...ms);
29
+ // The models a machine, or a system's rule, assumes.
30
+ export const modelsOf = (m) => models.get(m) ?? [];
31
+ const mapValues = (o, f) => Object.fromEntries(Object.entries(o ?? {}).map(([k, a]) => [k, f(a, k)]));
32
+ // m's terms with scalars replaced (`vars`) and flags renamed.
33
+ function mapper(m, vars, flag) {
34
+ const s = { vars, maps: {}, flags: mapValues(m.step.flags, (_c, f) => ({ op: 'flag', name: flag(f) })) };
35
+ const E = (e) => substE(e, s), C = (c) => substC(c, s);
36
+ return { E, C, W: (w) => ('each' in w ? { each: w.each, value: E(w.value) } : { key: E(w.key), value: E(w.value) }) };
37
+ }
38
+ const machineOf = (r) => ('machine' in r ? r.machine : r);
39
+ // The scalars a machine reads that are the system's, not a process's: the true time, which lift keeps shared.
40
+ const sharedOf = new WeakMap();
41
+ const plain = (m, what) => { if (m.history || m.sums || m.inputMaps?.length)
42
+ throw new Error(`${what}: ${m.name} has a history, sums or carried maps (not taken here)`); };
43
+ // --- one process, every process ------------------------------------------------------------------------------------
44
+ // Every process of m at once: each scalar but `shared` a map keyed by the process `id` (an input), read and written at
45
+ // the request's process; m's maps stay as they are, shared. A process starts where m starts (a constant: a map's cells
46
+ // all start at one value).
47
+ export function lift(m, id, given = []) {
48
+ plain(m, 'lift');
49
+ const shared = [...given, ...(sharedOf.get(m) ?? [])];
50
+ const locals = Object.keys(m.state).filter(s => !shared.includes(s));
51
+ for (const s of locals) {
52
+ if (m.state[s].op !== 'const')
53
+ throw new Error(`lift: ${m.name}'s ${s} starts at a term of the params; a process starts at constants`);
54
+ if (s in (m.maps ?? {}))
55
+ throw new Error(`lift: ${m.name}'s ${s} is a scalar and a map`);
56
+ }
57
+ // (an input named `id` is the process's own id, which m may read: a token, an owner)
58
+ if ([...m.params, ...Object.keys(m.state), ...Object.keys(m.maps ?? {})].includes(id))
59
+ throw new Error(`lift: ${id} is already a name of ${m.name}`);
60
+ const { E, C, W } = mapper(m, Object.fromEntries(locals.map(s => [s, get(s, x(id))])), f => f);
61
+ const kept = (s) => !locals.includes(s);
62
+ return {
63
+ ...m, inputs: [...new Set([...m.inputs, id])],
64
+ state: Object.fromEntries(Object.entries(m.state).filter(([s]) => kept(s))),
65
+ maps: { ...m.maps, ...Object.fromEntries(locals.map(s => [s, m.state[s].value])) },
66
+ step: {
67
+ flags: mapValues(m.step.flags, C),
68
+ state: Object.fromEntries(Object.entries(m.step.state ?? {}).filter(([s]) => kept(s)).map(([s, e]) => [s, E(e)])),
69
+ maps: { ...mapValues(m.step.maps, W), ...Object.fromEntries(locals.filter(s => m.step.state?.[s]).map(s => [s, { key: x(id), value: E(m.step.state[s]) }])) },
70
+ },
71
+ ...(m.assume ? { assume: C(m.assume) } : {}),
72
+ };
73
+ }
74
+ // The parts interleaved: at each request the part `act` names steps, the others keep their state. Params, inputs and
75
+ // stores (maps, scalars of parts without an id) are shared by name; each part's flags are its own (named part$flag),
76
+ // and its assumption is about its own steps. `kinds`: the inputs' kinds (by default naturals), for the runs' draws.
77
+ export function system(name, parts, opts = {}) {
78
+ const act = opts.act ?? 'act', names = Object.keys(parts);
79
+ if (!names.length)
80
+ throw new Error('system: no parts');
81
+ const ps = names.map((p, i) => {
82
+ const part = parts[p], spec = 'rule' in part && !('step' in part) && !('machine' in part) ? part : { rule: part };
83
+ const given = machineOf(spec.rule);
84
+ plain(given, 'system');
85
+ const m = spec.id ? lift(given, spec.id, spec.shared) : given;
86
+ return { p, m, assumed: models.get(spec.rule) ?? models.get(given) ?? [], on: same(x(act), n(i)), ...mapper(m, {}, f => `${p}$${f}`) };
87
+ });
88
+ const scalars = {}, maps = {};
89
+ for (const { m } of ps) {
90
+ for (const [s, e] of Object.entries(m.state)) {
91
+ if (s in scalars && JSON.stringify(scalars[s]) !== JSON.stringify(e))
92
+ throw new Error(`system: ${s} starts differently in two parts`);
93
+ scalars[s] = e;
94
+ }
95
+ for (const [mp, v] of Object.entries(m.maps ?? {})) {
96
+ if (mp in maps && maps[mp] !== v)
97
+ throw new Error(`system: store ${mp} starts at ${maps[mp]} and ${v}`);
98
+ maps[mp] = v;
99
+ }
100
+ }
101
+ const params = [...new Set(ps.flatMap(q => q.m.params))], inputs = [...new Set([act, ...ps.flatMap(q => q.m.inputs)])];
102
+ const clash = inputs.find(i => i in scalars || i in maps || params.includes(i));
103
+ if (clash)
104
+ throw new Error(`system: ${clash} is an input and a store or a param`);
105
+ // A scalar: the active part's update, else kept. A map: the active part's write; at every key where some part writes at
106
+ // every key, else at the active part's key (the last writer's, its value kept, where no writer is active).
107
+ const state = {}, writes = {};
108
+ for (const s of Object.keys(scalars)) {
109
+ const by = ps.filter(q => q.m.step.state?.[s]);
110
+ if (by.length)
111
+ state[s] = by.reduceRight((acc, q) => ite(q.on, q.E(q.m.step.state[s]), acc), x(s));
112
+ }
113
+ for (const mp of Object.keys(maps)) {
114
+ const by = ps.filter(q => q.m.step.maps?.[mp]).map(q => ({ q, w: q.W(q.m.step.maps[mp]) }));
115
+ if (!by.length)
116
+ continue;
117
+ if (by.some(b => 'each' in b.w)) {
118
+ const k = `k$${mp}`;
119
+ const at = (w) => ('each' in w ? substE(w.value, { vars: { [w.each]: x(k) }, maps: {}, flags: {} }) : ite(same(x(k), w.key), w.value, get(mp, x(k))));
120
+ writes[mp] = { each: k, value: by.reduceRight((acc, { q, w }) => ite(q.on, at(w), acc), get(mp, x(k))) };
121
+ }
122
+ else {
123
+ const point = by;
124
+ const key = point.slice(0, -1).reduceRight((acc, { q, w }) => ite(q.on, w.key, acc), point.at(-1).w.key);
125
+ writes[mp] = { key, value: point.reduceRight((acc, { q, w }) => ite(q.on, w.value, acc), get(mp, key)) };
126
+ }
127
+ }
128
+ const flags = Object.assign({}, ...ps.map(q => Object.fromEntries(Object.entries(q.m.step.flags ?? {}).map(([f, c]) => [`${q.p}$${f}`, q.C(c)]))));
129
+ const assume = ps.filter(q => q.m.assume).map(q => any(not(q.on), q.C(q.m.assume)));
130
+ const pres = ps.map(q => q.m.pre).filter((c) => !!c);
131
+ const m = {
132
+ name, params, inputs, state: scalars, maps,
133
+ step: { flags, state, maps: writes },
134
+ ...(assume.length ? { assume: all(...assume) } : {}),
135
+ ...(pres.length ? { pre: all(...pres) } : {}),
136
+ };
137
+ const ms = [...new Map(ps.flatMap(q => q.assumed).map(md => [md.name, md])).values()];
138
+ const r = asRule(m, { [act]: oneOf(...names), ...opts.kinds });
139
+ models.set(r, ms);
140
+ return r;
141
+ }
142
+ // --- a Machine as a Rule --------------------------------------------------------------------------------------------
143
+ // The same rule through the builders (its terms as they are), so proveRule, proveSteps and the runs take it. Every
144
+ // name is a natural unless `kinds` says otherwise (a choice, for the runs' draws); division by constants is kept.
145
+ export function asRule(m, kinds = {}) {
146
+ plain(m, 'asRule');
147
+ const ks = Object.keys(m.fns ?? {}).map(f => { const d = /^(?:div|mod)\$(\d+)$/.exec(f); if (!d)
148
+ throw new Error(`asRule: ${m.name} reads ${f}, a function other than division by a constant`); return Number(d[1]); });
149
+ const kindOf = (v) => kinds[v] ?? nat;
150
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
151
+ let r = rule(m.name);
152
+ if (m.params.length)
153
+ r = r.params(Object.fromEntries(m.params.map(p => [p, kindOf(p)])));
154
+ if (m.inputs.length)
155
+ r = r.inputs(Object.fromEntries(m.inputs.map(i => [i, kindOf(i)])));
156
+ r = r.state(mapValues(m.state, e => (e.op === 'const' ? e.value : () => new Term(e))));
157
+ if (m.maps && Object.keys(m.maps).length)
158
+ r = r.maps(m.maps);
159
+ if (m.step.flags && Object.keys(m.step.flags).length)
160
+ r = r.flags(() => mapValues(m.step.flags, c => new Cond(c)));
161
+ r = r.step(() => ({ ...mapValues(m.step.state, e => new Term(e)), ...mapValues(m.step.maps, (w, map) => ({ map, ...w })) }));
162
+ if (m.pre)
163
+ r = r.pre(() => new Cond(m.pre));
164
+ if (m.assume)
165
+ r = r.assume(() => new Cond(m.assume));
166
+ if (ks.length)
167
+ r = r.dividesBy(...ks);
168
+ return r;
169
+ }
170
+ export const ISOLATION = {
171
+ 'atomic': { name: 'atomic', assumes: 'the handler runs as one step: no other step sees it half done',
172
+ checked: 'PostgreSQL SERIALIZABLE (13.2.3), SELECT ... FOR UPDATE, UPDATE ... SET x = x + k; a Redis Lua script; asyncio code whose awaits never suspend' },
173
+ 'read committed': { name: 'read committed', assumes: 'each read of a store sees the latest committed value at its own step; the writes become visible together at commit; nothing is re-read at commit',
174
+ checked: 'PostgreSQL READ COMMITTED (13.2.1): the lost update, envcheck.py' },
175
+ 'snapshot': { name: 'snapshot', assumes: 'every read sees the store as it was at the transaction start; a commit is refused (aborted$) when a cell it writes changed since then (first committer wins); writes to different cells never conflict (write skew allowed)',
176
+ checked: 'PostgreSQL REPEATABLE READ (13.2.2): the refused commit and the write skew, envcheck.py' },
177
+ };
178
+ // A request's write of a cell, as it is and where it writes at all: an `if` whose branch is the cell itself is no write.
179
+ function writesWhen(v, cell) {
180
+ if (JSON.stringify(v) === JSON.stringify(cell))
181
+ return false;
182
+ if (v.op !== 'if')
183
+ return true;
184
+ const a = writesWhen(v.then, cell), b = writesWhen(v.else, cell);
185
+ if (a === true && b === true)
186
+ return true;
187
+ const side = (w, c) => (w === false ? false : w === true ? c : all(c, w));
188
+ const xs = [side(a, v.c), side(b, not(v.c))].filter((c) => c !== false);
189
+ return xs.length ? any(...xs) : false;
190
+ }
191
+ // m's one step (a request's) as a transaction of several: `pc$` 0 begins it (the request's inputs kept as in$<input>),
192
+ // then the reads (read committed: each store read site at its own step, inner ones first, as rd$<i>; snapshot: all at
193
+ // the begin), then the commit, which computes m's step from what was read and writes it (snapshot: unless a cell it
194
+ // writes moved since the begin, aborted$ then 1), then done. m's scalars are the request's own (a result, a flag); its
195
+ // maps are the stores. 'atomic' is m itself. Each step reads only its own process's state and the stores, so
196
+ // `system(..., {h: {rule: isolation(m, level), id: 't'}})` runs any number of transactions at once.
197
+ export function isolation(m, level) {
198
+ plain(m, 'isolation');
199
+ if (level === 'atomic')
200
+ return from({ ...m }, m, ISOLATION.atomic);
201
+ const stores = new Set(Object.keys(m.maps ?? {}));
202
+ const sites = [], seen = new Map();
203
+ const visitE = (e) => {
204
+ if (e.op === 'get') {
205
+ visitE(e.key);
206
+ if (stores.has(e.map)) {
207
+ const j = JSON.stringify(e);
208
+ if (!seen.has(j)) {
209
+ seen.set(j, sites.length);
210
+ sites.push({ map: e.map, key: e.key, e });
211
+ }
212
+ }
213
+ return;
214
+ }
215
+ if (e.op === 'if') {
216
+ visitC(e.c);
217
+ visitE(e.then);
218
+ visitE(e.else);
219
+ return;
220
+ }
221
+ if ('a' in e)
222
+ visitE(e.a);
223
+ if ('b' in e)
224
+ visitE(e.b);
225
+ };
226
+ const visitC = (c) => {
227
+ if (c.op === 'and' || c.op === 'or')
228
+ c.xs.forEach(visitC);
229
+ else if (c.op === 'not')
230
+ visitC(c.x);
231
+ else if (c.op === 'all')
232
+ throw new Error(`isolation: ${m.name} reads every key at once (a quantified flag): not split here`);
233
+ else if (c.op !== 'flag') {
234
+ visitE(c.a);
235
+ visitE(c.b);
236
+ }
237
+ };
238
+ const pointWrites = Object.entries(m.step.maps ?? {}).map(([map, w]) => {
239
+ if ('each' in w)
240
+ throw new Error(`isolation: ${m.name} writes ${map} at every key: not split here`);
241
+ return { map, ...w };
242
+ });
243
+ Object.values(m.step.flags ?? {}).forEach(visitC);
244
+ Object.values(m.step.state ?? {}).forEach(visitE);
245
+ for (const w of pointWrites) {
246
+ visitE(w.key);
247
+ visitE(w.value);
248
+ if (level === 'snapshot')
249
+ visitE(get(w.map, w.key));
250
+ }
251
+ if (m.assume)
252
+ visitC(m.assume);
253
+ if (level === 'snapshot' && sites.some(s => JSON.stringify(s.e).includes('"op":"flag"')))
254
+ throw new Error(`isolation: ${m.name} reads a store at a key a flag decides: not split at a snapshot here`);
255
+ const taken = new Set([...m.params, ...m.inputs, ...Object.keys(m.state), ...stores]);
256
+ for (const v of ['pc$', 'aborted$'])
257
+ if (taken.has(v))
258
+ throw new Error(`isolation: ${v} is a name of ${m.name}`);
259
+ // σ: what the commit reads: the kept inputs and what was read.
260
+ const rd = (j) => `rd$${j}`, inp = (i) => `in$${i}`;
261
+ const sigma = (e) => {
262
+ if (e.op === 'var')
263
+ return m.inputs.includes(e.name) ? x(inp(e.name)) : e;
264
+ if (e.op === 'get') {
265
+ const j = seen.get(JSON.stringify(e));
266
+ return j !== undefined ? x(rd(j)) : get(e.map, sigma(e.key));
267
+ }
268
+ if (e.op === 'if')
269
+ return ite(sigmaC(e.c), sigma(e.then), sigma(e.else));
270
+ if (e.op === 'const')
271
+ return e;
272
+ if (e.op === 'mul')
273
+ return { ...e, a: sigma(e.a) };
274
+ return { ...e, a: sigma(e.a), b: sigma(e.b) };
275
+ };
276
+ const sigmaC = (c) => {
277
+ if (c.op === 'and' || c.op === 'or')
278
+ return { op: c.op, xs: c.xs.map(sigmaC) };
279
+ if (c.op === 'not')
280
+ return not(sigmaC(c.x));
281
+ if (c.op === 'flag' || c.op === 'all')
282
+ return c;
283
+ return { ...c, a: sigma(c.a), b: sigma(c.b) };
284
+ };
285
+ const r = sites.length, snap = level === 'snapshot';
286
+ const commit = snap ? 1 : r + 1, done = commit + 1;
287
+ const at = (k) => same(x('pc$'), n(k));
288
+ 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;
289
+ const commits = valid ? all(at(commit), valid) : at(commit);
290
+ const reads = snap ? x('pc$') : Array.from({ length: r }, (_, j) => j + 1).reduceRight((acc, j) => ite(at(j), n(j + 1), acc), x('pc$'));
291
+ const state = {
292
+ 'pc$': ite(at(0), n(snap || !r ? commit : 1), ite(at(commit), n(done), reads)),
293
+ ...Object.fromEntries(m.inputs.map(i => [inp(i), ite(at(0), x(i), x(inp(i)))])),
294
+ ...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)))])),
295
+ ...mapValues(m.step.state, (e, s) => ite(commits, sigma(e), x(s))),
296
+ ...(snap ? { 'aborted$': ite(at(commit), valid.op === 'and' && !valid.xs.length ? n(0) : ite(valid, n(0), n(1)), x('aborted$')) } : {}),
297
+ };
298
+ const maps = Object.fromEntries(pointWrites.map(w => {
299
+ const on = writesWhen(w.value, get(w.map, w.key)), key = sigma(w.key);
300
+ const when = on === false ? undefined : on === true ? commits : all(commits, sigmaC(on));
301
+ return [w.map, { key, value: when ? ite(when, sigma(w.value), get(w.map, key)) : get(w.map, key) }];
302
+ }));
303
+ const out = {
304
+ name: `${m.name} (${level})`, params: m.params, inputs: m.inputs,
305
+ state: { ...m.state, 'pc$': n(0), ...Object.fromEntries(m.inputs.map(i => [inp(i), n(0)])), ...Object.fromEntries(sites.map((_s, j) => [rd(j), n(0)])), ...(snap ? { 'aborted$': n(0) } : {}) },
306
+ ...(m.maps ? { maps: m.maps } : {}),
307
+ step: { flags: mapValues(m.step.flags, sigmaC), state, maps },
308
+ // (the request's assumption, at the begin: the inputs it keeps)
309
+ ...(m.assume ? { assume: any(not(at(0)), m.assume) } : {}),
310
+ ...(m.pre ? { pre: m.pre } : {}),
311
+ };
312
+ return from(out, m, ISOLATION[level]);
313
+ }
314
+ export const DELIVERY = {
315
+ '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)',
316
+ checked: 'a transactional consume (Kafka transactions, an inbox row in the handler\'s transaction)' },
317
+ 'at-least-once': { name: 'at-least-once delivery', assumes: 'a sent message may be delivered any number of times, in any order, including while an earlier delivery is still being handled (redelivery, duplicates, a retrying client whose earlier try may still run or may have applied)',
318
+ checked: 'SQS standard queues, Kafka before an offset commit, Redis Streams (XAUTOCLAIM, envcheck.py)' },
319
+ };
320
+ // m's request taken from the message pool `pool`: each input in `fields` read from the message `msg` (an input): the
321
+ // pool's maps `${pool}` (1 once sent) and `${pool}_${field}`; `id`, an input that is the message's id itself (an
322
+ // idempotency key that is the message id). The request is one m may take only while the message was sent; exactly
323
+ // once also takes it (`${pool}_taken`). On a handler of several steps (pc$, isolation's), the message is taken at its
324
+ // begin.
325
+ export function delivery(m, pool, fields, mode, opts = {}) {
326
+ plain(m, 'delivery');
327
+ const msg = opts.msg ?? 'msg', bound = [...fields, ...(opts.id ? [opts.id] : [])];
328
+ for (const f of bound)
329
+ if (!m.inputs.includes(f))
330
+ throw new Error(`delivery: ${f} is no input of ${m.name}`);
331
+ if ([...m.inputs, ...Object.keys(m.state)].includes(msg))
332
+ throw new Error(`delivery: ${msg} is already a name of ${m.name}`);
333
+ const begin = 'pc$' in m.state ? same(x('pc$'), n(0)) : same(n(0), n(0));
334
+ const vars = { ...Object.fromEntries(fields.map(f => [f, get(`${pool}_${f}`, x(msg))])), ...(opts.id ? { [opts.id]: x(msg) } : {}) };
335
+ const { E, C, W } = mapper(m, vars, f => f), taken = `${pool}_taken`;
336
+ const guard = all(begin, ...[same(get(pool, x(msg)), n(1))], ...(mode === 'exactly-once' ? [same(get(taken, x(msg)), n(0))] : []));
337
+ return from({
338
+ ...m, name: `${m.name} (${mode} from ${pool})`, inputs: [...m.inputs.filter(i => !bound.includes(i)), msg],
339
+ maps: { ...m.maps, [pool]: 0, ...Object.fromEntries(fields.map(f => [`${pool}_${f}`, 0])), ...(mode === 'exactly-once' ? { [taken]: 0 } : {}) },
340
+ step: {
341
+ flags: mapValues(m.step.flags, C), state: mapValues(m.step.state, E),
342
+ maps: { ...mapValues(m.step.maps, W), ...(mode === 'exactly-once' ? { [taken]: { key: x(msg), value: ite(begin, n(1), get(taken, x(msg))) } } : {}) },
343
+ },
344
+ assume: all(any(not(begin), guard), ...(m.assume ? [C(m.assume)] : [])),
345
+ }, m, DELIVERY[mode]);
346
+ }
347
+ // The environment's sends into `pool`: a message at a fresh id, its fields any values (the request's).
348
+ export const client = (pool, fields, msg = 'msg') => ({
349
+ name: `client of ${pool}`, params: [], inputs: [msg, ...fields.map(f => `${pool}_${f}$in`)], state: {},
350
+ maps: { [pool]: 0, ...Object.fromEntries(fields.map(f => [`${pool}_${f}`, 0])) },
351
+ step: { maps: { [pool]: { key: x(msg), value: n(1) }, ...Object.fromEntries(fields.map(f => [`${pool}_${f}`, { key: x(msg), value: x(`${pool}_${f}$in`) }])) } },
352
+ assume: same(get(pool, x(msg)), n(0)),
353
+ });
354
+ // A retrying client is at-least-once delivery of its requests: each try a delivery, the next sent on a timeout.
355
+ export const RETRIES = { name: 'a retrying client', assumes: 'a request may be tried again at any time, any number of times, while an earlier try is still running or after it applied (its reply lost to a timeout)',
356
+ checked: 'urllib3 Retry after a read timeout (envcheck.py: one POST applied three times)' };
357
+ // A store's call fails: the code takes its failure path; a failed write may still have applied (a lost reply).
358
+ export const STORE_FAILS = { name: 'store calls fail', assumes: 'any call to the store may raise, before it applied or after (its reply lost)',
359
+ checked: 'redis-py\'s ConnectionError and TimeoutError (envcheck.py: a SET whose reply was lost, applied)' };
360
+ export const WRITES_FAIL = { name: 'database writes fail', assumes: 'a create may raise before its insert committed or after (a receiver run after the INSERT raising)',
361
+ checked: 'Django: post_save receivers and on_commit hooks raise after the INSERT; transaction.atomic rolls back before it' };
362
+ // --- stores that forget ---------------------------------------------------------------------------------------------
363
+ export const EXPIRY = { name: 'keys expire', assumes: 'any key of the store may vanish at any step, whatever its TTL (the TTL lapsed while its holder still worked, or an eviction)',
364
+ checked: 'Redis EX and maxmemory-policy volatile-lru (envcheck.py: a 30 s key evicted at once)' };
365
+ // A store's key reset to its start: `cells`, the maps of one store (a record's parts) and the value each holds when the
366
+ // key is absent.
367
+ export const expiry = (cells, key = 'key') => modelled({
368
+ name: `expiry of ${Object.keys(cells).join(', ')}`, params: [], inputs: [key], state: {}, maps: cells,
369
+ step: { maps: mapValues(cells, v => ({ key: x(key), value: n(v) })) },
370
+ }, EXPIRY);
371
+ // --- time -----------------------------------------------------------------------------------------------------------
372
+ // The true time: a natural the environment raises by any amount (`dt`) at a step of its own. Nothing bounds how many
373
+ // other steps run between two of its steps, or how far one goes: a law that needs time to pass says so by its fairness
374
+ // (a helpful request {act: <time's part>, dt: 1}), and a timer is a step allowed once the time has passed its deadline.
375
+ export const TIME = { name: 'time passes', assumes: 'one true time `now`, a natural that only rises, by any amount at a step of its own; nothing bounds how many other steps run between two of its steps',
376
+ checked: 'the time reference: a store\'s clock for its TTLs (Redis\'s own), a node\'s monotonic clock (CLOCK_MONOTONIC) for its own timers' };
377
+ export const time = (now = 'now', by = 'dt') => modelled({ name: 'time', params: [], inputs: [by], state: { [now]: n(0) }, step: { state: { [now]: plus(x(now), x(by)) } } }, TIME);
378
+ // A node's clock within `skew` of the true time: m's request time (the input `at`, as the readers read time.time(),
379
+ // Instant::now() and the like) is any reading t with now − skew ≤ t ≤ now + skew. A reading need not rise from the
380
+ // last: more runs than a monotonic clock's, so a proof holds for those too. `skew` is a constant or a param's name (a
381
+ // param of the rule then); 0 is the time itself (`at` replaced by `now`, no longer an input); Infinity is no bound (the
382
+ // reading any natural).
383
+ export const SKEW = (skew) => ({ name: `clock skew ${skew === Infinity ? 'unbounded' : `≤ ${skew}`}`,
384
+ assumes: skew === Infinity ? 'a node\'s clock may read any time at all' : `every reading of a node's clock is within ${skew} of the true time, either way; readings need not rise`,
385
+ checked: 'the deployment\'s bound (NTP or PTP discipline and its alarm, e.g. chrony\'s maxdistance): stated, not checked here' });
386
+ export function clocked(m, at, skew, now = 'now') {
387
+ plain(m, 'clocked');
388
+ if (!m.inputs.includes(at))
389
+ throw new Error(`clocked: ${at} is no input of ${m.name}`);
390
+ if (now in (m.maps ?? {}) || m.inputs.includes(now) || m.params.includes(now))
391
+ throw new Error(`clocked: ${now} is a name of ${m.name} other than a scalar`);
392
+ if (m.step.state?.[now])
393
+ throw new Error(`clocked: ${m.name} writes ${now}; the time is the environment's`);
394
+ if (typeof skew === 'number' && skew !== Infinity && !(Number.isSafeInteger(skew) && skew >= 0))
395
+ throw new Error(`clocked: a skew is a natural, a param's name or Infinity`);
396
+ const eps = typeof skew === 'string' ? x(skew) : n(skew), t = x(at), tn = x(now);
397
+ const bound = skew === Infinity || skew === 0 ? [] : [atMost(t, plus(tn, eps)), atMost(tn, plus(t, eps))];
398
+ // (no skew: the reading is the time itself, the input gone)
399
+ const { E: S, C, W } = mapper(m, skew === 0 ? { [at]: tn } : {}, f => f), assume = m.assume && C(m.assume);
400
+ const out = {
401
+ ...m, params: typeof skew === 'string' && !m.params.includes(skew) ? [...m.params, skew] : m.params,
402
+ inputs: skew === 0 ? m.inputs.filter(i => i !== at) : m.inputs,
403
+ state: { ...m.state, [now]: m.state[now] ?? n(0) },
404
+ step: { flags: mapValues(m.step.flags, C), state: mapValues(m.step.state, S), maps: mapValues(m.step.maps, W) },
405
+ ...(bound.length || assume ? { assume: all(...(assume ? [assume] : []), ...bound) } : {}),
406
+ ...(m.pre ? { pre: m.pre } : {}),
407
+ };
408
+ from(out, m, SKEW(skew));
409
+ sharedOf.set(out, [...new Set([...(sharedOf.get(m) ?? []), now])]);
410
+ return out;
411
+ }
412
+ // Keys that expire at their time: a key of the store vanishes (each of `cells`, the record's parts, back to its value
413
+ // when absent; the expiry `at` too) at any step once the true time has reached its expiry, and never before. With no
414
+ // `key`, the cells are scalars (one record).
415
+ export const TTL = { name: 'keys expire at their time', assumes: 'a key vanishes only once the store\'s clock (the true time) has reached its expiry, at any step after; never before (no eviction: maxmemory-policy noeviction, or no memory pressure)',
416
+ checked: 'Redis PX: the key is there before its time and gone after (envcheck.py); under noeviction a write past maxmemory is refused (OOM), not evicted' };
417
+ export function expires(cells, at, opts = {}) {
418
+ const now = opts.now ?? 'now', all0 = { ...cells, [at]: 0 }, key = opts.key;
419
+ const m = key
420
+ ? { name: `expiry of ${Object.keys(cells).join(', ')} at ${at}`, params: [], inputs: [key], state: { [now]: n(0) }, maps: all0,
421
+ step: { maps: mapValues(all0, v => ({ key: x(key), value: n(v) })) }, assume: atMost(get(at, x(key)), x(now)) }
422
+ : { name: `expiry of ${Object.keys(cells).join(', ')} at ${at}`, params: [], inputs: [], state: { ...mapValues(all0, v => n(v)), [now]: n(0) },
423
+ step: { state: mapValues(all0, v => n(v)) }, assume: atMost(x(at), x(now)) };
424
+ sharedOf.set(m, [now]);
425
+ return modelled(m, TTL);
426
+ }
@@ -830,7 +830,8 @@ export function scope(m, laws = []) {
830
830
  plainName(what, key);
831
831
  if ([...names, ...readable, ...flags].includes(key))
832
832
  throw new Error(`${what}: the key ${key} is already a name of ${m.name}`);
833
- keyOnly(what, t, key, fns);
833
+ // (a count map, like a function, has a value at every key, not cells a runtime can list: read at no key term)
834
+ keyOnly(what, t, key, [...fns, ...counts]);
834
835
  };
835
836
  inScope(`${m.name}'s start`, Object.values(m.state), m.params);
836
837
  flags.forEach((f, i) => {
@@ -898,7 +899,7 @@ export function scope(m, laws = []) {
898
899
  inScope(`fact ${fact.name}`, [fact.holds], [...m.params, ...keysOf(fact)], fns);
899
900
  }
900
901
  // A key bound in t is read in key terms only: the key, or the key plus or less a term that doesn't read it (k + e, e + k,
901
- // k ∸ e), each a map's key (no function's: a function's values don't stop where a map's cells do) or a side of a
902
+ // k ∸ e), each a map's key (no function's or count's: their values don't stop where a map's cells do) or a side of a
902
903
  // comparison whose other side doesn't read the key. Then t is constant between finitely many keys (the runtimes'
903
904
  // breakpoints: each map's cells and each compared value, shifted by the offsets), so a runtime decides it on those.
904
905
  const readsKey = (t, key) => JSON.stringify(t).includes(`"op":"var","name":${JSON.stringify(key)}`);
@@ -56,6 +56,7 @@ export declare const fullWork: () => number;
56
56
  export declare const withWork: <T>(cap: number, f: () => T) => T;
57
57
  export declare const pastWall: () => boolean;
58
58
  export declare function withWall<T>(end: number, f: () => T): T;
59
+ export declare const wallAt: () => number;
59
60
  export declare const late: (until: number) => boolean;
60
61
  export declare const withinDeadline: (until: number) => number;
61
62
  export declare function withDeadline<T>(until: number, f: () => T): T;
@@ -305,6 +305,10 @@ export function withWall(end, f) {
305
305
  wallEnd = outer;
306
306
  }
307
307
  }
308
+ // Past the wall or the deadline in force: a goal grown now is left unknown at once.
309
+ const ranOut = () => pastWall() || withinDeadline(Infinity) <= clock();
310
+ // (the wall's end in force, Infinity where none: a search inside that stops itself there)
311
+ export const wallAt = () => wallEnd;
308
312
  export const late = (until) => clock() > until || (workCap !== Infinity && fullWork() > workCap) || pastWall();
309
313
  // A budget's end, within the deadline (a translation's own bound, core/cyclic.ts's, kept by the export's GDP_CERT_MS).
310
314
  export const withinDeadline = (until) => Math.min(until, deadline);
@@ -1458,18 +1462,60 @@ const withReads = (laws, inst, keys, focus, byMap, fns = []) => {
1458
1462
  return { ...inst, ...Object.fromEntries(laws.filter(l => l.forall).map(l => {
1459
1463
  const had = inst[l.name] ?? [];
1460
1464
  if (l.keys?.length) {
1461
- const n = l.keys.length + 1, out = new Map(), sorted = byMap ? keySorted(l, byMap, fns) : undefined;
1465
+ const n = l.keys.length + 1, out = new Map();
1462
1466
  for (let i = 0; i + n <= had.length; i += n)
1463
1467
  out.set(JSON.stringify(had.slice(i, i + n)), had.slice(i, i + n));
1464
- for (const tuple of [...related(keys, focus, n, sorted, most), ...matched(l, keys, most)])
1465
- if (!sorted || sorted(tuple))
1468
+ // (a key the law's hypothesis fixes by an equation, x + c = t: the tuples of the others, x at t ∸ c in each)
1469
+ const { law: lr, back } = fixedOut(l), m2 = lr.keys?.length ?? 0, sorted = byMap ? keySorted(lr, byMap, fns) : undefined;
1470
+ const tuples = m2 ? [...related(keys, focus, m2 + 1, sorted, most), ...matched(lr, keys, most)] : related(keys, focus, 1, sorted, most);
1471
+ for (const t0 of tuples)
1472
+ if (!sorted || sorted(t0)) {
1473
+ const tuple = back(t0);
1466
1474
  out.set(JSON.stringify(tuple), tuple);
1475
+ }
1467
1476
  return [l.name, [...out.values()].flat()];
1468
1477
  }
1469
1478
  const seen = new Set(had.map(e => JSON.stringify(e)));
1470
1479
  return [l.name, [...had, ...keys.filter(e => { const id = JSON.stringify(e); return seen.has(id) ? false : (seen.add(id), true); })]];
1471
1480
  })) };
1472
1481
  };
1482
+ // A law's keys that its hypothesis fixes by an equation (x + c = t, or t = x, t reading no fixed key): the law without
1483
+ // them (each read at t ∸ c, c ≤ t a further hypothesis: the same law over the naturals), and `back`, a tuple of its keys
1484
+ // made a tuple of the law's (each fixed key at its t). A law with five keys of which two a cell fixes (Table[a·N + k] =
1485
+ // v + 1) has its instances over three. Untrusted: it chooses instances only.
1486
+ const fixedMemo = new WeakMap();
1487
+ function fixedOut(l) {
1488
+ let out = fixedMemo.get(l);
1489
+ if (!out)
1490
+ fixedMemo.set(l, (out = fixedOut0(l)));
1491
+ return out;
1492
+ }
1493
+ function fixedOut0(l) {
1494
+ const all = [l.forall, ...(l.keys ?? [])], same = { law: l, back: (t) => t };
1495
+ const hyps = l.holds.op === 'or' ? l.holds.xs.flatMap(d => (d.op === 'not' ? (d.x.op === 'and' ? d.x.xs : [d.x]) : [])) : [];
1496
+ const named = (e, x) => JSON.stringify(e).includes(`"name":${JSON.stringify(x)}`);
1497
+ const offset = (e) => (e.op === 'var' && all.includes(e.name) ? [e.name, 0] : e.op === 'add' && e.a.op === 'var' && all.includes(e.a.name) && e.b.op === 'const' ? [e.a.name, e.b.value] : undefined);
1498
+ const fixed = new Map();
1499
+ for (const h of hyps) {
1500
+ if (h.op !== '=')
1501
+ continue;
1502
+ for (const [x, t] of [[h.a, h.b], [h.b, h.a]]) {
1503
+ const o = offset(x);
1504
+ if (!o || o[0] === l.forall || fixed.has(o[0]) || named(t, o[0]) || [...fixed.keys()].some(f => named(t, f)) || [...fixed.values()].some(f => named(f.t, o[0])))
1505
+ continue;
1506
+ fixed.set(o[0], { t, c: o[1] });
1507
+ break;
1508
+ }
1509
+ }
1510
+ if (!fixed.size)
1511
+ return same;
1512
+ const at = (x) => { const { t, c } = fixed.get(x); return c ? { op: 'sub', a: t, b: { op: 'const', value: c } } : t; };
1513
+ const sub0 = { vars: Object.fromEntries([...fixed.keys()].map(x => [x, at(x)])), maps: {}, flags: {} };
1514
+ const guards = [...fixed.values()].flatMap(({ t, c }) => (c ? [{ op: '<=', a: { op: 'const', value: c }, b: t }] : []));
1515
+ const kept = all.filter(x => !fixed.has(x)), holds = substC(guards.length ? { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: guards } }, l.holds] } : l.holds, sub0);
1516
+ const law = { ...l, holds, keys: kept.slice(1) };
1517
+ return { law, back: t => { const s2 = { vars: Object.fromEntries(kept.map((x, i) => [x, t[i]])), maps: {}, flags: {} }; return all.map(x => (fixed.has(x) ? substE(at(x), s2) : t[kept.indexOf(x)])); } };
1518
+ }
1473
1519
  // A tuple of the key's sort: each of a law's keys read at a map (M[x], M[x·N + y]) takes only the terms its read matches
1474
1520
  // against the keys the goals read that map at (the key's sort, as the goal holds it: Link[c1·N + s] against
1475
1521
  // Link[a·N + b] gives c1 a and s b); a key no read binds, or a read no goal key matches, takes any. A function's
@@ -2185,8 +2231,21 @@ export function proveLaw(m, laws, i) {
2185
2231
  function proveOne(m, laws, i) {
2186
2232
  const law = laws[i], pm = plainOf(m), inst = lawInstances(m, laws, i);
2187
2233
  const few = triggered(pm, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
2188
- if (!sameInstances(few, inst) && obligations(m, laws, { [law.name]: few }, i).every(goal => 'tree' in grow(goal)))
2189
- return { proven: true };
2234
+ if (!sameInstances(few, inst)) {
2235
+ let proven = true;
2236
+ for (const goal of obligations(m, laws, { [law.name]: few }, i)) {
2237
+ const o = grow(goal);
2238
+ if ('tree' in o)
2239
+ continue;
2240
+ proven = false;
2241
+ // (a goal that ran out past the deadline: the next instances can't be tried, and it is the verdict's goal)
2242
+ if (o.stuck === 'unknown' && ranOut())
2243
+ return { proven: false, goal: goal.name, stuck: 'unknown' };
2244
+ break;
2245
+ }
2246
+ if (proven)
2247
+ return { proven: true };
2248
+ }
2190
2249
  // (a model breaking a law at a tuple of the goal's keys: those added, the law asked again)
2191
2250
  const { result: a } = withModels(m, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), growAll, grownModel, grownSettled);
2192
2251
  return a.out ? { proven: false, goal: a.goal.name, stuck: a.out.stuck, ...(a.out.witness ? { witness: a.out.witness } : {}), ...(a.out.diagram ? { diagram: a.out.diagram } : {}) } : { proven: true };
@@ -2482,15 +2541,17 @@ function thinned(m, laws, instances) {
2482
2541
  const trees = {}, fulls = { ...instances };
2483
2542
  let nodes = 0, leaves = 0;
2484
2543
  for (const [i, law] of laws.entries()) {
2485
- const full = instances[law.name];
2486
- const few = triggered(plainOf(m), laws, full, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), law.forall ? [`${law.forall}#`] : []);
2544
+ const full = instances[law.name], focus = law.forall ? [`${law.forall}#`] : [];
2545
+ const few = triggered(plainOf(m), laws, full, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), focus);
2487
2546
  // (thinned instances first, then the full ones; each asked again at the tuples its models ask for)
2488
2547
  for (const inst of sameInstances(few, full) ? [full] : [few, full]) {
2489
2548
  const { result: a, inst: at } = withModels(m, laws, inst, i2 => obligations(m, laws, { ...instances, [law.name]: i2 }, i), growAll, grownModel, grownSettled);
2490
2549
  instances[law.name] = at;
2491
2550
  if (inst === full)
2492
2551
  fulls[law.name] = at;
2493
- if (a.out && inst !== full)
2552
+ // (one that ran out past the wall: the next instances can't be tried, and the goal that ran out is the verdict's, not
2553
+ // the next one's first goal)
2554
+ if (a.out && inst !== full && !(a.out.stuck === 'unknown' && ranOut()))
2494
2555
  continue;
2495
2556
  if (a.out)
2496
2557
  return stuckAt(a.goal, a.out, nodes, leaves);
@@ -3,7 +3,7 @@ import { add, k, scale, sub } from "../core/solver.js";
3
3
  import { countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
4
  import { chooseLevels, clock, grow, minimal, proveBuilt, proveLaws, proveSetFast, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
- import { leanSurface, leanTerms } from "./lean-terms.js";
6
+ import { exactNat, leanSurface, leanTerms } from "./lean-terms.js";
7
7
  import { descentGoal, mainGoal, premiseGoal } from "../kernel/cyclic.js";
8
8
  import { allowNode, certMs, closingInsts, reqTS, withWitness, foldNodes, certMode, quietly, uncoveredWhy, hasQuantified, kWhens, machineNodes, proveCyclic, routeOf, searchedStepNodes, skMachine, stepLawNodes, tBack, tSub } from "../core/cyclic.js";
9
9
  import { leanLibrary } from "./library.js";
@@ -908,7 +908,7 @@ export function mmachineToLean(id, m, laws, opts = {}) {
908
908
  const ix = (name) => vars.indexOf(name);
909
909
  const lit = (mm) => `⟨⟨${list(mm.inputs.map(name => String(ix(name))))},
910
910
  ${list(Object.entries(mm.state).map(([name, e]) => `(${ix(name)}, ${any0.e(e)})`))},
911
- ${list(Object.entries(mm.maps ?? {}).map(([name, c2]) => `(${mapNames.indexOf(name)}, ${c2})`))},
911
+ ${list(Object.entries(mm.maps ?? {}).map(([name, c2]) => `(${mapNames.indexOf(name)}, ${exactNat(c2)})`))},
912
912
  ${list(Object.entries(mm.step.state ?? {}).map(([name, e]) => `(${ix(name)}, ${any0.e(e)})`))},
913
913
  ${list(Object.entries(mm.step.maps ?? {}).map(([name, w]) => { const pw = pointWrite(w, 'Lean (for now)'); return `(${mapNames.indexOf(name)}, ${any0.e(pw.key)}, ${any0.e(pw.value)})`; }))},
914
914
  ${mm.pre ? any0.c(mm.pre) : TRUE},
@@ -1004,7 +1004,7 @@ export function machineLit(mm, t, ix, mx) {
1004
1004
  const fl = flagsOfM(mm), fs = Object.entries(mm.step.flags ?? {}), ws = Object.entries(mm.step.maps ?? {});
1005
1005
  return `⟨⟨⟨${list(mm.inputs.map(name => String(ix(name))))},
1006
1006
  ${list(Object.entries(mm.state).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
1007
- ${list(Object.entries(mm.maps ?? {}).map(([name, c2]) => `(${mx(name)}, ${c2})`))},
1007
+ ${list(Object.entries(mm.maps ?? {}).map(([name, c2]) => `(${mx(name)}, ${exactNat(c2)})`))},
1008
1008
  ${list(Object.entries(mm.step.state ?? {}).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
1009
1009
  ${list(ws.flatMap(([name, w]) => ('each' in w ? [] : [`(${mx(name)}, ${e(w.key)}, ${e(w.value)})`])))},
1010
1010
  ${mm.pre ? c(mm.pre) : TRUE},
@@ -1,4 +1,5 @@
1
1
  import { type C, type E } from '../core/machine.js';
2
+ export declare const exactNat: (x: number) => string;
2
3
  export declare function leanTerms(vars: readonly string[], maps: readonly string[], where: string): {
3
4
  e: (t: E) => string;
4
5
  c: (t: C) => string;