reactor-effect-client 0.6.0 → 0.7.1

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.
@@ -1,11 +1,98 @@
1
1
  import * as Option from "effect/Option";
2
+ /**
3
+ * The indexes of a playing clip's cues that fall due by `untilMs` and have not fired, in
4
+ * the order they fall: an offset from its start, or back from the end of its length.
5
+ */
6
+ export const dueCues = (cues, fired, startedAtMs, durationSeconds, untilMs) => cues
7
+ .map((cue, index) => ({
8
+ index,
9
+ atMs: cue.from === "start"
10
+ ? startedAtMs + cue.offsetMs
11
+ : startedAtMs + durationSeconds * 1000 - cue.offsetMs,
12
+ }))
13
+ .filter(({ index, atMs }) => !fired.has(index) && atMs <= untilMs)
14
+ .sort((a, b) => a.atMs - b.atMs)
15
+ .map(({ index }) => index);
16
+ /**
17
+ * The requested length for the next filler clip. Before an anchor, equal clips that tile the
18
+ * uncovered gap within the provider's lengths, so filler ends on the anchor; otherwise the
19
+ * shortest clip, which keeps boundaries, and so reactions, frequent. `ratio` is a built
20
+ * clip's actual over requested length.
21
+ */
22
+ export const fillLength = (uncoveredSeconds, lengths, ratio) => {
23
+ const clamp = (requested) => Math.min(lengths.max, Math.max(lengths.min, requested));
24
+ if (!(uncoveredSeconds > 0))
25
+ return lengths.min;
26
+ const pieces = Math.max(1, Math.ceil(uncoveredSeconds / (lengths.max * ratio)));
27
+ return clamp(uncoveredSeconds / pieces / ratio);
28
+ };
29
+ /** A held clip that would be next within this many seconds is removed and rebuilt. */
30
+ const exposureMarginSeconds = 1.5;
31
+ /** Enough measured builds to act on. */
32
+ export const minimumSamples = 3;
33
+ const quantile = (values, q) => {
34
+ const sorted = [...values].sort((a, b) => a - b);
35
+ return sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
36
+ };
37
+ const spreadOf = (samples) => samples.length < minimumSamples
38
+ ? undefined
39
+ : { median: quantile(samples, 0.5), p95: quantile(samples, 0.95) };
40
+ /**
41
+ * Estimates from recent samples: build seconds per requested second, of independent and of
42
+ * continued clips, and actual over requested length.
43
+ */
44
+ export const estimatesFrom = (build, length, continued = []) => {
45
+ const continuedBuild = spreadOf(continued);
46
+ return {
47
+ build: spreadOf(build),
48
+ ...(continuedBuild === undefined ? {} : { continuedBuild }),
49
+ length: length.length === 0 ? 1 : quantile(length, 0.5),
50
+ };
51
+ };
52
+ /**
53
+ * Until a continued build is measured, one is projected at this multiple of an independent
54
+ * build. On hosted H3 a continued 5 s clip took 5.45 s to build, against 2.1 to 2.2 s for
55
+ * independent ones (the 0.7.0 `scheduler-edits` run).
56
+ */
57
+ const continuedBuildFactor = 2.5;
58
+ /**
59
+ * Build seconds per requested second that a continued build is projected at, erring long:
60
+ * the p95 of measured continued builds, or their longest while there are fewer than three;
61
+ * failing those, the same of independent builds times `continuedBuildFactor`. Undefined
62
+ * before any build was measured.
63
+ */
64
+ export const continuedBuildRate = (build, continued) => {
65
+ const long = (samples) => samples.length >= minimumSamples ? quantile(samples, 0.95) : Math.max(...samples);
66
+ if (continued.length > 0)
67
+ return long(continued);
68
+ if (build.length > 0)
69
+ return long(build) * continuedBuildFactor;
70
+ return undefined;
71
+ };
72
+ /**
73
+ * Seconds added to the measured p95 build time before a refill counts as early enough: the
74
+ * scheduler's 100 ms turn, a command round trip, and the provider's delay in starting the
75
+ * next clip (30 to 110 ms on hosted H3).
76
+ */
77
+ const lookaheadMarginSeconds = 1;
78
+ /** Items that pending batches withdraw. */
79
+ export const supersededBy = (batches) => new Set(batches.flatMap((batch) => batch.targets.map((target) => target.key)));
80
+ /** A clip ending within this many seconds is left to end rather than cut. */
81
+ const cutMarginSeconds = 1;
2
82
  const preferredSession = (state) => Option.getOrUndefined(state.preferredSessionId);
83
+ /**
84
+ * When the playing clip started on the monotonic clock. Engine state can show a new clip
85
+ * playing before its Started event is handled, so the state's own observation fills in.
86
+ */
87
+ const playingSince = (playing, playingStartedMs) => playing === undefined
88
+ ? undefined
89
+ : (playingStartedMs.get(playing.clipId) ?? playing.startedAtMonotonicMillis);
3
90
  /** Ready material on a retiring source is not runway for the replacement. */
