gdp-wired 0.56.0 → 0.57.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.
@@ -21,13 +21,13 @@ import { allowed } from "./watch.js";
21
21
  import { BudgetExpired, checkWorkEndpoint } from "./wall.js";
22
22
  import { WatchdogExpired } from "./search-watchdog.js";
23
23
  import * as I from "./extract-ir.js";
24
- import { Refusal, bare as strip, beside, impure, memberName, normalize, placed, refuse, shapeOf, sourceOf, text, where } from "./extract-read.js";
24
+ import { Refusal, assertNoReservedHarness, bare as strip, beside, declSpanOf, impure, initEffectAtom, memberName, mergeEffectAtom, normalize, placed, refuse, shapeOf, sourceOf, text, where } from "./extract-read.js";
25
25
  import { readFactory, setupOf } from "./extract-shapes.js";
26
26
  import { fromModel, namesOf } from "./extract.js";
27
27
  import { check, sandbox } from "./extract-check.js";
28
28
  import { Parts, readSchedule, replaySchedule, scheduleConforms, scheduleRule } from "./effect-schedule.js";
29
29
  import { asRule, lift } from "./system.js";
30
- import { attachSource, inheritSource } from "./source-check.js";
30
+ import { attachSource, inheritSource, rememberNative } from "./source-check.js";
31
31
  import { rewritePrims } from "./effect-prims.js";
32
32
  export { minimizeRun, minimizeRunDetailed, proveRule, proveSteps } from "./dsl.js";
33
33
  export { jitterRun, replaySchedule, scheduleConforms, stepper } from "./effect-schedule.js";
@@ -48,8 +48,9 @@ const changedOn = (p, k = CHANGED) => { const o = p.heap.get(k); return o?.k ===
48
48
  // Inside a transaction (STM.gen, STM.commit, 4.x's Effect.tx), the writes made before it: what a failure there keeps
49
49
  // (the transaction's own are rolled back).
50
50
  const OUTER = '$outer', flagged = (b) => ({ k: 'alias', to: { t: 'bool', e: b } });
51
+ const changedExpr = (e, ce) => I.same(e, ce) ? I.F : (e.op === 'ite' || e.op === 'kite') && e.c ? I.bite(e.c, changedExpr(e.a, ce), changedExpr(e.b, ce)) : I.T;
51
52
  const changedOf = (v, c) => (v.t === 'phi' ? I.bite(v.c, changedOf(v.a, c), changedOf(v.b, c)) : v.t === 'ref' && c.t === 'ref' && v.id === c.id ? I.F
52
- : (v.t === 'num' || v.t === 'bool' || v.t === 'str' || v.t === 'choice') && v.t === c.t && I.same(v.e, c.e) ? I.F : I.T);
53
+ : (v.t === 'num' || v.t === 'bool' || v.t === 'str' || v.t === 'choice') && v.t === c.t ? changedExpr(v.e, c.e) : I.T);
53
54
  // --- the reader -----------------------------------------------------------------------------------------------------
54
55
  // The module of Effect a name is (Ref for `import * as Ref from 'effect/Ref'`, `import {Ref} from 'effect'`, or `E.Ref`
55
56
  // of `import * as E from 'effect'`), with the member read of it: 'Ref.get'.
