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