@systemfsoftware/effect-sim-kernel 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1912 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { Clock, Config, Context, Deferred, Duration, Effect, Latch, Layer, Match, Option, PubSub, Queue, Ref, Scheduler, Scope, Semaphore } from "effect";
3
+ import { dual } from "effect/Function";
4
+ //#region src/Kernel/Bound.ts
5
+ const pruned = {
6
+ enabled: true,
7
+ disabledBy: []
8
+ };
9
+ const unpruned = (disabledBy) => ({
10
+ enabled: false,
11
+ disabledBy
12
+ });
13
+ const nightlyMissRate = .01;
14
+ const PROFILES = {
15
+ local: "local",
16
+ nightly: "nightly"
17
+ };
18
+ const profileOf = (name) => PROFILES[name] ?? "per-change";
19
+ const currentProfile = Effect.map(Config.option(Config.String("CONFORMANCE_PROFILE")), Option.match({
20
+ onNone: () => profileOf(""),
21
+ onSome: profileOf
22
+ }));
23
+ const bugProbability = (fibers, steps) => 1 / (fibers * steps ** 2);
24
+ const nightlyRuns = (fibers, steps) => Math.ceil(Math.log(nightlyMissRate) / Math.log(1 - bugProbability(fibers, steps)));
25
+ const nightlyOf = (budget) => nightlyRuns(budget.fibers, budget.steps);
26
+ const hasWork = (budget) => budget.fibers > 0 && budget.steps > 0;
27
+ const SEEDS = {
28
+ local: () => 25,
29
+ "per-change": () => 250,
30
+ nightly: (budget) => hasWork(budget) ? nightlyOf(budget) : 250
31
+ };
32
+ const seedsForImpl = (budget, profile = "per-change") => SEEDS[profile](budget);
33
+ const isBudgetFirst = (args) => args.length === 0 || typeof args[0] !== "string";
34
+ const seedsFor = dual(isBudgetFirst, seedsForImpl);
35
+ const currentSeedsFor = (budget) => Effect.map(currentProfile, (profile) => seedsFor(budget, profile));
36
+ const localBoundOf = (requested) => Math.min(requested ?? 1, 1);
37
+ const boundImpl = (requested, profile) => profile === "local" ? localBoundOf(requested) : requested;
38
+ const preemptionsFor = dual(2, boundImpl);
39
+ const currentPreemptionsFor = (requested) => Effect.map(currentProfile, (profile) => preemptionsFor(requested, profile));
40
+ //#endregion
41
+ //#region src/internal/runMark.ts
42
+ /**
43
+ * The one-live-run mark. A module-private slot on the patched fiber prototype
44
+ * names the kernel whose run is live: acquisition claims it, release clears it,
45
+ * and the concurrency guard reads it. The symbol never leaves this module, so
46
+ * the slot is unnameable from consumer code. No module-level mutable state
47
+ * lives here — the slot travels on the fiber prototype itself.
48
+ */
49
+ const ACTIVE_RUN = Symbol("~effect-sim-kernel/activeRun");
50
+ const isHostObject$4 = (candidate) => typeof candidate === "object";
51
+ const isKernel = (candidate) => "pending" in candidate && "release" in candidate;
52
+ const fieldOf$2 = (target, key) => Reflect.get(target, key);
53
+ const protoOf$2 = (value) => {
54
+ const proto = Object.getPrototypeOf(value);
55
+ return isHostObject$4(proto) ? proto : Object.prototype;
56
+ };
57
+ /** @internal */
58
+ const FIBER_PROTOTYPE = protoOf$2(Effect.runFork(Effect.void));
59
+ const heldRun = () => fieldOf$2(FIBER_PROTOTYPE, ACTIVE_RUN);
60
+ const isLiveKernel = (candidate) => isHostObject$4(candidate) && isKernel(candidate);
61
+ /** @internal */
62
+ const currentKernel = () => {
63
+ const candidate = heldRun();
64
+ return isLiveKernel(candidate) ? candidate : void 0;
65
+ };
66
+ /** @internal */
67
+ const isRunLive = () => isHostObject$4(heldRun());
68
+ /** @internal */
69
+ const claimRun = (kernel) => {
70
+ Reflect.set(FIBER_PROTOTYPE, ACTIVE_RUN, kernel);
71
+ };
72
+ /** @internal */
73
+ const releaseRun = () => {
74
+ Reflect.set(FIBER_PROTOTYPE, ACTIVE_RUN, void 0);
75
+ };
76
+ //#endregion
77
+ //#region src/internal/clocks.ts
78
+ /**
79
+ * The kernel's clocks (R2, R37). The root clock is virtual time the run owns:
80
+ * every sleep registers here, no host timer is ever created, and `advance`
81
+ * fires the earliest due batch in registration order at quiescence. The test
82
+ * clock is what a harness provides in place of `TestClock.layer()`: its
83
+ * `adjust` and `setTime` suspend the caller, and the kernel settles one
84
+ * request per quiescence, firing due batches in timestamp order and letting
85
+ * everything they wake run to a stop before the next one. State lives in the
86
+ * factory closures; nothing module-level survives a release.
87
+ */
88
+ const NANOS_PER_MILLI = 1000000n;
89
+ const removeBy = (items, item) => {
90
+ const index = items.indexOf(item);
91
+ if (index >= 0) items.splice(index, 1);
92
+ };
93
+ const dueBatchAt = (timers, at) => timers.filter((timer) => timer.at === at).sort((first, second) => first.seq - second.seq);
94
+ const fireAll = (due) => {
95
+ for (const timer of due) timer.wake();
96
+ };
97
+ const dropDueAt = (timers, at) => {
98
+ const kept = timers.filter((timer) => timer.at !== at);
99
+ timers.splice(0, timers.length, ...kept);
100
+ };
101
+ const earliestDueAtOf = (timers) => timers.length === 0 ? void 0 : Math.min(...timers.map((timer) => timer.at));
102
+ const sleepFor = (timers, now, seq, duration) => {
103
+ const millis = Duration.toMillis(duration);
104
+ if (millis <= 0) return Effect.yieldNow;
105
+ return Effect.callback((resume) => {
106
+ const timer = {
107
+ at: now() + millis,
108
+ seq: seq(),
109
+ wake: () => resume(Effect.void)
110
+ };
111
+ timers.push(timer);
112
+ return Effect.sync(() => {
113
+ removeBy(timers, timer);
114
+ });
115
+ });
116
+ };
117
+ /** @internal */
118
+ const makeVirtualTime = () => {
119
+ const timers = [];
120
+ let now = 0;
121
+ let seq = 0;
122
+ const currentTimeMillisUnsafe = () => now;
123
+ const currentTimeNanosUnsafe = () => BigInt(Math.trunc(now)) * NANOS_PER_MILLI;
124
+ const nextSeq = () => {
125
+ seq++;
126
+ return seq;
127
+ };
128
+ const advance = () => {
129
+ const at = earliestDueAtOf(timers);
130
+ if (at === void 0) return false;
131
+ const due = dueBatchAt(timers, at);
132
+ dropDueAt(timers, at);
133
+ now = at;
134
+ fireAll(due);
135
+ return true;
136
+ };
137
+ return {
138
+ currentTimeMillisUnsafe,
139
+ currentTimeNanosUnsafe,
140
+ monotonicTimeNanosUnsafe: currentTimeNanosUnsafe,
141
+ sleep: (duration) => sleepFor(timers, currentTimeMillisUnsafe, nextSeq, duration),
142
+ advance,
143
+ earliestDueAt: () => earliestDueAtOf(timers),
144
+ moveTo: (target) => {
145
+ now = Math.max(now, target);
146
+ }
147
+ };
148
+ };
149
+ const clockMembersOf = (time) => ({
150
+ currentTimeMillisUnsafe: time.currentTimeMillisUnsafe,
151
+ currentTimeMillis: Effect.sync(time.currentTimeMillisUnsafe),
152
+ currentTimeNanosUnsafe: time.currentTimeNanosUnsafe,
153
+ currentTimeNanos: Effect.sync(time.currentTimeNanosUnsafe),
154
+ monotonicTimeNanosUnsafe: time.monotonicTimeNanosUnsafe,
155
+ monotonicTimeNanos: Effect.sync(time.monotonicTimeNanosUnsafe),
156
+ sleep: time.sleep
157
+ });
158
+ /** @internal */
159
+ const makeKernelClock = () => {
160
+ const time = makeVirtualTime();
161
+ return {
162
+ ...clockMembersOf(time),
163
+ advance: time.advance
164
+ };
165
+ };
166
+ const requestMoveTo = (requests, target) => Effect.callback((resume) => {
167
+ const request = {
168
+ target,
169
+ resume: () => resume(Effect.void)
170
+ };
171
+ requests.push(request);
172
+ return Effect.sync(() => {
173
+ removeBy(requests, request);
174
+ });
175
+ });
176
+ const isDueBy = (time, target) => {
177
+ const at = time.earliestDueAt();
178
+ return at !== void 0 && at <= target;
179
+ };
180
+ const advanceToward = (time, requests, request) => {
181
+ if (isDueBy(time, request.target)) return time.advance();
182
+ time.moveTo(request.target);
183
+ requests.shift();
184
+ request.resume();
185
+ return true;
186
+ };
187
+ const settleOldest = (time, requests) => {
188
+ const request = requests[0];
189
+ if (request === void 0) return false;
190
+ return advanceToward(time, requests, request);
191
+ };
192
+ /** @internal */
193
+ const makeTestClock = (live) => {
194
+ const time = makeVirtualTime();
195
+ const requests = [];
196
+ const adjust = (duration) => Effect.suspend(() => requestMoveTo(requests, time.currentTimeMillisUnsafe() + Duration.toMillis(Duration.fromInputUnsafe(duration))));
197
+ const setTime = (timestamp) => requestMoveTo(requests, timestamp);
198
+ const withLive = (effect) => Effect.provideService(effect, Clock.Clock, live);
199
+ return {
200
+ ...clockMembersOf(time),
201
+ adjust,
202
+ setTime,
203
+ withLive,
204
+ stepTowardRequest: () => settleOldest(time, requests)
205
+ };
206
+ };
207
+ /** @internal */
208
+ const makeRunClocks = () => ({
209
+ clock: makeKernelClock(),
210
+ testClocks: []
211
+ });
212
+ /**
213
+ * The quiescence move (R37): settle the oldest test-clock request first, then
214
+ * advance the root clock. False when nothing can move, so the run classifies
215
+ * the stall.
216
+ */
217
+ /** @internal */
218
+ const stepClocks = (clocks) => clocks.testClocks.some((testClock) => testClock.stepTowardRequest()) || clocks.clock.advance();
219
+ /**
220
+ * Builds the run's test clock and registers it for quiescent settling. Only
221
+ * available inside a kernel run, where the run's clocks live.
222
+ */
223
+ /** @internal */
224
+ const kernelTestClock = Effect.sync(() => {
225
+ const kernel = currentKernel();
226
+ if (kernel === void 0) throw new Error("effect-sim-kernel: the kernel test clock is only available inside a kernel run");
227
+ const testClock = makeTestClock(kernel.clocks.clock);
228
+ kernel.clocks.testClocks.push(testClock);
229
+ return testClock;
230
+ });
231
+ //#endregion
232
+ //#region src/internal/deadlock.ts
233
+ const NO_FRAMES = [];
234
+ const NO_RESOURCES = [];
235
+ const isHostObject$3 = (candidate) => typeof candidate === "object";
236
+ const isFrameList = (candidate) => Array.isArray(candidate);
237
+ const isHostProcess = (candidate) => isHostObject$3(candidate);
238
+ const hostProcess = () => Reflect.get(globalThis, "process");
239
+ const resourceNames = () => {
240
+ const host = hostProcess();
241
+ return isHostProcess(host) ? host.getActiveResourcesInfo() : NO_RESOURCES;
242
+ };
243
+ const bump = (counts, resource) => {
244
+ counts.set(resource, (counts.get(resource) ?? 0) + 1);
245
+ };
246
+ /** A snapshot of the process resources alive right now, by resource kind. */
247
+ /** @internal */
248
+ const resourceCounts = () => {
249
+ const counts = /* @__PURE__ */ new Map();
250
+ for (const resource of resourceNames()) bump(counts, resource);
251
+ return counts;
252
+ };
253
+ const extraOf = (before, entry) => entry[1] - (before.get(entry[0]) ?? 0);
254
+ const appendExtra = (appeared, before, entry) => {
255
+ const extra = extraOf(before, entry);
256
+ if (extra > 0) appeared.push(`${entry[0]} x${extra}`);
257
+ };
258
+ /** Resource kinds that appeared since `before`, as `"<kind> x<count>"` entries. */
259
+ /** @internal */
260
+ const newResources = (before) => {
261
+ const appeared = [];
262
+ for (const entry of resourceCounts()) appendExtra(appeared, before, entry);
263
+ return appeared;
264
+ };
265
+ const FAMILY_PATTERNS = [
266
+ [/Socket|TCP|UDP|Pipe|GetAddrInfo/u, "Socket"],
267
+ [/FS|File/u, "File"],
268
+ [/Timeout|Immediate/u, "RealTimer"]
269
+ ];
270
+ const matchedFamily = (resource) => {
271
+ return FAMILY_PATTERNS.find(([pattern]) => pattern.test(resource))?.[1];
272
+ };
273
+ const familyOf = (resource) => matchedFamily(resource) ?? "Other";
274
+ const isNamed = (family) => family !== "Other";
275
+ /**
276
+ * What a set of newly appeared resources can wake. Files and sockets name
277
+ * themselves first; a leftover kind is still named, through `resources`.
278
+ */
279
+ /** @internal */
280
+ const waitKindOf = (resources) => {
281
+ return resources.map(familyOf).find(isNamed) ?? "Other";
282
+ };
283
+ const stringOn = (described, key) => {
284
+ const value = Reflect.get(described, key);
285
+ return typeof value === "string" ? value : void 0;
286
+ };
287
+ const stringFieldOf = (described, key) => {
288
+ if (!isHostObject$3(described)) return void 0;
289
+ return stringOn(described, key);
290
+ };
291
+ const argsNameOn = (described) => {
292
+ const args = Reflect.get(described, "args");
293
+ return typeof args === "function" ? args.name : void 0;
294
+ };
295
+ const nameOf = (described) => {
296
+ if (!isHostObject$3(described)) return void 0;
297
+ return argsNameOn(described);
298
+ };
299
+ const applyToJson = (frame) => {
300
+ const toJson = Reflect.get(frame, "toJSON");
301
+ return typeof toJson === "function" ? Reflect.apply(toJson, frame, []) : void 0;
302
+ };
303
+ const describeFrame = (frame) => {
304
+ if (!isHostObject$3(frame)) return void 0;
305
+ return applyToJson(frame);
306
+ };
307
+ const namedOp = (op, described) => {
308
+ const name = nameOf(described);
309
+ return name === void 0 ? op : `${op}(${name})`;
310
+ };
311
+ const renderFrame = (frame) => {
312
+ const described = describeFrame(frame);
313
+ const op = stringFieldOf(described, "op") ?? "?";
314
+ return namedOp(op, described);
315
+ };
316
+ const renderedFrames = (stack) => stack.slice(1, 7).map(renderFrame);
317
+ const framesOf = (fiber) => {
318
+ const stack = Reflect.get(fiber, "_stack");
319
+ return isFrameList(stack) ? renderedFrames(stack) : NO_FRAMES;
320
+ };
321
+ const isUnfinished = (fiber) => fiber.pollUnsafe() === void 0;
322
+ const collectSuspended = (suspended, fiber) => {
323
+ if (isUnfinished(fiber)) suspended.push({
324
+ id: fiber.id,
325
+ frames: framesOf(fiber)
326
+ });
327
+ };
328
+ /**
329
+ * Every unfinished fiber the kernel ran, innermost frame first. Fibers that
330
+ * already exited are not suspended, so they are left out.
331
+ */
332
+ /** @internal */
333
+ const describeSuspended = (fibers) => {
334
+ const suspended = [];
335
+ for (const fiber of fibers) collectSuspended(suspended, fiber);
336
+ return suspended;
337
+ };
338
+ //#endregion
339
+ //#region src/internal/escapeRecorder.ts
340
+ const TIMER_NAMES = [
341
+ "setTimeout",
342
+ "setInterval",
343
+ "setImmediate"
344
+ ];
345
+ const OWN_MODULE = /effect-sim-kernel[/\\](?:src|dist)[/\\]/u;
346
+ const BUNDLED_DEPENDENCY = /.*node_modules[/\\]\.pnpm[/\\][^/\\]+[/\\]node_modules[/\\]/u;
347
+ const stackFrames = () => ((/* @__PURE__ */ new Error()).stack ?? "").split("\n").slice(2);
348
+ const outsideFrames = () => stackFrames().filter((frame) => !OWN_MODULE.test(frame));
349
+ const shorten = (frame) => frame.trim().replace(/^at /u, "").replace(BUNDLED_DEPENDENCY, "");
350
+ const siteOf = () => outsideFrames().slice(0, 2).map(shorten).join(" <- ");
351
+ const isTimer = (candidate) => typeof candidate === "function";
352
+ const timerOf = (name) => {
353
+ const original = Reflect.get(globalThis, name);
354
+ return isTimer(original) ? original : void 0;
355
+ };
356
+ const wrapperOf = (name, original, report) => (...args) => {
357
+ report({
358
+ timer: name,
359
+ site: siteOf()
360
+ });
361
+ return Reflect.apply(original, globalThis, args);
362
+ };
363
+ const captureTimer = (originals, name) => {
364
+ const original = timerOf(name);
365
+ if (original !== void 0) originals.set(name, original);
366
+ };
367
+ const capturedTimers = () => {
368
+ const originals = /* @__PURE__ */ new Map();
369
+ for (const name of TIMER_NAMES) captureTimer(originals, name);
370
+ return originals;
371
+ };
372
+ const reinstall = (originals) => {
373
+ for (const [name, original] of originals) Reflect.set(globalThis, name, original);
374
+ };
375
+ /**
376
+ * Wrap the global timer functions so every call made while the run is live is
377
+ * reported, then still carried out so the run can be classified. Returns the
378
+ * restore function and the untouched host timer the kernel's own machinery
379
+ * uses to yield to completed host work; a run installs the recorder at its
380
+ * start and restores it in its `finally`, so nothing outside a run is ever
381
+ * observed.
382
+ */
383
+ /** @internal */
384
+ const installEscapeRecorder = (report) => {
385
+ const originals = capturedTimers();
386
+ for (const [name, original] of originals) Reflect.set(globalThis, name, wrapperOf(name, original, report));
387
+ return {
388
+ restore: () => reinstall(originals),
389
+ hostImmediate: hostImmediateOf(originals)
390
+ };
391
+ };
392
+ const hostImmediateOf = (originals) => {
393
+ const immediate = originals.get("setImmediate");
394
+ return immediate === void 0 ? syncImmediate : immediate;
395
+ };
396
+ const syncImmediate = (handler) => handler();
397
+ //#endregion
398
+ //#region src/internal/kernel.ts
399
+ /**
400
+ * The kernel instance (KTD2): it supplies Effect's `Scheduler`, wraps the fiber
401
+ * resume methods, and observes `Ref` and `Deferred` field access. The hooks are
402
+ * acquired for the lifetime of one run and restored when the run releases them:
403
+ * the patched wrappers close over their kernel, a fiber's `currentDispatcher`
404
+ * carries that kernel's dispatcher, and a module-private slot on the patched
405
+ * fiber prototype marks the one active run for the concurrency guard. No
406
+ * module-level mutable state survives a release.
407
+ *
408
+ * The hooks read Effect runtime internals, which the plan allows only inside this
409
+ * package (R17). They are pinned to `effect` 4.0.0-rc.117 and fail loudly when a
410
+ * field or method moves.
411
+ */
412
+ const CURRENT_FIBER = "~effect/Fiber/currentFiber";
413
+ const FIBER_METHODS = [
414
+ "addObserver",
415
+ "interruptUnsafe",
416
+ "pollUnsafe",
417
+ "evaluate"
418
+ ];
419
+ const REF_FIELDS = ["ref"];
420
+ const DEFERRED_FIELDS = ["effect", "resumes"];
421
+ const isFiberLike = (candidate) => typeof candidate === "object";
422
+ const isHostObject$2 = (candidate) => typeof candidate === "object";
423
+ const isMethod = (candidate) => typeof candidate === "function";
424
+ const fieldOf$1 = (target, key) => Reflect.get(target, key);
425
+ const methodOf = (target, name) => {
426
+ const candidate = fieldOf$1(target, name);
427
+ return isMethod(candidate) ? candidate : void 0;
428
+ };
429
+ const dispatcherOf = (fiber) => fieldOf$1(fiber, "currentDispatcher");
430
+ const protoOf$1 = (value) => {
431
+ const proto = Object.getPrototypeOf(value);
432
+ return isHostObject$2(proto) ? proto : Object.prototype;
433
+ };
434
+ const captureDescriptor = (proto, field) => {
435
+ const descriptor = Reflect.getOwnPropertyDescriptor(proto, field);
436
+ return isHostObject$2(descriptor) ? descriptor : void 0;
437
+ };
438
+ const descriptorEntryOf = (proto, field) => {
439
+ const descriptor = captureDescriptor(proto, field);
440
+ return descriptor === void 0 ? void 0 : [field, descriptor];
441
+ };
442
+ const captureDescriptors = (proto, fields) => fields.map((field) => descriptorEntryOf(proto, field)).filter((entry) => entry !== void 0);
443
+ const slotOf = (field) => Symbol.for(`~effect-sim-kernel/field/${field}`);
444
+ const passThroughField = (proto, field) => {
445
+ const slot = slotOf(field);
446
+ Reflect.defineProperty(proto, field, {
447
+ configurable: true,
448
+ get() {
449
+ return this[slot];
450
+ },
451
+ set(value) {
452
+ this[slot] = value;
453
+ }
454
+ });
455
+ };
456
+ const restoreField = (proto, field, captured) => {
457
+ const original = captured.find((entry) => entry[0] === field);
458
+ if (original === void 0) passThroughField(proto, field);
459
+ else Reflect.defineProperty(proto, original[0], original[1]);
460
+ };
461
+ const restoreFields = (proto, fields, captured) => {
462
+ for (const field of fields) restoreField(proto, field, captured);
463
+ };
464
+ const patchMethod = (proto, entry, kernel) => {
465
+ Reflect.defineProperty(proto, entry[0], {
466
+ configurable: true,
467
+ value: function(...args) {
468
+ return dispatchFiberCall(this, entry[0], entry[1], args, kernel);
469
+ },
470
+ writable: true
471
+ });
472
+ };
473
+ const patchMethods = (proto, originals, kernel) => {
474
+ for (const entry of originals) patchMethod(proto, entry, kernel);
475
+ };
476
+ const restoreMethod = (proto, entry) => {
477
+ Reflect.defineProperty(proto, entry[0], {
478
+ configurable: true,
479
+ value: entry[1],
480
+ writable: true
481
+ });
482
+ };
483
+ const restoreMethods = (proto, originals) => {
484
+ for (const entry of originals) restoreMethod(proto, entry);
485
+ };
486
+ const missingMethod = (name) => {
487
+ throw new Error(`effect-sim-kernel: FiberImpl.${name} is missing on the pinned Effect version`);
488
+ };
489
+ const originalMethodOf = (proto, name) => {
490
+ const original = methodOf(proto, name);
491
+ return original === void 0 ? missingMethod(name) : original;
492
+ };
493
+ const originalOf = (proto, name) => [name, originalMethodOf(proto, name)];
494
+ const originalMethodsOf = (proto) => FIBER_METHODS.map((name) => originalOf(proto, name));
495
+ const interceptField = (proto, field, guard) => {
496
+ const slot = slotOf(field);
497
+ Reflect.defineProperty(proto, field, {
498
+ configurable: true,
499
+ get() {
500
+ guard(this);
501
+ return this[slot];
502
+ },
503
+ set(value) {
504
+ guard(this);
505
+ this[slot] = value;
506
+ }
507
+ });
508
+ };
509
+ const interceptFields$1 = (proto, fields, guard) => {
510
+ for (const field of fields) interceptField(proto, field, guard);
511
+ };
512
+ const DEFAULT_VALUE = "~effect/Context/defaultValue";
513
+ const FIBER_CACHE = "_fiberCache";
514
+ const emptyContextRoot = () => {
515
+ const root = Reflect.get(Context.empty(), "cacheRoot");
516
+ if (!isHostObject$2(root)) throw new Error("effect-sim-kernel: Context no longer has a cache root on the pinned Effect version");
517
+ return root;
518
+ };
519
+ const setAsideFiberCache = (root) => {
520
+ const captured = captureDescriptor(root, FIBER_CACHE);
521
+ Reflect.deleteProperty(root, FIBER_CACHE);
522
+ return captured;
523
+ };
524
+ const restoreFiberCache = (root, captured) => {
525
+ if (captured === void 0) Reflect.deleteProperty(root, FIBER_CACHE);
526
+ else Reflect.defineProperty(root, FIBER_CACHE, captured);
527
+ };
528
+ const cachedDefaultOf = (reference) => {
529
+ Context.getOption(Context.empty(), reference);
530
+ const descriptor = captureDescriptor(reference, DEFAULT_VALUE);
531
+ if (descriptor === void 0) throw new Error("effect-sim-kernel: Context no longer caches reference defaults on the pinned Effect version");
532
+ return descriptor;
533
+ };
534
+ const pinDefault = (reference, value) => {
535
+ Reflect.defineProperty(reference, DEFAULT_VALUE, {
536
+ configurable: true,
537
+ writable: true,
538
+ value
539
+ });
540
+ };
541
+ const restoreDefault = (reference, captured) => {
542
+ Reflect.defineProperty(reference, DEFAULT_VALUE, captured);
543
+ };
544
+ /**
545
+ * Claims the hooks for one run: the fiber methods and the `Ref` and `Deferred`
546
+ * fields are patched with closures over this kernel, and the live run is
547
+ * marked. The returned restore undoes both and runs exactly once, at release.
548
+ */
549
+ const acquireHooks = (kernel) => {
550
+ if (isRunLive()) throw new Error("effect-sim-kernel: a kernel run is already active — one kernel owns the global hooks at a time");
551
+ const fiberProto = FIBER_PROTOTYPE;
552
+ const originals = originalMethodsOf(fiberProto);
553
+ const refProto = protoOf$1(Ref.makeUnsafe(0));
554
+ const deferredProto = protoOf$1(Deferred.makeUnsafe());
555
+ const capturedRef = captureDescriptors(refProto, REF_FIELDS);
556
+ const capturedDeferred = captureDescriptors(deferredProto, DEFERRED_FIELDS);
557
+ const capturedScheduler = cachedDefaultOf(Scheduler.Scheduler);
558
+ const capturedClock = cachedDefaultOf(Clock.Clock);
559
+ const emptyRoot = emptyContextRoot();
560
+ const guard = (target) => {
561
+ if (kernel.running) kernel.observeShared(target);
562
+ };
563
+ claimRun(kernel);
564
+ patchMethods(fiberProto, originals, kernel);
565
+ interceptFields$1(refProto, REF_FIELDS, guard);
566
+ interceptFields$1(deferredProto, DEFERRED_FIELDS, guard);
567
+ pinDefault(Scheduler.Scheduler, kernel.scheduler);
568
+ pinDefault(Clock.Clock, kernel.clocks.clock);
569
+ const capturedFiberCache = setAsideFiberCache(emptyRoot);
570
+ return () => {
571
+ releaseRun();
572
+ restoreMethods(fiberProto, originals);
573
+ restoreFields(refProto, REF_FIELDS, capturedRef);
574
+ restoreFields(deferredProto, DEFERRED_FIELDS, capturedDeferred);
575
+ restoreDefault(Scheduler.Scheduler, capturedScheduler);
576
+ restoreDefault(Clock.Clock, capturedClock);
577
+ restoreFiberCache(emptyRoot, capturedFiberCache);
578
+ };
579
+ };
580
+ const currentFiber = () => {
581
+ const current = Reflect.get(globalThis, CURRENT_FIBER);
582
+ return isFiberLike(current) ? current : void 0;
583
+ };
584
+ const applyOriginal = (original, fiber, args) => Reflect.apply(original, fiber, args);
585
+ const isOtherFiber = (running, fiber) => running !== void 0 && running !== fiber;
586
+ const noteOtherFiberWork = (fiber, kernel) => {
587
+ if (isOtherFiber(currentFiber(), fiber)) {
588
+ kernel.observeShared(fiber);
589
+ kernel.observeGlobalWork();
590
+ }
591
+ };
592
+ const dispatchObserved = (fiber, kernel, original, args) => {
593
+ noteOtherFiberWork(fiber, kernel);
594
+ return applyOriginal(original, fiber, args);
595
+ };
596
+ const isResumableBy = (fiber, kernel) => fiber.pollUnsafe() === void 0 && dispatcherOf(fiber) === kernel.dispatcher;
597
+ const isResumingRun = (fiber, kernel) => kernel.running && isResumableBy(fiber, kernel);
598
+ const resumeExternallyThrough = (fiber, kernel, original, args) => {
599
+ kernel.resumeExternally(fiber, () => applyOriginal(original, fiber, args));
600
+ };
601
+ /**
602
+ * A fiber's first evaluation inside a step is a start, not a resume: Effect runs
603
+ * it on the caller's stack (`startImmediately`, `runFork`), and a child that
604
+ * finishes there never joins its parent's children. Queuing it would let the
605
+ * parent exit first and interrupt a child Effect had already finished.
606
+ */
607
+ const startsInStep = (fiber, kernel) => kernel.firstEvaluation(fiber) && kernel.phase === "step";
608
+ const queuedOrObserved = (fiber, kernel, original, args) => {
609
+ if (isResumingRun(fiber, kernel)) return resumeExternallyThrough(fiber, kernel, original, args);
610
+ return dispatchObserved(fiber, kernel, original, args);
611
+ };
612
+ const dispatchEvaluate = (fiber, kernel, original, args) => {
613
+ if (startsInStep(fiber, kernel)) return dispatchObserved(fiber, kernel, original, args);
614
+ return queuedOrObserved(fiber, kernel, original, args);
615
+ };
616
+ const interruptAgain = (fiber, args) => () => {
617
+ Reflect.apply(Reflect.get(fiber, "interruptUnsafe"), fiber, args);
618
+ };
619
+ const dispatchInterrupt = (fiber, kernel, original, args) => {
620
+ if (kernel.afterQueuedResume(fiber, interruptAgain(fiber, args))) return void 0;
621
+ return dispatchObserved(fiber, kernel, original, args);
622
+ };
623
+ const dispatchFiberCall = (fiber, method, original, args, kernel) => Match.value(method).pipe(Match.when("evaluate", () => dispatchEvaluate(fiber, kernel, original, args)), Match.when("interruptUnsafe", () => dispatchInterrupt(fiber, kernel, original, args)), Match.orElse(() => dispatchObserved(fiber, kernel, original, args)));
624
+ /** @internal */
625
+ const makeKernel = (options) => {
626
+ const pending = [];
627
+ const fibers = /* @__PURE__ */ new Set();
628
+ const evaluated = /* @__PURE__ */ new WeakSet();
629
+ const steps = [];
630
+ const decisions = [];
631
+ const escapes = [];
632
+ const touches = /* @__PURE__ */ new Set();
633
+ const unobservedNames = /* @__PURE__ */ new Set();
634
+ const scopeHolders = /* @__PURE__ */ new WeakMap();
635
+ const clocks = makeRunClocks();
636
+ /**
637
+ * The limit starts at one operation so every adjacent primitive is separated
638
+ * by a step; after the kernel itself slices a fiber, its next slice gets two,
639
+ * because resuming from a yield spends runtime operations on bookkeeping.
640
+ */
641
+ const limit = /* @__PURE__ */ new WeakMap();
642
+ const yieldedByUs = /* @__PURE__ */ new WeakSet();
643
+ let phase = "paused";
644
+ let exploring = options.exploring;
645
+ let stepCount = 0;
646
+ let scheduledInStep = 0;
647
+ let globalWorkThisStep = false;
648
+ let ranInTask = void 0;
649
+ let lastRan = void 0;
650
+ let forcing = void 0;
651
+ let root = void 0;
652
+ let running = false;
653
+ let restoreHooks = void 0;
654
+ const taskAt = (index) => pending[index];
655
+ const stepOn = (task) => task === void 0 ? -1 : task.step;
656
+ const stepAt = (index) => stepOn(taskAt(index));
657
+ const isForcedTask = (task) => task !== void 0 && task.forced;
658
+ const laterThan = (best, index) => stepAt(index) > stepAt(best);
659
+ const keepsBest = (best, index, task) => !isForcedTask(task) || !laterThan(best, index);
660
+ const laterForced = (best, index, task) => {
661
+ if (keepsBest(best, index, task)) return best;
662
+ return index;
663
+ };
664
+ const latestForcedIndex = () => {
665
+ let best = -1;
666
+ for (const [index, task] of pending.entries()) best = laterForced(best, index, task);
667
+ return best;
668
+ };
669
+ const isExternalTask = (task) => task.external;
670
+ const firstExternalIndex = () => {
671
+ const found = pending.findIndex(isExternalTask);
672
+ return found >= 0 ? found : 0;
673
+ };
674
+ /**
675
+ * What Effect's own dispatcher would run next: the continuation the kernel
676
+ * sliced in the latest step goes first (Effect keeps running a fiber until it
677
+ * yields, so that continuation is what Effect would have kept running); then a
678
+ * fiber woken by a Promise or microtask, which runs in the microtask
679
+ * checkpoint ahead of the next dispatcher batch; then the oldest task.
680
+ */
681
+ const effectDefault = () => {
682
+ const forced = latestForcedIndex();
683
+ return forced >= 0 ? forced : firstExternalIndex();
684
+ };
685
+ const seedLimit = (fiber) => {
686
+ limit.set(fiber, yieldedByUs.has(fiber) ? 2 : 1);
687
+ yieldedByUs.delete(fiber);
688
+ };
689
+ const seededLimit = (fiber) => {
690
+ if (fiber.currentOpCount !== 1) return limit.get(fiber);
691
+ seedLimit(fiber);
692
+ return limit.get(fiber);
693
+ };
694
+ const opLimitOf = (fiber) => seededLimit(fiber) ?? 1;
695
+ const opLimitExceeded = (fiber) => fiber.currentOpCount > opLimitOf(fiber);
696
+ const firstHolderOf = (scope, holder) => {
697
+ if (scopeHolders.has(scope)) return scopeHolders.get(scope);
698
+ scopeHolders.set(scope, holder);
699
+ return holder;
700
+ };
701
+ const heldByAnother = (scope, holder) => firstHolderOf(scope, holder) !== holder;
702
+ const noteFirstRan = (fiber) => {
703
+ if (ranInTask === void 0) ranInTask = fiber;
704
+ };
705
+ const noteYieldedByUs = (fiber) => {
706
+ yieldedByUs.add(fiber);
707
+ forcing = fiber;
708
+ };
709
+ /**
710
+ * A fiber evaluated inside another fiber's slice (`startImmediately`, a nested
711
+ * runtime) runs on its parent's stack: a slice would hand control straight
712
+ * back to the parent, which Effect never does within its op budget, so such a
713
+ * fiber yields only where Effect's own scheduler would.
714
+ */
715
+ const runsNested = (fiber) => ranInTask !== fiber;
716
+ const effectWouldYield = (fiber) => fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield;
717
+ const slicedByUs = (fiber) => {
718
+ if (!opLimitExceeded(fiber)) return false;
719
+ noteYieldedByUs(fiber);
720
+ return true;
721
+ };
722
+ const shouldYield = (fiber) => {
723
+ fibers.add(fiber);
724
+ noteFirstRan(fiber);
725
+ return runsNested(fiber) ? effectWouldYield(fiber) : slicedByUs(fiber);
726
+ };
727
+ const isForcing = (owner) => owner !== void 0 && owner === forcing;
728
+ const scheduleTask = (task, _priority) => {
729
+ const owner = currentFiber();
730
+ const forced = isForcing(owner);
731
+ if (forced) forcing = void 0;
732
+ pending.push({
733
+ owner,
734
+ run: task,
735
+ external: false,
736
+ forced,
737
+ step: stepCount
738
+ });
739
+ scheduledInStep++;
740
+ };
741
+ const dispatcher = {
742
+ scheduleTask,
743
+ flush: () => {}
744
+ };
745
+ const scheduler = {
746
+ executionMode: "sync",
747
+ shouldYield,
748
+ makeDispatcher: () => dispatcher
749
+ };
750
+ const beginStep = () => {
751
+ stepCount++;
752
+ ranInTask = void 0;
753
+ scheduledInStep = 0;
754
+ globalWorkThisStep = false;
755
+ touches.clear();
756
+ phase = "step";
757
+ };
758
+ const endStep = () => {
759
+ phase = "paused";
760
+ };
761
+ const ranOn = (task) => ranInTask ?? task.owner;
762
+ const runTask = (task) => {
763
+ beginStep();
764
+ try {
765
+ task.run();
766
+ } finally {
767
+ endStep();
768
+ }
769
+ return ranOn(task);
770
+ };
771
+ const touchesFiber = (ran) => ran !== void 0 && touches.has(ran);
772
+ const extraScheduling = () => scheduledInStep > 1 || globalWorkThisStep;
773
+ const sharedWork = (ran) => extraScheduling() || touchesFiber(ran);
774
+ const isVisible = (task, ran) => task.external || sharedWork(ran);
775
+ const stepRecord = (input, task, ran) => ({
776
+ step: stepCount,
777
+ choice: input.choice,
778
+ options: input.options,
779
+ fallback: input.fallback,
780
+ deviation: input.choice !== input.fallback,
781
+ forced: task.forced,
782
+ external: task.external,
783
+ fiberId: ran?.id,
784
+ visible: isVisible(task, ran)
785
+ });
786
+ const recordStep = (input, task, ran) => {
787
+ lastRan = ran;
788
+ steps.push(stepRecord(input, task, ran));
789
+ if (exploring) decisions.push(input.choice);
790
+ };
791
+ const queuedResumeOf = (fiber) => (task) => task.external && task.owner === fiber;
792
+ const afterQueuedResume = (fiber, after) => {
793
+ const index = pending.findIndex(queuedResumeOf(fiber));
794
+ const task = pending[index];
795
+ if (task === void 0) return false;
796
+ pending[index] = {
797
+ ...task,
798
+ run: () => {
799
+ task.run();
800
+ after();
801
+ }
802
+ };
803
+ return true;
804
+ };
805
+ const takeTask = (choice) => {
806
+ const task = taskAt(choice);
807
+ if (task === void 0) return void 0;
808
+ pending.splice(choice, 1);
809
+ return task;
810
+ };
811
+ const step = (input) => {
812
+ const task = takeTask(input.choice);
813
+ if (task === void 0) throw new Error(`effect-sim-kernel: no task to run at decision ${input.choice}`);
814
+ const ran = runTask(task);
815
+ recordStep(input, task, ran);
816
+ };
817
+ const sharesId = (id) => (candidate) => candidate.id === id;
818
+ const fiberWithId = (id) => [...fibers].find(sharesId(id));
819
+ const namedTarget = (target) => target === "lastRan" ? lastRan : fiberWithId(target);
820
+ const targetFiber = (target) => target === "root" ? root : namedTarget(target);
821
+ const isUnfinished = (fiber) => fiber !== void 0 && fiber.pollUnsafe() === void 0;
822
+ const unfinished = (fiber) => isUnfinished(fiber) ? fiber : void 0;
823
+ const release = () => {
824
+ running = false;
825
+ if (restoreHooks !== void 0) restoreHooks();
826
+ restoreHooks = void 0;
827
+ };
828
+ const kernel = {
829
+ pending,
830
+ fibers,
831
+ steps,
832
+ decisions,
833
+ escapes,
834
+ scheduler,
835
+ dispatcher,
836
+ clocks,
837
+ get phase() {
838
+ return phase;
839
+ },
840
+ get exploring() {
841
+ return exploring;
842
+ },
843
+ get root() {
844
+ return root;
845
+ },
846
+ get running() {
847
+ return running;
848
+ },
849
+ start: (started) => {
850
+ root = started;
851
+ running = true;
852
+ },
853
+ release,
854
+ beginExploration: () => {
855
+ exploring = true;
856
+ },
857
+ effectDefault,
858
+ step,
859
+ resumeExternally: (fiber, run) => {
860
+ pending.push({
861
+ owner: fiber,
862
+ run,
863
+ external: true,
864
+ forced: false,
865
+ step: stepCount
866
+ });
867
+ scheduledInStep++;
868
+ },
869
+ firstEvaluation: (fiber) => {
870
+ if (evaluated.has(fiber)) return false;
871
+ evaluated.add(fiber);
872
+ return true;
873
+ },
874
+ afterQueuedResume,
875
+ observeShared: (target) => {
876
+ if (phase === "step") touches.add(target);
877
+ },
878
+ observeGlobalWork: () => {
879
+ if (phase === "step") globalWorkThisStep = true;
880
+ },
881
+ unobserved: (name) => {
882
+ unobservedNames.add(name);
883
+ },
884
+ holdScope: (scope, holder) => {
885
+ if (heldByAnother(scope, holder)) unobservedNames.add("Scope finalizer");
886
+ },
887
+ takeUnobserved: () => {
888
+ const found = [...unobservedNames].sort();
889
+ unobservedNames.clear();
890
+ return found;
891
+ },
892
+ resolveTarget: (target) => unfinished(targetFiber(target)),
893
+ interrupt: (fiber) => {
894
+ methodOf(fiber, "interruptUnsafe")?.call(fiber);
895
+ }
896
+ };
897
+ restoreHooks = acquireHooks(kernel);
898
+ return kernel;
899
+ };
900
+ //#endregion
901
+ //#region src/internal/runQueue.ts
902
+ let tail = Promise.resolve();
903
+ /** @internal */
904
+ const acquireRun = () => {
905
+ const previous = tail;
906
+ const turn = Promise.withResolvers();
907
+ tail = turn.promise;
908
+ return previous.then(() => turn.resolve);
909
+ };
910
+ //#endregion
911
+ //#region src/internal/stepLoop.ts
912
+ /**
913
+ * The async step loop (R1, R4, R5, R36). It picks one pending task per step —
914
+ * by a caller-supplied decision path, a `choose` callback, or Effect's own
915
+ * dispatcher order — runs it to its next yield, and drains in-process
916
+ * microtasks after every step so a Promise-woken fiber becomes the next
917
+ * scheduling choice. At quiescence the kernel settles its clocks (R37), and
918
+ * when nothing can move it names what the run waits on; a deadlock report
919
+ * lists every suspended fiber with its frames.
920
+ *
921
+ * The loop is written as explicit Promise chains on purpose: the kernel has to
922
+ * run outside Effect's runtime to control scheduling, and every `.then` is one
923
+ * microtask checkpoint — exactly the in-process work R36 hands to the kernel.
924
+ */
925
+ /**
926
+ * The discriminant tags of the run outcome; the variants inherit them because
927
+ * an `Exit` cannot travel through a schema.
928
+ */
929
+ /** @internal */
930
+ const runOutcomeTags = {
931
+ completed: { _tag: "Completed" },
932
+ failed: { _tag: "Failed" },
933
+ escape: { _tag: "Escape" },
934
+ blocked: { _tag: "Blocked" },
935
+ deadlock: { _tag: "Deadlock" },
936
+ runaway: { _tag: "Runaway" }
937
+ };
938
+ const DEFAULT_MAX_STEPS = 5e4;
939
+ const DEFAULT_STEP_TURNS = 4;
940
+ const DEFAULT_QUIESCENCE_TURNS = 1e3;
941
+ const MAX_HOST_WAITS = 1e4;
942
+ /**
943
+ * Marks the point in a program where exploration may begin (R15). Under
944
+ * `explore: 'body'`, every decision before it stays on Effect's order.
945
+ */
946
+ /** @internal */
947
+ const beginExploration = Effect.sync(() => {
948
+ const kernel = currentKernel();
949
+ if (kernel !== void 0) kernel.beginExploration();
950
+ });
951
+ /** One microtask checkpoint: already-queued callbacks run before this resumes. */
952
+ const turn = (value) => Promise.resolve().then(() => value);
953
+ const drain = (turns) => turns <= 0 ? Promise.resolve() : turn(void 0).then(() => drain(turns - 1));
954
+ const maxStepsOf = (options) => options.maxSteps ?? DEFAULT_MAX_STEPS;
955
+ const stepTurnsOf = (options) => options.stepTurns ?? DEFAULT_STEP_TURNS;
956
+ const quiescenceTurnsOf = (options) => options.quiescenceTurns ?? DEFAULT_QUIESCENCE_TURNS;
957
+ const choiceOption = (task, index, fallback) => ({
958
+ fiberId: task.owner?.id,
959
+ isDefault: index === fallback,
960
+ external: task.external,
961
+ forced: task.forced
962
+ });
963
+ const choiceOptions = (kernel, fallback) => kernel.pending.map((task, index) => choiceOption(task, index, fallback));
964
+ const recordedAt = (kernel, options) => options.path?.[kernel.decisions.length];
965
+ const chosenBy = (kernel, options, fallback) => {
966
+ const choice = {
967
+ index: kernel.decisions.length,
968
+ options: choiceOptions(kernel, fallback)
969
+ };
970
+ return options.choose?.(choice);
971
+ };
972
+ const pathOrChoose = (kernel, options, fallback) => {
973
+ const recorded = recordedAt(kernel, options);
974
+ if (recorded !== void 0) return recorded;
975
+ return chosenBy(kernel, options, fallback);
976
+ };
977
+ const exploredChoice = (kernel, options, fallback) => {
978
+ if (!kernel.exploring) return void 0;
979
+ return pathOrChoose(kernel, options, fallback);
980
+ };
981
+ const boundedChoice = (kernel, chosen, fallback) => {
982
+ if (chosen === void 0) return fallback;
983
+ return Math.max(0, Math.min(chosen, kernel.pending.length - 1));
984
+ };
985
+ const decide = (kernel, options) => {
986
+ const fallback = kernel.effectDefault();
987
+ return {
988
+ choice: boundedChoice(kernel, exploredChoice(kernel, options, fallback), fallback),
989
+ options: kernel.pending.length,
990
+ fallback
991
+ };
992
+ };
993
+ const escapeFailureOf = (escaped) => ({
994
+ ...runOutcomeTags.escape,
995
+ timer: escaped.timer,
996
+ site: escaped.site
997
+ });
998
+ const runawayOf = (kernel, options, guard) => {
999
+ if (guard <= maxStepsOf(options)) return void 0;
1000
+ return {
1001
+ ...runOutcomeTags.runaway,
1002
+ steps: kernel.steps.length,
1003
+ pending: kernel.pending.length
1004
+ };
1005
+ };
1006
+ const quiescenceFailure = (kernel, before) => {
1007
+ const resources = newResources(before);
1008
+ if (resources.length === 0) return {
1009
+ ...runOutcomeTags.deadlock,
1010
+ suspended: describeSuspended(kernel.fibers)
1011
+ };
1012
+ return {
1013
+ ...runOutcomeTags.blocked,
1014
+ on: waitKindOf(resources),
1015
+ resources
1016
+ };
1017
+ };
1018
+ const isBlockedStall = (excuse) => "on" in excuse;
1019
+ const isAwaitableKind = (excuse) => excuse.on === "File" || excuse.on === "Socket";
1020
+ const isAwaitableStall = (excuse) => isBlockedStall(excuse) && isAwaitableKind(excuse);
1021
+ const awaitsStall = (options, excuse) => options.external === "await" && isAwaitableStall(excuse);
1022
+ const tasksPending = (state) => state.kernel.pending.length > 0;
1023
+ const hostCheckYield = (state) => {
1024
+ const { promise, resolve } = Promise.withResolvers();
1025
+ state.hostImmediate(() => resolve(void 0));
1026
+ return promise;
1027
+ };
1028
+ const hostYield = (state) => hostCheckYield(state).then(() => drain(DEFAULT_STEP_TURNS)).then(() => drain(DEFAULT_QUIESCENCE_TURNS));
1029
+ const awaitedResources = (state) => newResources(state.before);
1030
+ const waitsRemain = (resources) => resources.some((resource) => waitKindOf([resource]) === "File" || waitKindOf([resource]) === "Socket");
1031
+ const loweredBaseline = (before, now) => new Map([...before].map(([name, count]) => [name, Math.min(count, now.get(name) ?? 0)]));
1032
+ const revivedDrive = (state) => drive({
1033
+ ...state,
1034
+ before: loweredBaseline(state.before, resourceCounts())
1035
+ });
1036
+ const waitedOutcome = (state) => revivedAfterHost(state, 0);
1037
+ const revivedAfterHost = (state, waited) => hostYield(state).then(() => revivedAfterYield(state, waited));
1038
+ const revivedAfterYield = (state, waited) => tasksPending(state) ? revivedDrive(state) : revivedByResources(state, waited);
1039
+ const revivedByResources = (state, waited) => waitsRemain(awaitedResources(state)) ? revivedAfterLimit(state, waited) : revivedAfterHost(state, waited + 1);
1040
+ const revivedAfterLimit = (state, waited) => waited > MAX_HOST_WAITS ? Promise.resolve(failedOn(state.kernel, quiescenceFailure(state.kernel, state.before))) : revivedAfterHost(state, waited + 1);
1041
+ const waitForExternal = (state, _excuse) => drain(quiescenceTurnsOf(state.options)).then(() => waitedOutcome(state));
1042
+ const awaitedStall = (state, excuse) => awaitsStall(state.options, excuse) ? waitForExternal(state, excuse) : Promise.resolve(failedOn(state.kernel, excuse));
1043
+ const stallByExternal = (state, excuse) => awaitedStall(state, excuse);
1044
+ const classifyStall = (state) => seamOffersProgress(state.options.onQuiescent) ? Promise.resolve(void 0) : stallByExternal(state, quiescenceFailure(state.kernel, state.before));
1045
+ const seamOrFailure = (state) => classifyStall(state);
1046
+ const completedOn = (kernel, exit) => ({
1047
+ ...runOutcomeTags.completed,
1048
+ exit,
1049
+ steps: kernel.steps,
1050
+ decisions: kernel.decisions
1051
+ });
1052
+ const failedOn = (kernel, failure) => ({
1053
+ ...runOutcomeTags.failed,
1054
+ failure,
1055
+ steps: kernel.steps,
1056
+ decisions: kernel.decisions
1057
+ });
1058
+ const interruptLive = (kernel, fiber) => {
1059
+ if (fiber !== void 0) kernel.interrupt(fiber);
1060
+ };
1061
+ const interruptTarget = (kernel, target) => interruptLive(kernel, kernel.resolveTarget(target ?? "root"));
1062
+ const interruptAt = (kernel, interruption) => {
1063
+ if (kernel.steps.length !== interruption.atStep) return;
1064
+ interruptTarget(kernel, interruption.target);
1065
+ };
1066
+ const applyInterrupt = (kernel, options) => {
1067
+ const interruption = options.interrupt;
1068
+ if (interruption !== void 0) interruptAt(kernel, interruption);
1069
+ };
1070
+ const advance$1 = (state) => {
1071
+ state.kernel.step(decide(state.kernel, state.options));
1072
+ applyInterrupt(state.kernel, state.options);
1073
+ return drain(stepTurnsOf(state.options));
1074
+ };
1075
+ const seamOffersProgress = (seam) => seam !== void 0 && seam();
1076
+ const resettled = (state) => {
1077
+ if (state.kernel.pending.length > 0) return Promise.resolve(void 0);
1078
+ return seamOrFailure(state);
1079
+ };
1080
+ const stalled = (state) => drain(quiescenceTurnsOf(state.options)).then(() => resettled(state));
1081
+ const quiescent = (state) => {
1082
+ const exit = state.root.pollUnsafe();
1083
+ if (exit !== void 0) return Promise.resolve(completedOn(state.kernel, exit));
1084
+ return stalled(state);
1085
+ };
1086
+ const settled$1 = (state) => {
1087
+ if (state.kernel.pending.length > 0) return Promise.resolve(void 0);
1088
+ return quiescent(state);
1089
+ };
1090
+ const progressed = (state, done) => done !== void 0 ? Promise.resolve(done) : advance$1(state).then(() => void 0);
1091
+ const escapeOrRunaway = (kernel, options, guard) => {
1092
+ const escaped = kernel.escapes[0];
1093
+ if (escaped !== void 0) return escapeFailureOf(escaped);
1094
+ return runawayOf(kernel, options, guard);
1095
+ };
1096
+ const rejectsChosenExploration = (options) => options.path !== void 0 || options.choose !== void 0;
1097
+ const rejectsAwaitedExploration = (options) => options.external === "await" && rejectsChosenExploration(options);
1098
+ const rejectAwaitedExploration = (options) => {
1099
+ if (rejectsAwaitedExploration(options)) throw new Error("effect-sim-kernel: external \"await\" runs only on Effect's own order, so it refuses path and choose");
1100
+ };
1101
+ const iteration = (state) => {
1102
+ const halt = escapeOrRunaway(state.kernel, state.options, state.guard);
1103
+ if (halt !== void 0) return Promise.resolve(failedOn(state.kernel, halt));
1104
+ return settled$1(state).then((done) => progressed(state, done));
1105
+ };
1106
+ const continued = (state, halted) => halted !== void 0 ? Promise.resolve(halted) : drive({
1107
+ ...state,
1108
+ guard: state.guard + 1
1109
+ });
1110
+ const drive = (state) => iteration(state).then((halted) => continued(state, halted));
1111
+ const RUN_OPTION_KEYS = [
1112
+ "choose",
1113
+ "explore",
1114
+ "external",
1115
+ "interrupt",
1116
+ "maxSteps",
1117
+ "onQuiescent",
1118
+ "path",
1119
+ "quiescenceTurns",
1120
+ "stepTurns"
1121
+ ];
1122
+ const isHostObject$1 = (candidate) => typeof candidate === "object";
1123
+ const hasOptionKeys = (candidate) => Object.keys(candidate).every((key) => RUN_OPTION_KEYS.includes(key));
1124
+ const isRunOptions = (candidate) => isHostObject$1(candidate) && hasOptionKeys(candidate);
1125
+ const isProgram = (candidate) => !isRunOptions(candidate);
1126
+ /**
1127
+ * Runs one Effect program under one kernel (R2: every clock the program can
1128
+ * reach is the kernel's virtual root clock; R37: at quiescence the kernel
1129
+ * settles its test clocks, then advances the root clock). Driven by the
1130
+ * decision path or chooser in `options`, it returns the exit, the decisions
1131
+ * taken, and a per-step record of which fiber ran. A run started while one is
1132
+ * active queues behind it, so two runs never share the global hooks.
1133
+ */
1134
+ const lockedRun = (program, options, release) => {
1135
+ const kernel = makeKernel({ exploring: options.explore !== "body" });
1136
+ const recorder = installEscapeRecorder((escape) => {
1137
+ kernel.escapes.push(escape);
1138
+ });
1139
+ const userSeam = options.onQuiescent;
1140
+ const root = Effect.runFork(Effect.provideService(program, Clock.Clock, kernel.clocks.clock), { scheduler: kernel.scheduler });
1141
+ kernel.start(root);
1142
+ return drive({
1143
+ kernel,
1144
+ root,
1145
+ options: {
1146
+ ...options,
1147
+ onQuiescent: () => stepClocks(kernel.clocks) || seamOffersProgress(userSeam)
1148
+ },
1149
+ before: resourceCounts(),
1150
+ guard: 0,
1151
+ hostImmediate: recorder.hostImmediate
1152
+ }).finally(() => {
1153
+ recorder.restore();
1154
+ kernel.release();
1155
+ release();
1156
+ });
1157
+ };
1158
+ const queuedRun = (program, options, release) => {
1159
+ try {
1160
+ return lockedRun(program, options, release);
1161
+ } catch (error) {
1162
+ release();
1163
+ return Promise.reject(error);
1164
+ }
1165
+ };
1166
+ const runKernelImpl = (program, options = {}) => {
1167
+ rejectAwaitedExploration(options);
1168
+ return acquireRun().then((release) => queuedRun(program, options, release));
1169
+ };
1170
+ //#endregion
1171
+ //#region src/Kernel/Run.ts
1172
+ const run = dual((args) => args.length > 0 && isProgram(args[0]), runKernelImpl);
1173
+ /**
1174
+ * Whether the live run is inside a synchronous step. A library that samples a
1175
+ * run from outside can tell work the run caused from work an outside fiber did
1176
+ * between steps. `false` when no run is live.
1177
+ */
1178
+ const isStepping = () => currentKernel()?.phase === "step";
1179
+ //#endregion
1180
+ //#region src/Kernel/Pct.ts
1181
+ /**
1182
+ * Seeded PCT (Burckhardt, Kothari & Musuvathi): each fiber gets a random
1183
+ * priority, the highest-priority runnable task runs, and `depth - 1` change
1184
+ * points among the first `steps` explored decisions lower the running fiber's
1185
+ * priority. A seed replays the whole schedule deterministically, and a
1186
+ * parent-owned child-start task is targeted positionally so a newly started
1187
+ * child still gets its own chance to run.
1188
+ */
1189
+ const mulberry32 = (seed) => {
1190
+ let state = seed | 0;
1191
+ return () => {
1192
+ state = state + 1831565813 | 0;
1193
+ let mixed = state;
1194
+ mixed = Math.imul(mixed ^ mixed >>> 15, mixed | 1);
1195
+ mixed ^= mixed + Math.imul(mixed ^ mixed >>> 7, mixed | 61);
1196
+ return ((mixed ^ mixed >>> 14) >>> 0) / 4294967296;
1197
+ };
1198
+ };
1199
+ const NO_FIBER = -1;
1200
+ const changePoints = (rng, depth, steps) => {
1201
+ const changes = /* @__PURE__ */ new Map();
1202
+ for (let lowered = 1; lowered < depth; lowered++) changes.set(Math.floor(rng() * Math.max(steps, 1)), depth - lowered);
1203
+ return changes;
1204
+ };
1205
+ const fiberIdOf = (choice, position) => {
1206
+ const option = choice.options[position];
1207
+ return option === void 0 ? void 0 : option.fiberId;
1208
+ };
1209
+ const fiberKeyOf = (choice, position) => {
1210
+ return fiberIdOf(choice, position) ?? NO_FIBER;
1211
+ };
1212
+ const priorityOf = (picker, key) => {
1213
+ const known = picker.priorities.get(key);
1214
+ if (known !== void 0) return known;
1215
+ const fresh = picker.depth + picker.rng();
1216
+ picker.priorities.set(key, fresh);
1217
+ return fresh;
1218
+ };
1219
+ const scoresOf = (picker, choice) => choice.options.map((_option, position) => priorityOf(picker, fiberKeyOf(choice, position)));
1220
+ const highestOf = (scores) => Math.max(...scores);
1221
+ const bestPositions = (scores, highest) => scores.flatMap((score, position) => score === highest ? [position] : []);
1222
+ const bestOf = (picker, choice) => {
1223
+ const scores = scoresOf(picker, choice);
1224
+ return bestPositions(scores, highestOf(scores));
1225
+ };
1226
+ const soleOf = (best) => best.length === 1 ? best[0] : void 0;
1227
+ const randomAmong = (draw, best) => {
1228
+ return best[Math.floor(draw * best.length)] ?? 0;
1229
+ };
1230
+ const selected = (picker, best) => {
1231
+ const sole = soleOf(best);
1232
+ if (sole !== void 0) return sole;
1233
+ return randomAmong(picker.rng(), best);
1234
+ };
1235
+ const bestKey = (choice, best) => fiberKeyOf(choice, best[0] ?? NO_FIBER);
1236
+ const applyChange = (picker, choice, best) => {
1237
+ const lowered = picker.changes.get(choice.index);
1238
+ if (lowered === void 0) return;
1239
+ picker.priorities.set(bestKey(choice, best), lowered);
1240
+ };
1241
+ const pick = (options) => {
1242
+ const rng = mulberry32(options.seed);
1243
+ const depth = options.depth ?? 3;
1244
+ const picker = {
1245
+ priorities: /* @__PURE__ */ new Map(),
1246
+ changes: changePoints(rng, depth, options.steps),
1247
+ rng,
1248
+ depth
1249
+ };
1250
+ return (choice) => {
1251
+ if (choice.options.length <= 1) return void 0;
1252
+ const best = bestOf(picker, choice);
1253
+ applyChange(picker, choice, best);
1254
+ return selected(picker, best);
1255
+ };
1256
+ };
1257
+ const failKept$2 = (result) => "failure" in result;
1258
+ const distinctFibers$1 = (result) => new Set(result.steps.map((step) => step.fiberId)).size;
1259
+ const stepCountOf = (result) => result.steps.length;
1260
+ const surveyed = (result, survey) => ({
1261
+ steps: Math.max(survey.steps, stepCountOf(result)),
1262
+ fibers: Math.max(survey.fibers, distinctFibers$1(result))
1263
+ });
1264
+ const boundOf$1 = (survey, depth, runs) => ({
1265
+ fibers: survey.fibers,
1266
+ operations: survey.steps,
1267
+ preemptions: 0,
1268
+ depth,
1269
+ runs,
1270
+ pruning: {
1271
+ enabled: false,
1272
+ disabledBy: []
1273
+ }
1274
+ });
1275
+ const failureOf = (result, isFailure) => isFailure(result);
1276
+ const chooserFor$1 = (state, seed) => pick({
1277
+ seed,
1278
+ depth: state.depth,
1279
+ steps: state.steps
1280
+ });
1281
+ const optionsFor = (state, seed) => {
1282
+ const chooser = chooserFor$1(state, seed);
1283
+ if (state.maxSteps === void 0) return { choose: chooser };
1284
+ return {
1285
+ choose: chooser,
1286
+ maxSteps: state.maxSteps
1287
+ };
1288
+ };
1289
+ const runSeed = (state, seed) => run(state.program, optionsFor(state, seed));
1290
+ const failureFor = (state, seed, result) => failureOf(result, state.isFailure) ? {
1291
+ seed,
1292
+ result
1293
+ } : void 0;
1294
+ const collectedFailure = (state, seed, result) => {
1295
+ const failure = failureFor(state, seed, result);
1296
+ if (failure !== void 0) state.failures.push(failure);
1297
+ };
1298
+ const exploreSeeds = (state, seed) => {
1299
+ if (seed >= state.seeds) return Promise.resolve(state.failures);
1300
+ return runSeed(state, seed).then((result) => {
1301
+ collectedFailure(state, seed, result);
1302
+ return exploreSeeds(state, seed + 1);
1303
+ });
1304
+ };
1305
+ const absorbBaseline = (state, baseline) => {
1306
+ const survey = surveyed(baseline, state.survey);
1307
+ state.steps = survey.steps;
1308
+ state.survey.fibers = survey.fibers;
1309
+ state.survey.steps = survey.steps;
1310
+ };
1311
+ const baselineOptions = (state) => {
1312
+ if (state.maxSteps === void 0) return {};
1313
+ return { maxSteps: state.maxSteps };
1314
+ };
1315
+ const seedsOf = (options) => options.seeds ?? 250;
1316
+ const depthOf = (options) => options.depth ?? 3;
1317
+ const stepsOf = (options) => options.steps ?? 0;
1318
+ const failureCheckOf = (options) => options.isFailure ?? failKept$2;
1319
+ const pctImpl = (program, options = {}) => {
1320
+ const state = {
1321
+ program,
1322
+ depth: depthOf(options),
1323
+ seeds: seedsOf(options),
1324
+ steps: stepsOf(options),
1325
+ isFailure: failureCheckOf(options),
1326
+ maxSteps: options.maxSteps,
1327
+ survey: {
1328
+ steps: 0,
1329
+ fibers: 0
1330
+ },
1331
+ failures: []
1332
+ };
1333
+ return run(program, baselineOptions(state)).then((baseline) => {
1334
+ absorbBaseline(state, baseline);
1335
+ return exploreSeeds(state, 0).then((failures) => ({
1336
+ failures,
1337
+ bound: boundOf$1(state.survey, state.depth, state.seeds + 1)
1338
+ }));
1339
+ });
1340
+ };
1341
+ const pct = dual((args) => args.length === 2 || Effect.isEffect(args[0]), pctImpl);
1342
+ //#endregion
1343
+ //#region src/internal/Unobserved.ts
1344
+ /**
1345
+ * Unobserved shared-primitive detection (R35, AE12). The kernel observes `Ref`
1346
+ * and `Deferred` only, so a run that touches `Queue`, `PubSub`, `Semaphore`,
1347
+ * `Latch`, or a scope finalizer must be searched unpruned, with the primitive
1348
+ * named in the result. A queue's state lives in plain properties assigned onto
1349
+ * a prototype-backed object, so its fields are intercepted through accessors
1350
+ * on that prototype; the other three primitives are class instances whose
1351
+ * fields are defined directly on each instance and would shadow such
1352
+ * accessors, so their prototype methods are intercepted instead. Every
1353
+ * accessor and method notes through `currentKernel()` — the live kernel owns
1354
+ * the per-run collector, so nothing is recorded outside a run and no
1355
+ * module-level mutable state exists here. Installation is claimed once per
1356
+ * patched prototype by a symbol slot on that prototype, and the members the
1357
+ * interception depends on are checked against a freshly constructed instance
1358
+ * before it is sealed: an Effect that renames or reshapes them fails the run
1359
+ * loudly instead of silently leaving races unsearched.
1360
+ */
1361
+ const INSTALLED = Symbol("~effect-sim-kernel/unobservedInstalled");
1362
+ const isHostObject = (candidate) => typeof candidate === "object" && candidate !== null;
1363
+ const isFunction = (candidate) => typeof candidate === "function";
1364
+ const isScopeContext = (candidate) => isHostObject(candidate);
1365
+ const fieldOf = (target, key) => {
1366
+ const host = isHostObject(target) ? target : {};
1367
+ return Reflect.get(host, key);
1368
+ };
1369
+ const objectOf = (candidate) => isHostObject(candidate) ? candidate : void 0;
1370
+ const protoOf = (value) => objectOf(Object.getPrototypeOf(value));
1371
+ const note = (name) => {
1372
+ currentKernel()?.unobserved(name);
1373
+ };
1374
+ const slotFor = (field) => Symbol(field);
1375
+ const readSlot = (slots, slot, name) => {
1376
+ note(name);
1377
+ return slots[slot];
1378
+ };
1379
+ const defineField = (proto, field, name) => {
1380
+ const slot = slotFor(field);
1381
+ Object.defineProperty(proto, field, {
1382
+ configurable: true,
1383
+ get() {
1384
+ return readSlot(this, slot, name);
1385
+ },
1386
+ set(value) {
1387
+ note(name);
1388
+ this[slot] = value;
1389
+ }
1390
+ });
1391
+ };
1392
+ const interceptFields = (proto, fields, name) => {
1393
+ for (const field of fields) defineField(proto, field, name);
1394
+ };
1395
+ const noteAndCall = (original, name) => function(...args) {
1396
+ note(name);
1397
+ return Reflect.apply(original, this, args);
1398
+ };
1399
+ const defineMethod = (proto, method, name) => {
1400
+ const original = fieldOf(proto, method);
1401
+ Object.defineProperty(proto, method, {
1402
+ configurable: true,
1403
+ value: isFunction(original) ? noteAndCall(original, name) : original
1404
+ });
1405
+ };
1406
+ const interceptMethods = (proto, methods, name) => {
1407
+ for (const method of methods) defineMethod(proto, method, name);
1408
+ };
1409
+ const sealed = (proto) => fieldOf(proto, INSTALLED) !== void 0;
1410
+ const sealAndReturn = (proto) => {
1411
+ Reflect.set(proto, INSTALLED, true);
1412
+ return proto;
1413
+ };
1414
+ const isUnsealed = (proto) => proto !== void 0 && !sealed(proto);
1415
+ const requireField = (instance, field, name) => {
1416
+ if (!Object.hasOwn(instance, field)) throw new Error(`effect-sim-kernel: ${name} has no '${field}' state field on the pinned Effect version; unobserved detection would silently miss it`);
1417
+ };
1418
+ const requireFields = (instance, fields, name) => {
1419
+ for (const field of fields) requireField(instance, field, name);
1420
+ };
1421
+ const hasMethod = (proto, method) => proto !== void 0 && Object.hasOwn(proto, method);
1422
+ const requireMethod = (proto, method, name) => {
1423
+ if (!hasMethod(proto, method)) throw new Error(`effect-sim-kernel: ${name} has no '${method}' method on the pinned Effect version; unobserved detection would silently miss it`);
1424
+ };
1425
+ const requireUnshadowed = (instance, method, name) => {
1426
+ if (Object.hasOwn(instance, method)) throw new Error(`effect-sim-kernel: ${name} has an own '${method}' property shadowing the method on the pinned Effect version; unobserved detection would silently miss it`);
1427
+ };
1428
+ const requireMethods = (instance, methods, name) => {
1429
+ const proto = protoOf(instance);
1430
+ for (const method of methods) {
1431
+ requireMethod(proto, method, name);
1432
+ requireUnshadowed(instance, method, name);
1433
+ }
1434
+ };
1435
+ const installFields = (instance, fields, name) => {
1436
+ const proto = protoOf(instance);
1437
+ if (!isUnsealed(proto)) return;
1438
+ requireFields(instance, fields, name);
1439
+ interceptFields(sealAndReturn(proto), fields, name);
1440
+ };
1441
+ const installMethods = (instance, methods, name) => {
1442
+ const proto = protoOf(instance);
1443
+ if (!isUnsealed(proto)) return;
1444
+ requireMethods(instance, methods, name);
1445
+ interceptMethods(sealAndReturn(proto), methods, name);
1446
+ };
1447
+ const queueStateFields = [
1448
+ "dispatcher",
1449
+ "capacity",
1450
+ "strategy",
1451
+ "messages",
1452
+ "scheduleRunning",
1453
+ "state"
1454
+ ];
1455
+ const semaphoreMethods = [
1456
+ "take",
1457
+ "takeIfAvailable",
1458
+ "release",
1459
+ "resize",
1460
+ "withPermits",
1461
+ "withPermitsIfAvailable"
1462
+ ];
1463
+ const latchMethods = [
1464
+ "scheduleUnsafe",
1465
+ "openUnsafe",
1466
+ "closeUnsafe",
1467
+ "isOpen"
1468
+ ];
1469
+ const pubSubMethods = [
1470
+ "publish",
1471
+ "publishAll",
1472
+ "subscribe"
1473
+ ];
1474
+ /**
1475
+ * A PubSub hands its work to a backing instance carried on its `pubsub`
1476
+ * property: the wrapper's own prototype only carries `pipe`, while every
1477
+ * publish and subscribe dispatches to the backing's methods.
1478
+ */
1479
+ const pubSubBacking = () => {
1480
+ const backing = fieldOf(Effect.runSync(PubSub.unbounded()), "pubsub");
1481
+ return isHostObject(backing) ? backing : {};
1482
+ };
1483
+ const fiberContext = (fiber) => fieldOf(fiber, "context");
1484
+ const scopedContext = (fiber) => {
1485
+ const context = fiberContext(fiber);
1486
+ return isScopeContext(context) ? context : void 0;
1487
+ };
1488
+ const heldScope = (fiber) => {
1489
+ const context = scopedContext(fiber);
1490
+ return context === void 0 ? void 0 : Option.getOrUndefined(Context.getOption(context, Scope.Scope));
1491
+ };
1492
+ const holdIn = (scope, holder) => {
1493
+ currentKernel()?.holdScope(scope, holder);
1494
+ };
1495
+ const noteHeldScope = (self) => {
1496
+ const scope = heldScope(self);
1497
+ if (scope !== void 0) holdIn(scope, self);
1498
+ };
1499
+ /**
1500
+ * A scope's finalizers live in plain object state the kernel cannot watch, but
1501
+ * only a scope two fibers hold can race: the kernel is told who holds each
1502
+ * scope and records the finalizer as unobserved once a second fiber does.
1503
+ */
1504
+ const setAndNote = (original, self, args) => {
1505
+ Reflect.apply(original, self, args);
1506
+ noteHeldScope(self);
1507
+ };
1508
+ const originalSetContext = (proto) => {
1509
+ const candidate = fieldOf(proto, "setContext");
1510
+ return isFunction(candidate) ? candidate : void 0;
1511
+ };
1512
+ const installSetContext = (proto, original) => {
1513
+ Object.defineProperty(proto, "setContext", {
1514
+ configurable: true,
1515
+ value: function(...args) {
1516
+ setAndNote(original, this, args);
1517
+ }
1518
+ });
1519
+ };
1520
+ const fiberProto = () => {
1521
+ if (!isUnsealed(FIBER_PROTOTYPE)) return void 0;
1522
+ return sealAndReturn(FIBER_PROTOTYPE);
1523
+ };
1524
+ const withOriginalSetContext = (proto) => {
1525
+ const original = originalSetContext(proto);
1526
+ if (original === void 0) return;
1527
+ installSetContext(proto, original);
1528
+ };
1529
+ const wrapSetContext = () => {
1530
+ const proto = fiberProto();
1531
+ if (proto === void 0) return;
1532
+ withOriginalSetContext(proto);
1533
+ };
1534
+ /** @internal */
1535
+ const installUnobserved = () => {
1536
+ installFields(Effect.runSync(Queue.unbounded()), queueStateFields, "Queue");
1537
+ installMethods(Semaphore.makeUnsafe(1), semaphoreMethods, "Semaphore");
1538
+ installMethods(Latch.makeUnsafe(false), latchMethods, "Latch");
1539
+ installMethods(pubSubBacking(), pubSubMethods, "PubSub");
1540
+ wrapSetContext();
1541
+ };
1542
+ const searchTags = {
1543
+ completed: { _tag: "Completed" },
1544
+ overBudget: { _tag: "OverBudget" }
1545
+ };
1546
+ const PRIMITIVES = {
1547
+ Queue: "Queue",
1548
+ PubSub: "PubSub",
1549
+ Semaphore: "Semaphore",
1550
+ Latch: "Latch",
1551
+ "Scope finalizer": "Scope finalizer"
1552
+ };
1553
+ const failKept$1 = (result) => "failure" in result;
1554
+ const DEFAULT_PREEMPTIONS = 2;
1555
+ const DEFAULT_MAX_SCHEDULES = 1e5;
1556
+ const branchable = (position, explored) => position >= explored;
1557
+ const distinctFibers = (result) => new Set(result.steps.map((step) => step.fiberId)).size;
1558
+ const preemptionsOf = (options) => options.preemptions ?? DEFAULT_PREEMPTIONS;
1559
+ const maxSchedulesOf = (options) => options.maxSchedules ?? DEFAULT_MAX_SCHEDULES;
1560
+ const pruneOf = (options) => options.prune ?? true;
1561
+ const searchState = (program, options) => ({
1562
+ program,
1563
+ queue: [{
1564
+ path: [],
1565
+ used: 0
1566
+ }],
1567
+ head: 0,
1568
+ schedules: 0,
1569
+ fibers: 0,
1570
+ operations: 0,
1571
+ collected: [],
1572
+ preemptions: preemptionsOf(options),
1573
+ maxSchedules: maxSchedulesOf(options),
1574
+ isFailure: options.isFailure ?? failKept$1,
1575
+ maxSteps: options.maxSteps,
1576
+ prune: pruneOf(options)
1577
+ });
1578
+ const namedPrimitives = (collected) => [...new Set(collected)].sort((left, right) => left < right ? -1 : 1).flatMap((name) => {
1579
+ const primitive = PRIMITIVES[name];
1580
+ return primitive === void 0 ? [] : [primitive];
1581
+ });
1582
+ const pruningLive = (state) => state.prune && state.collected.length === 0;
1583
+ const pruningSkipped = (state) => !pruningLive(state);
1584
+ const disabledPruning = (state) => unpruned(namedPrimitives(state.collected));
1585
+ const pruningOf = (state) => {
1586
+ if (pruningSkipped(state)) return disabledPruning(state);
1587
+ return pruned;
1588
+ };
1589
+ const boundOf = (state) => ({
1590
+ fibers: state.fibers,
1591
+ operations: state.operations,
1592
+ preemptions: state.preemptions,
1593
+ depth: state.preemptions,
1594
+ runs: state.schedules,
1595
+ pruning: pruningOf(state)
1596
+ });
1597
+ const drainNow = (collected) => {
1598
+ const kernel = currentKernel();
1599
+ if (kernel !== void 0) collected.push(...kernel.takeUnobserved());
1600
+ };
1601
+ const chooserFor = (schedule, collected) => {
1602
+ const recorded = (choice) => schedule.path[choice.index];
1603
+ return (choice) => {
1604
+ drainNow(collected);
1605
+ return recorded(choice);
1606
+ };
1607
+ };
1608
+ const runOptions = (state, choose) => {
1609
+ const maxSteps = state.maxSteps;
1610
+ if (maxSteps === void 0) return { choose };
1611
+ return {
1612
+ choose,
1613
+ maxSteps
1614
+ };
1615
+ };
1616
+ const spentAt = (result, position) => result.steps.slice(0, position).filter((step) => step.deviation).length;
1617
+ const indices$1 = (count) => Array.from({ length: count }, (_value, index) => index);
1618
+ const preemptableStep = (state, visible) => pruningLive(state) ? visible : true;
1619
+ const branchCost = (fallback, alt, spent) => alt === fallback ? spent : spent + 1;
1620
+ const altBranch = (state, fallback, position, choices, spent, alt) => {
1621
+ const cost = branchCost(fallback, alt, spent);
1622
+ return cost <= state.preemptions ? {
1623
+ path: [...choices.slice(0, position), alt],
1624
+ used: cost
1625
+ } : void 0;
1626
+ };
1627
+ const branchSkipped = (step, alt, preemptable) => alt === step.choice || !preemptable;
1628
+ const visibleBranch = (state, step, position, choices, spent, alt) => {
1629
+ if (branchSkipped(step, alt, preemptableStep(state, step.visible))) return void 0;
1630
+ return altBranch(state, step.fallback, position, choices, spent, alt);
1631
+ };
1632
+ const stepBranches = (state, result, position) => {
1633
+ const step = result.steps[position];
1634
+ if (step === void 0) return [];
1635
+ const spent = spentAt(result, position);
1636
+ return indices$1(step.options).flatMap((alt) => {
1637
+ const branch = visibleBranch(state, step, position, result.decisions, spent, alt);
1638
+ return branch === void 0 ? [] : [branch];
1639
+ });
1640
+ };
1641
+ const freshBranches = (state, result, explored, position) => {
1642
+ if (!branchable(position, explored)) return [];
1643
+ return stepBranches(state, result, position);
1644
+ };
1645
+ const branchesOf = (state, result, explored) => result.decisions.flatMap((_decision, position) => freshBranches(state, result, explored, position));
1646
+ const absorb = (state, observed) => {
1647
+ state.schedules += 1;
1648
+ state.collected.push(...observed.unobserved);
1649
+ state.fibers = Math.max(state.fibers, distinctFibers(observed.result));
1650
+ state.operations = Math.max(state.operations, observed.result.steps.length);
1651
+ };
1652
+ const found = (state, observed) => ({
1653
+ ...searchTags.completed,
1654
+ failures: [{
1655
+ path: observed.result.decisions,
1656
+ preemptions: observed.schedule.used,
1657
+ result: observed.result
1658
+ }],
1659
+ bound: boundOf(state)
1660
+ });
1661
+ const observe = (state, observed) => {
1662
+ absorb(state, observed);
1663
+ if (state.isFailure(observed.result)) return Promise.resolve(found(state, observed));
1664
+ return expand(state, observed);
1665
+ };
1666
+ const completedOutcome = (state) => ({
1667
+ ...searchTags.completed,
1668
+ failures: [],
1669
+ bound: boundOf(state)
1670
+ });
1671
+ const overBudget = (state) => ({
1672
+ ...searchTags.overBudget,
1673
+ failures: [],
1674
+ bound: boundOf(state)
1675
+ });
1676
+ const scheduleHalt = (state) => {
1677
+ if (state.schedules < state.maxSchedules) return void 0;
1678
+ return overBudget(state);
1679
+ };
1680
+ const pendingSchedule = (state) => {
1681
+ const schedule = state.queue[state.head];
1682
+ if (schedule !== void 0) state.head += 1;
1683
+ return schedule;
1684
+ };
1685
+ const exploreNext = (state) => {
1686
+ const schedule = pendingSchedule(state);
1687
+ if (schedule === void 0) return Promise.resolve(completedOutcome(state));
1688
+ const collected = [];
1689
+ return run(state.program, runOptions(state, chooserFor(schedule, collected))).then((result) => observe(state, {
1690
+ result,
1691
+ schedule,
1692
+ unobserved: collected
1693
+ }));
1694
+ };
1695
+ const driveSearch = (state) => {
1696
+ const halted = scheduleHalt(state);
1697
+ if (halted !== void 0) return Promise.resolve(halted);
1698
+ return exploreNext(state);
1699
+ };
1700
+ const expand = (state, observed) => {
1701
+ const explored = observed.schedule.path.length;
1702
+ const fresh = branchesOf(state, observed.result, explored);
1703
+ for (const branch of fresh) state.queue.push(branch);
1704
+ return driveSearch(state);
1705
+ };
1706
+ const searchImpl = (program, options = {}) => {
1707
+ installUnobserved();
1708
+ const state = searchState(program, options);
1709
+ return driveSearch(state);
1710
+ };
1711
+ const search = dual((args) => args.length === 2 || Effect.isEffect(args[0]), searchImpl);
1712
+ //#endregion
1713
+ //#region src/Kernel/Shrink.ts
1714
+ const failKept = (result) => "failure" in result;
1715
+ const withoutSteps = (state) => {
1716
+ const maxSteps = state.maxSteps;
1717
+ if (maxSteps === void 0) return {};
1718
+ return { maxSteps };
1719
+ };
1720
+ const withSteps = (state) => {
1721
+ const maxSteps = state.maxSteps;
1722
+ if (maxSteps === void 0) return { path: state.path };
1723
+ return {
1724
+ path: state.path,
1725
+ maxSteps
1726
+ };
1727
+ };
1728
+ const optionsOf = (state) => {
1729
+ if (state.path.length === 0) return withoutSteps(state);
1730
+ return withSteps(state);
1731
+ };
1732
+ const runRound = (state) => run(state.program, optionsOf(state));
1733
+ const indices = (count) => Array.from({ length: count }, (_value, index) => index);
1734
+ const entryAt = (path, index) => path[index];
1735
+ const clonedEntries = (path) => {
1736
+ const clone = [];
1737
+ for (const index of indices(path.length)) clone[index] = entryAt(path, index);
1738
+ return clone;
1739
+ };
1740
+ const withoutAt = (path, position) => {
1741
+ const candidate = clonedEntries(path);
1742
+ candidate[position] = void 0;
1743
+ return candidate;
1744
+ };
1745
+ const withoutFrom = (path, position) => clonedEntries(path).slice(0, position);
1746
+ const deviationAt = (step) => step.deviation;
1747
+ const nextOffset = (result, from) => result.steps.slice(from).findIndex(deviationAt);
1748
+ const nextPosition = (result, from) => {
1749
+ const offset = nextOffset(result, from);
1750
+ return offset < 0 ? void 0 : from + offset;
1751
+ };
1752
+ const notedEntry = (entries, step) => {
1753
+ if (deviationAt(step)) entries[step.step - 1] = step.choice;
1754
+ };
1755
+ const deviationEntriesOf = (result) => {
1756
+ const entries = [];
1757
+ for (const step of result.steps) notedEntry(entries, step);
1758
+ return entries;
1759
+ };
1760
+ const PASS_LIMIT = 256;
1761
+ const attemptPath = (progress, candidate) => runRound({
1762
+ ...progress.state,
1763
+ path: candidate
1764
+ }).then((reset) => progress.state.isFailure(reset) ? { kept: candidate } : { kept: void 0 });
1765
+ /**
1766
+ * Deviations can hold each other up: a later detour that only matters because
1767
+ * of an earlier one survives every single reset, yet the schedule fails
1768
+ * without either. Resetting a deviation together with every later one first
1769
+ * clears such a chain in one attempt; the single reset follows only when
1770
+ * later deviations exist, since otherwise both candidates are the same.
1771
+ */
1772
+ const singleAfterMissedSuffix = (progress, position, suffix) => {
1773
+ if (nextPosition(progress.result, position + 1) === void 0) return Promise.resolve(suffix);
1774
+ return attemptPath(progress, withoutAt(progress.path, position));
1775
+ };
1776
+ const attemptSingleAfterSuffix = (progress, position, suffix) => suffix.kept === void 0 ? singleAfterMissedSuffix(progress, position, suffix) : Promise.resolve(suffix);
1777
+ const attemptReset = (progress, position) => attemptPath(progress, withoutFrom(progress.path, position)).then((suffix) => attemptSingleAfterSuffix(progress, position, suffix));
1778
+ const settled = (progress) => Promise.resolve(progress.path);
1779
+ const adoptedPass = (progress, kept) => runRound({
1780
+ ...progress.state,
1781
+ path: kept
1782
+ }).then((replay) => pass({
1783
+ state: progress.state,
1784
+ path: kept,
1785
+ result: replay,
1786
+ from: 0,
1787
+ passes: progress.passes + 1
1788
+ }));
1789
+ const advance = (progress, attempt) => {
1790
+ if (attempt.kept !== void 0) return adoptedPass(progress, attempt.kept);
1791
+ return pass({
1792
+ ...progress,
1793
+ from: progress.from + 1
1794
+ });
1795
+ };
1796
+ const resetStep = (progress, position) => attemptReset(progress, position).then((attempt) => advance(progress, attempt));
1797
+ const resumePass = (progress) => {
1798
+ const position = nextPosition(progress.result, progress.from);
1799
+ return position === void 0 ? settled(progress) : resetStep(progress, position);
1800
+ };
1801
+ const pass = (progress) => {
1802
+ if (progress.passes >= PASS_LIMIT) return settled(progress);
1803
+ return resumePass(progress);
1804
+ };
1805
+ const deviationsOf = (result) => result.steps.filter(deviationAt).length;
1806
+ const shrunkOf = (state, path) => runRound({
1807
+ ...state,
1808
+ path
1809
+ }).then((replay) => ({
1810
+ path: replay.decisions,
1811
+ deviations: deviationsOf(replay),
1812
+ result: replay
1813
+ }));
1814
+ const shrinkImpl = (program, options) => {
1815
+ const state = {
1816
+ program,
1817
+ path: options.path,
1818
+ isFailure: options.isFailure ?? failKept,
1819
+ maxSteps: options.maxSteps
1820
+ };
1821
+ return runRound(state).then((failing) => pass({
1822
+ state,
1823
+ path: deviationEntriesOf(failing),
1824
+ result: failing,
1825
+ from: 0,
1826
+ passes: 0
1827
+ }).then((path) => shrunkOf({
1828
+ ...state,
1829
+ path
1830
+ }, path)));
1831
+ };
1832
+ const shrink = dual(2, shrinkImpl);
1833
+ const withoutIndex = (commands, index) => [...commands.slice(0, index), ...commands.slice(index + 1)];
1834
+ const COMMAND_PASS_LIMIT = 64;
1835
+ const restartCommands = (state, candidate) => commandsPass({
1836
+ commands: candidate,
1837
+ stillFails: state.stillFails,
1838
+ passes: state.passes + 1
1839
+ });
1840
+ const tryIndex = (state, index) => {
1841
+ const candidate = withoutIndex(state.commands, index);
1842
+ return state.stillFails(candidate).then((failed) => {
1843
+ if (failed) return restartCommands(state, candidate);
1844
+ return tryNext(state, index);
1845
+ });
1846
+ };
1847
+ const tryNext = (state, index) => {
1848
+ const next = index + 1;
1849
+ if (next >= state.commands.length) return Promise.resolve(state.commands);
1850
+ return tryIndex(state, next);
1851
+ };
1852
+ const commandsPass = (state) => {
1853
+ if (state.passes >= COMMAND_PASS_LIMIT) return Promise.resolve(state.commands);
1854
+ return tryIndex(state, 0);
1855
+ };
1856
+ const shrinkCommandsImpl = (commands, stillFails) => commandsPass({
1857
+ commands,
1858
+ stillFails,
1859
+ passes: 0
1860
+ });
1861
+ const shrinkCommands = dual((args) => Array.isArray(args[0]), shrinkCommandsImpl);
1862
+ //#endregion
1863
+ //#region src/Kernel/TestClock.ts
1864
+ /**
1865
+ * The kernel's controllable test clock (R37): what a harness provides in place
1866
+ * of `TestClock.layer()`. Programs keep calling Effect's `TestClock` API —
1867
+ * `adjust` and `setTime` reach this clock through the `Clock` service — but
1868
+ * they suspend the caller, and the kernel moves time only when nothing can
1869
+ * run, firing due sleeps in timestamp order with everything they wake run to a
1870
+ * stop between them.
1871
+ */
1872
+ var TestClock_exports = /* @__PURE__ */ __exportAll({
1873
+ layer: () => layer,
1874
+ make: () => make
1875
+ });
1876
+ /**
1877
+ * Builds the run's test clock and registers it with the kernel, so the run
1878
+ * settles its requests only when nothing else can run. Only available inside a
1879
+ * kernel run.
1880
+ */
1881
+ const make = kernelTestClock;
1882
+ const contextOf = (testClock) => Context.makeUnsafe(/* @__PURE__ */ new Map([[Clock.Clock.key, testClock]]));
1883
+ /** The layer a harness provides in place of `TestClock.layer()`. */
1884
+ const layer = Layer.effectContext(Effect.map(make, contextOf));
1885
+ //#endregion
1886
+ //#region src/Kernel/mod.ts
1887
+ var Kernel_exports = /* @__PURE__ */ __exportAll({
1888
+ TestClock: () => TestClock_exports,
1889
+ beginExploration: () => beginExploration,
1890
+ currentPreemptionsFor: () => currentPreemptionsFor,
1891
+ currentProfile: () => currentProfile,
1892
+ currentSeedsFor: () => currentSeedsFor,
1893
+ isStepping: () => isStepping,
1894
+ localPreemptions: () => 1,
1895
+ localSeeds: () => 25,
1896
+ outcomeTags: () => runOutcomeTags,
1897
+ pct: () => pct,
1898
+ pctDepth: () => 3,
1899
+ perChangeSeeds: () => 250,
1900
+ pick: () => pick,
1901
+ preemptionsFor: () => preemptionsFor,
1902
+ pruned: () => pruned,
1903
+ run: () => run,
1904
+ search: () => search,
1905
+ searchTags: () => searchTags,
1906
+ seedsFor: () => seedsFor,
1907
+ shrink: () => shrink,
1908
+ shrinkCommands: () => shrinkCommands,
1909
+ unpruned: () => unpruned
1910
+ });
1911
+ //#endregion
1912
+ export { Kernel_exports as Kernel };