@@ -99,9 +100,19 @@ const genOf = (s, e, which = 'Effect.gen') => {
99
100
  // A type's type argument: Ref<A>'s A, Effect<A, E, R>'s A, Generator<Y, R, N>'s R.
100
101
  const argOf = (s, t, i) => (t.aliasTypeArguments ?? (t.flags & ts.TypeFlags.Object ? s.checker.getTypeArguments(t) : undefined))?.[i];
101
102
  const lastReturn = (b) => { const st = b && ts.isBlock(b) ? b.statements.at(-1) : undefined; return st && ts.isReturnStatement(st) ? st.expression : b && !ts.isBlock(b) ? b : undefined; };
103
+ const makeAtomTracker = () => ({ pass: 'first', mutableClosure: new Map(), methods: new Map(), failAtoms: new Map(), syncSeq: 0 });
104
+ const addUniqueStr = (xs, x) => (xs.includes(x) ? xs : [...xs, x]);
105
+ const addUniqueNode = (xs, x) => (xs.includes(x) ? xs : [...xs, x]);
106
+ const bumpTopScope = (scopeOps) => {
107
+ if (!scopeOps.length)
108
+ return scopeOps;
109
+ const next = [...scopeOps];
110
+ next[next.length - 1] = next[next.length - 1] + 1;
111
+ return next;
112
+ };
102
113
  // The service's make: the generator whose statements make the Refs and return the object, its params, and how the check
103
114
  // makes the service (by calling the entry, or the effect captured where it is written).
104
- function factoryOf(s, entry) {
115
+ function factoryOf(s, entry, tracker) {
105
116
  const [name, member] = entry.split('.'), NO = 'no make effect (an Effect.gen, a function returning one, Effect.fn, or Layer.effect of one)';
106
117
  let decl;
107
118
  for (const st of s.sf.statements) {
@@ -114,17 +125,32 @@ function factoryOf(s, entry) {
114
125
  }
115
126
  if (!decl)
116
127
  return refuse(s.sf.statements[0] ?? s.sf, `no ${name} in the file`);
128
+ const spans = [];
129
+ const pushSpan = (sp) => { if (!spans.some(x => x.file === sp.file && x.start === sp.start && x.end === sp.end))
130
+ spans.push(sp); };
131
+ const addSpan = (n) => pushSpan(declSpanOf(s.sf, n));
117
132
  // The make effect as written (a class's option or static member, a variable's value), through Layer.effect and names.
118
133
  let e, at = decl;
119
134
  if (ts.isClassDeclaration(decl)) {
120
135
  const opts = member ? undefined : decl.heritageClauses?.[0]?.types[0]?.expression, o = opts && ts.isCallExpression(opts) && opts.arguments[1] ? strip(opts.arguments[1]) : undefined;
121
- const prop = member ? decl.members.find(x => ts.isPropertyDeclaration(x) && memberName(x.name) === member) : o && ts.isObjectLiteralExpression(o) ? o.properties.find(p => ts.isPropertyAssignment(p) && ['make', 'effect', 'scoped'].includes(memberName(p.name))) : undefined;
136
+ const prop = member ? decl.members.find(x => (ts.isPropertyDeclaration(x) || ts.isMethodDeclaration(x)) && memberName(x.name) === member) : o && ts.isObjectLiteralExpression(o) ? o.properties.find(p => ts.isPropertyAssignment(p) && ['make', 'effect', 'scoped'].includes(memberName(p.name))) : undefined;
137
+ if (member) {
138
+ if (prop)
139
+ pushSpan({ file: s.sf.fileName, start: prop.getStart(s.sf), end: prop.end });
140
+ }
141
+ else
142
+ addSpan(decl);
143
+ if (prop && ts.isMethodDeclaration(prop))
144
+ return fromFunction(prop);
122
145
  e = prop?.initializer;
123
146
  }
124
- else if (ts.isVariableDeclaration(decl))
125
- e = decl.initializer;
126
- else if (ts.isFunctionDeclaration(decl))
127
- return fromFunction(decl);
147
+ else {
148
+ addSpan(decl);
149
+ if (ts.isVariableDeclaration(decl))
150
+ e = decl.initializer;
151
+ else if (ts.isFunctionDeclaration(decl))
152
+ return fromFunction(decl);
153
+ }
128
154
  for (let i = 0; e && i < 8; i++) {
129
155
  e = strip(e);
130
156
  const api = callOf(s, e), d = ts.isIdentifier(e) ? s.checker.getSymbolAtLocation(e)?.valueDeclaration : undefined;
@@ -133,6 +159,7 @@ function factoryOf(s, entry) {
133
159
  else if (d && ts.isVariableDeclaration(d) && d.getSourceFile() === s.sf) {
134
160
  e = d.initializer;
135
161
  at = d;
162
+ addSpan(d);
136
163
  }
137
164
  else
138
165
  break;
@@ -159,11 +186,67 @@ function factoryOf(s, entry) {
159
186
  if (!o || !ts.isObjectLiteralExpression(o))
160
187
  return refuse(fn, `${entry}'s make effect returns no object of methods (\`return {...}\` or \`return Tag.of({...})\`)`);
161
188
  const refs = new Map(), locks = new Set(), effects = new Map();
162
- s.effect = hook(s, refs, locks, effects);
189
+ s.effect = hook(s, refs, locks, effects, tracker);
190
+ if (tracker) {
191
+ s.onStateAccess = (fieldName, _kind, p, node) => {
192
+ if (tracker.pass !== 'final' || !p.atom || !tracker.mutableClosure.has(fieldName))
193
+ return p;
194
+ const a = p.atom;
195
+ if (a.txDepth > 0)
196
+ refuse(node, `${fieldName}: closure state cannot be used inside a transaction (only TxRef and TRef participate in a transaction)`);
197
+ const epoch = `${a.yieldEpoch}:${a.syncId}`;
198
+ const touchedState = addUniqueStr(a.touchedState, fieldName);
199
+ const closureStateTouched = addUniqueStr(a.closureStateTouched, fieldName);
200
+ if (a.lastClosureEpoch === epoch)
201
+ return { ...p, atom: { ...a, touchedState, closureStateTouched } };
202
+ const inAtomic = a.txDepth > 0 || a.locks.length > 0;
203
+ return {
204
+ ...p,
205
+ atom: {
206
+ ...a,
207
+ units: inAtomic ? a.units : a.units + 1,
208
+ rawStateOps: a.rawStateOps + 1,
209
+ unlockedStateOps: inAtomic ? a.unlockedStateOps : a.unlockedStateOps + 1,
210
+ stateAfterSleptClock: a.stateAfterSleptClock || a.sleptAfterClock,
211
+ touchedState,
212
+ closureStateTouched,
213
+ lastClosureEpoch: epoch,
214
+ closureMultiStep: a.closureMultiStep || (!inAtomic && a.lastClosureEpoch !== undefined),
215
+ scopeOps: inAtomic ? bumpTopScope(a.scopeOps) : a.scopeOps,
216
+ },
217
+ };
218
+ };
219
+ }
163
220
  s.notes.add(`${entry} is an Effect service: its state is its Refs, each method an event, a failure the step's refusal; each method is one step, which holds where calls don't interleave (one at a time, or under a Semaphore of 1)`);
164
- const R = 'require("gdp-wired:effect")', run = (f) => `{ const f = ${f}; return __R.run(typeof f === 'function' ? f(...args) : f, __now()) }`;
221
+ const R = 'require("gdp-wired:effect")', run = (f) => `{ const f = ${f}; return __R.run(typeof f === 'function' ? f(...args) : f, __gdp_clock(), __gdp_observe_clock) }`;
165
222
  return {
166
- fn, params, obj: o,
223
+ fn, params, obj: o, declSpans: spans,
224
+ ...(tracker ? {
225
+ initAtom: initEffectAtom,
226
+ onFields: (fields, written, first) => {
227
+ tracker.pass = first ? 'first' : 'final';
228
+ if (!first) {
229
+ tracker.methods.clear();
230
+ tracker.failAtoms.clear();
231
+ tracker.mutableClosure.clear();
232
+ tracker.currentMethod = undefined;
233
+ for (const fl of fields)
234
+ if (!refs.has(fl.name) && ((!fl.param && !fl.isConst) || written.has(fl.name)))
235
+ tracker.mutableClosure.set(fl.name, fl.node);
236
+ }
237
+ },
238
+ beginMethod: mName => { if (tracker.pass === 'final')
239
+ tracker.currentMethod = mName; },
240
+ endMethod: (mName, atoms) => {
241
+ if (tracker.pass !== 'final')
242
+ return;
243
+ let acc = tracker.failAtoms.get(mName);
244
+ for (const a of atoms)
245
+ acc = mergeEffectAtom(acc, a);
246
+ tracker.methods.set(mName, acc ?? initEffectAtom());
247
+ tracker.currentMethod = undefined;
248
+ },
249
+ } : {}),
167
250
  decl: d => {
168
251
  const init = d.initializer && strip(d.initializer), id = d.name.text;
169
252
  if (!init)
@@ -214,9 +297,60 @@ const LOGS = new Set(['log', 'logTrace', 'logDebug', 'logInfo', 'logWarning', 'l
214
297
  const ANNOTATIONS = new Set(['Effect.withSpan', 'Effect.withLogSpan', 'Effect.annotateLogs', 'Effect.annotateSpans']);
215
298
  // What a Ref operation answers: the value before, the value after, or nothing; and whether it takes a value or a function.
216
299
  const ANSWERS = { get: 'old', set: 'none', getAndSet: 'old', setAndGet: 'new', update: 'none', updateAndGet: 'new', getAndUpdate: 'old', modify: 'none' };
217
- function hook(s, refs, locks, effects) {
300
+ function hook(s, refs, locks, effects, tracker) {
218
301
  const eff = (run) => ({ t: 'eff', run }), undef = { t: 'undef' };
219
- const lockOf = (x) => { const d = x && ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.valueDeclaration : undefined; return !!d && locks.has(d); };
302
+ const lockOf = (x) => { const d = x && ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.valueDeclaration : undefined; return d && locks.has(d) ? d : undefined; };
303
+ const mapAtom = (p, f) => (p.atom ? { ...p, atom: f(p.atom) } : p);
304
+ const recordRefOp = (p, refName) => mapAtom(p, a => {
305
+ const inAtomic = a.txDepth > 0 || a.locks.length > 0;
306
+ return {
307
+ ...a,
308
+ units: inAtomic ? a.units : a.units + 1,
309
+ rawStateOps: a.rawStateOps + 1,
310
+ unlockedStateOps: inAtomic ? a.unlockedStateOps : a.unlockedStateOps + 1,
311
+ stateAfterSleptClock: a.stateAfterSleptClock || a.sleptAfterClock,
312
+ touchedState: addUniqueStr(a.touchedState, refName),
313
+ scopeOps: inAtomic ? bumpTopScope(a.scopeOps) : a.scopeOps,
314
+ };
315
+ });
316
+ const enterTx = (p) => mapAtom(p, a => ({
317
+ ...a,
318
+ txDepth: a.txDepth + 1,
319
+ scopeOps: a.txDepth === 0 && a.locks.length === 0 ? [...a.scopeOps, 0] : a.scopeOps,
320
+ }));
321
+ const exitTx = (p) => mapAtom(p, a => {
322
+ const txDepth = Math.max(0, a.txDepth - 1);
323
+ if (txDepth > 0 || a.locks.length > 0)
324
+ return { ...a, txDepth };
325
+ const innerOps = a.scopeOps.at(-1) ?? 0;
326
+ return { ...a, txDepth, scopeOps: a.scopeOps.slice(0, -1), units: innerOps > 0 ? a.units + 1 : a.units };
327
+ });
328
+ const enterLock = (p, lock) => mapAtom(p, a => ({
329
+ ...a,
330
+ locks: [...a.locks, lock],
331
+ scopeOps: a.txDepth === 0 && a.locks.length === 0 ? [...a.scopeOps, 0] : a.scopeOps,
332
+ }));
333
+ const exitLock = (p, lock) => mapAtom(p, a => {
334
+ const nextLocks = a.locks.length ? a.locks.slice(0, -1) : [];
335
+ if (a.txDepth > 0 || nextLocks.length > 0)
336
+ return { ...a, locks: nextLocks };
337
+ const innerOps = a.scopeOps.at(-1) ?? 0;
338
+ return {
339
+ ...a,
340
+ locks: nextLocks,
341
+ scopeOps: a.scopeOps.slice(0, -1),
342
+ units: innerOps > 0 ? a.units + 1 : a.units,
343
+ locksUsed: innerOps > 0 ? addUniqueNode(a.locksUsed, lock) : a.locksUsed,
344
+ multiOpLocks: innerOps >= 2 ? addUniqueNode(a.multiOpLocks, lock) : a.multiOpLocks,
345
+ };
346
+ });
347
+ const enterSync = (p) => mapAtom(p, a => ({ ...a, syncDepth: a.syncDepth + 1, syncId: tracker ? ++tracker.syncSeq : a.syncId + 1 }));
348
+ const exitSync = (p) => mapAtom(p, a => ({ ...a, syncDepth: Math.max(0, a.syncDepth - 1) }));
349
+ const bumpYield = (p) => mapAtom(p, a => ({ ...a, yieldEpoch: a.yieldEpoch + 1 }));
350
+ const locked = (lock, inner, at) => (inner.t !== 'eff' ? refuse(at, `${text(at)}: a lock of other than an effect`) : eff(q => {
351
+ const [v, q2] = inner.run(enterLock(q, lock));
352
+ return [v, exitLock(q2, lock)];
353
+ }));
220
354
  // An error made of pure values: `new E({...})` of a class (an error class has no effects), or a plain value.
221
355
  const effectful = (x) => (x = strip(x), ts.isNewExpression(x) && ts.isIdentifier(x.expression) ? (x.arguments ?? []).some(impure) : impure(x));
222
356
  // A failure: the step refused where it is reached; where a Ref has been changed on the path, the Ref keeps it.
@@ -224,6 +358,9 @@ function hook(s, refs, locks, effects) {
224
358
  const kept = q.heap.has(OUTER) ? changedOn(q, OUTER) : changedOn(q), at2 = { ...q, pc: [...q.pc, when] };
225
359
  if (!ex.known(at2, I.not(kept)))
226
360
  refuse(at, `fails after writing ${q.wrote.join(', ')}${q.heap.has(OUTER) ? ' before the transaction' : ''}: a Ref keeps what was written (a rule's refusal leaves the state as it was)`);
361
+ if (tracker?.pass === 'final' && tracker.currentMethod && at2.atom && ex.feasible(at2)) {
362
+ tracker.failAtoms.set(tracker.currentMethod, mergeEffectAtom(tracker.failAtoms.get(tracker.currentMethod), at2.atom));
363
+ }
227
364
  ex.throws.push({ pc: at2.pc });
228
365
  return [undef, { ...q, pc: [...q.pc, I.not(when)] }];
229
366
  };
@@ -231,10 +368,10 @@ function hook(s, refs, locks, effects) {
231
368
  const tx = (inner, at) => (inner.t !== 'eff' ? refuse(at, `${text(at)}: a transaction of other than an effect`) : eff(q => {
232
369
  if (q.heap.has(OUTER))
233
370
  return inner.run(q);
234
- const [v, q2] = inner.run({ ...q, heap: new Map(q.heap).set(OUTER, flagged(changedOn(q))).set(CHANGED, flagged(I.F)) });
371
+ const [v, q2] = inner.run(enterTx({ ...q, heap: new Map(q.heap).set(OUTER, flagged(changedOn(q))).set(CHANGED, flagged(I.F)) }));
235
372
  const heap = new Map(q2.heap).set(CHANGED, flagged(I.or(changedOn(q2, OUTER), changedOn(q2))));
236
373
  heap.delete(OUTER);
237
- return [v, { ...q2, heap }];
374
+ return [v, exitTx({ ...q2, heap })];
238
375
  }));
239
376
  // A transaction that waits (STM.check of false, STM.retry, 4.x's Effect.txRetry): the request isn't taken until a TRef it
240
377
  // read changes, a refusal in the rule.
@@ -255,7 +392,10 @@ function hook(s, refs, locks, effects) {
255
392
  if (ts.isNewExpression(x))
256
393
  return effectful(x) ? refuse(x, `${text(x)}: an error made with effects`) : fail(ex, x, p);
257
394
  const [v, q] = ex.ev(x, p);
258
- return v.t === 'eff' ? v.run(q) : refuse(x, `yield* of ${text(x)}, not an effect the reader runs (a ${v.t})`);
395
+ if (v.t !== 'eff')
396
+ return refuse(x, `yield* of ${text(x)}, not an effect the reader runs (a ${v.t})`);
397
+ const [v2, q2] = v.run(q);
398
+ return [v2, bumpYield(q2)];
259
399
  }
260
400
  if (ts.isIdentifier(e)) {
261
401
  const d = s.checker.getSymbolAtLocation(e)?.valueDeclaration, init = d && effects.get(d);
@@ -271,9 +411,14 @@ function hook(s, refs, locks, effects) {
271
411
  if (api === 'Effect.txRetry' || api === 'STM.retry')
272
412
  return [eff(q => waits(ex, e, q)), p];
273
413
  if (api === 'Effect.yieldNow')
274
- return [eff(q => [undef, q]), p];
414
+ return [eff(q => [undef, mapAtom(q, a => ({ ...a, sleptAfterClock: a.sleptAfterClock || a.sawClock, yieldEpoch: a.yieldEpoch + 1 }))]), p];
275
415
  if (api === 'Clock.currentTimeMillis')
276
- return [eff(q => (q.heap.has(SLEPT) ? refuse(e, 'the clock read after a repeat that waits (the time has moved on by its delays)') : ex.now(e, q))), p];
416
+ return [eff(q => {
417
+ if (q.heap.has(SLEPT))
418
+ refuse(e, 'the clock read after a repeat that waits (the time has moved on by its delays)');
419
+ const [v, q2] = ex.now(e, q);
420
+ return [v, mapAtom(q2, a => ({ ...a, sawClock: true }))];
421
+ }), p];
277
422
  if (api?.startsWith('Clock.'))
278
423
  return refuse(e, `${api} (Clock.currentTimeMillis is read, as an input)`);
279
424
  if (!api && ['_tag', 'value'].includes(memberName(e.name)) && /^Option<|^(Some|None)</.test(s.checker.typeToString(s.checker.getTypeAtLocation(e.expression))))
@@ -286,13 +431,22 @@ function hook(s, refs, locks, effects) {
286
431
  return undefined;
287
432
  const callee = strip(e.expression), api = apiOf(s, callee), [m = '', op = ''] = api?.split('.') ?? [], one = e.arguments[0];
288
433
  // A lock: sem.withPermit(effect), sem.withPermits(1)(effect), Semaphore.withPermits(sem, 1)(effect).
289
- if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'withPermit' && lockOf(callee.expression) && e.arguments.length === 1)
290
- return ex.ev(one, p);
434
+ if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'withPermit' && e.arguments.length === 1) {
435
+ const lock = lockOf(callee.expression);
436
+ if (lock) {
437
+ const [v, q] = ex.ev(one, p);
438
+ return [locked(lock, v, e), q];
439
+ }
440
+ }
291
441
  if (ts.isCallExpression(callee) && e.arguments.length === 1) {
292
442
  const inner = strip(callee.expression), n = callee.arguments.at(-1);
293
- const sem = ts.isPropertyAccessExpression(inner) && memberName(inner.name) === 'withPermits' ? (lockOf(inner.expression) ? inner.expression : apiOf(s, inner) === 'Semaphore.withPermits' ? callee.arguments[0] : undefined) : undefined;
294
- if (lockOf(sem))
295
- return n && ts.isNumericLiteral(n) && n.text === '1' ? ex.ev(one, p) : refuse(e, 'withPermits of other than 1 (a Semaphore of 1 is a lock; more permits let calls interleave)');
443
+ const lock = ts.isPropertyAccessExpression(inner) && memberName(inner.name) === 'withPermits' ? (lockOf(inner.expression) ?? (apiOf(s, inner) === 'Semaphore.withPermits' ? lockOf(callee.arguments[0]) : undefined)) : undefined;
444
+ if (lock) {
445
+ if (!n || !ts.isNumericLiteral(n) || n.text !== '1')
446
+ return refuse(e, 'withPermits of other than 1 (a Semaphore of 1 is a lock; more permits let calls interleave)');
447
+ const [v, q] = ex.ev(one, p);
448
+ return [locked(lock, v, e), q];
449
+ }
296
450
  }
297
451
  // x.pipe(...): only annotations (a span, a log annotation) are read through.
298
452
  if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'pipe' && !api) {
@@ -354,14 +508,17 @@ function hook(s, refs, locks, effects) {
354
508
  const [v, q] = ex.ev(one ?? refuse(e, 'Effect.succeed()'), p);
355
509
  return [eff(r => [v, r]), q];
356
510
  }
357
- if (op === 'sync')
358
- return [body(ex, fnOf(s, one ?? refuse(e, 'Effect.sync()')) ?? refuse(e, 'Effect.sync of other than a function written here'), e, p.locals), p];
511
+ if (op === 'sync') {
512
+ const fn = fnOf(s, one ?? refuse(e, 'Effect.sync()')) ?? refuse(e, 'Effect.sync of other than a function written here');
513
+ const syncLocals = p.locals;
514
+ return [eff(q => { const [v, q2] = ex.inline({ decl: fn }, [], e, enterSync(q), syncLocals); return [v, exitSync(q2)]; }), p];
515
+ }
359
516
  if (FAILS.has(op))
360
517
  return e.arguments.some(effectful) ? refuse(e, `Effect.${op} of a value that has effects`) : [eff(q => fail(ex, e, q)), p];
361
518
  if (op === 'sleep') {
362
519
  if (e.arguments.some(impure))
363
520
  return refuse(e, 'Effect.sleep of a value that has effects');
364
- return [eff(q => [undef, { ...q, heap: new Map(q.heap).set(SLEPT, flagged(I.T)) }]), p];
521
+ return [eff(q => [undef, mapAtom({ ...q, heap: new Map(q.heap).set(SLEPT, flagged(I.T)) }, a => ({ ...a, sleptAfterClock: a.sleptAfterClock || a.sawClock, yieldEpoch: a.yieldEpoch + 1 }))]), p];
365
522
  }
366
523
  if (LOGS.has(op)) {
367
524
  if (e.arguments.some(impure))
@@ -542,18 +699,20 @@ function hook(s, refs, locks, effects) {
542
699
  return f ? refuse(f, `${m}.${op} of other than a function written here`) : refuse(e, `${m}.${op} with no function`);
543
700
  const [given, q0] = /[sS]et/.test(base) ? ex.ev(f ?? refuse(e, `${m}.${op} with no value`), p) : [undefined, p];
544
701
  return [eff(q => {
702
+ if (q.heap.has(OUTER) && m !== 'TxRef' && m !== 'TRef')
703
+ refuse(e, `${m}.${op} inside a transaction (only TxRef and TRef participate in a transaction)`);
545
704
  const [c, q1] = ex.field(self, name, r, q);
546
705
  if (base === 'get')
547
- return [c, q1];
706
+ return [c, recordRefOp(q1, name)];
548
707
  let [v, q2] = given ? [given, q1] : ex.inline({ decl: fn }, [c], f, q1, ts.isIdentifier(f) ? new Map() : locals);
549
708
  if (/Effect$/.test(op))
550
709
  [v, q2] = v.t === 'eff' ? v.run(q2) : refuse(f, `${m}.${op}'s function returns other than an effect`);
551
710
  if (base === 'modify') {
552
711
  if (v.t !== 'tuple' || v.xs.length !== 2)
553
712
  return refuse(f, `${m}.${op}'s function returns other than [result, value]`);
554
- return [v.xs[0], put(v.xs[1], q2)];
713
+ return [v.xs[0], recordRefOp(put(v.xs[1], q2), name)];
555
714
  }
556
- return [answer === 'old' ? c : answer === 'new' ? v : undef, put(v, q2)];
715
+ return [answer === 'old' ? c : answer === 'new' ? v : undef, recordRefOp(put(v, q2), name)];
557
716
  }), q0];
558
717
  }
559
718
  }
@@ -561,53 +720,140 @@ export function runner(E) {
561
720
  const { Effect, Exit, Cause, Clock } = E, v4 = 'TxRef' in E;
562
721
  if (!Effect?.runSyncExit)
563
722
  throw new Error('effect: give the `effect` package itself (import * as effect from \'effect\')');
564
- let now = 0;
723
+ let now = 0, onClock;
724
+ const readMillis = () => { onClock?.(now); return now; };
565
725
  // A Clock at `now`: 4.x names its unsafe reads currentTime<X>Unsafe, 3.x unsafeCurrentTime<X>.
726
+ // Effect.fn span tracing reads nanos internally; only millisecond reads observe the service's clock.
566
727
  const unsafe = (x) => (v4 ? `currentTime${x}Unsafe` : `unsafeCurrentTime${x}`), ns = () => BigInt(now) * 1000000n;
567
728
  // (a sleep, a retry's or a repeat's, passes at once: the clock moves on by its duration)
568
- const clock = Object.create(Effect.runSync(v4 ? Effect.clockWith((c) => Effect.succeed(c)) : Effect.clock), { [unsafe('Millis')]: { value: () => now }, currentTimeMillis: { value: Effect.sync(() => now) }, [unsafe('Nanos')]: { value: ns }, currentTimeNanos: { value: Effect.sync(ns) },
729
+ const clock = Object.create(Effect.runSync(v4 ? Effect.clockWith((c) => Effect.succeed(c)) : Effect.clock), { [unsafe('Millis')]: { value: readMillis }, currentTimeMillis: { value: Effect.sync(readMillis) }, [unsafe('Nanos')]: { value: ns }, currentTimeNanos: { value: Effect.sync(ns) },
569
730
  sleep: { value: (d) => Effect.sync(() => { now += E.Duration.toMillis(d); }) } });
570
- const exit = (eff, t) => {
731
+ const exit = (eff, t, observeClock) => {
571
732
  if (!Effect.isEffect(eff))
572
733
  return { ok: false, error: `not an effect: ${String(eff).slice(0, 60)}` };
573
734
  now = t;
735
+ onClock = observeClock;
574
736
  // (3.x on a scheduler of its own, so a fiber left waiting, a transaction that retries, is interrupted at once: it
575
737
  // would otherwise wake and commit inside a later request)
576
738
  let x, waiting;
577
- if (v4) {
578
- x = Effect.runSyncExit(Effect.provideService(eff, Clock.Clock, clock));
579
- waiting = Exit.isSuccess(x) ? undefined : (x.cause.reasons ?? []).map((r) => r.defect).find((d) => d && typeof d === 'object' && 'fiber' in d);
580
- waiting?.fiber.interruptUnsafe();
581
- }
582
- else {
583
- // (on a scheduler of its own: what yields to it (a SynchronizedRef's lock) runs on when it is flushed; a fiber still
584
- // waiting then is interrupted there)
585
- const sch = new E.Scheduler.SyncScheduler();
586
- x = Effect.runSyncExit(Effect.withScheduler(Effect.withClock(eff, clock), sch));
587
- const fiber = Exit.isSuccess(x) ? undefined : x.cause.defect?.fiber;
588
- if (fiber) {
589
- for (let i = 0; i < 64 && !(x = fiber.unsafePoll()); i++)
590
- sch.flush();
591
- if (!x) {
592
- waiting = { fiber };
593
- fiber.unsafeInterruptAsFork(E.FiberId.none);
594
- sch.flush();
739
+ try {
740
+ if (v4) {
741
+ x = Effect.runSyncExit(Effect.provideService(eff, Clock.Clock, clock));
742
+ waiting = Exit.isSuccess(x) ? undefined : (x.cause.reasons ?? []).map((r) => r.defect).find((d) => d && typeof d === 'object' && 'fiber' in d);
743
+ waiting?.fiber.interruptUnsafe();
744
+ }
745
+ else {
746
+ // (on a scheduler of its own: what yields to it (a SynchronizedRef's lock) runs on when it is flushed; a fiber still
747
+ // waiting then is interrupted there)
748
+ const sch = new E.Scheduler.SyncScheduler();
749
+ x = Effect.runSyncExit(Effect.withScheduler(Effect.withClock(eff, clock), sch));
750
+ const fiber = Exit.isSuccess(x) ? undefined : x.cause.defect?.fiber;
751
+ if (fiber) {
752
+ for (let i = 0; i < 64 && !(x = fiber.unsafePoll()); i++)
753
+ sch.flush();
754
+ if (!x) {
755
+ waiting = { fiber };
756
+ fiber.unsafeInterruptAsFork(E.FiberId.none);
757
+ sch.flush();
758
+ }
595
759
  }
596
760
  }
597
761
  }
762
+ finally {
763
+ onClock = undefined;
764
+ }
598
765
  if (x && Exit.isSuccess(x))
599
766
  return { ok: true, value: x.value };
600
767
  return { ok: false, error: waiting ? 'it waits (an effect that suspends: a transaction that retries, a fiber it waits for)' : String(Cause.pretty(x.cause)).split('\n')[0] };
601
768
  };
602
- const run = (eff, t = now) => { const x = exit(eff, t); if (!x.ok)
769
+ const run = (eff, t = now, observeClock) => { const x = exit(eff, t, observeClock); if (!x.ok)
603
770
  throw new Error(x.error); return x.value; };
604
771
  return { run, exit, get: (mod, ref) => run(E[mod].get(ref)), set: (mod, ref, v) => run(E[mod].set(ref, v)) };
605
772
  }
773
+ // Decide single-step atomicity exclusively from what the reader actually read and inlined per method (no parallel AST walk).
774
+ function analyzeAtomicity(model, tracker, file) {
775
+ const methodNames = [...new Set(model.events.map(e => e.call))];
776
+ const unclassified = methodNames.filter(n => !tracker.methods.has(n));
777
+ const multiMethods = [], sleptClockMethods = [];
778
+ const multiLocks = new Set(), lockedMultiMethods = [];
779
+ for (const name of methodNames) {
780
+ const a = tracker.methods.get(name);
781
+ if (!a)
782
+ continue;
783
+ if (a.units >= 2)
784
+ multiMethods.push(name);
785
+ if (a.stateAfterSleptClock)
786
+ sleptClockMethods.push(name);
787
+ if (a.multiOpLocks.length) {
788
+ lockedMultiMethods.push(name);
789
+ a.multiOpLocks.forEach(l => multiLocks.add(l));
790
+ }
791
+ }
792
+ const lockGapMethods = [];
793
+ if (multiLocks.size) {
794
+ const soleLock = multiLocks.size === 1 ? [...multiLocks][0] : undefined;
795
+ for (const name of methodNames) {
796
+ const a = tracker.methods.get(name);
797
+ if (!a || a.rawStateOps === 0)
798
+ continue;
799
+ if (a.unlockedStateOps > 0 || !soleLock || a.locksUsed.length !== 1 || a.locksUsed[0] !== soleLock)
800
+ lockGapMethods.push(name);
801
+ }
802
+ }
803
+ // Closure `let`/mutable state in Effect services is refused unless provably touched only inside one atomic step.
804
+ const unsafeClosureMethods = methodNames.filter(name => {
805
+ const a = tracker.methods.get(name);
806
+ return !!a && a.closureStateTouched.length > 0 && (a.closureMultiStep || a.units >= 2 || a.stateAfterSleptClock || lockGapMethods.includes(name));
807
+ });
808
+ if (unsafeClosureMethods.length || (tracker.mutableClosure.size > 0 && (multiMethods.length || sleptClockMethods.length || lockGapMethods.length || unclassified.length))) {
809
+ const touchedNames = [...new Set(methodNames.flatMap(n => tracker.methods.get(n)?.closureStateTouched ?? []))];
810
+ const names = touchedNames.length ? touchedNames : [...tracker.mutableClosure.keys()];
811
+ const firstNode = tracker.mutableClosure.get(names[0]);
812
+ const at = firstNode ? where(firstNode) : file;
813
+ const whereMethods = unsafeClosureMethods.length ? unsafeClosureMethods : [...new Set([...multiMethods, ...sleptClockMethods, ...lockGapMethods, ...unclassified])];
814
+ return {
815
+ multiMethods,
816
+ refusal: {
817
+ where: at,
818
+ what: `closure state ${names.join(', ')} is not provably confined to one atomic step (${whereMethods.join(', ')}): concurrent calls can interleave; use Ref / Ref.modify, a Semaphore(1) lock across all stateful methods, or one synchronous Effect.sync step`,
819
+ },
820
+ };
821
+ }
822
+ if (unclassified.length) {
823
+ return { multiMethods, nonAtomicReason: `${unclassified.join(', ')} could not be classified as a single atomic step` };
824
+ }
825
+ if (multiMethods.length) {
826
+ const refNames = [...new Set(multiMethods.flatMap(n => tracker.methods.get(n)?.touchedState ?? []))];
827
+ const verb = multiMethods.length === 1 ? 'reads and writes' : 'read and write';
828
+ const pron = multiMethods.length === 1 ? 'it' : 'them';
829
+ return {
830
+ multiMethods,
831
+ nonAtomicReason: `${multiMethods.join(', ')} ${verb} ${refNames.length ? refNames.join(', ') : 'state'} in separate steps; concurrent calls can interleave: make ${pron} atomic with Ref.modify, a Semaphore(1) lock or a transaction`,
832
+ };
833
+ }
834
+ if (sleptClockMethods.length) {
835
+ const refNames = [...new Set(sleptClockMethods.flatMap(n => tracker.methods.get(n)?.touchedState ?? []))];
836
+ return {
837
+ multiMethods: sleptClockMethods,
838
+ nonAtomicReason: `${sleptClockMethods.join(', ')} reads the clock and updates ${refNames.length ? refNames.join(', ') : 'state'} across a suspension; concurrent calls can interleave: remove the suspension or guard all stateful methods with a Semaphore(1) lock`,
839
+ };
840
+ }
841
+ if (lockGapMethods.length) {
842
+ const verb = lockGapMethods.length === 1 ? 'accesses' : 'access';
843
+ return {
844
+ multiMethods,
845
+ nonAtomicReason: `${lockGapMethods.join(', ')} ${verb} state outside the Semaphore(1) lock held by ${lockedMultiMethods.join(', ')}; concurrent calls can interleave: guard all stateful methods with the same Semaphore(1) lock, or use Ref.modify or a transaction`,
846
+ };
847
+ }
848
+ return { multiMethods: [] };
849
+ }
606
850
  export function extractEffect(at, opts = {}) {
607
- let m, code, file, E;
851
+ let m, code, file, E, nonAtomicReason;
852
+ const tracker = makeAtomTracker();
608
853
  try {
609
854
  ;
610
855
  ({ code, file } = sourceOf(at, opts.file, 'input.ts'));
856
+ assertNoReservedHarness(code, file, opts.files);
611
857
  E = opts.effect ?? beside(file, 'effect');
612
858
  if (!E)
613
859
  throw new Refusal(file, 'no effect package resolves from the file (install it in its project, or give it: {effect: await import(\'effect\')})');
@@ -620,15 +866,25 @@ export function extractEffect(at, opts = {}) {
620
866
  const pr = modelled(code, file, entry, E, opts);
621
867
  if (pr)
622
868
  return pr;
623
- if (opts.fibers !== false) {
624
- const f = fibered(code, file, entry, E, opts);
625
- if (f)
626
- return f;
869
+ // Explicit fibers: true or multi-transaction STM/TxRef services use the multi-fiber lifter directly (preserving STM lifting and refusals).
870
+ if (opts.fibers === true || (opts.fibers !== false && TX.test(code))) {
871
+ const fl = fibered(code, file, entry, E, opts);
872
+ if (fl && 'ok' in fl)
873
+ return fl;
627
874
  }
628
- m = readFactory(code, placed(file), { ...opts, entry }, s => factoryOf(s, entry));
875
+ m = readFactory(code, placed(file), { ...opts, entry }, s => factoryOf(s, entry, tracker));
629
876
  m.file = file;
630
877
  if (!opts.entry)
631
878
  m.notes.unshift(`the entry inferred: ${entry}, the file's one make effect`);
879
+ const analysis = analyzeAtomicity(m, tracker, file);
880
+ if (analysis.refusal)
881
+ return { ok: false, refusals: [analysis.refusal], notes: [] };
882
+ nonAtomicReason = analysis.nonAtomicReason;
883
+ if (analysis.multiMethods.length && opts.fibers !== false) {
884
+ const fl = fibered(code, file, entry, E, opts, nonAtomicReason, m.declSpans);
885
+ if (fl && 'ok' in fl)
886
+ return fl;
887
+ }
632
888
  }
633
889
  catch (e) {
634
890
  if (e instanceof Refusal)
@@ -638,15 +894,22 @@ export function extractEffect(at, opts = {}) {
638
894
  // The modules the code imports, by specifier (effect, effect/<Module>), and the check's runner.
639
895
  const model = m, modules = { effect: E, ...Object.fromEntries(Object.entries(E).map(([k, x]) => [`effect/${k}`, x])), 'gdp-wired:effect': runner(E), ...opts.modules };
640
896
  const schedules = found;
641
- return { ...fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model), ...(schedules.length ? { schedules } : {}) };
897
+ const checkOpts = nonAtomicReason ? { ...opts.check, lawCrossCheck: false } : opts.check;
898
+ const out = { ...fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...checkOpts, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model), ...(schedules.length ? { schedules } : {}) };
899
+ if (nonAtomicReason && out.ok && out.rule) {
900
+ const token = out.evidence ?? {};
901
+ rememberNative(token, { enabled: false, complete: false, scope: 'sampled', reason: nonAtomicReason, observations: [] });
902
+ attachSource(out.rule, token, out.invariants ?? []);
903
+ }
904
+ return out;
642
905
  }
643
906
  function modelled(code, file, entry, E, opts) {
644
907
  if (!/\b(Queue|Semaphore|makeSemaphore|unsafeMakeSemaphore)\b/.test(code))
645
908
  return undefined;
646
- const s = setupOf(code, placed(file), {}, opts.files), w = rewritePrims(s, factoryOf(s, entry), x => apiOf(s, x), V4, { params: !!opts.capacityParam });
909
+ const s = setupOf(code, placed(file), {}, opts.files), f0 = factoryOf(s, entry), w = rewritePrims(s, f0, x => apiOf(s, x), V4, { params: !!opts.capacityParam });
647
910
  if (!w)
648
911
  return undefined;
649
- const x = extractEffect(w.code, { ...opts, capacityParam: false, file: normalize(placed(file)), entry, effect: E, perFiber: w.prims.flatMap(p => (p.kind === 'semaphore' ? [`${p.name}_held`] : [])) });
912
+ const x = extractEffect(w.code, { ...opts, check: { ...opts.check, lawCrossCheck: false }, capacityParam: false, file: normalize(placed(file)), entry, effect: E, perFiber: w.prims.flatMap(p => (p.kind === 'semaphore' ? [`${p.name}_held`] : [])) });
650
913
  if (!x.ok || !x.rule)
651
914
  return { ...x, notes: [...w.notes, ...x.notes] };
652
915
  const r = x.rule;
@@ -670,8 +933,13 @@ function modelled(code, file, entry, E, opts) {
670
933
  return { ...p, invariants: [r.law(`${p.name} never has more permits taken than ${typeof p.permits === 'number' ? `its ${p.permits}` : p.permits}`, st => val(st, f('taken')).atMost(total(st))), r.law(`${p.name}'s permits taken are those its fibers hold`, st => val(st, f('taken')).eq(held(st)))],
671
934
  laws: [r.law(`${p.name} is never released past what was taken`, st => val(st, f('taken')).atLeast(0))], lemmas };
672
935
  });
673
- const lemmas = prims.flatMap(p => p.lemmas ?? []);
674
- return { ...x, invariants: [...x.invariants ?? [], ...prims.flatMap(p => p.invariants)], notes: [...w.notes, ...x.notes], primitives: prims, ...(lemmas.length ? { lemmas } : {}) };
936
+ const lemmas = prims.flatMap(p => p.lemmas ?? []), invariants = [...x.invariants ?? [], ...prims.flatMap(p => p.invariants)];
937
+ // Rewritten Queue/Semaphore models do not run native primitives; never treat their check as native source confirmation.
938
+ if (!x.fibers && x.evidence) {
939
+ rememberNative(x.evidence, { enabled: false, complete: false, scope: 'sampled', reason: 'Effect Queue/Semaphore primitives are checked through a rewritten model, not native source replay', observations: [] });
940
+ attachSource(x.rule, x.evidence, invariants);
941
+ }
942
+ return { ...x, invariants, notes: [...w.notes, ...x.notes], primitives: prims, ...(lemmas.length ? { lemmas } : {}), ...(f0.declSpans ? { declSpans: f0.declSpans } : {}) };
675
943
  }
676
944
  // work and watchdogMs are PER LEMMA, like the legacy ms option, not a
677
945
  // whole-call grant. Every child is clamped to any enclosing work/watchdog
@@ -722,73 +990,175 @@ export function withLemmas(x, opts = {}) {
722
990
  // (`__gdp_pc`) and what it carries from one step to the next (its arguments, its locals) in Refs of its own, read and
723
991
  // checked as any service; then lift (core/system.ts) makes those Refs every fiber's at once (maps keyed by `fiber`, an
724
992
  // input), the service's own Refs shared, and each request one fiber's next step.
725
- const QUIET = new Set(['Effect.fail', 'Effect.failSync', 'Effect.die', 'Effect.dieMessage', 'Effect.void', 'Effect.sleep', 'Effect.yieldNow', 'Effect.txRetry', 'STM.fail', 'STM.die', 'STM.retry', ...[...LOGS].map(l => `Effect.${l}`)]);
993
+ const QUIET = new Set(['Effect.fail', 'Effect.failSync', 'Effect.die', 'Effect.dieMessage', 'Effect.void', 'Effect.unit', 'Effect.succeed', 'Effect.sync', 'Effect.sleep', 'Effect.yieldNow', 'Effect.txRetry', 'Clock.currentTimeMillis', 'STM.fail', 'STM.failSync', 'STM.die', 'STM.dieMessage', 'STM.void', 'STM.unit', 'STM.succeed', 'STM.sync', 'STM.retry', 'STM.check', ...[...LOGS].map(l => `Effect.${l}`)]);
726
994
  const TX = /\b(TRef|TxRef|STM)\.|Effect\.tx\b/, WAITS = new Set(['Effect.txRetry', 'STM.retry']);
727
- function fibered(code, file, entry, E, opts) {
995
+ function fibered(code, file, entry, E, opts, reasonOverride, origDeclSpans) {
728
996
  const s = setupOf(code, placed(file), {}, opts.files), f = factoryOf(s, entry);
997
+ const declSpans = origDeclSpans ?? f.declSpans;
729
998
  const failing = (y) => { const x = y.expression && strip(y.expression); return !!x && (ts.isNewExpression(x) || /^(Effect|STM)\.(fail|failSync|die|dieMessage)$/.test((ts.isCallExpression(x) ? callOf(s, x) : '') ?? '')); };
999
+ // Collect the service's declared Refs and Semaphore(1) locks from make's body.
1000
+ const serviceRefs = new Set(), serviceLocks = new Set();
1001
+ if (f.fn.body && ts.isBlock(f.fn.body)) {
1002
+ for (const st of f.fn.body.statements) {
1003
+ if (!ts.isVariableStatement(st))
1004
+ continue;
1005
+ for (const d of st.declarationList.declarations) {
1006
+ if (!ts.isIdentifier(d.name) || !d.initializer)
1007
+ continue;
1008
+ const init = strip(d.initializer), call = ts.isYieldExpression(init) && init.expression ? strip(init.expression) : init;
1009
+ const api = callOf(s, call) ?? '', [m = '', op = ''] = api.split('.');
1010
+ if (REFS.has(m) && MAKES.includes(op))
1011
+ serviceRefs.add(d.name.text);
1012
+ else if (m === 'Semaphore' || /^Effect\.(unsafeM|m)akeSemaphore$/.test(api)) {
1013
+ const n = call.arguments[0];
1014
+ if (n && ts.isNumericLiteral(n) && n.text === '1')
1015
+ serviceLocks.add(d);
1016
+ }
1017
+ }
1018
+ }
1019
+ }
1020
+ const lockOf = (x) => {
1021
+ const d = x && ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.valueDeclaration : undefined;
1022
+ return d && serviceLocks.has(d) ? d : undefined;
1023
+ };
1024
+ const lockCall = (e) => {
1025
+ if (e.arguments.length !== 1)
1026
+ return undefined;
1027
+ const callee = strip(e.expression), body = e.arguments[0];
1028
+ if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'withPermit') {
1029
+ const lock = lockOf(callee.expression);
1030
+ return lock ? { lock, body } : undefined;
1031
+ }
1032
+ if (ts.isCallExpression(callee)) {
1033
+ const inner = strip(callee.expression), n = callee.arguments.at(-1);
1034
+ if (ts.isPropertyAccessExpression(inner) && memberName(inner.name) === 'withPermits' && n && ts.isNumericLiteral(n) && n.text === '1') {
1035
+ const lock = lockOf(inner.expression) ?? (apiOf(s, inner) === 'Semaphore.withPermits' ? lockOf(callee.arguments[0]) : undefined);
1036
+ if (lock)
1037
+ return { lock, body };
1038
+ }
1039
+ }
1040
+ return undefined;
1041
+ };
730
1042
  // How many effects on the state a piece of a method runs one after another, each a point another fiber's step may
731
- // come between: a Ref or TRef operation, a transaction or a lock's body one each; an Effect.gen's or a helper's body
732
- // counted through; a branch its larger side; a repeat several; a failure, a log, a sleep or a wait none.
1043
+ // come between: a Ref or TRef operation, a transaction or a Semaphore(1) lock's body one each; an Effect.gen's or a
1044
+ // helper's body counted through; a branch its larger side; a repeat several; a failure, a log, a sleep, a Clock read
1045
+ // or a wait none.
733
1046
  const TXS = new Set(['Effect.tx', 'STM.gen', 'STM.commit']);
734
- const units = (n) => {
1047
+ const makeCtx = (raw = false) => ({ raw, inTx: false, refs: new Set(), locks: new Set(), lockedMulti: new Set(), unlockedOps: 0, seen: new Set() });
1048
+ const units = (n, ctx) => {
735
1049
  if (ts.isFunctionLike(n))
736
1050
  return 0;
737
1051
  if (ts.isIfStatement(n))
738
- return units(n.expression) + Math.max(units(n.thenStatement), n.elseStatement ? units(n.elseStatement) : 0);
1052
+ return units(n.expression, ctx) + Math.max(units(n.thenStatement, ctx), n.elseStatement ? units(n.elseStatement, ctx) : 0);
739
1053
  if (ts.isConditionalExpression(n))
740
- return units(n.condition) + Math.max(units(n.whenTrue), units(n.whenFalse));
1054
+ return units(n.condition, ctx) + Math.max(units(n.whenTrue, ctx), units(n.whenFalse, ctx));
741
1055
  // (a yield inside the effect's arguments runs before it: its own points first)
742
1056
  if (ts.isYieldExpression(n)) {
743
1057
  let inner = 0;
744
1058
  if (n.expression)
745
- ts.forEachChild(n.expression, c => { inner += units(c); });
746
- return inner + (n.expression ? ran(n.expression) : 0);
1059
+ ts.forEachChild(n.expression, c => { inner += units(c, ctx); });
1060
+ return inner + (n.expression ? ran(n.expression, ctx) : 0);
747
1061
  }
748
1062
  let t = 0;
749
- ts.forEachChild(n, c => { t += units(c); });
1063
+ ts.forEachChild(n, c => { t += units(c, ctx); });
750
1064
  return t;
751
1065
  };
752
1066
  const helper = (x) => { const d = ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.valueDeclaration : undefined; return d && ts.isVariableDeclaration(d) && d.initializer ? fnOf(s, d.initializer) ?? genOf(s, d.initializer) : undefined; };
753
- const bodyUnits = (fn) => (!fn.body ? 0 : ts.isBlock(fn.body) ? units(fn.body) : ran(fn.body));
754
- const ran = (e0) => {
1067
+ const bodyUnits = (fn, ctx) => (!fn.body ? 0 : ts.isBlock(fn.body) ? units(fn.body, ctx) : ran(fn.body, ctx));
1068
+ const ran = (e0, ctx) => {
755
1069
  const e = strip(e0);
756
1070
  if (ts.isNewExpression(e))
757
1071
  return 0;
758
1072
  const api = (ts.isCallExpression(e) ? callOf(s, e) : apiOf(s, e)) ?? '';
759
1073
  if (QUIET.has(api))
760
1074
  return 0;
761
- if (TXS.has(api))
762
- return 1;
1075
+ if (TXS.has(api)) {
1076
+ const innerCtx = { ...ctx, raw: true, inTx: true };
1077
+ let inner = 1;
1078
+ if (ts.isCallExpression(e)) {
1079
+ if (api === 'STM.gen') {
1080
+ const g = genOf(s, e, 'STM.gen');
1081
+ inner = g ? bodyUnits(g, innerCtx) : 1;
1082
+ }
1083
+ else if (e.arguments[0])
1084
+ inner = ran(e.arguments[0], innerCtx);
1085
+ }
1086
+ ctx.unlockedOps += 0; // transactions serialize via STM, not a Semaphore lock
1087
+ return ctx.raw ? inner : inner > 0 ? 1 : 0;
1088
+ }
763
1089
  if (ts.isCallExpression(e)) {
1090
+ const lc = lockCall(e);
1091
+ if (lc) {
1092
+ const innerCtx = { ...ctx, raw: true, inLock: lc.lock };
1093
+ const inner = ran(lc.body, innerCtx);
1094
+ if (inner > 0) {
1095
+ ctx.locks.add(lc.lock);
1096
+ if (inner >= 2)
1097
+ ctx.lockedMulti.add(lc.lock);
1098
+ }
1099
+ return ctx.raw ? inner : inner > 0 ? 1 : 0;
1100
+ }
764
1101
  const callee = strip(e.expression);
765
1102
  if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'pipe' && !api) {
766
- const fs = e.arguments.map(a => callOf(s, a) ?? apiOf(s, a) ?? ''), head = ran(callee.expression);
767
- return fs.includes('STM.commit') ? 1 : fs.includes('Effect.repeat') && head ? 2 : head;
1103
+ const fs = e.arguments.map(a => callOf(s, a) ?? apiOf(s, a) ?? '');
1104
+ if (fs.includes('STM.commit')) {
1105
+ const inner = ran(callee.expression, { ...ctx, raw: true, inTx: true });
1106
+ return ctx.raw ? inner : inner > 0 ? 1 : 0;
1107
+ }
1108
+ const head = ran(callee.expression, ctx);
1109
+ return fs.includes('Effect.repeat') && head ? Math.max(2, head) : head;
768
1110
  }
769
- // (a lock's body: one at a time)
770
- if (ts.isCallExpression(callee) && ts.isPropertyAccessExpression(strip(callee.expression)) && /^withPermits?$/.test(memberName(strip(callee.expression).name)))
771
- return e.arguments[0] && ran(e.arguments[0]) ? 1 : 0;
772
1111
  if (api === 'Effect.gen') {
773
1112
  const g = genOf(s, e);
774
- return g ? bodyUnits(g) : 1;
1113
+ return g ? bodyUnits(g, ctx) : 1;
775
1114
  }
776
1115
  if (api === 'Effect.retry')
777
- return ran(e.arguments[0]);
778
- if (api === 'Effect.repeat')
779
- return ran(e.arguments[0]) ? 2 : 0;
1116
+ return e.arguments[0] ? ran(e.arguments[0], ctx) : 1;
1117
+ if (api === 'Effect.repeat') {
1118
+ const h = e.arguments[0] ? ran(e.arguments[0], ctx) : 1;
1119
+ return h ? Math.max(2, h) : 0;
1120
+ }
1121
+ const [m = '', op = ''] = api.split('.');
1122
+ if (REFS.has(m)) {
1123
+ const r = e.arguments[0] && strip(e.arguments[0]);
1124
+ if (r && ts.isIdentifier(r) && serviceRefs.has(r.text))
1125
+ ctx.refs.add(r.text);
1126
+ if (!ctx.inLock && !ctx.inTx)
1127
+ ctx.unlockedOps++;
1128
+ let extra = 0;
1129
+ if (/Effect$/.test(op) && e.arguments[1]) {
1130
+ const cb = fnOf(s, e.arguments[1]);
1131
+ if (cb)
1132
+ extra = bodyUnits(cb, ctx);
1133
+ }
1134
+ return 1 + extra;
1135
+ }
780
1136
  const h = helper(callee);
781
- if (h)
782
- return bodyUnits(h);
1137
+ if (h) {
1138
+ if (ctx.seen.has(h))
1139
+ return 1;
1140
+ ctx.seen.add(h);
1141
+ const n = bodyUnits(h, ctx);
1142
+ ctx.seen.delete(h);
1143
+ return n;
1144
+ }
783
1145
  }
784
1146
  if (ts.isIdentifier(e)) {
785
1147
  const d = s.checker.getSymbolAtLocation(e)?.valueDeclaration;
786
- if (d && ts.isVariableDeclaration(d) && d.initializer && !fnOf(s, d.initializer))
787
- return ran(d.initializer);
1148
+ if (d && ts.isVariableDeclaration(d) && d.initializer && !fnOf(s, d.initializer)) {
1149
+ if (ctx.seen.has(d))
1150
+ return 1;
1151
+ ctx.seen.add(d);
1152
+ const n = ran(d.initializer, ctx);
1153
+ ctx.seen.delete(d);
1154
+ return n;
1155
+ }
788
1156
  }
1157
+ if (!ctx.inLock && !ctx.inTx)
1158
+ ctx.unlockedOps++;
789
1159
  return 1;
790
1160
  };
791
- const methods = [], several = [];
1161
+ const methods = [], several = [], metas = [];
792
1162
  for (const pr of f.obj.properties) {
793
1163
  const name = pr.name ? memberName(pr.name) : '';
794
1164
  let init = ts.isPropertyAssignment(pr) ? pr.initializer : ts.isShorthandPropertyAssignment(pr) ? pr.name : undefined;
@@ -799,13 +1169,15 @@ function fibered(code, file, entry, E, opts) {
799
1169
  const fn = init && fnOf(s, init);
800
1170
  if (!fn?.body)
801
1171
  continue;
1172
+ const rawCtx = makeCtx(true), rawOps = bodyUnits(fn, rawCtx);
1173
+ metas.push({ name, refs: rawCtx.refs, locks: rawCtx.locks, lockedMulti: rawCtx.lockedMulti, unlockedOps: rawCtx.unlockedOps, rawOps });
802
1174
  if (!ts.isFunctionExpression(fn) || !fn.asteriskToken || !ts.isBlock(fn.body)) {
803
- const n = bodyUnits(fn);
1175
+ const n = bodyUnits(fn, makeCtx(false));
804
1176
  if (n >= 2)
805
1177
  several.push([name, fn, n]);
806
1178
  continue;
807
1179
  }
808
- const stmts = fn.body.statements, per = stmts.map(units), units0 = stmts.flatMap((_, i) => (per[i] > 0 ? [i] : []));
1180
+ const stmts = fn.body.statements, per = stmts.map(st => units(st, makeCtx(false))), units0 = stmts.flatMap((_, i) => (per[i] > 0 ? [i] : []));
809
1181
  if (per.reduce((a, b) => a + b, 0) >= 2)
810
1182
  for (const [i, n] of per.entries())
811
1183
  if (n >= 2)
@@ -813,122 +1185,170 @@ function fibered(code, file, entry, E, opts) {
813
1185
  methods.push({ name, fn, at: init, units: units0, stmts });
814
1186
  }
815
1187
  const split = methods.filter(mt => mt.units.length >= 2 || several.some(([n]) => n === mt.name));
816
- if ((!split.length && !several.length) || (opts.fibers === undefined && !TX.test(code))) {
817
- if (split.length || several.length)
818
- s.notes.add(`${[...new Set([...split.map(mt => mt.name), ...several.map(([n]) => n)])].join(', ')} run several Ref operations one after another: each method is read as one step, which holds where calls don't interleave (fibers: true reads them as interleaving steps)`);
819
- return undefined;
1188
+ const multiNames = [...new Set([...split.map(mt => mt.name), ...several.map(([n]) => n)])];
1189
+ // Check cross-method lock consistency: if any method relies on a Semaphore(1) lock across >=2 raw state ops,
1190
+ // every stateful method must guard its state operations with that same Semaphore(1) lock.
1191
+ const multiLocks = new Set(), lockedMultiMethods = [];
1192
+ for (const mt of metas)
1193
+ if (mt.lockedMulti.size) {
1194
+ lockedMultiMethods.push(mt.name);
1195
+ mt.lockedMulti.forEach(l => multiLocks.add(l));
1196
+ }
1197
+ const lockGapMethods = [];
1198
+ if (multiLocks.size) {
1199
+ const soleLock = multiLocks.size === 1 ? [...multiLocks][0] : undefined;
1200
+ for (const mt of metas) {
1201
+ if (mt.rawOps === 0)
1202
+ continue;
1203
+ if (mt.unlockedOps > 0 || !soleLock || !mt.locks.has(soleLock) || mt.locks.size > 1)
1204
+ lockGapMethods.push(mt.name);
1205
+ }
820
1206
  }
821
- // (each step of a method read for many fibers is one statement of its body, with one effect on the state at most)
822
- for (const [name, at, n] of several)
823
- refuse(at, `${name}: ${text(at)} runs ${n} effects on the state one after another${ts.isStatement(at) ? ' in one statement' : ''}, and another fiber's step may come between them: write the method as Effect.fn('${name}')(function* ...) with each in a statement of its own (each a step), or in one transaction`);
824
- // Each split method's segments, the names each carries on, and the service written again.
825
- if (/\b__gdp_/.test(code))
826
- return refuse(s.sf.statements[0] ?? s.sf, 'a name of the code starts with __gdp_ (the names the fibers\' places and carried values are given)');
827
- const edits = [], decls = [], resumes = [], made = new Set(['__gdp_pc']);
828
- const tyOf = (n) => { const t = s.checker.getTypeAtLocation(n), str = s.checker.typeToString(s.checker.getBaseTypeOfLiteralType(t)); return t.flags & ts.TypeFlags.BooleanLike ? ['boolean', 'false'] : t.flags & ts.TypeFlags.NumberLike ? ['number', '0'] : t.isUnion() && t.types.every(u => u.isStringLiteral()) ? [s.checker.typeToString(t), JSON.stringify(t.types[0].value)] : t.flags & ts.TypeFlags.StringLike ? ['string', "''"] : refuse(n, `${text(n)} is carried from one step to the next, and is a ${str} (a number, a boolean or a string is carried)`); };
829
- split.forEach((mt, mi) => {
830
- const base = (mi + 1) * 100, K = mt.units.length, segs = [];
831
- mt.units.forEach((u, k) => segs.push([...mt.stmts.slice(k === 0 ? 0 : mt.units[k - 1] + 1, u + 1), ...(k === K - 1 ? mt.stmts.slice(u + 1) : [])]));
832
- for (const [k, seg] of segs.entries())
833
- for (const st of seg) {
834
- // (a later step's failing transaction: the call would end with the earlier steps' writes kept and this one's rolled
835
- // back, which a refusal of this step leaves the fiber waiting on instead)
836
- if (k > 0) {
837
- const go = (x, inner) => { if (ts.isYieldExpression(x) && inner && failing(x))
838
- refuse(x, `${mt.name}: a transaction that fails in a step after the first (the call ends there, its earlier steps' writes kept): fail in the first step, or wait (STM.check, Effect.txRetry) instead`); ts.forEachChild(x, c => go(c, inner || ts.isFunctionLike(x))); };
839
- go(st, false);
1207
+ let nonAtomicReason = reasonOverride;
1208
+ if (!nonAtomicReason && multiNames.length) {
1209
+ const refNames = [...new Set(multiNames.flatMap(n => [...(metas.find(mt => mt.name === n)?.refs ?? [])]))];
1210
+ const verb = multiNames.length === 1 ? 'reads and writes' : 'read and write';
1211
+ const pron = multiNames.length === 1 ? 'it' : 'them';
1212
+ nonAtomicReason = `${multiNames.join(', ')} ${verb} ${refNames.length ? refNames.join(', ') : 'state'} in separate steps; concurrent calls can interleave: make ${pron} atomic with Ref.modify, a Semaphore(1) lock or a transaction`;
1213
+ }
1214
+ else if (!nonAtomicReason && lockGapMethods.length) {
1215
+ const verb = lockGapMethods.length === 1 ? 'accesses' : 'access';
1216
+ nonAtomicReason = `${lockGapMethods.join(', ')} ${verb} state outside the Semaphore(1) lock held by ${lockedMultiMethods.join(', ')}; concurrent calls can interleave: guard all stateful methods with the same Semaphore(1) lock, or use Ref.modify or a transaction`;
1217
+ }
1218
+ if (!multiNames.length)
1219
+ return nonAtomicReason ? { nonAtomicReason } : undefined;
1220
+ if (opts.fibers === false)
1221
+ return { nonAtomicReason: nonAtomicReason };
1222
+ // For plain-Ref services (or when called after reader-driven atomicity detection), if lifting refuses
1223
+ // (e.g. non-scalar carried local, FunctionDeclaration helper, or multi-op expression), fall back cleanly so the
1224
+ // caller retains the sequential model with native confirmation explicitly disabled and nonAtomicReason attached.
1225
+ const canFallback = opts.fibers === undefined && (!!reasonOverride || !TX.test(code));
1226
+ try {
1227
+ // (each step of a method read for many fibers is one statement of its body, with one effect on the state at most)
1228
+ for (const [name, at, n] of several)
1229
+ refuse(at, `${name}: ${text(at)} runs ${n} effects on the state one after another${ts.isStatement(at) ? ' in one statement' : ''}, and another fiber's step may come between them: write the method as Effect.fn('${name}')(function* ...) with each in a statement of its own (each a step), or in one transaction`);
1230
+ // Each split method's segments, the names each carries on, and the service written again.
1231
+ if (/\b__gdp_/.test(code))
1232
+ return refuse(s.sf.statements[0] ?? s.sf, 'a name of the code starts with __gdp_ (the names the fibers\' places and carried values are given)');
1233
+ const edits = [], decls = [], resumes = [], made = new Set(['__gdp_pc']);
1234
+ const tyOf = (n) => { const t = s.checker.getTypeAtLocation(n), str = s.checker.typeToString(s.checker.getBaseTypeOfLiteralType(t)); return t.flags & ts.TypeFlags.BooleanLike ? ['boolean', 'false'] : t.flags & ts.TypeFlags.NumberLike ? ['number', '0'] : t.isUnion() && t.types.every(u => u.isStringLiteral()) ? [s.checker.typeToString(t), JSON.stringify(t.types[0].value)] : t.flags & ts.TypeFlags.StringLike ? ['string', "''"] : refuse(n, `${text(n)} is carried from one step to the next, and is a ${str} (a number, a boolean or a string is carried)`); };
1235
+ split.forEach((mt, mi) => {
1236
+ const base = (mi + 1) * 100, K = mt.units.length, segs = [];
1237
+ mt.units.forEach((u, k) => segs.push([...mt.stmts.slice(k === 0 ? 0 : mt.units[k - 1] + 1, u + 1), ...(k === K - 1 ? mt.stmts.slice(u + 1) : [])]));
1238
+ for (const [k, seg] of segs.entries())
1239
+ for (const st of seg) {
1240
+ // (a later step's failing transaction: the call would end with the earlier steps' writes kept and this one's rolled
1241
+ // back, which a refusal of this step leaves the fiber waiting on instead)
1242
+ if (k > 0) {
1243
+ const go = (x, inner) => { if (ts.isYieldExpression(x) && inner && failing(x))
1244
+ refuse(x, `${mt.name}: a transaction that fails in a step after the first (the call ends there, its earlier steps' writes kept): fail in the first step, or wait (STM.check, Effect.txRetry) instead`); ts.forEachChild(x, c => go(c, inner || ts.isFunctionLike(x))); };
1245
+ go(st, false);
1246
+ }
840
1247
  }
1248
+ // What a later step reads of an earlier one: the arguments and the locals declared at the top of a segment.
1249
+ const carried = new Map();
1250
+ for (const p of mt.fn.parameters)
1251
+ if (ts.isIdentifier(p.name))
1252
+ carried.set(p, p.name.text);
1253
+ segs.forEach(seg => seg.forEach(st => { if (ts.isVariableStatement(st))
1254
+ for (const d of st.declarationList.declarations)
1255
+ carried.set(d, ts.isIdentifier(d.name) ? d.name.text : refuse(d, `${mt.name}: ${text(d)} (a name is carried, not a pattern)`)); }));
1256
+ const usedIn = (seg) => { const u = new Set(); const go = (x) => { if (ts.isIdentifier(x)) {
1257
+ const d = s.checker.getSymbolAtLocation(x)?.valueDeclaration;
1258
+ if (d && carried.has(d))
1259
+ u.add(d);
1260
+ } ts.forEachChild(x, go); }; seg.forEach(go); return u; };
1261
+ const later = segs.map((_, k) => { const u = new Set(); segs.slice(k + 1).forEach(sg => usedIn(sg).forEach(d => u.add(d))); return u; });
1262
+ const ref = (d) => `__gdp_${mt.name}_${carried.get(d)}`;
1263
+ const kept = new Set();
1264
+ later.forEach(u => u.forEach(d => kept.add(d)));
1265
+ for (const d of kept) {
1266
+ const [t, zero] = tyOf(d);
1267
+ decls.push(`const ${ref(d)} = yield* __gdp_Ref.make<${t}>(${zero})`);
1268
+ made.add(ref(d));
841
1269
  }
842
- // What a later step reads of an earlier one: the arguments and the locals declared at the top of a segment.
843
- const carried = new Map();
844
- for (const p of mt.fn.parameters)
845
- if (ts.isIdentifier(p.name))
846
- carried.set(p, p.name.text);
847
- segs.forEach(seg => seg.forEach(st => { if (ts.isVariableStatement(st))
848
- for (const d of st.declarationList.declarations)
849
- carried.set(d, ts.isIdentifier(d.name) ? d.name.text : refuse(d, `${mt.name}: ${text(d)} (a name is carried, not a pattern)`)); }));
850
- const usedIn = (seg) => { const u = new Set(); const go = (x) => { if (ts.isIdentifier(x)) {
851
- const d = s.checker.getSymbolAtLocation(x)?.valueDeclaration;
852
- if (d && carried.has(d))
853
- u.add(d);
854
- } ts.forEachChild(x, go); }; seg.forEach(go); return u; };
855
- const later = segs.map((_, k) => { const u = new Set(); segs.slice(k + 1).forEach(sg => usedIn(sg).forEach(d => u.add(d))); return u; });
856
- const ref = (d) => `__gdp_${mt.name}_${carried.get(d)}`;
857
- const kept = new Set();
858
- later.forEach(u => u.forEach(d => kept.add(d)));
859
- for (const d of kept) {
860
- const [t, zero] = tyOf(d);
861
- decls.push(`const ${ref(d)} = yield* __gdp_Ref.make<${t}>(${zero})`);
862
- made.add(ref(d));
863
- }
864
- // (where each carried name is defined: a parameter, or the segment that declares it)
865
- const defined = (d, k) => (ts.isParameter(d) ? k === 0 : segs[k].some(st => st.pos <= d.pos && d.end <= st.end));
866
- const body = (seg, k) => {
867
- // (what it reads of earlier steps loaded first; what a later step reads stored last: defined here, or loaded here
868
- // and perhaps assigned again)
869
- const used = usedIn(seg);
870
- const loads = k === 0 ? '' : [...used].filter(d => !defined(d, k)).map(d => `let ${carried.get(d)} = yield* __gdp_Ref.get(${ref(d)})\n`).join('');
871
- const stores = [...later[k]].filter(d => defined(d, k) || used.has(d) || ts.isParameter(d) && k === 0).map(d => `yield* __gdp_Ref.set(${ref(d)}, ${carried.get(d)})\n`).join('');
872
- // (a return ends the call, its value left out (under fibers a step's result is no part of the rule): what it
873
- // returns is run, then the fiber goes back to where it starts. In a later step a failure outside a transaction ends
874
- // the call too, as a return (the earlier steps' writes kept, as Effect keeps them); a wait, or a failure in the
875
- // first step, leaves the fiber where it is)
876
- const textOf = (st) => {
877
- let t = st.getText();
878
- const rs = [];
879
- const go = (x) => { if (ts.isReturnStatement(x) || k > 0 && ts.isExpressionStatement(x) && ts.isYieldExpression(strip(x.expression)) && failing(strip(x.expression)))
880
- rs.push(x); if (!ts.isFunctionLike(x))
881
- ts.forEachChild(x, go); };
882
- go(st);
883
- for (const r of rs.reverse()) {
884
- const y = ts.isReturnStatement(r) ? r.expression && strip(r.expression) : strip(r.expression), fails = !!y && ts.isYieldExpression(y) && failing(y);
885
- // (a wait leaves the fiber where it is; so does a failure in the first step, which ends the call with nothing done)
886
- if (y && ts.isYieldExpression(y) && (WAITS.has(apiOf(s, strip(y.expression)) ?? '') || fails && k === 0))
887
- continue;
888
- const run = fails || !y ? '' : `${ts.isYieldExpression(y) ? '' : 'void '}(${y.getText()}); `;
889
- t = t.slice(0, r.getStart() - st.getStart()) + `{ ${run}${k > 0 ? 'yield* __gdp_Ref.set(__gdp_pc, 0); ' : ''}return }` + t.slice(r.end - st.getStart());
890
- }
891
- return t;
1270
+ // (where each carried name is defined: a parameter, or the segment that declares it)
1271
+ const defined = (d, k) => (ts.isParameter(d) ? k === 0 : segs[k].some(st => st.pos <= d.pos && d.end <= st.end));
1272
+ const body = (seg, k) => {
1273
+ // (what it reads of earlier steps loaded first; what a later step reads stored last: defined here, or loaded here
1274
+ // and perhaps assigned again)
1275
+ const used = usedIn(seg);
1276
+ const loads = k === 0 ? '' : [...used].filter(d => !defined(d, k)).map(d => `let ${carried.get(d)} = yield* __gdp_Ref.get(${ref(d)})\n`).join('');
1277
+ const stores = [...later[k]].filter(d => defined(d, k) || used.has(d) || ts.isParameter(d) && k === 0).map(d => `yield* __gdp_Ref.set(${ref(d)}, ${carried.get(d)})\n`).join('');
1278
+ // (a return ends the call, its value left out (under fibers a step's result is no part of the rule): what it
1279
+ // returns is run, then the fiber goes back to where it starts. In a later step a failure outside a transaction ends
1280
+ // the call too, as a return (the earlier steps' writes kept, as Effect keeps them); a wait, or a failure in the
1281
+ // first step, leaves the fiber where it is)
1282
+ const textOf = (st) => {
1283
+ let t = st.getText();
1284
+ const rs = [];
1285
+ const go = (x) => { if (ts.isReturnStatement(x) || k > 0 && ts.isExpressionStatement(x) && ts.isYieldExpression(strip(x.expression)) && failing(strip(x.expression)))
1286
+ rs.push(x); if (!ts.isFunctionLike(x))
1287
+ ts.forEachChild(x, go); };
1288
+ go(st);
1289
+ for (const r of rs.reverse()) {
1290
+ const y = ts.isReturnStatement(r) ? r.expression && strip(r.expression) : strip(r.expression), fails = !!y && ts.isYieldExpression(y) && failing(y);
1291
+ // (a wait leaves the fiber where it is; so does a failure in the first step, which ends the call with nothing done)
1292
+ if (y && ts.isYieldExpression(y) && (WAITS.has(apiOf(s, strip(y.expression)) ?? '') || fails && k === 0))
1293
+ continue;
1294
+ const run = fails || !y ? '' : `${ts.isYieldExpression(y) ? '' : 'void '}(${y.getText()}); `;
1295
+ t = t.slice(0, r.getStart() - st.getStart()) + `{ ${run}${k > 0 ? 'yield* __gdp_Ref.set(__gdp_pc, 0); ' : ''}return }` + t.slice(r.end - st.getStart());
1296
+ }
1297
+ return t;
1298
+ };
1299
+ return `${loads}${seg.map(textOf).join('\n')}\n${stores}yield* __gdp_Ref.set(__gdp_pc, ${k === K - 1 ? 0 : base + k + 2})`;
892
1300
  };
893
- return `${loads}${seg.map(textOf).join('\n')}\n${stores}yield* __gdp_Ref.set(__gdp_pc, ${k === K - 1 ? 0 : base + k + 2})`;
894
- };
895
- resumes.push(...segs.slice(1).map((seg, j) => `if (__gdp_p === ${base + j + 2}) {\n${body(seg, j + 1)}\n}`));
896
- const params = mt.fn.parameters.map(p => p.getText()).join(', ');
897
- edits.push([mt.fn.getStart(), mt.fn.end, `function* (${params}) {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\nif (__gdp_p !== 0) return yield* __gdp_resume()\n${body(segs[0], 0)}\n}`]);
898
- });
899
- const ret = f.fn.body.statements.at(-1);
900
- edits.push([ret.getStart(), ret.getStart(), `const __gdp_pc = yield* __gdp_Ref.make<number>(0)\n${decls.join('\n')}\nconst __gdp_resume = __gdp_Effect.fn('__gdp_resume')(function* () {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\n${resumes.join(' else ')}\n})\n`]);
901
- let out = code;
902
- for (const [a, b, t] of edits.sort((x, y) => y[0] - x[0]))
903
- out = out.slice(0, a) + t + out.slice(b);
904
- out = `import {Effect as __gdp_Effect, Ref as __gdp_Ref} from 'effect'\n${out}`;
905
- // One fiber: the service written again, read and checked as any.
906
- // (by its absolute path, `..` resolved: the checker reads the code written again there, not the file on disk)
907
- const one = extractEffect(out, { ...opts, file: normalize(placed(file)), entry, effect: E, fibers: false });
908
- if (!one.ok || !one.rule)
909
- return { ...one, notes: [`read as one fiber's steps (${split.map(mt => `${mt.name}: ${mt.units.length}`).join(', ')}), the service written again:`, out, ...one.notes] };
910
- const m0 = one.rule.machine, model = one.model;
911
- // (an integer is two naturals, x and x$neg)
912
- const local = (n0) => { const n = n0.replace(/\$neg$/, ''); return made.has(n) || !!opts.perFiber?.includes(n) || model.outputs.some(o => n === o || n.startsWith(`${o}_`)) || n === 'failed'; };
913
- const shared = Object.keys(m0.state).filter(n => !local(n));
914
- if (m0.inputs.includes('fiber'))
915
- return { ok: false, refusals: [{ where: file, what: 'a method takes an argument named fiber (the name the fibers are told apart by)' }], notes: [] };
916
- const lifted = lift(m0, 'fiber', shared);
917
- const parts = one.rule.parts;
918
- // (the kinds of the requests' choices kept; an integer is its two naturals, x and x$neg, as the machine has it)
919
- const named = new Set([...lifted.params, ...lifted.inputs]), whole = ([n]) => named.has(n) && !named.has(`${n}$neg`);
920
- // (and the shared integers' kinds: a law reads an integer of the service's as it does where the rule is one fiber's)
921
- const one2 = one.rule;
922
- const ints = [...one2.kindsOfState().filter(([n]) => shared.includes(n) && shared.includes(`${n}$neg`)), ...one2.kindsOfCells().filter(([n, k]) => k.vars(n).every(p => !local(p)))];
923
- const rule = asRule({ ...lifted, name: `${m0.name}, every fiber` }, Object.fromEntries([...parts.params, ...parts.inputs].filter(whole).concat(ints)));
924
- // Lifting is not transparent native replay: retain provenance, not the old journal.
925
- inheritSource(one.rule, rule);
926
- const names = (one.names ?? []).filter(n => !(n.role === 'state' && local(n.rule)) && n.role !== 'result' && !made.has(n.code));
927
- const inv = (one.invariants ?? []).filter(l => ![...JSON.stringify(l.holds).matchAll(/"name":"([^"]*)"/g)].some(m => local(m[1])));
928
- const steps = split.map((mt, mi) => ({ name: mt.name, steps: mt.units.length, base: (mi + 1) * 100 }));
929
- return { ...one, rule, names: [...names, { code: 'fiber', rule: 'fiber', role: 'input' }], invariants: inv, fibers: steps, replay: undefined,
930
- notes: [`calls from many fibers at once: ${split.map(mt => `${mt.name} is ${mt.units.length} steps`).join(', ')} (each transaction or Ref operation one), the fibers interleaving them: the rule is every fiber's (lift: each fiber's place and what it carries a map keyed by the input fiber, the service's Refs (${shared.filter(n => !n.endsWith('$neg')).join(', ')}) shared); each other method is one step. A request is one fiber's next step: a fiber in the middle of a call takes its next step whatever method the request names. A failure in a later step ends the call as a return does. A law reads the service's Refs`, ...one.notes],
931
- source: out };
1301
+ resumes.push(...segs.slice(1).map((seg, j) => `if (__gdp_p === ${base + j + 2}) {\n${body(seg, j + 1)}\n}`));
1302
+ const params = mt.fn.parameters.map(p => p.getText()).join(', ');
1303
+ edits.push([mt.fn.getStart(), mt.fn.end, `function* (${params}) {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\nif (__gdp_p !== 0) return yield* __gdp_resume()\n${body(segs[0], 0)}\n}`]);
1304
+ });
1305
+ const ret = f.fn.body.statements.at(-1);
1306
+ edits.push([ret.getStart(), ret.getStart(), `const __gdp_pc = yield* __gdp_Ref.make<number>(0)\n${decls.join('\n')}\nconst __gdp_resume = __gdp_Effect.fn('__gdp_resume')(function* () {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\n${resumes.join(' else ')}\n})\n`]);
1307
+ let out = code;
1308
+ for (const [a, b, t] of edits.sort((x, y) => y[0] - x[0]))
1309
+ out = out.slice(0, a) + t + out.slice(b);
1310
+ out = `import {Effect as __gdp_Effect, Ref as __gdp_Ref} from 'effect'\n${out}`;
1311
+ // One fiber: the service written again, read and checked as any.
1312
+ // (by its absolute path, `..` resolved: the checker reads the code written again there, not the file on disk)
1313
+ const one = extractEffect(out, { ...opts, check: { ...opts.check, lawCrossCheck: false }, file: normalize(placed(file)), entry, effect: E, fibers: false });
1314
+ if (!one.ok || !one.rule) {
1315
+ if (canFallback)
1316
+ return { nonAtomicReason: nonAtomicReason };
1317
+ return { ...one, notes: [`read as one fiber's steps (${split.map(mt => `${mt.name}: ${mt.units.length}`).join(', ')}), the service written again:`, out, ...one.notes] };
1318
+ }
1319
+ const m0 = one.rule.machine, model = one.model;
1320
+ // (an integer is two naturals, x and x$neg)
1321
+ const local = (n0) => { const n = n0.replace(/\$neg$/, ''); return made.has(n) || !!opts.perFiber?.includes(n) || model.outputs.some(o => n === o || n.startsWith(`${o}_`)) || n === 'failed'; };
1322
+ const shared = Object.keys(m0.state).filter(n => !local(n));
1323
+ if (m0.inputs.includes('fiber'))
1324
+ return { ok: false, refusals: [{ where: file, what: 'a method takes an argument named fiber (the name the fibers are told apart by)' }], notes: [] };
1325
+ const lifted = lift(m0, 'fiber', shared);
1326
+ const parts = one.rule.parts;
1327
+ // (the kinds of the requests' choices kept; an integer is its two naturals, x and x$neg, as the machine has it)
1328
+ const named = new Set([...lifted.params, ...lifted.inputs]), whole = ([n]) => named.has(n) && !named.has(`${n}$neg`);
1329
+ // (and the shared integers' kinds: a law reads an integer of the service's as it does where the rule is one fiber's)
1330
+ const one2 = one.rule;
1331
+ const ints = [...one2.kindsOfState().filter(([n]) => shared.includes(n) && shared.includes(`${n}$neg`)), ...one2.kindsOfCells().filter(([n, k]) => k.vars(n).every(p => !local(p)))];
1332
+ const rule = asRule({ ...lifted, name: `${m0.name}, every fiber` }, Object.fromEntries([...parts.params, ...parts.inputs].filter(whole).concat(ints)));
1333
+ // Lifting is not transparent native replay: retain provenance and the explicit non-atomic reason, never the old journal.
1334
+ inheritSource(one.rule, rule);
1335
+ const names = (one.names ?? []).filter(n => !(n.role === 'state' && local(n.rule)) && n.role !== 'result' && !made.has(n.code));
1336
+ const inv = (one.invariants ?? []).filter(l => ![...JSON.stringify(l.holds).matchAll(/"name":"([^"]*)"/g)].some(m => local(m[1])));
1337
+ if (nonAtomicReason) {
1338
+ const token = {};
1339
+ rememberNative(token, { enabled: false, complete: false, scope: 'sampled', reason: nonAtomicReason, observations: [] });
1340
+ attachSource(rule, token, inv);
1341
+ }
1342
+ const steps = split.map((mt, mi) => ({ name: mt.name, steps: mt.units.length, base: (mi + 1) * 100 }));
1343
+ return { ...one, rule, names: [...names, { code: 'fiber', rule: 'fiber', role: 'input' }], invariants: inv, fibers: steps, replay: undefined, ...(declSpans ? { declSpans } : {}),
1344
+ notes: [`calls from many fibers at once: ${split.map(mt => `${mt.name} is ${mt.units.length} steps`).join(', ')} (each transaction or Ref operation one), the fibers interleaving them: the rule is every fiber's (lift: each fiber's place and what it carries a map keyed by the input fiber, the service's Refs (${shared.filter(n => !n.endsWith('$neg')).join(', ')}) shared); each other method is one step. A request is one fiber's next step: a fiber in the middle of a call takes its next step whatever method the request names. A failure in a later step ends the call as a return does. A law reads the service's Refs`, ...one.notes],
1345
+ source: out };
1346
+ }
1347
+ catch (e) {
1348
+ if (canFallback && e instanceof Refusal)
1349
+ return { nonAtomicReason: nonAtomicReason };
1350
+ throw e;
1351
+ }
932
1352
  }
933
1353
  // A run of every fiber's rule as what each fiber does: starts a call (with its arguments), or takes the next step of the
934
1354
  // call it is in.
@@ -944,16 +1364,16 @@ function scheduleEntry(code, file, opts) {
944
1364
  return undefined;
945
1365
  const s = setupOf(code, placed(file), {}, opts.files), found = [];
946
1366
  for (const st of s.sf.statements) {
947
- const decls = ts.isVariableStatement(st) ? st.declarationList.declarations.filter(d => ts.isIdentifier(d.name) && d.initializer).map(d => [d.name.text, d.initializer])
948
- : ts.isFunctionDeclaration(st) && st.name ? [[st.name.text, st]] : [];
949
- for (const [name, init] of decls) {
1367
+ const decls = ts.isVariableStatement(st) ? st.declarationList.declarations.filter(d => ts.isIdentifier(d.name) && d.initializer).map(d => [d.name.text, d.initializer, d])
1368
+ : ts.isFunctionDeclaration(st) && st.name ? [[st.name.text, st, st]] : [];
1369
+ for (const [name, init, declNode] of decls) {
950
1370
  if (opts.entry && opts.entry !== name)
951
1371
  continue;
952
1372
  const f = ts.isFunctionDeclaration(init) ? init : ts.isArrowFunction(strip(init)) || ts.isFunctionExpression(strip(init)) ? strip(init) : undefined;
953
1373
  const body = f ? lastReturn(f.body) : init;
954
1374
  if (!body || !isSchedule(s, body) || (f && ts.isBlock(f.body) && f.body.statements.length > 1))
955
1375
  continue;
956
- found.push({ name, expr: body, params: (f?.parameters ?? []).map(p => (ts.isIdentifier(p.name) ? p.name.text : refuse(p, `${text(p)}: a parameter other than a name`))), s });
1376
+ found.push({ name, expr: body, params: (f?.parameters ?? []).map(p => (ts.isIdentifier(p.name) ? p.name.text : refuse(p, `${text(p)}: a parameter other than a name`))), s, declSpan: declSpanOf(s.sf, declNode) });
957
1377
  }
958
1378
  }
959
1379
  if (opts.entry)
@@ -1007,7 +1427,7 @@ function fromScheduleEntry(code, file, e, E, opts) {
1007
1427
  attachSource(sr.rule, evidence, []);
1008
1428
  if (c.failure)
1009
1429
  return { ok: false, rule: sr.rule, source, refusals: [{ where: file, what: `the rule and Effect's own schedule part: ${c.failure}` }], notes, names: sr.names, evidence };
1010
- return { ok: true, rule: sr.rule, source, refusals: [], notes, names: sr.names, evidence, schedule: sr, replay: run => replaySchedule(sr, make(run.params), E, run) };
1430
+ return { ok: true, rule: sr.rule, source, refusals: [], notes, names: sr.names, evidence, schedule: sr, declSpans: [e.declSpan], replay: run => replaySchedule(sr, make(run.params), E, run) };
1011
1431
  }
1012
1432
  // A schedule written as source (an expression over Schedule and Duration, with `params` its free names) read into its
1013
1433
  // rule and checked against the schedule Effect makes of it: fromSchedule('Schedule.exponential("10 millis").pipe(Schedule.upTo({times: 5}))', {effect}).