4
91
  export const runwaySeconds = (state, nowMs, playingStartedMs, owned, items) => {
5
92
  const preferred = preferredSession(state);
6
93
  const playing = Option.getOrUndefined(state.playing);
7
94
  const record = playing === undefined ? undefined : Option.getOrUndefined(playing.record);
8
- const started = playing === undefined ? undefined : playingStartedMs.get(playing.clipId);
95
+ const started = playingSince(playing, playingStartedMs);
9
96
  const rest = record === undefined || started === undefined
10
97
  ? 0
11
98
  : Math.max(0, record.durationSeconds - (nowMs - started) / 1000);
@@ -18,22 +105,295 @@ export const runwaySeconds = (state, nowMs, playingStartedMs, owned, items) => {
18
105
  if (owner?._tag !== "Item")
19
106
  return true;
20
107
  const item = items.find((candidate) => candidate.key === owner.key);
21
- return item?.atMs === undefined || item.atMs <= nowMs;
108
+ return item?.held !== true && (item?.atMs === undefined || item.atMs <= nowMs);
22
109
  })
23
110
  .reduce((seconds, clip) => seconds + clip.durationSeconds, 0));
24
111
  };
25
- /** A pure, single-action policy. The actor re-reads Engine after each applied action. */
112
+ /**
113
+ * Which of two waiting items the build slot takes first: Asap, then everything but held
114
+ * items, then lane, a replacement racing its item, a group already under way, the earlier
115
+ * deadline, and admission.
116
+ */
117
+ const buildOrder = (lanes) => (a, b) => {
118
+ const asap = Number(b.asap === true) - Number(a.asap === true);
119
+ const held = Number(a.held === true) - Number(b.held === true);
120
+ const lane = lanes.indexOf(a.lane) - lanes.indexOf(b.lane);
121
+ // A replacement races the clip it replaces, so it builds first in its lane.
122
+ const replacing = Number(b.replaces !== undefined) - Number(a.replaces !== undefined);
123
+ // A deadline may move a whole group ahead in its lane, never into one being built.
124
+ const open = Number(b.group !== undefined && b.group.index > 0) -
125
+ Number(a.group !== undefined && a.group.index > 0);
126
+ return (asap ||
127
+ held ||
128
+ lane ||
129
+ replacing ||
130
+ open ||
131
+ (a.startByMs ?? Infinity) - (b.startByMs ?? Infinity) ||
132
+ a.admission - b.admission);
133
+ };
134
+ const compareRank = (left, right) => left[0] - right[0] || left[1] - right[1] || left[2] - right[2] || left[3] - right[3];
135
+ /** Where a place sits among a group's parts, and whether a part must wait for the one before it. */
136
+ const ordering = (items, lanes, nowMs, superseded, owned,
137
+ /** Ready clips that have not started: an item following one of them waits behind it. */
138
+ waiting) => {
139
+ // A group's parts in order. A part already pruned has settled, so it counts as admitted.
140
+ const groups = new Map();
141
+ for (const item of items)
142
+ if (item.group !== undefined)
143
+ groups.set(item.group.key, [...(groups.get(item.group.key) ?? []), item]);
144
+ const previousAdmitted = (item) => {
145
+ if (item.group === undefined)
146
+ return true;
147
+ const index = item.group.index;
148
+ const parts = groups.get(item.group.key) ?? [];
149
+ const previous = Math.max(...parts.map((part) => part.group?.index ?? 0).filter((value) => value < index));
150
+ // The previous place may hold a part and its replacement; either one unadmitted holds this part.
151
+ return !parts.some((part) => part.group?.index === previous && part.phase === "Accepted");
152
+ };
153
+ // Once a group airs, its remaining parts stay ahead of the rest of their lane. A group
154
+ // whose first part was pruned has settled it, and a settled first part that did not
155
+ // air withdrew the others.
156
+ const begun = (item) => {
157
+ if (item?.group === undefined)
158
+ return false;
159
+ const parts = groups.get(item.group.key) ?? [];
160
+ return (parts.some((part) => part.startedAtMonoMs !== undefined) ||
161
+ Math.min(...parts.map((part) => part.group?.index ?? 0)) > 0);
162
+ };
163
+ // Within its place, a Ready replacement airs ahead of the item it replaces.
164
+ const byKey = new Map(items.map((item) => [item.key, item]));
165
+ /**
166
+ * The live item a replacement takes the place of. Replacing a replacement that was never
167
+ * built drops that one, so the chain leads back to the item still in the place.
168
+ */
169
+ const replacedOf = (item) => {
170
+ let old = item.replaces === undefined ? undefined : byKey.get(item.replaces);
171
+ while (old?.phase === "Terminal" && old.replaces !== undefined)
172
+ old = byKey.get(old.replaces);
173
+ return old;
174
+ };
175
+ const replacedReady = new Set(items.flatMap((item) => {
176
+ const old = item.phase === "Ready" || item.phase === "Started" ? replacedOf(item) : undefined;
177
+ return old === undefined ? [] : [old.key];
178
+ }));
179
+ const rankItem = (item) => {
180
+ const generation = item?.key !== undefined && replacedReady.has(item.key) ? Infinity : (item?.generation ?? 0);
181
+ if (item?.held === true || (item?.atMs !== undefined && nowMs < item.atMs))
182
+ return [lanes.length + 1, 1, item.admission, generation];
183
+ // It continues the clip it follows, so it airs right behind that clip until that starts.
184
+ if (item?.follows !== undefined && waiting.has(item.follows)) {
185
+ const behind = rankClip(item.follows);
186
+ return [behind[0], behind[1], behind[2], behind[3] + 0.5];
187
+ }
188
+ if (item?.asap === true)
189
+ return [-0.5, 0, item.admission, generation];
190
+ return [
191
+ Math.max(0, lanes.indexOf(item?.lane ?? "")),
192
+ item?.key !== undefined && superseded.has(item.key) ? 2 : begun(item) ? 0 : 1,
193
+ item?.admission ?? 0,
194
+ generation,
195
+ ];
196
+ };
197
+ const rankClip = (clipId) => {
198
+ const clip = owned.get(clipId);
199
+ if (clip === undefined)
200
+ return [-1, 0, 0, 0];
201
+ if (clip._tag === "Filler")
202
+ return [lanes.length, 1, clip.index, 0];
203
+ return rankItem(items.find((value) => value.key === clip.key));
204
+ };
205
+ return { previousAdmitted, begun, rankItem, rankClip, replacedOf };
206
+ };
207
+ /**
208
+ * An accepted drain still owes air to every line not yet Ready, and to a Ready line held
209
+ * for a future At anchor, which runway must reach. Filler is the only material that can
210
+ * cover either, so it keeps playing and refilling until nothing accepted can still leave
211
+ * the host frozen. An Unknown item does not count: without a fenced source it can stay
212
+ * open until the scheduler closes, and filler for it would never stop.
213
+ */
214
+ const fillerHeldFor = (snapshot) => snapshot.drain === "accepted" &&
215
+ snapshot.items.some((item) => item.held !== true &&
216
+ (item.phase === "Accepted" ||
217
+ item.phase === "Building" ||
218
+ (item.phase === "Ready" && item.atMs !== undefined && item.atMs > snapshot.nowMs)));
219
+ /**
220
+ * When a clip could start at the earliest if it took `place`, optimistically, so a refusal
221
+ * means it cannot make it: after the rest of the playing clip and every Ready clip on the
222
+ * preferred source ranked ahead, and after its own build, once builds have been measured.
223
+ * The build waits for the one in flight and for every build that must go first: higher
224
+ * lanes, a replacement or a group already under way in its lane, and earlier deadlines.
225
+ */
226
+ export const projectedStartMs = (view, place) => {
227
+ const { engine, owned, nowMs } = view;
228
+ const playing = Option.getOrUndefined(engine.playing);
229
+ const playingRecord = playing === undefined ? undefined : Option.getOrUndefined(playing.record);
230
+ const started = playingSince(playing, view.playingStartedMs);
231
+ const restMs = playingRecord === undefined || started === undefined
232
+ ? 0
233
+ : Math.max(0, playingRecord.durationSeconds * 1000 - (nowMs - started));
234
+ const { rankItem, rankClip, previousAdmitted } = ordering(view.items, view.lanes, nowMs, supersededBy(view.batches), owned, new Set(engine.ready.map((clip) => clip.clipId)));
235
+ const rank = rankItem(place);
236
+ const preferred = preferredSession(engine);
237
+ const withdrawing = view.withdrawing ?? new Set();
238
+ const aheadMs = engine.ready.reduce((total, record) => {
239
+ if (record.sessionId !== preferred || compareRank(rankClip(record.clipId), rank) >= 0)
240
+ return total;
241
+ const owner = owned.get(record.clipId);
242
+ if (owner?._tag === "Item" && withdrawing.has(owner.key))
243
+ return total;
244
+ return total + record.durationSeconds * 1000;
245
+ }, 0);
246
+ const playable = nowMs + restMs + aheadMs;
247
+ const perSecond = view.estimates.build?.median;
248
+ if (perSecond === undefined || place.seconds === undefined)
249
+ return playable;
250
+ const buildMs = (seconds) => seconds * perSecond * 1000;
251
+ // The build slot is busy until the build in flight is done.
252
+ const inFlight = [
253
+ ...view.items.flatMap((item) => item.phase === "Building" && item.dispatchedAtMs !== undefined && item.key !== place.key
254
+ ? [item.dispatchedAtMs + buildMs(item.seconds ?? 0)]
255
+ : []),
256
+ ...(view.fillerDispatchedAtMs === undefined || view.fillerSeconds === undefined
257
+ ? []
258
+ : [view.fillerDispatchedAtMs + buildMs(view.fillerSeconds)]),
259
+ ];
260
+ // Only builds that can go now and that the build order puts first count, so the
261
+ // projection stays optimistic: not held, future or not-yet items, nor a group's parts
262
+ // after one not yet built.
263
+ const order = buildOrder(view.lanes);
264
+ const first = view.items
265
+ .filter((item) => item.phase === "Accepted" &&
266
+ item.key !== place.key &&
267
+ !withdrawing.has(item.key) &&
268
+ item.held !== true &&
269
+ (item.atMs === undefined || item.atMs <= nowMs) &&
270
+ (item.notBeforeMs === undefined || item.notBeforeMs <= nowMs) &&
271
+ previousAdmitted(item) &&
272
+ order(item, place) < 0)
273
+ .reduce((total, item) => total + buildMs(item.seconds ?? 0), 0);
274
+ const built = Math.max(nowMs, ...inFlight) + first + buildMs(place.seconds);
275
+ return Math.max(playable, built);
276
+ };
277
+ /**
278
+ * The pure policy: every withdrawal the plan wants now, and at most one serialized provider
279
+ * command. The actor re-reads Engine after each applied command.
280
+ */
26
281
  export const plan = (snapshot) => {
27
282
  const { engine, items, nowMs, owned } = snapshot;
283
+ const { previousAdmitted, rankClip, rankItem, replacedOf } = ordering(items, snapshot.lanes, nowMs, supersededBy(snapshot.batches), owned, new Set(engine.ready.map((clip) => clip.clipId)));
284
+ /**
285
+ * The clip that airs just before `item` if its continued build starts now: `predecessor`,
286
+ * unless that build is projected to be Ready only after `predecessor` ends. The clips Ready
287
+ * behind it then air first, and the item continues from, and follows, the one that will be
288
+ * playing when it is Ready, or the last of them. A clip it continues from must already be
289
+ * generated, so none that is still to be built is chosen.
290
+ */
291
+ const airsBefore = (item, predecessor, gone) => {
292
+ const rate = snapshot.continuedBuildRate;
293
+ if (rate === undefined || item.seconds === undefined)
294
+ return { clipId: predecessor };
295
+ const readyAtMs = nowMs + (rate * item.seconds + lookaheadMarginSeconds) * 1000;
296
+ const playing = Option.getOrUndefined(engine.playing);
297
+ const record = playing === undefined ? undefined : Option.getOrUndefined(playing.record);
298
+ const since = playingSince(playing, snapshot.playingStartedMs);
299
+ if (playing !== undefined && (record === undefined || since === undefined))
300
+ return { clipId: predecessor };
301
+ let endMs = record === undefined || since === undefined ? nowMs : since + record.durationSeconds * 1000;
302
+ // The preferred source's Ready clips in the order they air; held and future ones wait.
303
+ const queued = engine.ready
304
+ .filter((clip) => {
305
+ const owner = owned.get(clip.clipId);
306
+ return (clip.sessionId === preferredSession(engine) &&
307
+ !(owner?._tag === "Item" && gone.has(owner.key)) &&
308
+ rankClip(clip.clipId)[0] <= snapshot.lanes.length);
309
+ })
310
+ .sort((a, b) => compareRank(rankClip(a.clipId), rankClip(b.clipId)));
311
+ const after = playing?.clipId === predecessor
312
+ ? 0
313
+ : queued.findIndex((clip) => clip.clipId === predecessor) + 1;
314
+ if (after === 0 && playing?.clipId !== predecessor)
315
+ return { clipId: predecessor };
316
+ for (const clip of queued.slice(0, after))
317
+ endMs += clip.durationSeconds * 1000;
318
+ if (readyAtMs <= endMs)
319
+ return { clipId: predecessor };
320
+ const behind = queued.slice(after);
321
+ for (const [index, clip] of behind.entries()) {
322
+ endMs += clip.durationSeconds * 1000;
323
+ if (readyAtMs <= endMs || index === behind.length - 1)
324
+ return { clipId: clip.clipId, follows: clip.clipId };
325
+ }
326
+ return { clipId: predecessor };
327
+ };
328
+ /**
329
+ * What an item continuing from its predecessor continues from: the Ready clip or waiting
330
+ * item that airs just before it on the preferred source, else the clip playing there, or
331
+ * the one that will be by the time it is built (`airsBefore`). `wait` while that predecessor
332
+ * is not built yet; no clip when there is none, or when the provider no longer offers it
333
+ * for continuation.
334
+ */
335
+ const continuation = (item) => {
336
+ const place = rankItem(item);
337
+ // What will not air before it is no predecessor: the item it replaces, and what a batch
338
+ // or a withdrawal is taking off.
339
+ const gone = new Set([...supersededBy(snapshot.batches), ...snapshot.withdrawing]);
340
+ const replaced = replacedOf(item);
341
+ if (replaced !== undefined)
342
+ gone.add(replaced.key);
343
+ let best;
344
+ const consider = (rank, clipId) => {
345
+ if (compareRank(rank, place) < 0 && (best === undefined || compareRank(rank, best.rank) > 0))
346
+ best = clipId === undefined ? { rank } : { rank, clipId };
347
+ };
348
+ for (const clip of engine.ready) {
349
+ const owner = owned.get(clip.clipId);
350
+ if (clip.sessionId === preferredSession(engine) &&
351
+ !(owner?._tag === "Item" && gone.has(owner.key)))
352
+ consider(rankClip(clip.clipId), clip.clipId);
353
+ }
354
+ for (const other of items)
355
+ if (other.key !== item.key &&
356
+ !gone.has(other.key) &&
357
+ (other.phase === "Accepted" || other.phase === "Building" || other.phase === "Unknown"))
358
+ consider(rankItem(other), undefined);
359
+ if (best !== undefined && best.clipId === undefined)
360
+ return { _tag: "wait" };
361
+ const predecessor = best?.clipId ?? Option.getOrUndefined(engine.playing)?.clipId;
362
+ if (predecessor === undefined)
363
+ return { _tag: "from" };
364
+ const from = airsBefore(item, predecessor, gone);
365
+ return engine.continuable.includes(from.clipId) ? { _tag: "from", ...from } : { _tag: "from" };
366
+ };
28
367
  const runway = runwaySeconds(engine, nowMs, snapshot.playingStartedMs, owned, items);
29
368
  const nextAnchorMs = items
30
369
  .filter((item) => item.phase !== "Terminal" && item.atMs !== undefined && item.atMs > nowMs)
31
370
  .reduce((earliest, item) => Math.min(earliest, item.atMs ?? Infinity), Infinity);
32
371
  const anchorGapSeconds = nextAnchorMs === Infinity ? 0 : (nextAnchorMs - nowMs) / 1000;
33
- const fillTarget = Math.max(snapshot.targetSeconds, anchorGapSeconds);
372
+ // A nonzero floor covers at least one measured p95 build of the next filler clip, so a
373
+ // refill started at the floor is Ready before the picture runs out. A zero floor keeps
374
+ // filler off.
375
+ const p95 = snapshot.estimates.build?.p95;
376
+ const floorSeconds = snapshot.floorSeconds > 0 && p95 !== undefined && snapshot.fillerSeconds !== undefined
377
+ ? Math.max(snapshot.floorSeconds, p95 * snapshot.fillerSeconds + lookaheadMarginSeconds)
378
+ : snapshot.floorSeconds;
379
+ const targetSeconds = Math.max(snapshot.targetSeconds, floorSeconds);
380
+ const fillTarget = Math.max(targetSeconds, anchorGapSeconds);
34
381
  const filling = anchorGapSeconds > runway ||
35
- (snapshot.refillActive ? runway < snapshot.targetSeconds : runway < snapshot.floorSeconds);
36
- const base = { runwaySeconds: runway, refillActive: filling };
382
+ (snapshot.refillActive ? runway < targetSeconds : runway < floorSeconds);
383
+ const playingId = Option.getOrUndefined(engine.playing)?.clipId;
384
+ const fillerHeld = fillerHeldFor(snapshot);
385
+ const withdraw = [];
386
+ const listed = new Set();
387
+ const drop = (item, reason) => {
388
+ if (snapshot.withdrawing.has(item.key) || listed.has(item.key))
389
+ return;
390
+ listed.add(item.key);
391
+ withdraw.push({ key: item.key, reason });
392
+ };
393
+ const waiting = (item) => item.phase === "Accepted" ||
394
+ item.phase === "Building" ||
395
+ item.phase === "Ready" ||
396
+ item.phase === "Unknown";
37
397
  // Sweep every status; expiry behind a nonexpired head must not be stranded.
38
398
  for (const item of items) {
39
399
  if (item.phase !== "Accepted" && item.phase !== "Building" && item.phase !== "Ready")
@@ -45,8 +405,74 @@ export const plan = (snapshot) => {
45
405
  ? lateBy > 0
46
406
  : lateBy > item.late.skipIfLaterThanMs;
47
407
  if ((item.firm && item.startByMs !== undefined && nowMs > item.startByMs) || atExpired)
48
- return { ...base, action: { _tag: "Withdraw", key: item.key, reason: "late" } };
408
+ drop(item, "late");
409
+ }
410
+ // A firm item that cannot start before its deadline is dropped before it takes the build
411
+ // slot, once builds have been measured.
412
+ if (snapshot.estimates.build !== undefined)
413
+ for (const item of items)
414
+ if (item.firm &&
415
+ item.phase === "Accepted" &&
416
+ item.startByMs !== undefined &&
417
+ !snapshot.dispatched.has(item.key) &&
418
+ projectedStartMs(snapshot, item) > item.startByMs)
419
+ drop(item, "late");
420
+ // A part that failed or was dropped withdraws the parts after it.
421
+ for (const item of items) {
422
+ const brokenAt = item.group === undefined ? undefined : snapshot.brokenGroups.get(item.group.key);
423
+ if (brokenAt !== undefined && item.group.index > brokenAt && waiting(item))
424
+ drop(item, "withdrawn");
425
+ }
426
+ // A replacement takes the place once Ready, or at once if nothing was built for the item it
427
+ // replaces; a batch's replacement waits for its batch. If the replaced item starts first,
428
+ // the replacement goes.
429
+ const pendingReplacements = new Set(snapshot.batches.flatMap((batch) => batch.waitFor));
430
+ for (const item of items) {
431
+ if (item.replaces === undefined || item.phase === "Terminal")
432
+ continue;
433
+ const old = replacedOf(item);
434
+ if (old === undefined || old.phase === "Terminal")
435
+ continue;
436
+ if (old.phase === "Started") {
437
+ if (item.phase !== "Started")
438
+ drop(item, "withdrawn");
439
+ }
440
+ else if (
441
+ // A batch's Ready replacement waits for its batch, but one that has started takes
442
+ // the place at once, so the item it replaces never follows it.
443
+ (item.phase === "Ready" && !pendingReplacements.has(item.key)) ||
444
+ item.phase === "Started" ||
445
+ (old.phase === "Accepted" && !snapshot.dispatched.has(old.key)))
446
+ drop(old, "replaced");
49
447
  }
448
+ // A batch takes effect once everything it adds is Ready or has settled. Until then what it
449
+ // withdraws keeps its place, except an item nothing was built for, which covers nothing.
450
+ const commit = [];
451
+ for (const batch of snapshot.batches) {
452
+ const find = (key) => items.find((item) => item.key === key);
453
+ if (batch.waitFor.every((key) => {
454
+ const phase = find(key)?.phase;
455
+ return (phase === undefined || phase === "Ready" || phase === "Started" || phase === "Terminal");
456
+ }))
457
+ commit.push(batch.id);
458
+ else
459
+ for (const { key, reason } of batch.targets) {
460
+ const target = find(key);
461
+ if (target?.phase === "Accepted" && !snapshot.dispatched.has(key))
462
+ drop(target, reason);
463
+ }
464
+ }
465
+ // A held item cannot air without a release a drain will not wait for.
466
+ if (snapshot.drain !== undefined)
467
+ for (const item of items)
468
+ if (item.held === true && waiting(item))
469
+ drop(item, "withdrawn");
470
+ // A drain that finishes only the playing clip withdraws everything waiting.
471
+ if (snapshot.drain === "playing")
472
+ for (const item of items)
473
+ if (waiting(item) && (item.clipId === undefined || item.clipId !== playingId))
474
+ drop(item, "withdrawn");
475
+ const withdrawFiller = [];
50
476
  const preferred = preferredSession(engine);
51
477
  const retiring = Option.getOrUndefined(engine.retiringSessionId);
52
478
  if (preferred !== undefined &&
@@ -56,14 +482,16 @@ export const plan = (snapshot) => {
56
482
  Option.getOrUndefined(engine.building)?.record.sessionId !== retiring &&
57
483
  !items.some((item) => (item.phase === "Building" || item.phase === "Unknown") &&
58
484
  (item.sessionId ?? item.unknownSessionId) === retiring) &&
59
- engine.ready.some((clip) => clip.sessionId === preferred && owned.get(clip.clipId)?._tag === "Item")) {
60
- const staleFiller = engine.ready.filter((clip) => clip.sessionId === retiring && owned.get(clip.clipId)?._tag === "Filler");
61
- if (staleFiller.length > 0)
62
- return {
63
- ...base,
64
- action: { _tag: "WithdrawFiller", clipIds: staleFiller.map((clip) => clip.clipId) },
65
- };
66
- }
485
+ engine.ready.some((clip) => clip.sessionId === preferred && owned.get(clip.clipId)?._tag === "Item"))
486
+ for (const clip of engine.ready)
487
+ if (clip.sessionId === retiring && owned.get(clip.clipId)?._tag === "Filler")
488
+ withdrawFiller.push(clip.clipId);
489
+ // A drain withdraws filler once nothing accepted still needs it to cover the wait.
490
+ if (snapshot.drain !== undefined && !fillerHeld)
491
+ for (const [clipId, owner] of owned)
492
+ if (owner._tag === "Filler" && clipId !== playingId && !withdrawFiller.includes(clipId))
493
+ withdrawFiller.push(clipId);
494
+ const base = { runwaySeconds: runway, refillActive: filling, withdraw, withdrawFiller, commit };
67
495
  // Physical sources are independent queues. A move never ranks across them.
68
496
  let offset = 0;
69
497
  for (const session of engine.ready.length === 0 ? [] : engine.sessions) {
@@ -74,22 +502,7 @@ export const plan = (snapshot) => {
74
502
  }
75
503
  if (actual.length === 0)
76
504
  continue;
77
- const rank = (clipId) => {
78
- const clip = owned.get(clipId);
79
- if (clip === undefined)
80
- return [-1, 0];
81
- if (clip._tag === "Filler")
82
- return [snapshot.lanes.length, clip.index];
83
- const item = items.find((value) => value.key === clip.key);
84
- if (item?.atMs !== undefined && nowMs < item.atMs)
85
- return [snapshot.lanes.length + 1, item.admission];
86
- return [Math.max(0, snapshot.lanes.indexOf(item?.lane ?? "")), item?.admission ?? 0];
87
- };
88
- const desired = [...actual].sort((a, b) => {
89
- const left = rank(a.clipId);
90
- const right = rank(b.clipId);
91
- return left[0] - right[0] || left[1] - right[1];
92
- });
505
+ const desired = [...actual].sort((a, b) => compareRank(rankClip(a.clipId), rankClip(b.clipId)));
93
506
  for (let index = 0; index < actual.length; index++) {
94
507
  if (actual[index]?.clipId === desired[index]?.clipId)
95
508
  continue;
@@ -122,19 +535,51 @@ export const plan = (snapshot) => {
122
535
  }
123
536
  offset += actual.length;
124
537
  }
538
+ // A cut lane's Ready item at the front of its session cuts the playing clip there, once
539
+ // the provider has it at the front.
540
+ if (snapshot.cutLanes.size > 0) {
541
+ const current = Option.getOrUndefined(engine.playing);
542
+ const record = current === undefined ? undefined : Option.getOrUndefined(current.record);
543
+ const since = playingSince(current, snapshot.playingStartedMs);
544
+ const front = record === undefined
545
+ ? undefined
546
+ : engine.ready.find((clip) => clip.sessionId === record.sessionId);
547
+ const owner = front === undefined ? undefined : owned.get(front.clipId);
548
+ const cutter = owner?._tag === "Item" ? items.find((item) => item.key === owner.key) : undefined;
549
+ // Only filler or a clip of a strictly lower lane is cut, never a clip of the cutter's
550
+ // own lane, whatever its rank.
551
+ const playingOwner = current === undefined ? undefined : owned.get(current.clipId);
552
+ const playingItem = playingOwner?._tag === "Item"
553
+ ? items.find((item) => item.key === playingOwner.key)
554
+ : undefined;
555
+ const lower = cutter !== undefined &&
556
+ (playingOwner?._tag === "Filler" ||
557
+ (playingItem !== undefined &&
558
+ snapshot.lanes.indexOf(playingItem.lane) > snapshot.lanes.indexOf(cutter.lane)));
559
+ if (current !== undefined &&
560
+ record !== undefined &&
561
+ since !== undefined &&
562
+ front !== undefined &&
563
+ cutter !== undefined &&
564
+ snapshot.cutLanes.has(cutter.lane) &&
565
+ snapshot.blockedCut !== current.clipId &&
566
+ lower &&
567
+ record.durationSeconds - (nowMs - since) / 1000 > cutMarginSeconds)
568
+ return { ...base, action: { _tag: "Cut", clipId: current.clipId } };
569
+ }
125
570
  // Reorder movable Ready runway before treating a future At clip as exposed.
126
571
  // A wall-clock correction can otherwise require removing and rebuilding it.
127
572
  const playing = Option.getOrUndefined(engine.playing);
128
573
  const playingRecord = playing === undefined ? undefined : Option.getOrUndefined(playing.record);
129
- const playingStarted = playing === undefined ? undefined : snapshot.playingStartedMs.get(playing.clipId);
574
+ const playingStarted = playingSince(playing, snapshot.playingStartedMs);
130
575
  const playingRest = playingRecord === undefined || playingStarted === undefined
131
576
  ? 0
132
577
  : Math.max(0, playingRecord.durationSeconds - (nowMs - playingStarted) / 1000);
133
578
  const exposedAnchor = items.find((item) => {
579
+ const held = item.held === true;
134
580
  if (item.phase !== "Ready" ||
135
581
  item.clipId === undefined ||
136
- item.atMs === undefined ||
137
- item.atMs <= nowMs)
582
+ (!held && (item.atMs === undefined || item.atMs <= nowMs)))
138
583
  return false;
139
584
  const index = engine.ready.findIndex((clip) => clip.clipId === item.clipId);
140
585
  if (index < 0)
@@ -149,10 +594,12 @@ export const plan = (snapshot) => {
149
594
  if (owner?._tag !== "Item")
150
595
  return true;
151
596
  const prior = items.find((candidate) => candidate.key === owner.key);
152
- return prior?.atMs === undefined || prior.atMs <= nowMs;
597
+ return prior?.held !== true && (prior?.atMs === undefined || prior.atMs <= nowMs);
153
598
  })
154
599
  .reduce((seconds, clip) => seconds + clip.durationSeconds, 0);
155
- return playingRest + ahead < (item.atMs - nowMs) / 1000;
600
+ return held
601
+ ? ahead === 0 && playingRest < exposureMarginSeconds
602
+ : playingRest + ahead < (item.atMs - nowMs) / 1000;
156
603
  });
157
604
  if (exposedAnchor?.clipId !== undefined)
158
605
  return {
@@ -160,7 +607,7 @@ export const plan = (snapshot) => {
160
607
  action: { _tag: "DeferAt", key: exposedAnchor.key, clipId: exposedAnchor.clipId },
161
608
  };
162
609
  const preferredAvailability = engine.sessions.find((session) => session.sessionId === preferred)?.availability;
163
- if (!snapshot.accepting || preferredAvailability !== "Ready")
610
+ if (!(snapshot.accepting || snapshot.drain === "accepted") || preferredAvailability !== "Ready")
164
611
  return base;
165
612
  const activeFiller = [...owned.entries()].filter(([clipId, owner]) => owner._tag === "Filler" &&
166
613
  (owner.sessionId === undefined || owner.sessionId === preferred) &&
@@ -175,25 +622,46 @@ export const plan = (snapshot) => {
175
622
  return base;
176
623
  const eligible = items
177
624
  .filter((item) => item.phase === "Accepted" &&
625
+ !listed.has(item.key) &&
626
+ !snapshot.withdrawing.has(item.key) &&
627
+ previousAdmitted(item) &&
178
628
  (item.retryAtMs === undefined || nowMs >= item.retryAtMs) &&
179
629
  (item.notBeforeMs === undefined || nowMs >= item.notBeforeMs) &&
180
630
  // Autoplay cannot hold a Ready clip. Admit a future anchor only once
181
631
  // known material ahead of it covers the time until that anchor.
182
- (item.atMs === undefined || item.atMs <= nowMs || runway >= (item.atMs - nowMs) / 1000))
183
- .sort((a, b) => {
184
- const lane = snapshot.lanes.indexOf(a.lane) - snapshot.lanes.indexOf(b.lane);
185
- return (lane || (a.startByMs ?? Infinity) - (b.startByMs ?? Infinity) || a.admission - b.admission);
186
- });
187
- if (eligible[0] !== undefined)
188
- return { ...base, action: { _tag: "Build", key: eligible[0].key } };
189
- if (snapshot.fillerEnabled &&
632
+ (item.atMs === undefined || item.atMs <= nowMs || runway >= (item.atMs - nowMs) / 1000) &&
633
+ // A held item is built ahead only while filler keeps the runway at its floor.
634
+ (item.held !== true || (floorSeconds > 0 && runway >= floorSeconds)) &&
635
+ // A continuing clip waits for the clip it continues from to be built.
636
+ (item.continuity !== "previous" || continuation(item)._tag !== "wait"))
637
+ .sort(buildOrder(snapshot.lanes));
638
+ const next = eligible[0];
639
+ if (next !== undefined) {
640
+ const from = next.continuity === "previous" ? continuation(next) : undefined;
641
+ return {
642
+ ...base,
643
+ action: from?._tag === "from" && from.clipId !== undefined
644
+ ? {
645
+ _tag: "Build",
646
+ key: next.key,
647
+ continueFrom: from.clipId,
648
+ ...(from.follows === undefined ? {} : { follows: from.follows }),
649
+ }
650
+ : { _tag: "Build", key: next.key },
651
+ };
652
+ }
653
+ if ((snapshot.drain === undefined || fillerHeld) &&
190
654
  filling &&
191
655
  runway < fillTarget &&
192
656
  snapshot.unknownFillerCount === 0 &&
193
657
  nowMs >= snapshot.fillerRetryAtMs)
194
658
  return {
195
659
  ...base,
196
- action: { _tag: "BuildFiller", targetSeconds: fillTarget - runway },
660
+ action: {
661
+ _tag: "BuildFiller",
662
+ targetSeconds: fillTarget - runway,
663
+ durationSeconds: fillLength(anchorGapSeconds - runway, snapshot.fillLengths, snapshot.estimates.length),
664
+ },
197
665
  };
198
666
  return base;
199
667
  };