@wardic/core 1.0.0-rc.7 → 1.0.0-rc.9

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.
@@ -6,7 +6,7 @@
6
6
  * Primitive's per-frame cost.
7
7
  *
8
8
  * - **A run** is `run(machine, sink)`: an entry added, its Frames handed to `sink` from the loop's
9
- * next tick, and its settled Frame returned. `acquireUseRelease` removes the entry on every
9
+ * next tick (or its Late step, below), and its settled Frame returned. `acquireUseRelease` removes the entry on every
10
10
  * exit (a settle, an interruption, a defect), so interrupting a run removes it at once. A run
11
11
  * given a token (`run(machine, sink, { supersede })`, #200) joins it, and `Supersede.end` takes
12
12
  * it off at once too, completing its fiber with `Superseded`: no interrupt, and no interrupt
@@ -17,15 +17,25 @@
17
17
  * a Retarget (a removal, then an add, in one call) keeps it, and the Clock goes idle at its
18
18
  * next Refresh frame. The Layer's `Scope` closing interrupts it.
19
19
  * - **A tick** steps the entries the tick began with: an entry added during it (from a sink)
20
- * waits for the next tick, and one removed during it gets no Frame. It steps them in add
20
+ * isn't stepped by it, and one removed during it gets no Frame. It steps them in add
21
21
  * order, those added with `runLast` after all the others (ADR-0027, *Amendment (#137)*). A step or sink that
22
22
  * throws ends only its own run (`Exit.die`); a failure of the loop itself fails every run
23
23
  * still on it, and the next run starts a fresh burst. That includes a run a continuation
24
24
  * starts while the ending burst resumes its runs (#81).
25
- * - **The end of a tick** calls each `afterTick` hook, after every step and sink and the
26
- * continuations of the runs that settled in it, the tick that ends a burst included. The flush
25
+ * - **The end of a tick** calls each `afterTick` hook, with the tick's dt, after every step and sink
26
+ * and the continuations of the runs that settled in it, the tick that ends a burst included. The flush
27
27
  * gate flushes there, so a value paints in the Refresh frame that computed it (ADR-0033). A run
28
28
  * a hook starts keeps the burst: whether it ends is counted after the hooks (#209).
29
+ * - **The Late window** runs from a tick's first step until a microtask the tick queues at its end
30
+ * (ADR-0027 *Amendment (#680)*): what starts in it is drawn in that tick's Refresh frame, after the
31
+ * tick. A run `run` added in it, during the tick or in a microtask the tick's own code queued (Solid
32
+ * 2's effects, a promise it resolved), takes its **Late step** in that microtask: one step at the
33
+ * tick's dt, and the hooks again, so the frame paints it, not its origin. A round whose steps or hooks
34
+ * add more runs is followed by another, at most `MAX_LATE_ROUNDS`; the rest step at the next tick. A
35
+ * `runLast` run takes none: the projection's coordinator, its one caller, would step again the nodes
36
+ * an after-tick Measure pass already stepped. One the tick stepped steps again at dt 0 after a round
37
+ * that stepped a `run` run, so it reads what that round wrote.
38
+ * `inLateWindow()` reads it, for the projection's Measure pass (ADR-0018 *Amendment (#673)*).
29
39
  *
30
40
  * Observability: a span per run, named after its Primitive (`machine.span`), and one per burst
31
41
  * (`wardic.frameloop`). A run's `<name>: start` debug log, annotated with its span's attributes,
@@ -43,8 +53,8 @@
43
53
  * The dev check for non-finite Frames (`CheckFrames`, ADR-0030 decision 7) is a sink wrapper a
44
54
  * run gets at its start when the check is on, so the tick is the same either way.
45
55
  *
46
- * Internal (ADR-0028, decision 11): the service's shape (`run`, `afterTick`) and `make`, behind
47
- * `FrameLoop.layer`.
56
+ * Internal (ADR-0028, decision 11): the service's shape (`run`, `runLast`, `afterTick`,
57
+ * `inLateWindow`) and `make`, behind `FrameLoop.layer`.
48
58
  */
49
59
  import * as Arr from "effect/Array"
50
60
  import * as Bool from "effect/Boolean"
@@ -54,6 +64,7 @@ import * as Data from "effect/Data"
54
64
  import * as Deferred from "effect/Deferred"
55
65
  import * as Effect from "effect/Effect"
56
66
  import * as Exit from "effect/Exit"
67
+ import type * as Fiber from "effect/Fiber"
57
68
  import * as FiberHandle from "effect/FiberHandle"
58
69
  import { constUndefined, identity } from "effect/Function"
59
70
  import * as LogLevel from "effect/LogLevel"
@@ -64,6 +75,7 @@ import * as References from "effect/References"
64
75
  import type * as Scope from "effect/Scope"
65
76
  import * as Stream from "effect/Stream"
66
77
  import * as Tracer from "effect/Tracer"
78
+ import * as UndefinedOr from "effect/UndefinedOr"
67
79
  import * as Clock from "../Clock.ts"
68
80
  import type * as Frame from "../Frame.ts"
69
81
  import * as Supersede from "../Supersede.ts"
@@ -74,6 +86,8 @@ import { isTraced, traced } from "./tracing.ts"
74
86
  // @wardic/core compiles against ES2022 alone, which does not declare `performance` (see
75
87
  // refresh-frame-clock.ts). It is a host global in every Environment Wardic targets.
76
88
  declare const performance: { readonly now: () => number }
89
+ // The same for `queueMicrotask` (see Microtask.ts): the Late window's end (#680).
90
+ declare const queueMicrotask: (callback: () => void) => void
77
91
 
78
92
  /** A run's options: the token it joins, so its caller can end it with others. */
79
93
  // #200.
@@ -92,7 +106,7 @@ export interface Run {
92
106
  export interface Shape {
93
107
  /**
94
108
  * Runs `machine` on the loop, handing each of its Frames to `sink`, from the loop's next tick until it
95
- * settles. Succeeds with the settled Frame; a machine that never settles, `chase`, runs until it's
109
+ * settles; added in the loop's Late window, from its Late step there. Succeeds with the settled Frame; a machine that never settles, `chase`, runs until it's
96
110
  * interrupted or superseded. Dies with the defect if its step or its sink throws. Interrupting it
97
111
  * removes it at once.
98
112
  *
@@ -105,22 +119,33 @@ export interface Shape {
105
119
  /**
106
120
  * `run`, but stepped after every run `run` added, in each tick: for a machine that reads what the
107
121
  * others' sinks wrote in the same tick. Among themselves, these runs step in the order they were added.
122
+ * One added in the Late window takes no Late step: its first step is the next tick. One the tick
123
+ * stepped steps again at dt 0 after a Late round that stepped a `run` run.
108
124
  */
109
125
  // ADR-0027, *Amendment (#137)*: the projection's coordinator is the one caller.
110
126
  readonly runLast: Run
111
127
  /**
112
- * Calls `hook` at the end of every tick, after every run's step and sink and the continuations of the
113
- * runs that settled in it, until the `Scope` closes. Hooks run in the order they were added. A plain
114
- * call, typed like a `Sink`, so a hook that returns an Effect doesn't compile. A hook doesn't throw:
115
- * one that does fails the tick, and with it every run on the loop.
128
+ * Calls `hook` at the end of every tick, with the tick's seconds, after every run's step and sink and
129
+ * the continuations of the runs that settled in it, and again after each of its Late rounds, until the
130
+ * `Scope` closes. Hooks run in the order they were added. A plain call, typed like a `Sink`, so a hook
131
+ * that returns an Effect doesn't compile. A hook doesn't throw: one that does fails the tick, and with
132
+ * it every run on the loop.
116
133
  */
117
- // ADR-0033: the flush gate is the one caller.
118
- readonly afterTick: (hook: () => undefined) => Effect.Effect<void, never, Scope.Scope>
134
+ // ADR-0033: the flush gate's flush. The tick's dt: ADR-0027 *Amendment (#673)*, for the projection's
135
+ // after-tick pass. Again after a Late round (#680), so the gate flushes what the round wrote.
136
+ readonly afterTick: (hook: (dt: number) => undefined) => Effect.Effect<void, never, Scope.Scope>
137
+ /**
138
+ * Whether the **Late window** is open now: from a tick's first step until the microtask it queued at
139
+ * its end has run. What's written then is drawn in that tick's Refresh frame, after the tick.
140
+ */
141
+ // ADR-0027 *Amendment (#680)* (was `ticking()`, #673): the projection's Measure pass reads it at a
142
+ // trigger, to know it will run after its frame's tick.
143
+ readonly inLateWindow: () => boolean
119
144
  }
120
145
 
121
146
  /** One hook on the loop's ticks, one object per `afterTick`, so removing it removes only that one. */
122
147
  interface Hook {
123
- readonly hook: () => undefined
148
+ readonly hook: (dt: number) => undefined
124
149
  }
125
150
 
126
151
  /** One run on the loop. */
@@ -133,8 +158,18 @@ interface Entry {
133
158
  /** Completed by the loop: the settled Frame, the defect, or an interruption; or by its token, `Superseded` (#200). */
134
159
  readonly settled: Deferred.Deferred<Frame.Frame<unknown> | Supersede.Superseded>
135
160
  removed: boolean
161
+ /**
162
+ * Added in the Late window and not yet stepped (#680): a `run` run's Late step is due; a `runLast` run
163
+ * waits for the next tick, and the dt-0 step leaves it out.
164
+ */
165
+ late: boolean
166
+ /** Its span, when traced: marked `late` at its Late step (#680). */
167
+ readonly span: Tracer.Span | undefined
136
168
  }
137
169
 
170
+ /** How many Late rounds a window runs before the rest wait for the next tick: the Measure pass's cap (#680). */
171
+ const MAX_LATE_ROUNDS = 5
172
+
138
173
  /**
139
174
  * The Frame loop's metrics: the running animations, the runs that settled and failed, and each tick's
140
175
  * ms. None unless an app gives them (`FrameLoop.layerMetrics`, #518), so an app that reads none ships and
@@ -268,6 +303,19 @@ export const make = Effect.fnUntraced(
268
303
  // ending burst is still in `burst`, so the loop tracks its burst itself rather than asking the
269
304
  // handle (#81).
270
305
  let bursting = false
306
+ // The Late window (ADR-0027 *Amendment (#680)*): open from a tick's first step until the microtask
307
+ // queued at its end has run. `windowQueued` keeps one microtask per window, however many ticks open
308
+ // it before a checkpoint (a test firing frames back to back).
309
+ let windowOpen = false
310
+ let windowQueued = false
311
+ // The dt of the tick that opened the window: a Late step's.
312
+ let windowDt = 0
313
+ // The `run` runs added in the window, in add order: their Late step is due. The `runLast` runs added
314
+ // in it take none, and are marked only so the dt-0 step leaves them out: they step at the next tick.
315
+ const lateFirst: Array<Entry> = []
316
+ const lateLast: Array<Entry> = []
317
+ // A hook that threw in a Late round: the burst it interrupts ends every run with it (#680, Q15).
318
+ let lateFailure: Cause.Cause<never> | undefined
271
319
  // The runs the loop ended since it last counted (#542): a settle or a failure, into the counters
272
320
  // once per tick. An interruption is neither, nor a superseded run, which the loop doesn't end.
273
321
  let settledCount = 0
@@ -334,10 +382,16 @@ export const make = Effect.fnUntraced(
334
382
  // The first lane's loops stay inline in `tick`: moved into a function shared with the last lane,
335
383
  // Node's `chase/loop` ran 55% slower (`bench:core`, ADR-0027 *Amendment (#137)*).
336
384
  const tick = (dt: number): boolean => {
385
+ // A window this tick finds open is the last frame's, its checkpoint not yet run (back-to-back
386
+ // frames in a test): its runs are on the lanes, so this tick steps them.
387
+ if (lateFirst.length + lateLast.length > 0) dropLate()
388
+ windowOpen = true
389
+ windowDt = dt
337
390
  // The tick's start, read only for the metrics' histogram (#518).
338
391
  let t0 = 0
339
392
  if (Predicate.isNotUndefined(metrics)) t0 = performance.now()
340
- // Both counts before any step: a run added during the tick, to either lane, waits for the next.
393
+ // Both counts before any step: a run added during the tick isn't stepped by it. A `run` run takes its
394
+ // Late step at the window's end, a `runLast` run waits for the next tick (#680).
341
395
  const count = entries.length
342
396
  const lastCount = lastEntries.length
343
397
  for (let i = 0; i < count; i++) {
@@ -370,13 +424,118 @@ export const make = Effect.fnUntraced(
370
424
  // The end of the tick: everything for this Refresh frame is written (ADR-0033). After
371
425
  // `tickMs`, which stays the cost of the steps alone.
372
426
  const ended = hooks
373
- for (let i = 0; i < ended.length; i++) ended[i].hook()
427
+ for (let i = 0; i < ended.length; i++) ended[i].hook(dt)
428
+ // The window stays open to the end of this frame's microtasks, which take the Late steps (#680).
429
+ if (!windowQueued) {
430
+ windowQueued = true
431
+ queueMicrotask(endLateWindow)
432
+ }
374
433
  // The burst ends with no run left, counted after the hooks: one a hook started (the flush
375
- // gate's, running a binding's batch, #209) takes its first step at the next tick.
434
+ // gate's, running a binding's batch, #209) takes its Late step and starts the next burst.
376
435
  return entries.length + lastEntries.length === 0
377
436
  }
378
437
 
379
- const afterTick = (hook: () => undefined): Effect.Effect<void, never, Scope.Scope> => {
438
+ /** Clear the Late lists: each run on them steps at the next tick. */
439
+ const dropLate = (): void => {
440
+ for (let i = 0; i < lateFirst.length; i++) lateFirst[i].late = false
441
+ for (let i = 0; i < lateLast.length; i++) lateLast[i].late = false
442
+ lateFirst.length = 0
443
+ lateLast.length = 0
444
+ }
445
+
446
+ /** Drop `list`'s first `count` entries in place, keeping the rest's order. */
447
+ const dropFirst = (list: Array<Entry>, count: number): void => {
448
+ const left = list.length - count
449
+ for (let i = 0; i < left; i++) list[i] = list[i + count]
450
+ list.length = left
451
+ }
452
+
453
+ /** One step of `entry` at `dt`: its Frame to its sink, its settle, or its defect, as a tick's. */
454
+ const stepOne = (entry: Entry, dt: number): void => {
455
+ try {
456
+ const frame = entry.step(dt)
457
+ entry.sink(frame)
458
+ if (entry.settles && frame.done) end(entry, Exit.succeed(frame))
459
+ } catch (defect) {
460
+ end(entry, dieNamed(entry.name, defect))
461
+ }
462
+ }
463
+
464
+ /** `entry`'s Late step, at the last tick's dt, its span marked. */
465
+ const lateStep = (entry: Entry): boolean => {
466
+ entry.late = false
467
+ if (entry.removed) return false
468
+ if (Predicate.isNotUndefined(entry.span)) entry.span.attribute("late", true)
469
+ stepOne(entry, windowDt)
470
+ return true
471
+ }
472
+
473
+ /**
474
+ * One Late round: the first lane's due runs, then, when one of them stepped, the last lane's runs the
475
+ * tick stepped again at dt 0, so they read what it wrote (#137's reads, Q9), then every hook. What the
476
+ * round adds is the next round's.
477
+ */
478
+ const lateRound = (): void => {
479
+ const firstCount = lateFirst.length
480
+ let stepped = 0
481
+ for (let i = 0; i < firstCount; i++) if (lateStep(lateFirst[i])) stepped++
482
+ if (stepped > 0) {
483
+ const count = lastEntries.length
484
+ for (let i = 0; i < count; i++) {
485
+ const entry = lastEntries[i]
486
+ if (entry.removed || entry.late) continue
487
+ stepOne(entry, 0)
488
+ }
489
+ }
490
+ dropFirst(lateFirst, firstCount)
491
+ const again = hooks
492
+ for (let i = 0; i < again.length; i++) again[i].hook(windowDt)
493
+ }
494
+
495
+ /**
496
+ * The Late window's end, the microtask its tick queued: the Late rounds, then the window closes. A run
497
+ * left past the cap steps at the next tick. A hook that throws ends every run, as in a tick (Q15).
498
+ */
499
+ const endLateWindow = (): void => {
500
+ windowQueued = false
501
+ if (!windowOpen) return
502
+ let rounds = 0
503
+ try {
504
+ while (lateFirst.length > 0 && rounds < MAX_LATE_ROUNDS) {
505
+ rounds++
506
+ lateRound()
507
+ }
508
+ } catch (defect) {
509
+ failLate(defect)
510
+ return
511
+ }
512
+ // Past the cap, the first lane's rest step at the next tick; the last lane's were never due.
513
+ if (lateFirst.length + lateLast.length > 0) dropLate()
514
+ windowOpen = false
515
+ }
516
+
517
+ /**
518
+ * A hook threw in a Late round, outside the burst's stream: the burst is interrupted, and its end
519
+ * fails every run with the defect, as a hook that throws in a tick fails it (#680, Q15).
520
+ */
521
+ const failLate = (defect: unknown): void => {
522
+ lateFailure = Cause.die(defect)
523
+ const fiber = burstFiber()
524
+ if (Predicate.isNotUndefined(fiber)) {
525
+ fiber.interruptUnsafe()
526
+ return
527
+ }
528
+ endAll(Exit.void)
529
+ }
530
+
531
+ /** The burst's fiber, if one holds the subscription. */
532
+ const burstFiber = (): Fiber.Fiber<void, unknown> | undefined => {
533
+ const state = burst.state
534
+ if (state._tag === "Closed") return undefined
535
+ return state.fiber
536
+ }
537
+
538
+ const afterTick = (hook: (dt: number) => undefined): Effect.Effect<void, never, Scope.Scope> => {
380
539
  const added: Hook = { hook }
381
540
  return Effect.acquireRelease(
382
541
  Effect.sync(() => {
@@ -396,8 +555,18 @@ export const make = Effect.fnUntraced(
396
555
  * the runs it ends are still starting, not waiting. Not the per-frame path.
397
556
  */
398
557
  const endAll = (exit: Exit.Exit<void>): void => {
399
- const ending = endingOf(exit)
558
+ // A Late round's hook threw (#680, Q15): this burst was interrupted for it, and its runs end with it.
559
+ const failure = lateFailure
560
+ lateFailure = undefined
561
+ const ending = UndefinedOr.match(failure, { onUndefined: () => endingOf(exit), onDefined: (cause) => Exit.failCause(cause) })
562
+ const failed = Bool.or(Exit.isFailure(exit), Predicate.isNotUndefined(failure))
400
563
  bursting = false
564
+ // A burst that failed closes the window: no later call is in it (#673, TK3; #680). One that ran out
565
+ // of runs leaves it open, so a run started after its last tick, in its frame, takes its Late step.
566
+ if (failed) {
567
+ windowOpen = false
568
+ dropLate()
569
+ }
401
570
  Arr.forEach(Arr.appendAll(entries.splice(0), lastEntries.splice(0)), (entry) => {
402
571
  if (!entry.removed) end(entry, ending)
403
572
  })
@@ -434,16 +603,16 @@ export const make = Effect.fnUntraced(
434
603
  * installed (ADR-0040, *Amendment (#460)*): an app's, the devtools', a test's. Effect's default
435
604
  * records a span nothing reads, a leg's largest cost after its machine.
436
605
  */
437
- const runIn = (lane: Array<Entry>): Run =>
606
+ const runIn = (lane: Array<Entry>, late: Array<Entry>): Run =>
438
607
  (<F extends Frame.Frame<unknown>>(machine: Machine.Machine<F>, sink: FrameLoop.Sink<F>, options?: RunOptions) =>
439
608
  Effect.withFiber((fiber) => {
440
609
  // Its start log only when a Debug log would be kept (#542): Effect's own rule, read once.
441
610
  const logged = !LogLevel.isGreaterThan(fiber.getRef(References.MinimumLogLevel), "Debug")
442
611
  // The metrics from the first run whose fiber has them (#518); none is read once they're in.
443
612
  if (Predicate.isUndefined(metrics)) metrics = fiber.getRef(MetricsGiven)
444
- if (!isTraced(fiber)) return added(lane, machine, sink, options, undefined, logged)
613
+ if (!isTraced(fiber)) return added(lane, late, machine, sink, options, undefined, logged)
445
614
  return Effect.useSpan(machine.span.name, { attributes: machine.span.attributes }, (span) =>
446
- Effect.provideService(added(lane, machine, sink, options, span, logged), Tracer.ParentSpan, span))
615
+ Effect.provideService(added(lane, late, machine, sink, options, span, logged), Tracer.ParentSpan, span))
447
616
  })) as Run
448
617
 
449
618
  /**
@@ -452,6 +621,7 @@ export const make = Effect.fnUntraced(
452
621
  */
453
622
  const added = <F extends Frame.Frame<unknown>>(
454
623
  lane: Array<Entry>,
624
+ late: Array<Entry>,
455
625
  machine: Machine.Machine<F>,
456
626
  sink: FrameLoop.Sink<F>,
457
627
  options: RunOptions | undefined,
@@ -461,7 +631,7 @@ export const make = Effect.fnUntraced(
461
631
  // Per run, a leg each (#460, compose once): Effect's calls data-first, the steps statements.
462
632
  const run = Effect.acquireUseRelease(
463
633
  // `CheckFrames` from the caller's fiber, once per run: with it off, the sink as it is.
464
- Effect.flatMap(Effect.service(CheckFrames), (check) => entered(lane, machine, sink, options, check)),
634
+ Effect.flatMap(Effect.service(CheckFrames), (check) => entered(lane, late, machine, sink, options, check, span)),
465
635
  settledOf as (entry: Entry) => Effect.Effect<F | Supersede.Superseded>,
466
636
  (entry, exit) =>
467
637
  Effect.sync(() => {
@@ -475,13 +645,18 @@ export const make = Effect.fnUntraced(
475
645
  return Effect.annotateLogs(Effect.andThen(Effect.logDebug(`${machine.span.name}: start`), run), machine.span.attributes)
476
646
  }
477
647
 
478
- /** A run's entry on `lane` (and in its token, given one), and the burst started for it. */
648
+ /**
649
+ * A run's entry on `lane` (and in its token, given one), and the burst started for it. Added in the
650
+ * Late window, it's on `late` too: its Late step is due (#680).
651
+ */
479
652
  const entered = <F extends Frame.Frame<unknown>>(
480
653
  lane: Array<Entry>,
654
+ late: Array<Entry>,
481
655
  machine: Machine.Machine<F>,
482
656
  sink: FrameLoop.Sink<F>,
483
657
  options: RunOptions | undefined,
484
658
  check: boolean,
659
+ span: Tracer.Span | undefined,
485
660
  ): Effect.Effect<Entry> => {
486
661
  // A closed Environment takes no runs: nothing would tick them.
487
662
  if (burst.state._tag === "Closed") return Effect.interrupt
@@ -494,13 +669,18 @@ export const make = Effect.fnUntraced(
494
669
  settles: machine.settles,
495
670
  settled: Deferred.makeUnsafe<Frame.Frame<unknown> | Supersede.Superseded>(),
496
671
  removed: false,
672
+ late: windowOpen,
673
+ span,
497
674
  }
498
675
  lane.push(entry)
676
+ if (entry.late) late.push(entry)
499
677
  if (Predicate.isNotUndefined(options)) joinSupersede(options.supersede, entry)
500
678
  return Effect.as(startBurst, entry)
501
679
  }
502
680
 
503
- return { run: runIn(entries), runLast: runIn(lastEntries), afterTick } satisfies Shape
681
+ const inLateWindow = (): boolean => windowOpen
682
+
683
+ return { run: runIn(entries, lateFirst), runLast: runIn(lastEntries, lateLast), afterTick, inLateWindow } satisfies Shape
504
684
  },
505
685
  (self) => traced(self, "wardic.frameloop.make"),
506
686
  )