@torrent-tv/proxy 2.82.0 → 2.83.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/CLAUDE.md +11 -0
  3. package/docs/disk-architecture.md +161 -0
  4. package/docs/encode-architecture.md +36 -7
  5. package/package.json +1 -1
  6. package/routes/api/sources/stats/get.js +11 -2
  7. package/routes/stream/get.js +74 -3
  8. package/services/delivery-probe.js +248 -43
  9. package/services/disk/keep.js +48 -0
  10. package/services/disk/returns.js +103 -0
  11. package/services/download/SwarmSelection.js +5 -5
  12. package/services/download/registry.js +20 -0
  13. package/services/encode/EncodeRun.js +1 -0
  14. package/services/encode/Encoder.js +15 -0
  15. package/services/encode/QsvEncoder.js +5 -0
  16. package/services/encode/SegmentStore.js +14 -0
  17. package/services/encode/VaapiEncoder.js +5 -0
  18. package/services/encode/encode-exit.js +17 -0
  19. package/services/encode/start-stop-cost.js +6 -2
  20. package/services/files/CompletedFiles.js +276 -0
  21. package/services/files/piece-from-whole-file.js +118 -0
  22. package/services/hls-session-manager.js +17 -1
  23. package/services/hwaccel.js +4 -0
  24. package/services/output/cut-grid.js +13 -3
  25. package/services/piece-store/piece-disk-store.js +143 -8
  26. package/services/piece-store/piece-lru.js +17 -0
  27. package/services/piece-store/shared-piece-store.js +1803 -1549
  28. package/services/torrent-pool.js +246 -26
  29. package/services/torrent-worker/client.js +21 -0
  30. package/services/torrent-worker/protocol.js +9 -1
  31. package/services/torrent-worker/worker.js +183 -2
  32. package/test/completed-files.test.js +115 -0
  33. package/test/cuts-follow-published-grid.test.js +35 -0
  34. package/test/delivery-probe.test.js +114 -1
  35. package/test/encode-exit.test.js +18 -0
  36. package/test/keeping-period.test.js +83 -0
  37. package/test/piece-disk-store.test.js +114 -0
  38. package/test/piece-from-whole-file.test.js +129 -0
  39. package/test/piece-store-eviction.test.js +28 -15
  40. package/test/piece-store-never-refuses.test.js +153 -0
  41. package/test/piece-store-reservations.test.js +16 -3
  42. package/test/probe-wedge-certainty.test.js +3 -3
  43. package/test/shared-piece-store.test.js +27 -13
  44. package/test/stream-route.test.js +41 -0
  45. package/test/swarm-follows-readers.test.js +126 -0
  46. package/test/swarm-reach.test.js +5 -0
  47. package/test/upload-hurry.test.js +27 -0
@@ -1,1549 +1,1803 @@
1
- /**
2
- * @file Torrent pieces in shared memory, with disk as the second tier.
3
- *
4
- * Replaces the chunk store WebTorrent would otherwise build for itself. Two
5
- * reasons, one forced and one chosen.
6
- *
7
- * **Forced.** WebTorrent's own piece cache hands out the buffer it keeps using
8
- * and slices again on the next read. The torrent client now runs on its own
9
- * thread, and moving a piece to the main thread by transferring ownership
10
- * detached the cache's memory: proxy 2.9.71-2.9.73 answered every read with an
11
- * empty body (`Stream ends prematurely at 0`) and the failure was invisible,
12
- * because the error never reached the reader. Owning the memory ourselves
13
- * removes the question of whose it was.
14
- *
15
- * **Chosen.** Memory this side of the thread boundary can be *shared* memory,
16
- * which the main thread reads without receiving bytes as a copy — see
17
- * {@link SharedPieceStore#locate}. Measured on the field host: a piece copy
18
- * costs 3.64 ms, a read from the page cache into a buffer we own 7.63 ms, and
19
- * re-downloading a piece from the swarm ~1430 ms. So memory first, disk under
20
- * it, and never the swarm twice.
21
- *
22
- * Per piece allocation: each resident piece owns its own `SharedArrayBuffer`.
23
- * Evicting a piece deletes its entry and the memory is reclaimable by GC.
24
- * `committed` therefore equals `resident`, not a high-water mark.
25
- *
26
- * **Room for a piece is an owned reservation, not a shared number.**
27
- * `#claimSlot` hands back a release the caller runs in a `finally`; nothing
28
- * else touches `#outstandingPieces`. It was a counter incremented in one
29
- * function and decremented in another, and every consequence of that was a
30
- * defect: a failure between the two lost a slot for the life of the process,
31
- * `put`'s error path guessed at the correction and could take back a
32
- * reservation belonging to a different claim, and one lost reservation made
33
- * the five-second "everything is pinned" error permanently unreachable, so a
34
- * read retried every 50 ms for ever without completing or failing. Read out of
35
- * the field failure of 2026-08-31 (`research/worker-heap-oom-2026-08-31.md`).
36
- *
37
- * What this deliberately does NOT do is manage the disk as a cache of its own.
38
- * Pieces evicted from memory are written once and read back on demand; the file
39
- * is discarded whole when the torrent goes away. libtorrent 2.0 and webtor's
40
- * seeder both concluded that a hand-rolled disk cache earns less than it costs,
41
- * and nothing here disagrees.
42
- */
43
-
44
- import os from "node:os";
45
- import { readFileSync } from "node:fs";
46
- import { divideAllowance, machineAllowanceBytes, OtherDemand } from "./allowance.js";
47
- import { PieceLru } from "./piece-lru.js";
48
- import { PieceDiskStore } from "./piece-disk-store.js";
49
-
50
- /**
51
- * Live stores, so the worker can report on them.
52
- *
53
- * @type {Set<SharedPieceStore>}
54
- */
55
- const liveStores = new Set();
56
-
57
- export function collectStoreStats() {
58
- return [...liveStores].map((store) => store.stats());
59
- }
60
-
61
- export function findSharedStore(torrent) {
62
- let candidate = torrent?.store;
63
- for (let depth = 0; candidate && depth < 8; depth += 1) {
64
- if (candidate instanceof SharedPieceStore) {
65
- return candidate;
66
- }
67
- candidate = candidate.store;
68
- }
69
- return null;
70
- }
71
-
72
- /**
73
- * The largest fall in the machine's available memory that this process has
74
- * seen and did not cause itself.
75
- *
76
- * What has to be left for everything else on the machine. It cannot be a share
77
- * of what is free — a share is a number chosen out of nothing, which is what
78
- * `AVAILABLE_MEMORY_SHARE = 0.25`, `MIN_BUDGET_BYTES` and
79
- * `MEMORY_BUDGET_CEILING_BYTES` were until 2026-09-02, all three traceable to
80
- * one observation of one host on 2026-08-03. It is measured instead: between
81
- * two readings, how much available memory went away beyond what the stores
82
- * themselves took. On the field host that quantity is large — while the proxy
83
- * held 76-133 MB overnight the machine's available memory fell from 2378 MB to
84
- * 306 MB and came back — and on a quiet host it stays near zero, which is the
85
- * right answer there.
86
- *
87
- * Starts at zero: nothing is reserved until somebody else has been seen to
88
- * need it.
89
- */
90
- const otherDemand = new OtherDemand();
91
-
92
- /**
93
- * Note what the machine had, and how much of the change was not ours.
94
- *
95
- * @param {number} availableBytes
96
- * @param {number} storeBytes - What the live stores hold right now.
97
- * @returns {number} The reserve, in bytes.
98
- */
99
- export function noteMachineMemory(availableBytes, storeBytes) {
100
- return otherDemand.note(availableBytes, storeBytes);
101
- }
102
-
103
- /** What has recently been observed to be needed by everything that is not us. */
104
- export function machineReserveBytes() {
105
- return otherDemand.reserve();
106
- }
107
-
108
- /** Forget what other processes have needed. For tests, which share a module. */
109
- export function forgetMachineMemory() {
110
- otherDemand.forget();
111
- }
112
-
113
- export { divideAllowance, machineAllowanceBytes };
114
-
115
- export function reviseStoreBudgets() {
116
- const stores = [...liveStores];
117
- const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
118
- const available = availableMemorySync();
119
- const reserve = noteMachineMemory(available, held);
120
- const allowance = machineAllowanceBytes(available, held, reserve);
121
- const shares = divideAllowance(stores.map((store) => store.wantedBytes), allowance);
122
- const revised = [];
123
- for (const [position, store] of stores.entries()) {
124
- revised.push(store.reviseGrowthCeiling(shares[position]));
125
- }
126
- return revised;
127
- }
128
-
129
- /**
130
- * Say how much disk the spilled pieces may take between them.
131
- *
132
- * Told rather than worked out. The disk is one and this store is not its only
133
- * user — the segments an encoder produces are on it too — so a ceiling one of
134
- * two users sets for itself is not a ceiling. Until 2026-09-10 the spill had no
135
- * ceiling of any kind: 14 400 MB written in one fifty-minute viewing.
136
- *
137
- * @param {number | null} allowanceBytes - This thread's whole share, from the
138
- * owner of the disk on the main thread. Null means nobody has said yet, and
139
- * nothing is thrown away until somebody does.
140
- * @param {SharedPieceStore[]} [live] - The stores to divide between.
141
- * @returns {{ name: string, allowanceBytes: number | null, bytes: number }[]}
142
- */
143
- export function reviseSpillBudgets(allowanceBytes, live = [...liveStores]) {
144
- if (live.length === 0) {
145
- return [];
146
- }
147
- // NOT READ HERE. The disk has one owner and it is on the main thread, where
148
- // the segments an encoder produces live on the same disk. Reading it here as
149
- // well is exactly the fault this replaced: two ceilings, each standing for the
150
- // whole disk. What arrives is this thread's whole share.
151
- const total = Number.isFinite(allowanceBytes) && allowanceBytes >= 0 ? allowanceBytes : null;
152
- if (total === null) {
153
- return live.map((store) => store.reviseSpillCeiling(null));
154
- }
155
- // EQUALLY, unlike memory. A store's memory ask is its readers' declared
156
- // windows; the spill has no such statement, because whatever memory evicts
157
- // arrives here. Every store's ask is "all of it", nothing distinguishes them,
158
- // and an equal share is what that means.
159
- const share = Math.floor(total / live.length);
160
- return live.map((store) => store.reviseSpillCeiling(share));
161
- }
162
-
163
- function defaultMemoryBytes() {
164
- const stores = [...liveStores];
165
- const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
166
- const available = availableMemorySync();
167
- const allowance = machineAllowanceBytes(available, held, machineReserveBytes());
168
- // A store being created has no readers, so it has no demand to state and no
169
- // basis for asking for more or less than the others. It opens on an equal
170
- // share and the first revision — within a minute, and within seconds of a
171
- // read starting — replaces that with what its readers actually declare.
172
- // Deliberately not the whole allowance: on a machine with gigabytes free that
173
- // would let a torrent nobody is reading yet fill memory before the first
174
- // revision arrives.
175
- return Math.floor(allowance / (stores.length + 1));
176
- }
177
-
178
- function availableMemorySync() {
179
- try {
180
- const text = readFileSync("/proc/meminfo", "utf8");
181
- const match = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(text);
182
- if (match) {
183
- return Number(match[1]) * 1024;
184
- }
185
- } catch {
186
- }
187
- return os.freemem();
188
- }
189
-
190
- /**
191
- * How many blocks of piece memory this thread has let go of, and how many the
192
- * collector has actually taken back.
193
- *
194
- * Since the store keeps a pool, one block serves many pieces, so this counts
195
- * blocks and not pieces — and a healthy store allocates only as many as its
196
- * allowance permits, so both numbers are now small and nearly equal.
197
- *
198
- * The one reading that separates the two explanations of the 700 MB nobody can
199
- * account for (roadmap item 2, field 2026-08-31): if the two numbers track each
200
- * other, this code is holding nothing and whatever grows is below us, in the
201
- * allocator — on musl there is no `malloc_trim` and no way to ask. If the gap
202
- * widens, a reference of ours outlives the piece, and then a heap snapshot can
203
- * name the holder.
204
- *
205
- * What it does NOT prove: a `SharedArrayBuffer`'s memory is shared between the
206
- * isolates, so this thread's handle going means only that THIS thread let go.
207
- * The main thread counts its own (`torrent-worker/client.js`), and the pair is
208
- * what answers the question.
209
- */
210
- const released = { count: 0, collected: 0 };
211
- const collector = typeof FinalizationRegistry === "function"
212
- ? new FinalizationRegistry(() => {
213
- released.collected += 1;
214
- })
215
- : null;
216
-
217
- /**
218
- * What the collector has taken back against what was let go.
219
- *
220
- * @returns {{ released: number, collected: number }}
221
- */
222
- export function pieceBufferCollection() {
223
- return { released: released.count, collected: released.collected };
224
- }
225
-
226
- const MIN_RESIDENT_PIECES = 2;
227
- /**
228
- * How long a claim may go without ANYTHING moving before it gives up.
229
- *
230
- * Measured against progress, not against activity. The earlier rule skipped
231
- * this timer entirely while a spill was in flight or a reservation was held —
232
- * so one reservation that was never returned made the timer unreachable and a
233
- * read retried every 50 ms for the life of the process, never completing and
234
- * never failing (field 2026-08-31).
235
- */
236
- const PINNED_WAIT_MS = 5_000;
237
-
238
- /**
239
- * How many revival ages are kept for the median. A window, not a history: two
240
- * hundred covers several minutes of the busiest session measured (7575
241
- * revivals in 44 minutes) and costs two hundred numbers.
242
- */
243
- const REVIVAL_AGE_SAMPLES = 200;
244
-
245
- /**
246
- * How many block re-use gaps are kept. The same window as the revival ages, and
247
- * for the same reason: what is wanted is the rhythm of recent work, not a
248
- * history of it.
249
- */
250
- const REUSE_GAP_SAMPLES = 200;
251
-
252
- /** How many write durations are kept for the median. */
253
- const WRITE_DURATION_SAMPLES = 50;
254
- /** How many admission times are kept, and how far back they are counted. */
255
- const ARRIVAL_SAMPLES = 100;
256
- const ARRIVAL_WINDOW_MS = 10_000;
257
-
258
- /**
259
- * The middle value of a sample, or null when there is nothing to take a middle
260
- * of. Null rather than zero: no revivals and instant revivals are different
261
- * facts and must not print the same.
262
- *
263
- * @param {number[]} values
264
- * @returns {number | null}
265
- */
266
- function median(values) {
267
- if (values.length === 0) {
268
- return null;
269
- }
270
- const sorted = [...values].sort((left, right) => left - right);
271
- const middle = Math.floor(sorted.length / 2);
272
- return sorted.length % 2 === 0
273
- ? Math.round((sorted[middle - 1] + sorted[middle]) / 2)
274
- : sorted[middle];
275
- }
276
- const CLAIM_RETRY_MS = 50;
277
-
278
- export class SharedPieceStore {
279
- #chunkLength;
280
- #lastChunkLength;
281
- #lastChunkIndex;
282
- #growthCeiling;
283
- /** Piece index → SharedArrayBuffer of that piece */
284
- #buffers = new Map();
285
- /** @type {Map<number, Promise<void>>} */
286
- #evicting = new Map();
287
- /**
288
- * Slots claimed but not yet filled.
289
- *
290
- * Handed out by {@link SharedPieceStore##claimSlot} as a release function the
291
- * caller must call in a `finally`, never as a number one function increments
292
- * and another decrements. The counter used to be paired across
293
- * `#claimSlot`/`#registerPiece`, so any failure between the two lost a slot
294
- * for the life of the process, and `put`'s error path tried to correct that
295
- * by guessing — which could take back a reservation belonging to a different
296
- * claim and let the store admit past its allowance.
297
- */
298
- #outstandingPieces = 0;
299
- /** When something last actually moved: a piece admitted, spilled or unpinned. */
300
- #lastProgressAt = 0;
301
- #waiters = [];
302
- #lru;
303
- #disk;
304
- #closed = false;
305
- #name;
306
- #counters = {
307
- fromMemory: 0,
308
- fromDisk: 0,
309
- spills: 0,
310
- revivals: 0,
311
- blockedByPins: 0,
312
- waitedForPins: 0,
313
- evictedOnRevise: 0,
314
- spillFailures: 0,
315
- // Whether the store is doing its job or being asked to hold more than it
316
- // has room for. An eviction that had to take a piece a reader declared it
317
- // wants is the second, and it comes back from disk moments later
318
- // (roadmap item 9).
319
- evictedProtected: 0,
320
- evictedDistanceSum: 0,
321
- evictedWithDistance: 0,
322
- // Where an arriving piece went. A piece nobody has declared is being
323
- // downloaded ahead of every reader; putting it in memory pushes out one
324
- // that IS declared, which is then read back from disk moments later
325
- // (roadmap item 9).
326
- admittedInsideWindow: 0,
327
- admittedOutsideWindow: 0,
328
- admittedToDisk: 0,
329
- /** Blocks given back to the operating system. */
330
- blocksReleased: 0,
331
- /**
332
- * A block put back for re-use while a reader still held the piece. Zero by
333
- * construction a pinned piece is never evicted, and a re-put of a pinned
334
- * one drops its block instead of recycling it. Counted because if it ever
335
- * stops being zero, a consumer is reading another piece's bytes, and that
336
- * is invisible from anywhere else.
337
- */
338
- returnedWhilePinned: 0,
339
- /** Spills that found the disk already holding identical bytes. */
340
- spillsSkipped: 0,
341
- /**
342
- * Blocks a second registration of the same piece displaced. Expected to be
343
- * small and non-zero: two callers racing for one piece is ordinary. What is
344
- * NOT ordinary is the block going missing when it happens, which is what
345
- * killed the process on 2026-09-02.
346
- */
347
- blocksDisplaced: 0,
348
- /** Admissions that waited for the disk instead of evicting another piece. */
349
- waitedForDisk: 0,
350
- /**
351
- * Admissions that grew memory because the disk had stopped answering.
352
- * Non-zero means the store exceeded its allowance on purpose, and by how
353
- * many pieces.
354
- */
355
- grewWaitingForDisk: 0,
356
- /**
357
- * Times a block was wanted, none was free, and the pool was already at its
358
- * ceiling. Zero by construction — a block is only taken after a slot has
359
- * been claimed, and slots are what the ceiling counts — so a number here
360
- * means the two have come apart and the pool is growing past its allowance.
361
- */
362
- blocksBeyondCeiling: 0
363
- };
364
- /**
365
- * Blocks that hold no piece, most recently freed last.
366
- *
367
- * A block is one piece's worth of memory. Allocating a new one for every
368
- * piece meant 7575 allocations of 4 MiB in 44 minutes on 2026-09-02, each
369
- * released only when the collector got to it which is why the process held
370
- * 1.86 GB while its own accounting said 352 MB. Blocks are taken from here
371
- * and put back here instead (roadmap item 2).
372
- *
373
- * @type {{ buffer: SharedArrayBuffer, freedAt: number }[]}
374
- */
375
- #freeBlocks = [];
376
- /** Blocks that exist at all: free plus holding a piece. */
377
- #blocksAllocated = 0;
378
- /** Whether a reader has ever declared a window here. See `wantedBytes`. */
379
- #everHadReader = false;
380
- /** Whether the last revision had to exceed the machine's share. */
381
- #beyondTheMachine = false;
382
- /**
383
- * How long a block sat free before it was taken again, in milliseconds.
384
- * Bounded, because what is wanted is the longest gap of RECENT work: an
385
- * all-time maximum would be raised by one long pause and then never let a
386
- * block go again.
387
- *
388
- * @type {number[]}
389
- */
390
- #reuseGaps = [];
391
- /**
392
- * How long recent writes to disk took, in milliseconds, and when pieces were
393
- * admitted. Together they say how much room the store needs beyond what the
394
- * readers ask for: while one write is finishing, more pieces arrive, and each
395
- * needs somewhere to go. Without that room every arrival evicts something,
396
- * which is what produced 233 evictions against 119 completed writes in a
397
- * minute on 2026-09-02.
398
- *
399
- * @type {number[]}
400
- */
401
- #writeDurations = [];
402
- /** When the last few pieces were admitted, for the arrival rate. */
403
- #admittedAt = [];
404
- /** Piece index when it was written out, for the age it comes back at. */
405
- #spilledAt = new Map();
406
- /**
407
- * Ages, in milliseconds, of the last revivals — bounded, because the figure
408
- * wanted is a median and not a history. A piece that comes back seconds
409
- * after it left should not have left.
410
- *
411
- * @type {number[]}
412
- */
413
- #revivalAges = [];
414
-
415
- constructor(chunkLength, options = {}) {
416
- if (!Number.isInteger(chunkLength) || chunkLength < 1) {
417
- throw new Error(`Chunk length must be a positive integer, got ${chunkLength}.`);
418
- }
419
- this.#chunkLength = chunkLength;
420
-
421
- const totalLength = Number.isFinite(options.length) ? options.length : 0;
422
- this.#lastChunkIndex = totalLength > 0 ? Math.ceil(totalLength / chunkLength) - 1 : -1;
423
- const remainder = totalLength % chunkLength;
424
- this.#lastChunkLength = remainder === 0 ? chunkLength : remainder;
425
-
426
- const memoryBytes = Number.isFinite(options.memoryBytes) && options.memoryBytes > 0
427
- ? options.memoryBytes
428
- : defaultMemoryBytes();
429
- // Only where this store STARTS. It is not kept, so it cannot come back as a
430
- // cap on the revision the way `#capacity` did.
431
- const openingCeiling = Math.max(MIN_RESIDENT_PIECES, Math.floor(memoryBytes / chunkLength));
432
- this.#growthCeiling = openingCeiling;
433
- this.#lru = new PieceLru(openingCeiling);
434
- this.#name = options.name ?? "pieces";
435
- // `options.disk` exists so a test can hold a write open or make one fail on
436
- // purpose. Four of the defects fixed here live in what happens when the
437
- // disk tier does not answer immediately or at all, and none of them is
438
- // reachable from outside without saying so.
439
- this.#disk = options.disk ?? new PieceDiskStore({
440
- directory: options.path ?? ".",
441
- name: `${this.#name}.pieces`,
442
- chunkLength,
443
- // What it may hold is settled by the same revision that settles memory,
444
- // within a minute of the store existing. Until then it is unbounded, which
445
- // is what it has always been the difference is that it now stops.
446
- allowanceBytes: null
447
- });
448
- liveStores.add(this);
449
- }
450
-
451
- stats() {
452
- const resident = this.#buffers.size;
453
- const residentBytes = resident * this.#chunkLength;
454
- // Last piece may be short but stats historically use chunkLength.
455
- return {
456
- name: this.#name,
457
- resident,
458
- capacity: this.#growthCeiling,
459
- residentBytes,
460
- allocatedSlots: this.#blocksAllocated,
461
- // What the process HOLDS, which with a pool is the blocks that exist —
462
- // not the pieces in them. Holding and using are different quantities and
463
- // the difference is the point of the reading.
464
- committedBytes: this.#blocksAllocated * this.#chunkLength,
465
- budgetBytes: this.#growthCeiling * this.#chunkLength,
466
- pinned: this.#lru.pinnedCount,
467
- // Slots claimed and not yet filled. Reported because a reservation that
468
- // is never returned is invisible until the store cannot admit anything,
469
- // and by then the reason is long gone. At rest this is zero.
470
- outstanding: this.#outstandingPieces,
471
- spilled: this.#disk.size,
472
- // What the spill file ACTUALLY weighs, piece by piece, rather than the
473
- // piece count times a full piece length. The last piece of a torrent is
474
- // short, and until 2026-09-10 nothing here counted disk at all — the
475
- // figure was a multiplication, and the thing it stood for had no ceiling.
476
- spilledBytes: this.#disk.bytes,
477
- spillAllowanceBytes: this.#disk.allowanceBytes,
478
- spillEvictions: this.#disk.stats().evictions,
479
- // What the readers between them are asking this store to keep, against
480
- // what it may hold. A union wider than the capacity cannot be held
481
- // however the eviction is ordered, and that is the difference between a
482
- // policy to fix and arithmetic to accept (roadmap item 9).
483
- demand: this.#lru.demand(),
484
- // What the process actually holds for this store, which is not the same
485
- // as what it is using: blocks are kept for re-use. The difference is the
486
- // spare, and it is the whole of the question whether consumption only
487
- // grows (roadmap item 2).
488
- blocksAllocated: this.#blocksAllocated,
489
- blocksFree: this.#freeBlocks.length,
490
- blocksDisplaced: this.#counters.blocksDisplaced,
491
- blocksInUse: this.#blocksInUse(),
492
- blocksInFlight: this.#blocksInFlight(),
493
- blocksBeyondCeiling: this.#counters.blocksBeyondCeiling,
494
- blockBytes: this.#blocksAllocated * this.#chunkLength,
495
- reuseGapMs: this.#reuseGapCeilingMs(),
496
- revivalAgeMedianMs: median(this.#revivalAges),
497
- revivalAgeSamples: this.#revivalAges.length,
498
- revivedWithinFiveSeconds: this.#revivalAges.filter((age) => age <= 5_000).length,
499
- ...this.#counters
500
- };
501
- }
502
-
503
- /**
504
- * Whether the machine's share of memory is smaller than one reader's window.
505
- *
506
- * The store holds the window anyway — refusing would leave the read it is
507
- * serving unable to finish, which is worse — but it is the honest measure of
508
- * "this machine cannot take any more", and it is measured rather than
509
- * guessed: it is the last revision's own comparison of what the machine
510
- * allowed against what the widest reader declared.
511
- */
512
- get isBeyondTheMachine() {
513
- return this.#beyondTheMachine;
514
- }
515
-
516
- /** What this store holds right now, in bytes. */
517
- get residentBytes() {
518
- return this.#buffers.size * this.#chunkLength;
519
- }
520
-
521
- /** What this store's spilled pieces weigh on disk. */
522
- get spilledBytes() {
523
- return this.#disk.bytes;
524
- }
525
-
526
- /** Where this store's spilled pieces live, which is the disk they are on. */
527
- get spillPath() {
528
- return this.#disk.path;
529
- }
530
-
531
- /**
532
- * Say how much disk this store's spilled pieces may take.
533
- *
534
- * The counterpart of `reviseGrowthCeiling`, and settled by the same pass: the
535
- * two tiers of one store are two readings of one machine.
536
- *
537
- * @param {number | null} allowedBytes
538
- * @returns {{ name: string, allowanceBytes: number | null, bytes: number }}
539
- */
540
- reviseSpillCeiling(allowedBytes) {
541
- return {
542
- name: this.#name,
543
- allowanceBytes: this.#disk.reviseAllowance(allowedBytes),
544
- bytes: this.#disk.bytes
545
- };
546
- }
547
-
548
- /**
549
- * What this store is asking to be allowed to hold, in bytes.
550
- *
551
- * The union of its readers' declared windows — what they have said they will
552
- * need — never below the widest single window, because a store that cannot
553
- * hold one reader's window cannot complete that reader's read at all: every
554
- * resident piece ends up pinned, the read returns zero bytes and ffmpeg takes
555
- * that for the end of the file (field 2026-08-15, roadmap item 9).
556
- *
557
- * With no reader declaring anything there is no demand to speak of, so the
558
- * store asks for what the machine allows and the first revision after a read
559
- * begins brings it down to what that read needs.
560
- */
561
- get wantedBytes() {
562
- const demand = this.#lru.demand();
563
- if (demand.readers > 0) {
564
- this.#everHadReader = true;
565
- const pieces = Math.max(MIN_RESIDENT_PIECES, demand.unionPieces, demand.widestPieces);
566
- // Plus room to absorb what arrives while a write is finishing. Asking for
567
- // exactly what the readers want leaves no free place ever, so every
568
- // arrival evicts one of them measured 2026-09-02: `6 reader(s) want 23
569
- // piece(s) of 23 the store may hold`, and 233 evictions in the minute
570
- // that followed.
571
- return (pieces + this.slackPieces()) * this.#chunkLength;
572
- }
573
- // Readers that have GONE are not the same as readers that have not arrived.
574
- // A store whose readers ended has nothing to hold pieces for — its torrent
575
- // sits until the pool's idle timer removes it, which needs a refcount of
576
- // zero and can be a quarter of an hour away — so it asks for nothing and
577
- // its memory goes back to the machine now. A store that has never had a
578
- // reader is being filled for one that is on its way, and asks for what it
579
- // was opened with until the first read says what it needs.
580
- return this.#everHadReader
581
- ? (MIN_RESIDENT_PIECES + this.slackPieces()) * this.#chunkLength
582
- : this.#growthCeiling * this.#chunkLength;
583
- }
584
-
585
- reviseGrowthCeiling(allowedBytes) {
586
- // No cap at what the machine could spare when this store was CREATED.
587
- // `#capacity` was computed once in the constructor and used as an upper
588
- // bound here, so the allowance could only ever fall: a torrent opened while
589
- // the machine was full kept a small allowance for its whole life, however
590
- // much memory was freed afterwards (roadmap item 2, 2026-09-02).
591
- const wanted = Math.floor(Number(allowedBytes) / this.#chunkLength);
592
- // Never below what the live readers together hold, even when the machine's
593
- // share says less. A store that cannot hold what its readers are pinning
594
- // cannot complete any of their reads at all: every resident piece ends up
595
- // pinned, a read returns zero bytes and ffmpeg takes that for the end of
596
- // the file, which killed every encoder on that file in the field on
597
- // 2026-08-15 (one reader) and again on 2026-09-07 (three readers of one
598
- // file at once picture, sound and the edge-warming readwhere this
599
- // floor was still computed from only the widest one of them, `wantedBytes`
600
- // above already asks for the union and got it right; this is the same
601
- // union, used as the floor instead of only as the ask). Exceeding the share
602
- // is the lesser failure, and the line below says when it happens.
603
- const demand = this.#lru.demand();
604
- this.#growthCeiling = Math.max(
605
- MIN_RESIDENT_PIECES,
606
- demand.readers > 0 ? demand.unionPieces : MIN_RESIDENT_PIECES,
607
- Number.isFinite(wanted) ? wanted : MIN_RESIDENT_PIECES
608
- );
609
- const belowAWindow = demand.readers > 0
610
- && Number.isFinite(wanted)
611
- && wanted < demand.unionPieces;
612
- this.#beyondTheMachine = belowAWindow;
613
- // The LRU is told too. It was constructed with the store's original
614
- // capacity and never revised, so `isFull()` answered against a number that
615
- // had not been the limit for some time dormant only because nothing calls
616
- // it, which is a trap for whoever calls it next.
617
- this.#lru.setCapacity(this.#growthCeiling);
618
- // With per-piece buffers memory CAN be given back immediately, unlike the
619
- // old growable pool. Eagerly evict excess to honour the new ceiling.
620
- let evicted = 0;
621
- while (this.#buffers.size > this.#growthCeiling) {
622
- const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
623
- if (victim === null) {
624
- break;
625
- }
626
- const victimBuffer = this.#buffers.get(victim);
627
- if (victimBuffer === undefined) {
628
- this.#lru.remove(victim);
629
- continue;
630
- }
631
- this.#buffers.delete(victim);
632
- this.#lru.remove(victim);
633
- evicted += 1;
634
- this.#counters.evictedOnRevise += 1;
635
- this.#noteEviction(protectionYielded, distance);
636
- // Nobody awaits this spill, so its failure has to end here. Rethrowing
637
- // made it an unhandled rejection, and an unhandled rejection in the
638
- // torrent worker ends the thread a second way to lose the torrent
639
- // client, on top of the one that already loses it.
640
- void this.#spill(victim, victimBuffer).catch(() => {
641
- this.#counters.spillFailures += 1;
642
- });
643
- }
644
- // Blocks the store is no longer using and has waited long enough to give
645
- // up. The allowance falling is the moment to ask, because that is when the
646
- // machine has been shown to need the memory.
647
- const releasedBlocks = this.sweepFreeBlocks();
648
- return {
649
- name: this.#name,
650
- ceilingBytes: this.#growthCeiling * this.#chunkLength,
651
- committedBytes: this.#blocksAllocated * this.#chunkLength,
652
- evicted,
653
- releasedBlocks,
654
- belowAWindow
655
- };
656
- }
657
-
658
- get chunkLength() {
659
- return this.#chunkLength;
660
- }
661
-
662
- get capacity() {
663
- return this.#growthCeiling;
664
- }
665
-
666
- get residentCount() {
667
- return this.#buffers.size;
668
- }
669
-
670
- get spilledCount() {
671
- return this.#disk.size;
672
- }
673
-
674
- #lengthOf(index) {
675
- return index === this.#lastChunkIndex ? this.#lastChunkLength : this.#chunkLength;
676
- }
677
-
678
- /**
679
- * Where a resident piece sits, or `null` if not resident.
680
- * Returns the piece's own SharedArrayBuffer and the intra-piece range.
681
- * @param {number} index
682
- * @returns {{ buffer: SharedArrayBuffer, offset: number, length: number } | null}
683
- */
684
- locate(index) {
685
- const buffer = this.#buffers.get(index);
686
- if (buffer === undefined) {
687
- return null;
688
- }
689
- return { buffer, offset: 0, length: this.#lengthOf(index) };
690
- }
691
-
692
- /**
693
- * Direct access to a piece's buffer for zero-copy consumers.
694
- * @param {number} index
695
- * @returns {SharedArrayBuffer | undefined}
696
- */
697
- getPieceBuffer(index) {
698
- return this.#buffers.get(index);
699
- }
700
-
701
- pin(index) {
702
- this.#lru.pin(index);
703
- }
704
-
705
- unpin(index) {
706
- this.#lru.unpin(index);
707
- this.#noteProgress();
708
- }
709
-
710
- /**
711
- * Reserve room for one piece.
712
- *
713
- * @returns {Promise<() => void>} The release, which the caller MUST call in a
714
- * `finally`. Calling it twice is harmless.
715
- */
716
- async #claimSlot() {
717
- // How long THIS claim has been trying, kept here and not on the store.
718
- // It was a field, `#pinnedWaitStartedAt`, shared by the two waits inside
719
- // `#claimSlotOnce` — the one for the disk and the one for a piece that may
720
- // be evicted — and each of them zeroed it on giving up, which restarted the
721
- // other's clock. Measured 2026-09-03: the claim cycled for ever, five
722
- // seconds per side, `grewWaitingForDisk` and `waitedForPins` both climbing
723
- // once every five seconds while `blockedByPins` stayed at 0 — the refusal
724
- // was unreachable. A claim's patience belongs to the claim; with several
725
- // claimants a shared field is wrong anyway, since one caller giving up
726
- // would reset the wait of every other.
727
- const waitingSince = Date.now();
728
- for (;;) {
729
- if (this.#closed) {
730
- throw new Error("Piece store is closed.");
731
- }
732
- const ok = await this.#claimSlotOnce(waitingSince);
733
- if (ok) {
734
- let released = false;
735
- return () => {
736
- if (released) {
737
- return;
738
- }
739
- released = true;
740
- this.#outstandingPieces -= 1;
741
- this.#noteProgress();
742
- };
743
- }
744
- await this.#waitForSlot();
745
- }
746
- }
747
-
748
- /**
749
- * Sleep until something moves, or until the retry interval, whichever first.
750
- *
751
- * One handler, idempotent, and its timer is cleared when it is woken. The
752
- * earlier version attached a fresh pair of handlers to EVERY pending spill on
753
- * every attempt and left a timer running each time, so a claim that could not
754
- * be satisfied allocated in proportion to attempts times pending spills. A
755
- * settling spill now wakes the store itself, which is where that belongs.
756
- *
757
- * @returns {Promise<void>}
758
- */
759
- #waitForSlot() {
760
- return new Promise((resolve) => {
761
- let settled = false;
762
- /** @type {ReturnType<typeof setTimeout> | null} */
763
- let retry = null;
764
- const finish = () => {
765
- if (settled) {
766
- return;
767
- }
768
- settled = true;
769
- if (retry !== null) {
770
- clearTimeout(retry);
771
- }
772
- resolve();
773
- };
774
- this.#waiters.push(finish);
775
- retry = setTimeout(finish, CLAIM_RETRY_MS);
776
- retry.unref?.();
777
- });
778
- }
779
-
780
- #registerPiece(index, buffer) {
781
- // A piece may already be here. Both paths that register one look first and
782
- // then await — `put` waits for a slot, `#revive` waits for the disk — and
783
- // in that gap another caller can register the same index. Overwriting the
784
- // entry used to drop the previous block on the floor: its memory was not
785
- // returned to the pool and the pool's own count was never decremented, so
786
- // the count climbed past the ceiling for ever and the pool degenerated into
787
- // allocating a fresh block per piece. Field 2026-09-02: a store holding
788
- // THREE pieces reported 812 MB committed against 68 MB allowed, 739 blocks
789
- // allocated and 676 still alive, and the process was killed at 4.37 GB.
790
- const displaced = this.#buffers.get(index);
791
- this.#buffers.set(index, buffer);
792
- if (displaced !== undefined && displaced !== buffer) {
793
- this.#counters.blocksDisplaced += 1;
794
- this.#returnBlock(displaced);
795
- }
796
- this.#lru.touch(index);
797
- this.#noteProgress();
798
- }
799
-
800
- /**
801
- * Write a piece out and account for it, from the one place that does it.
802
- *
803
- * @param {number} index
804
- * @param {SharedArrayBuffer} buffer
805
- * @returns {Promise<void>}
806
- */
807
- #spill(index, buffer) {
808
- // The disk may already hold these very bytes. `#revive` reads a piece back
809
- // into memory and leaves the copy on disk, and only `put` removes it — so a
810
- // piece that was revived and not re-put is identical to what is already
811
- // written, and writing it again is work for nothing. There were 7575
812
- // revivals in one session on 2026-09-02, and every later eviction of one of
813
- // them wrote a second time (roadmap item 66: 14.4 GB written in a single
814
- // viewing).
815
- if (this.#disk.has(index)) {
816
- this.#counters.spills += 1;
817
- this.#counters.spillsSkipped += 1;
818
- this.#spilledAt.set(index, Date.now());
819
- this.#returnBlock(buffer);
820
- this.#noteProgress();
821
- return Promise.resolve();
822
- }
823
-
824
- const bytes = Buffer.from(buffer, 0, this.#lengthOf(index));
825
- const startedAt = Date.now();
826
- const spill = this.#disk.write(index, bytes).then(
827
- () => {
828
- this.#noteWriteDuration(Date.now() - startedAt);
829
- this.#counters.spills += 1;
830
- this.#spilledAt.set(index, Date.now());
831
- this.#evicting.delete(index);
832
- // Only now. The write reads out of this block, so a block handed to
833
- // another piece before the write finished would put that piece's bytes
834
- // into this piece's place in the file.
835
- this.#returnBlock(buffer);
836
- this.#noteProgress();
837
- },
838
- (error) => {
839
- this.#evicting.delete(index);
840
- // The block is no longer holding anything either way; keeping it out of
841
- // the pool because the write failed would lose it for good.
842
- this.#returnBlock(buffer);
843
- this.#noteProgress();
844
- throw error;
845
- }
846
- );
847
- this.#evicting.set(index, spill);
848
- return spill;
849
- }
850
-
851
- /** Something actually moved: wake whoever is waiting and restart the clock. */
852
- #noteProgress() {
853
- this.#lastProgressAt = Date.now();
854
- this.#wake();
855
- }
856
-
857
- /**
858
- * Record how long one write to disk took.
859
- *
860
- * @param {number} durationMs
861
- * @returns {void}
862
- */
863
- #noteWriteDuration(durationMs) {
864
- this.#writeDurations.push(Math.max(0, durationMs));
865
- if (this.#writeDurations.length > WRITE_DURATION_SAMPLES) {
866
- this.#writeDurations.shift();
867
- }
868
- }
869
-
870
- /** Record that a piece arrived, for the arrival rate. */
871
- #noteArrival() {
872
- const now = Date.now();
873
- this.#admittedAt.push(now);
874
- while (this.#admittedAt.length > ARRIVAL_SAMPLES
875
- || (this.#admittedAt.length > 0 && now - this.#admittedAt[0] > ARRIVAL_WINDOW_MS)) {
876
- this.#admittedAt.shift();
877
- }
878
- }
879
-
880
- /**
881
- * How many pieces the store needs room for beyond what the readers ask for.
882
- *
883
- * Measured, not chosen: the pieces that arrive while one write to disk is
884
- * finishing. Without this room every arrival must evict something, and each
885
- * eviction holds its block until its write completes — so a disk slower than
886
- * the swarm turns every admission into one more block held. On 2026-09-02
887
- * that was 233 evictions against 119 completed writes in a minute, and 203
888
- * blocks held with three pieces resident.
889
- *
890
- * Zero until both quantities have been seen, because a slack invented before
891
- * anything is measured is a chosen number, and this store has been bitten by
892
- * those.
893
- *
894
- * @returns {number} Pieces.
895
- */
896
- slackPieces() {
897
- if (this.#writeDurations.length === 0 || this.#admittedAt.length < 2) {
898
- return 0;
899
- }
900
- const sorted = [...this.#writeDurations].sort((left, right) => left - right);
901
- const writeMs = sorted[Math.floor(sorted.length / 2)];
902
- const spanMs = this.#admittedAt[this.#admittedAt.length - 1] - this.#admittedAt[0];
903
- if (!(spanMs > 0)) {
904
- return 0;
905
- }
906
- const perMs = (this.#admittedAt.length - 1) / spanMs;
907
- return Math.ceil(perMs * writeMs);
908
- }
909
-
910
- /**
911
- * Blocks that are not free: resident pieces, blocks being written out, and
912
- * blocks taken but not yet registered.
913
- *
914
- * This is what the ceiling has to bound, and until 2026-09-02 it bounded
915
- * resident pieces instead. The difference is exactly the memory that goes
916
- * missing from the count: a piece being spilled leaves `#buffers` the moment
917
- * the eviction begins, while its block stays held until the write it feeds
918
- * has finished.
919
- *
920
- * @returns {number}
921
- */
922
- #blocksInUse() {
923
- return this.#blocksAllocated - this.#freeBlocks.length;
924
- }
925
-
926
- /**
927
- * Blocks held by writes that have not finished.
928
- *
929
- * @returns {number}
930
- */
931
- #blocksInFlight() {
932
- return Math.max(0, this.#blocksInUse() - this.#buffers.size);
933
- }
934
-
935
- /**
936
- * Whether admitting one more piece would need something evicted first.
937
- *
938
- * Reservations count: a slot claimed and not yet filled is as taken as a
939
- * resident piece.
940
- *
941
- * @returns {boolean}
942
- */
943
- #isFullNow() {
944
- return this.#blocksInUse() + this.#outstandingPieces >= this.#growthCeiling;
945
- }
946
-
947
- /**
948
- * Write an arriving piece straight to disk, without it ever occupying memory.
949
- *
950
- * Registered in `#evicting` like a spill, so a `get` for this index waits for
951
- * the write instead of finding the piece on neither tier. Deliberately NOT
952
- * recorded in `#spilledAt`: that clock measures how long an EVICTED piece
953
- * stayed away, and a piece that was never resident has no such age.
954
- *
955
- * @param {number} index
956
- * @param {Uint8Array} bytes
957
- * @returns {Promise<void>}
958
- */
959
- #writeThrough(index, bytes) {
960
- // Copied, not viewed. `PieceDiskStore.write` opens the file before it reads the
961
- // bytes, so a view onto the caller's buffer could be written to in between
962
- // and the file would get the wrong data. The spill path may pass a view
963
- // because that memory is ours; this buffer belongs to the torrent client.
964
- // It costs nothing extra: the piece was being copied into a shared buffer
965
- // on this path before, and now it is copied here instead.
966
- const copy = Buffer.from(bytes.subarray(0, Math.min(bytes.length, this.#lengthOf(index))));
967
- const write = this.#disk.write(index, copy).then(
968
- () => {
969
- this.#evicting.delete(index);
970
- this.#noteProgress();
971
- },
972
- (error) => {
973
- this.#evicting.delete(index);
974
- this.#noteProgress();
975
- throw error;
976
- }
977
- );
978
- this.#evicting.set(index, write);
979
- return write;
980
- }
981
-
982
- /**
983
- * Record how long a piece stayed on disk before it was wanted again.
984
- *
985
- * A piece that comes back seconds after it left was evicted from a working
986
- * set that does not fit, and the write and the read were both waste. Kept as
987
- * a bounded window of ages because the figure wanted is a median, not a
988
- * history.
989
- *
990
- * @param {number} index
991
- * @returns {void}
992
- */
993
- #noteRevival(index) {
994
- const spilledAt = this.#spilledAt.get(index);
995
- if (spilledAt === undefined) {
996
- return;
997
- }
998
- this.#spilledAt.delete(index);
999
- this.#revivalAges.push(Date.now() - spilledAt);
1000
- if (this.#revivalAges.length > REVIVAL_AGE_SAMPLES) {
1001
- this.#revivalAges.shift();
1002
- }
1003
- }
1004
-
1005
- /**
1006
- * Record what an eviction had to take.
1007
- *
1008
- * @param {boolean} protectionYielded - The victim was inside a window a
1009
- * reader had declared, and was taken anyway because nothing else was free.
1010
- * @param {number} distance - Pieces from the nearest declared window, -1 when
1011
- * no reader declared one.
1012
- * @returns {void}
1013
- */
1014
- #noteEviction(protectionYielded, distance) {
1015
- if (protectionYielded) {
1016
- this.#counters.evictedProtected += 1;
1017
- }
1018
- if (distance >= 0) {
1019
- this.#counters.evictedDistanceSum += distance;
1020
- this.#counters.evictedWithDistance += 1;
1021
- }
1022
- }
1023
-
1024
- #wake() {
1025
- const waiting = this.#waiters;
1026
- this.#waiters = [];
1027
- for (const resolve of waiting) {
1028
- resolve();
1029
- }
1030
- }
1031
-
1032
- /**
1033
- * One attempt at a reservation.
1034
- *
1035
- * @param {number} waitingSince - When the claim this attempt belongs to began
1036
- * trying. Both waits below are measured from the later of it and the last
1037
- * time the store moved, so neither can restart the other's clock — see
1038
- * `#claimSlot`.
1039
- * @returns {Promise<boolean>} Whether a slot was reserved.
1040
- */
1041
- async #claimSlotOnce(waitingSince) {
1042
- // Reserve before suspension so concurrent callers see the reservation.
1043
- if (this.#blocksInUse() + this.#outstandingPieces < this.#growthCeiling) {
1044
- this.#outstandingPieces += 1;
1045
- return true;
1046
- }
1047
- const stillFor = () => Date.now() - Math.max(waitingSince, this.#lastProgressAt);
1048
-
1049
- // Full, and evicting would make it worse rather than better. A piece being
1050
- // written out has already left `#buffers` while its block is still held —
1051
- // the write reads from that block — so evicting another one converts a
1052
- // resident block into an in-flight block and takes a fresh block for the
1053
- // arrival: the memory in use goes UP by one per admission for as long as
1054
- // the disk is behind. Field 2026-09-02: 233 evictions against 119 completed
1055
- // writes in a minute, 203 blocks held with three pieces resident, and the
1056
- // process killed at 4.37 GB.
1057
- //
1058
- // So when the disk is what the store is waiting for, it waits. A completing
1059
- // write calls `#noteProgress`, which wakes whoever is here.
1060
- if (this.#blocksInFlight() > 0 && this.#blocksInUse() >= this.#growthCeiling) {
1061
- if (stillFor() < PINNED_WAIT_MS) {
1062
- this.#counters.waitedForDisk += 1;
1063
- return false;
1064
- }
1065
- // The disk has stopped answering. Falling through to eviction is the
1066
- // lesser failure: it grows memory, and the line above says by how much,
1067
- // where refusing would fail the read outright. The clock is NOT restarted
1068
- // here: the wait that follows asks the same question of the same claim,
1069
- // and zeroing it was half of the loop described in `#claimSlot`.
1070
- this.#counters.grewWaitingForDisk += 1;
1071
- }
1072
-
1073
- const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
1074
- if (victim === null) {
1075
- // Nothing may leave. Wait while the store is still MOVING — a spill
1076
- // completing, a piece admitted, a pin released and give up when it has
1077
- // not moved for PINNED_WAIT_MS, whatever is nominally in flight. The old
1078
- // rule asked whether anything was in flight rather than whether anything
1079
- // had happened, which is why one lost reservation could hold a read here
1080
- // for ever.
1081
- if (stillFor() < PINNED_WAIT_MS) {
1082
- this.#counters.waitedForPins += 1;
1083
- return false;
1084
- }
1085
- this.#counters.blockedByPins += 1;
1086
- throw new Error(
1087
- `Every resident piece is pinned and nothing moved for ${PINNED_WAIT_MS}ms; no slot can be freed.`
1088
- );
1089
- }
1090
-
1091
- const victimBuffer = this.#buffers.get(victim);
1092
- if (victimBuffer === undefined) {
1093
- // Should not happen: LRU says resident but buffer missing.
1094
- this.#lru.remove(victim);
1095
- return false;
1096
- }
1097
-
1098
- // Claim atomically before await.
1099
- this.#buffers.delete(victim);
1100
- this.#lru.remove(victim);
1101
- this.#outstandingPieces += 1;
1102
- this.#noteEviction(protectionYielded, distance);
1103
-
1104
- try {
1105
- await this.#spill(victim, victimBuffer);
1106
- } catch (error) {
1107
- // The caller never received a release for this reservation, so it is
1108
- // given back here rather than left outstanding for ever.
1109
- this.#outstandingPieces -= 1;
1110
- this.#noteProgress();
1111
- throw error;
1112
- }
1113
- // Outstanding stays +1 for the caller; the slot for the new piece is now free.
1114
- return true;
1115
- }
1116
-
1117
- /**
1118
- * Bring a spilled piece back into memory, once, however many callers ask.
1119
- *
1120
- * @param {number} index
1121
- * @returns {Promise<SharedArrayBuffer | null>} `null` when the piece is on
1122
- * neither tier.
1123
- */
1124
- async #revive(index) {
1125
- const spill = this.#evicting.get(index);
1126
- if (spill) {
1127
- await spill.catch(() => undefined);
1128
- }
1129
-
1130
- if (!this.#disk.has(index)) {
1131
- return null;
1132
- }
1133
-
1134
- const release = await this.#claimSlot();
1135
- try {
1136
- // Another caller may have brought it back while this one waited for a
1137
- // slot. Registering a second buffer for the same piece would leave
1138
- // whoever holds the first reading memory nothing evicts.
1139
- const already = this.#buffers.get(index);
1140
- if (already !== undefined) {
1141
- this.#lru.touch(index);
1142
- this.#counters.fromMemory += 1;
1143
- return already;
1144
- }
1145
- const target = this.#takeBlock();
1146
- try {
1147
- // Only this piece's own length: the block is a full piece long and the
1148
- // last piece of a file is shorter, so reading the whole block would ask
1149
- // the file for bytes past its end.
1150
- await this.#disk.read(index, Buffer.from(target, 0, this.#lengthOf(index)));
1151
- } catch (error) {
1152
- this.#returnBlock(target);
1153
- throw error;
1154
- }
1155
- this.#registerPiece(index, target);
1156
- this.#counters.fromDisk += 1;
1157
- this.#counters.revivals += 1;
1158
- this.#noteRevival(index);
1159
- return target;
1160
- } finally {
1161
- release();
1162
- }
1163
- }
1164
-
1165
- /**
1166
- * A block to hold one piece: the most recently freed one, or a new one.
1167
- *
1168
- * Every block is a full piece long, whatever piece will live in it. The last
1169
- * piece of a file is shorter, and it occupies a full block with only its own
1170
- * bytes meaningful — `#lengthOf` is what decides how much is ever read out.
1171
- * Uniform blocks are what makes them interchangeable at all.
1172
- *
1173
- * Most recently freed first, deliberately: a few blocks then carry the whole
1174
- * of a busy store's traffic and the rest age out of use, which is what makes
1175
- * {@link SharedPieceStore#sweepFreeBlocks} able to tell a spare block from a
1176
- * working one.
1177
- *
1178
- * @returns {SharedArrayBuffer}
1179
- */
1180
- #takeBlock() {
1181
- const spare = this.#freeBlocks.pop();
1182
- if (spare !== undefined) {
1183
- this.#noteReuseGap(Date.now() - spare.freedAt);
1184
- return spare.buffer;
1185
- }
1186
- // Nothing spare and the pool is already as large as it is allowed to be.
1187
- // This cannot happen while the accounting is sound: a block is taken only
1188
- // after a slot has been claimed, and slots are exactly what the ceiling
1189
- // counts. It is recorded rather than hidden because when it does happen the
1190
- // pool grows without bound, and every block it then allocates is used once
1191
- // and thrown to a collector that has no reason to run the heap stays at
1192
- // 50 MB of 2240 while the process reaches four gigabytes.
1193
- // Strictly greater: reaching the ceiling exactly is what a full store looks
1194
- // like, and a slot has just been claimed for this block. Being ALREADY past
1195
- // it and allocating anyway is the state that runs away.
1196
- if (this.#blocksAllocated > this.#growthCeiling) {
1197
- this.#counters.blocksBeyondCeiling += 1;
1198
- }
1199
- this.#blocksAllocated += 1;
1200
- return this.#watchForCollection(new SharedArrayBuffer(this.#chunkLength));
1201
- }
1202
-
1203
- /**
1204
- * Put a block back for re-use, or give it up.
1205
- *
1206
- * Given up when the allowance has fallen below the number of blocks that
1207
- * exist: keeping it would hold memory the machine has just been shown to
1208
- * need. Otherwise it waits in the free list for the next piece.
1209
- *
1210
- * @param {SharedArrayBuffer | undefined} buffer
1211
- * @returns {void}
1212
- */
1213
- #returnBlock(buffer) {
1214
- if (buffer === undefined) {
1215
- return;
1216
- }
1217
- if (this.#closed || this.#blocksAllocated > this.#growthCeiling) {
1218
- // Never below zero: `close` gives up every block at once, and a spill
1219
- // that was already in flight resolves afterwards and arrives here.
1220
- if (this.#blocksAllocated > 0) {
1221
- this.#blocksAllocated -= 1;
1222
- this.#counters.blocksReleased += 1;
1223
- }
1224
- return;
1225
- }
1226
- this.#freeBlocks.push({ buffer, freedAt: Date.now() });
1227
- }
1228
-
1229
- /**
1230
- * Record how long a block waited to be used again.
1231
- *
1232
- * @param {number} gapMs
1233
- * @returns {void}
1234
- */
1235
- #noteReuseGap(gapMs) {
1236
- this.#reuseGaps.push(Math.max(0, gapMs));
1237
- if (this.#reuseGaps.length > REUSE_GAP_SAMPLES) {
1238
- this.#reuseGaps.shift();
1239
- }
1240
- }
1241
-
1242
- /**
1243
- * The longest a block has recently waited before being wanted again, or null
1244
- * when no block has yet been re-used.
1245
- *
1246
- * This is the store's own working rhythm, measured rather than chosen: while
1247
- * a film is being watched a block is taken again within milliseconds, because
1248
- * one is taken for every piece that arrives. A block that has been sitting
1249
- * longer than the longest of those waits is not part of the work.
1250
- *
1251
- * @returns {number | null}
1252
- */
1253
- #reuseGapCeilingMs() {
1254
- if (this.#reuseGaps.length === 0) {
1255
- return null;
1256
- }
1257
- return Math.max(...this.#reuseGaps);
1258
- }
1259
-
1260
- /**
1261
- * Give up blocks that have sat unused longer than this store's own working
1262
- * rhythm.
1263
- *
1264
- * The case it is for: a torrent whose peers have gone. Its readers are still
1265
- * attached, so nothing removes the torrent — the pool's idle timer needs a
1266
- * refcount of zero and never starts. Its allowance falls to what those
1267
- * readers declared, the pieces beyond it are written out, and their blocks
1268
- * would otherwise wait in the free list for peers that may not return.
1269
- *
1270
- * @param {number} [now]
1271
- * @returns {number} Blocks given up.
1272
- */
1273
- sweepFreeBlocks(now = Date.now()) {
1274
- const ceiling = this.#reuseGapCeilingMs();
1275
- if (ceiling === null) {
1276
- return 0;
1277
- }
1278
- const keeping = [];
1279
- let released = 0;
1280
- for (const spare of this.#freeBlocks) {
1281
- if (now - spare.freedAt <= ceiling) {
1282
- keeping.push(spare);
1283
- continue;
1284
- }
1285
- this.#blocksAllocated -= 1;
1286
- this.#counters.blocksReleased += 1;
1287
- released += 1;
1288
- }
1289
- this.#freeBlocks = keeping;
1290
- return released;
1291
- }
1292
-
1293
- /**
1294
- * Count this buffer as one this thread will have to let go of, and notice
1295
- * when the collector takes it. See {@link pieceBufferCollection}.
1296
- *
1297
- * @param {SharedArrayBuffer} buffer
1298
- * @returns {SharedArrayBuffer} The same buffer.
1299
- */
1300
- #watchForCollection(buffer) {
1301
- released.count += 1;
1302
- collector?.register(buffer, null);
1303
- return buffer;
1304
- }
1305
-
1306
- /**
1307
- * A fresh buffer holding this piece's bytes.
1308
- *
1309
- * @param {number} index
1310
- * @param {Uint8Array} bytes
1311
- * @returns {SharedArrayBuffer}
1312
- */
1313
- #copyIntoNewBuffer(index, bytes) {
1314
- const length = this.#lengthOf(index);
1315
- const block = this.#takeBlock();
1316
- const view = Buffer.from(block, 0, length);
1317
- if (bytes.copy) {
1318
- bytes.copy(view, 0, 0, length);
1319
- } else {
1320
- view.set(bytes.subarray(0, length), 0);
1321
- }
1322
- return block;
1323
- }
1324
-
1325
- /**
1326
- * Drop the disk copy of a piece that memory now holds — after any spill of
1327
- * that same piece has finished.
1328
- *
1329
- * `PieceDiskStore.write` records the index when it COMPLETES, so forgetting while a
1330
- * spill of that index is still running let the completing write put it back,
1331
- * and a later read then returned the stale bytes.
1332
- *
1333
- * @param {number} index
1334
- * @returns {Promise<void>}
1335
- */
1336
- async #forgetOnDisk(index) {
1337
- const spill = this.#evicting.get(index);
1338
- if (spill) {
1339
- await spill.catch(() => undefined);
1340
- }
1341
- this.#disk.forget(index);
1342
- this.#spilledAt.delete(index);
1343
- }
1344
-
1345
- put(index, bytes, callback = () => undefined) {
1346
- if (this.#closed) {
1347
- queueMicrotask(() => callback(new Error("Piece store is closed.")));
1348
- return;
1349
- }
1350
-
1351
- const write = async () => {
1352
- // Already resident: the buffer is replaced, not added, so no slot is
1353
- // needed and none is claimed. A fresh buffer rather than a write into the
1354
- // old one, so a reader holding the old reference cannot see a torn write.
1355
- if (this.#buffers.has(index)) {
1356
- const previous = this.#buffers.get(index);
1357
- // A fresh block rather than a write into the old one, so a reader
1358
- // holding the old reference cannot see a torn write.
1359
- this.#buffers.set(index, this.#copyIntoNewBuffer(index, bytes));
1360
- this.#lru.touch(index);
1361
- // And the old block goes back for re-use only if nobody is reading it.
1362
- // A pinned piece has a view onto its memory somewhere; that block is
1363
- // given up instead, and the pool allocates another when it needs one.
1364
- if (this.#lru.isPinned(index)) {
1365
- if (this.#blocksAllocated > 0) {
1366
- this.#blocksAllocated -= 1;
1367
- this.#counters.blocksReleased += 1;
1368
- }
1369
- } else {
1370
- this.#returnBlock(previous);
1371
- }
1372
- await this.#forgetOnDisk(index);
1373
- this.#noteProgress();
1374
- return;
1375
- }
1376
-
1377
- this.#noteArrival();
1378
- const declared = this.#lru.wants(index);
1379
- if (declared) {
1380
- this.#counters.admittedInsideWindow += 1;
1381
- } else {
1382
- this.#counters.admittedOutsideWindow += 1;
1383
- }
1384
-
1385
- // A piece wanted LESS than the one it would displace goes straight to
1386
- // disk instead of being admitted.
1387
- //
1388
- // The same comparison eviction makes, in the same order, from the other
1389
- // end: the priority map's level first, and the distance to a read head
1390
- // only between pieces the map wants equally. Answering the two from
1391
- // different quantities would let the store admit a piece by one rule and
1392
- // evict it again by the other in the same second.
1393
- //
1394
- // Two cases, and the second was missing until 2026-09-02. The first: the
1395
- // arrival is in nobody's zone at all. The second: it IS in a zone, but
1396
- // one the map wants less than the zone holding the piece the store would
1397
- // have to evict for it. The field session had six readers whose windows
1398
- // covered the whole file, so the first case never applied and `0 of those
1399
- // went straight to disk` while the store spilled 233 pieces in a minute.
1400
- //
1401
- // Only when SOMETHING is stated: before that there is no basis for
1402
- // calling one piece more wanted than another.
1403
- const worseThanTheVictim = () => {
1404
- const victim = this.#lru.nextVictim();
1405
- if (victim.index === null) {
1406
- return false;
1407
- }
1408
- const arrivingWant = this.#lru.wantAt(index);
1409
- if (arrivingWant !== victim.want) {
1410
- return arrivingWant > victim.want;
1411
- }
1412
- const arriving = this.#lru.waitFor(index);
1413
- return arriving >= 0 && victim.wait >= 0 && arriving > victim.wait;
1414
- };
1415
- if (this.#lru.protectedCount > 0 && this.#isFullNow()
1416
- && (!declared || worseThanTheVictim())) {
1417
- this.#counters.admittedToDisk += 1;
1418
- await this.#writeThrough(index, bytes);
1419
- this.#noteProgress();
1420
- return;
1421
- }
1422
-
1423
- const release = await this.#claimSlot();
1424
- try {
1425
- this.#registerPiece(index, this.#copyIntoNewBuffer(index, bytes));
1426
- await this.#forgetOnDisk(index);
1427
- } finally {
1428
- release();
1429
- }
1430
- };
1431
-
1432
- write().then(() => callback(null), (error) => callback(error));
1433
- }
1434
-
1435
- get(index, options, callback) {
1436
- if (typeof options === "function") {
1437
- return this.get(index, undefined, options);
1438
- }
1439
- const done = callback ?? (() => undefined);
1440
- if (this.#closed) {
1441
- queueMicrotask(() => done(new Error("Piece store is closed.")));
1442
- return;
1443
- }
1444
-
1445
- const pieceLength = this.#lengthOf(index);
1446
- const offset = options?.offset ?? 0;
1447
- const length = options?.length ?? pieceLength - offset;
1448
-
1449
- const fetch = async () => {
1450
- const buffer = this.#buffers.get(index);
1451
- if (buffer !== undefined) {
1452
- this.#lru.touch(index);
1453
- this.#counters.fromMemory += 1;
1454
- return Buffer.from(Buffer.from(buffer, offset, length));
1455
- }
1456
-
1457
- const revived = await this.#revive(index);
1458
- if (revived === null) {
1459
- throw new Error(`Piece ${index} is not in the store.`);
1460
- }
1461
- return Buffer.from(Buffer.from(revived, offset, length));
1462
- };
1463
-
1464
- fetch().then((bytes) => done(null, bytes), (error) => done(error));
1465
- }
1466
-
1467
- /**
1468
- * State a range of pieces and how much they are wanted. The number is the
1469
- * priority map's own, and it is what eviction compares — see
1470
- * {@link PieceLru#protect}.
1471
- *
1472
- * @param {string|number} readerId
1473
- * @param {number} from
1474
- * @param {number} to
1475
- * @param {number} [urgency]
1476
- * @returns {void}
1477
- */
1478
- protectRange(readerId, from, to, urgency) {
1479
- this.#lru.protect(readerId, from, to, urgency);
1480
- }
1481
-
1482
- protectedRanges() {
1483
- return this.#lru.protectedRanges();
1484
- }
1485
-
1486
- releaseProtection(readerId) {
1487
- this.#lru.unprotect(readerId);
1488
- }
1489
-
1490
- warmRange(from, to, limit = Math.max(1, Math.floor(this.#growthCeiling / 4))) {
1491
- if (this.#closed || !Number.isInteger(from) || !Number.isInteger(to)) {
1492
- return 0;
1493
- }
1494
- let started = 0;
1495
- for (let index = from; index <= to && started < limit; index += 1) {
1496
- if (this.#buffers.has(index) || !this.#disk.has(index)) {
1497
- continue;
1498
- }
1499
- started += 1;
1500
- void this.reside(index).catch(() => undefined);
1501
- }
1502
- return started;
1503
- }
1504
-
1505
- async reside(index) {
1506
- if (this.#closed) {
1507
- throw new Error("Piece store is closed.");
1508
- }
1509
-
1510
- const buffer = this.#buffers.get(index);
1511
- if (buffer !== undefined) {
1512
- this.#lru.touch(index);
1513
- this.#counters.fromMemory += 1;
1514
- return this.locate(index);
1515
- }
1516
-
1517
- const revived = await this.#revive(index);
1518
- if (revived === null) {
1519
- return null;
1520
- }
1521
- return { buffer: revived, offset: 0, length: this.#lengthOf(index) };
1522
- }
1523
-
1524
- close(callback = () => undefined) {
1525
- this.#closed = true;
1526
- liveStores.delete(this);
1527
- this.#buffers.clear();
1528
- this.#spilledAt.clear();
1529
- this.#counters.blocksReleased += this.#blocksAllocated;
1530
- this.#blocksAllocated = 0;
1531
- this.#freeBlocks = [];
1532
- // Whoever is waiting for a slot is woken and finds the store closed, which
1533
- // is an error they can report. Left asleep they simply never returned.
1534
- this.#wake();
1535
- this.#disk.close().then(() => callback(null), (error) => callback(error));
1536
- }
1537
-
1538
- destroy(callback = () => undefined) {
1539
- this.#closed = true;
1540
- liveStores.delete(this);
1541
- this.#buffers.clear();
1542
- this.#spilledAt.clear();
1543
- this.#counters.blocksReleased += this.#blocksAllocated;
1544
- this.#blocksAllocated = 0;
1545
- this.#freeBlocks = [];
1546
- this.#wake();
1547
- this.#disk.destroy().then(() => callback(null), (error) => callback(error));
1548
- }
1549
- }
1
+ /**
2
+ * @file Torrent pieces in shared memory, with disk as the second tier.
3
+ *
4
+ * Replaces the chunk store WebTorrent would otherwise build for itself. Two
5
+ * reasons, one forced and one chosen.
6
+ *
7
+ * **Forced.** WebTorrent's own piece cache hands out the buffer it keeps using
8
+ * and slices again on the next read. The torrent client now runs on its own
9
+ * thread, and moving a piece to the main thread by transferring ownership
10
+ * detached the cache's memory: proxy 2.9.71-2.9.73 answered every read with an
11
+ * empty body (`Stream ends prematurely at 0`) and the failure was invisible,
12
+ * because the error never reached the reader. Owning the memory ourselves
13
+ * removes the question of whose it was.
14
+ *
15
+ * **Chosen.** Memory this side of the thread boundary can be *shared* memory,
16
+ * which the main thread reads without receiving bytes as a copy — see
17
+ * {@link SharedPieceStore#locate}. Measured on the field host: a piece copy
18
+ * costs 3.64 ms, a read from the page cache into a buffer we own 7.63 ms, and
19
+ * re-downloading a piece from the swarm ~1430 ms. So memory first, disk under
20
+ * it, and never the swarm twice.
21
+ *
22
+ * Per piece allocation: each resident piece owns its own `SharedArrayBuffer`.
23
+ * Evicting a piece deletes its entry and the memory is reclaimable by GC.
24
+ * `committed` therefore equals `resident`, not a high-water mark.
25
+ *
26
+ * **Room for a piece is an owned reservation, not a shared number.**
27
+ * `#claimSlot` hands back a release the caller runs in a `finally`; nothing
28
+ * else touches `#outstandingPieces`. It was a counter incremented in one
29
+ * function and decremented in another, and every consequence of that was a
30
+ * defect: a failure between the two lost a slot for the life of the process,
31
+ * `put`'s error path guessed at the correction and could take back a
32
+ * reservation belonging to a different claim, and one lost reservation made
33
+ * the five-second "everything is pinned" error permanently unreachable, so a
34
+ * read retried every 50 ms for ever without completing or failing. Read out of
35
+ * the field failure of 2026-08-31 (`research/worker-heap-oom-2026-08-31.md`).
36
+ *
37
+ * What this deliberately does NOT do is manage the disk as a cache of its own.
38
+ * Pieces evicted from memory are written once and read back on demand; the file
39
+ * is discarded whole when the torrent goes away. libtorrent 2.0 and webtor's
40
+ * seeder both concluded that a hand-rolled disk cache earns less than it costs,
41
+ * and nothing here disagrees.
42
+ */
43
+
44
+ import os from "node:os";
45
+ import { readFileSync } from "node:fs";
46
+ import { divideAllowance, machineAllowanceBytes, OtherDemand } from "./allowance.js";
47
+ import { PieceLru } from "./piece-lru.js";
48
+ import { PieceDiskStore } from "./piece-disk-store.js";
49
+
50
+ /**
51
+ * Live stores, so the worker can report on them.
52
+ *
53
+ * @type {Set<SharedPieceStore>}
54
+ */
55
+ const liveStores = new Set();
56
+
57
+ export function collectStoreStats() {
58
+ return [...liveStores].map((store) => store.stats());
59
+ }
60
+
61
+ export function findSharedStore(torrent) {
62
+ let candidate = torrent?.store;
63
+ for (let depth = 0; candidate && depth < 8; depth += 1) {
64
+ if (candidate instanceof SharedPieceStore) {
65
+ return candidate;
66
+ }
67
+ candidate = candidate.store;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /**
73
+ * The largest fall in the machine's available memory that this process has
74
+ * seen and did not cause itself.
75
+ *
76
+ * What has to be left for everything else on the machine. It cannot be a share
77
+ * of what is free — a share is a number chosen out of nothing, which is what
78
+ * `AVAILABLE_MEMORY_SHARE = 0.25`, `MIN_BUDGET_BYTES` and
79
+ * `MEMORY_BUDGET_CEILING_BYTES` were until 2026-09-02, all three traceable to
80
+ * one observation of one host on 2026-08-03. It is measured instead: between
81
+ * two readings, how much available memory went away beyond what the stores
82
+ * themselves took. On the field host that quantity is large — while the proxy
83
+ * held 76-133 MB overnight the machine's available memory fell from 2378 MB to
84
+ * 306 MB and came back — and on a quiet host it stays near zero, which is the
85
+ * right answer there.
86
+ *
87
+ * Starts at zero: nothing is reserved until somebody else has been seen to
88
+ * need it.
89
+ */
90
+ const otherDemand = new OtherDemand();
91
+
92
+ /**
93
+ * Note what the machine had, and how much of the change was not ours.
94
+ *
95
+ * @param {number} availableBytes
96
+ * @param {number} storeBytes - What the live stores hold right now.
97
+ * @returns {number} The reserve, in bytes.
98
+ */
99
+ export function noteMachineMemory(availableBytes, storeBytes) {
100
+ return otherDemand.note(availableBytes, storeBytes);
101
+ }
102
+
103
+ /** What has recently been observed to be needed by everything that is not us. */
104
+ export function machineReserveBytes() {
105
+ return otherDemand.reserve();
106
+ }
107
+
108
+ /** Forget what other processes have needed. For tests, which share a module. */
109
+ export function forgetMachineMemory() {
110
+ otherDemand.forget();
111
+ }
112
+
113
+ export { divideAllowance, machineAllowanceBytes };
114
+
115
+ export function reviseStoreBudgets() {
116
+ const stores = [...liveStores];
117
+ const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
118
+ const available = availableMemorySync();
119
+ const reserve = noteMachineMemory(available, held);
120
+ const allowance = machineAllowanceBytes(available, held, reserve);
121
+ const shares = divideAllowance(stores.map((store) => store.wantedBytes), allowance);
122
+ const revised = [];
123
+ for (const [position, store] of stores.entries()) {
124
+ revised.push(store.reviseGrowthCeiling(shares[position]));
125
+ }
126
+ return revised;
127
+ }
128
+
129
+ /**
130
+ * Say how much disk the spilled pieces may take between them.
131
+ *
132
+ * Told rather than worked out. The disk is one and this store is not its only
133
+ * user — the segments an encoder produces are on it too — so a ceiling one of
134
+ * two users sets for itself is not a ceiling. Until 2026-09-10 the spill had no
135
+ * ceiling of any kind: 14 400 MB written in one fifty-minute viewing.
136
+ *
137
+ * @param {number | null} allowanceBytes - This thread's whole share, from the
138
+ * owner of the disk on the main thread. Null means nobody has said yet, and
139
+ * nothing is thrown away until somebody does.
140
+ * @param {SharedPieceStore[]} [live] - The stores to divide between.
141
+ * @returns {{ name: string, allowanceBytes: number | null, bytes: number }[]}
142
+ */
143
+ export function reviseSpillBudgets(allowanceBytes, live = [...liveStores]) {
144
+ if (live.length === 0) {
145
+ return [];
146
+ }
147
+ // NOT READ HERE. The disk has one owner and it is on the main thread, where
148
+ // the segments an encoder produces live on the same disk. Reading it here as
149
+ // well is exactly the fault this replaced: two ceilings, each standing for the
150
+ // whole disk. What arrives is this thread's whole share.
151
+ const total = Number.isFinite(allowanceBytes) && allowanceBytes >= 0 ? allowanceBytes : null;
152
+ if (total === null) {
153
+ return live.map((store) => store.reviseSpillCeiling(null));
154
+ }
155
+ // EQUALLY, unlike memory. A store's memory ask is its readers' declared
156
+ // windows; the spill has no such statement, because whatever memory evicts
157
+ // arrives here. Every store's ask is "all of it", nothing distinguishes them,
158
+ // and an equal share is what that means.
159
+ const share = Math.floor(total / live.length);
160
+ return live.map((store) => store.reviseSpillCeiling(share));
161
+ }
162
+
163
+ function defaultMemoryBytes() {
164
+ const stores = [...liveStores];
165
+ const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
166
+ const available = availableMemorySync();
167
+ const allowance = machineAllowanceBytes(available, held, machineReserveBytes());
168
+ // A store being created has no readers, so it has no demand to state and no
169
+ // basis for asking for more or less than the others. It opens on an equal
170
+ // share and the first revision — within a minute, and within seconds of a
171
+ // read starting — replaces that with what its readers actually declare.
172
+ // Deliberately not the whole allowance: on a machine with gigabytes free that
173
+ // would let a torrent nobody is reading yet fill memory before the first
174
+ // revision arrives.
175
+ return Math.floor(allowance / (stores.length + 1));
176
+ }
177
+
178
+ function availableMemorySync() {
179
+ try {
180
+ const text = readFileSync("/proc/meminfo", "utf8");
181
+ const match = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(text);
182
+ if (match) {
183
+ return Number(match[1]) * 1024;
184
+ }
185
+ } catch {
186
+ }
187
+ return os.freemem();
188
+ }
189
+
190
+ /**
191
+ * How many blocks of piece memory this thread has let go of, and how many the
192
+ * collector has actually taken back.
193
+ *
194
+ * Since the store keeps a pool, one block serves many pieces, so this counts
195
+ * blocks and not pieces — and a healthy store allocates only as many as its
196
+ * allowance permits, so both numbers are now small and nearly equal.
197
+ *
198
+ * The one reading that separates the two explanations of the 700 MB nobody can
199
+ * account for (roadmap item 2, field 2026-08-31): if the two numbers track each
200
+ * other, this code is holding nothing and whatever grows is below us, in the
201
+ * allocator — on musl there is no `malloc_trim` and no way to ask. If the gap
202
+ * widens, a reference of ours outlives the piece, and then a heap snapshot can
203
+ * name the holder.
204
+ *
205
+ * What it does NOT prove: a `SharedArrayBuffer`'s memory is shared between the
206
+ * isolates, so this thread's handle going means only that THIS thread let go.
207
+ * The main thread counts its own (`torrent-worker/client.js`), and the pair is
208
+ * what answers the question.
209
+ */
210
+ const released = { count: 0, collected: 0 };
211
+ const collector = typeof FinalizationRegistry === "function"
212
+ ? new FinalizationRegistry(() => {
213
+ released.collected += 1;
214
+ })
215
+ : null;
216
+
217
+ /**
218
+ * What the collector has taken back against what was let go.
219
+ *
220
+ * @returns {{ released: number, collected: number }}
221
+ */
222
+ export function pieceBufferCollection() {
223
+ return { released: released.count, collected: released.collected };
224
+ }
225
+
226
+ const MIN_RESIDENT_PIECES = 2;
227
+ /**
228
+ * How long a claim may go without ANYTHING moving before it gives up.
229
+ *
230
+ * Measured against progress, not against activity. The earlier rule skipped
231
+ * this timer entirely while a spill was in flight or a reservation was held —
232
+ * so one reservation that was never returned made the timer unreachable and a
233
+ * read retried every 50 ms for the life of the process, never completing and
234
+ * never failing (field 2026-08-31).
235
+ */
236
+ const PINNED_WAIT_MS = 5_000;
237
+
238
+ /**
239
+ * How many revival ages are kept for the median. A window, not a history: two
240
+ * hundred covers several minutes of the busiest session measured (7575
241
+ * revivals in 44 minutes) and costs two hundred numbers.
242
+ */
243
+ const REVIVAL_AGE_SAMPLES = 200;
244
+
245
+ /**
246
+ * How many block re-use gaps are kept. The same window as the revival ages, and
247
+ * for the same reason: what is wanted is the rhythm of recent work, not a
248
+ * history of it.
249
+ */
250
+ const REUSE_GAP_SAMPLES = 200;
251
+
252
+ /** How many write durations are kept for the median. */
253
+ const WRITE_DURATION_SAMPLES = 50;
254
+ /** How many admission times are kept, and how far back they are counted. */
255
+ const ARRIVAL_SAMPLES = 100;
256
+ const ARRIVAL_WINDOW_MS = 10_000;
257
+
258
+ /**
259
+ * The middle value of a sample, or null when there is nothing to take a middle
260
+ * of. Null rather than zero: no revivals and instant revivals are different
261
+ * facts and must not print the same.
262
+ *
263
+ * @param {number[]} values
264
+ * @returns {number | null}
265
+ */
266
+ function median(values) {
267
+ if (values.length === 0) {
268
+ return null;
269
+ }
270
+ const sorted = [...values].sort((left, right) => left - right);
271
+ const middle = Math.floor(sorted.length / 2);
272
+ return sorted.length % 2 === 0
273
+ ? Math.round((sorted[middle - 1] + sorted[middle]) / 2)
274
+ : sorted[middle];
275
+ }
276
+ const CLAIM_RETRY_MS = 50;
277
+
278
+ export class SharedPieceStore {
279
+ #chunkLength;
280
+ #lastChunkLength;
281
+ #lastChunkIndex;
282
+ #growthCeiling;
283
+ /** Piece index → SharedArrayBuffer of that piece */
284
+ #buffers = new Map();
285
+ /** @type {Map<number, Promise<void>>} */
286
+ #evicting = new Map();
287
+ /**
288
+ * Slots claimed but not yet filled.
289
+ *
290
+ * Handed out by {@link SharedPieceStore##claimSlot} as a release function the
291
+ * caller must call in a `finally`, never as a number one function increments
292
+ * and another decrements. The counter used to be paired across
293
+ * `#claimSlot`/`#registerPiece`, so any failure between the two lost a slot
294
+ * for the life of the process, and `put`'s error path tried to correct that
295
+ * by guessing — which could take back a reservation belonging to a different
296
+ * claim and let the store admit past its allowance.
297
+ */
298
+ #outstandingPieces = 0;
299
+ /** When something last actually moved: a piece admitted, spilled or unpinned. */
300
+ #lastProgressAt = 0;
301
+ #waiters = [];
302
+ #lru;
303
+ #disk;
304
+ #closed = false;
305
+ #name;
306
+ #counters = {
307
+ fromMemory: 0,
308
+ fromDisk: 0,
309
+ // Reads answered from the file this torrent has been assembled into. Not a
310
+ // miss and not a spill: the bytes were never lost, they are simply kept as
311
+ // a file now.
312
+ fromWholeFile: 0,
313
+ spills: 0,
314
+ revivals: 0,
315
+ blockedByPins: 0,
316
+ waitedForPins: 0,
317
+ // Pieces that went to disk because no block could be had for them. Not a
318
+ // failure the piece is kept and a later read revives it — but it is the
319
+ // measure of how often the store is asked to hold more than it may, and
320
+ // before 2026-09-11 this case ended the torrent instead of being counted.
321
+ admittedWithoutSlot: 0,
322
+ evictedOnRevise: 0,
323
+ spillFailures: 0,
324
+ // Whether the store is doing its job or being asked to hold more than it
325
+ // has room for. An eviction that had to take a piece a reader declared it
326
+ // wants is the second, and it comes back from disk moments later
327
+ // (roadmap item 9).
328
+ evictedProtected: 0,
329
+ evictedDistanceSum: 0,
330
+ evictedWithDistance: 0,
331
+ // Where an arriving piece went. A piece nobody has declared is being
332
+ // downloaded ahead of every reader; putting it in memory pushes out one
333
+ // that IS declared, which is then read back from disk moments later
334
+ // (roadmap item 9).
335
+ admittedInsideWindow: 0,
336
+ admittedOutsideWindow: 0,
337
+ admittedToDisk: 0,
338
+ /** Blocks given back to the operating system. */
339
+ blocksReleased: 0,
340
+ /**
341
+ * A block put back for re-use while a reader still held the piece. Zero by
342
+ * construction a pinned piece is never evicted, and a re-put of a pinned
343
+ * one drops its block instead of recycling it. Counted because if it ever
344
+ * stops being zero, a consumer is reading another piece's bytes, and that
345
+ * is invisible from anywhere else.
346
+ */
347
+ returnedWhilePinned: 0,
348
+ /** Spills that found the disk already holding identical bytes. */
349
+ spillsSkipped: 0,
350
+ /**
351
+ * Blocks a second registration of the same piece displaced. Expected to be
352
+ * small and non-zero: two callers racing for one piece is ordinary. What is
353
+ * NOT ordinary is the block going missing when it happens, which is what
354
+ * killed the process on 2026-09-02.
355
+ */
356
+ blocksDisplaced: 0,
357
+ /** Admissions that waited for the disk instead of evicting another piece. */
358
+ waitedForDisk: 0,
359
+ /**
360
+ * Admissions that grew memory because the disk had stopped answering.
361
+ * Non-zero means the store exceeded its allowance on purpose, and by how
362
+ * many pieces.
363
+ */
364
+ grewWaitingForDisk: 0,
365
+ /**
366
+ * Times a block was wanted, none was free, and the pool was already at its
367
+ * ceiling. Zero by construction a block is only taken after a slot has
368
+ * been claimed, and slots are what the ceiling counts so a number here
369
+ * means the two have come apart and the pool is growing past its allowance.
370
+ */
371
+ blocksBeyondCeiling: 0
372
+ };
373
+ /**
374
+ * Blocks that hold no piece, most recently freed last.
375
+ *
376
+ * A block is one piece's worth of memory. Allocating a new one for every
377
+ * piece meant 7575 allocations of 4 MiB in 44 minutes on 2026-09-02, each
378
+ * released only when the collector got to it which is why the process held
379
+ * 1.86 GB while its own accounting said 352 MB. Blocks are taken from here
380
+ * and put back here instead (roadmap item 2).
381
+ *
382
+ * @type {{ buffer: SharedArrayBuffer, freedAt: number }[]}
383
+ */
384
+ #freeBlocks = [];
385
+ /** Blocks that exist at all: free plus holding a piece. */
386
+ #blocksAllocated = 0;
387
+ /**
388
+ * The widest window any reader has declared here, in pieces.
389
+ *
390
+ * The floor this store asks for between readers: one window is what the next
391
+ * read will ask for, and it is a measurement rather than a chosen number.
392
+ * See `wantedBytes`.
393
+ */
394
+ #widestSeenPieces = 0;
395
+ /** The torrent's files in order, passed through to whoever can read them. @type {object[]} */
396
+ #files = [];
397
+
398
+ /** What the whole torrent weighs, so a last piece is not read past its end. */
399
+ #torrentLength = 0;
400
+
401
+ /**
402
+ * How to read a piece neither tier has, or null when there is nowhere else.
403
+ *
404
+ * @type {((where: object) => Promise<Uint8Array | null>) | null}
405
+ */
406
+ #readElsewhere = null;
407
+
408
+ /**
409
+ * Whether a piece can be had elsewhere, asked without reading it — so a
410
+ * spilled copy that has become a duplicate can be dropped.
411
+ *
412
+ * @type {((where: object) => boolean) | null}
413
+ */
414
+ #isElsewhere = null;
415
+
416
+ /** Whether the last revision had to exceed the machine's share. */
417
+ #beyondTheMachine = false;
418
+ /**
419
+ * How long a block sat free before it was taken again, in milliseconds.
420
+ * Bounded, because what is wanted is the longest gap of RECENT work: an
421
+ * all-time maximum would be raised by one long pause and then never let a
422
+ * block go again.
423
+ *
424
+ * @type {number[]}
425
+ */
426
+ #reuseGaps = [];
427
+ /**
428
+ * How long recent writes to disk took, in milliseconds, and when pieces were
429
+ * admitted. Together they say how much room the store needs beyond what the
430
+ * readers ask for: while one write is finishing, more pieces arrive, and each
431
+ * needs somewhere to go. Without that room every arrival evicts something,
432
+ * which is what produced 233 evictions against 119 completed writes in a
433
+ * minute on 2026-09-02.
434
+ *
435
+ * @type {number[]}
436
+ */
437
+ #writeDurations = [];
438
+ /** When the last few pieces were admitted, for the arrival rate. */
439
+ #admittedAt = [];
440
+ /** Piece index → when it was written out, for the age it comes back at. */
441
+ #spilledAt = new Map();
442
+ /**
443
+ * Ages, in milliseconds, of the last revivals bounded, because the figure
444
+ * wanted is a median and not a history. A piece that comes back seconds
445
+ * after it left should not have left.
446
+ *
447
+ * @type {number[]}
448
+ */
449
+ #revivalAges = [];
450
+
451
+ constructor(chunkLength, options = {}) {
452
+ if (!Number.isInteger(chunkLength) || chunkLength < 1) {
453
+ throw new Error(`Chunk length must be a positive integer, got ${chunkLength}.`);
454
+ }
455
+ this.#chunkLength = chunkLength;
456
+
457
+ const totalLength = Number.isFinite(options.length) ? options.length : 0;
458
+ this.#lastChunkIndex = totalLength > 0 ? Math.ceil(totalLength / chunkLength) - 1 : -1;
459
+ const remainder = totalLength % chunkLength;
460
+ this.#lastChunkLength = remainder === 0 ? chunkLength : remainder;
461
+
462
+ const memoryBytes = Number.isFinite(options.memoryBytes) && options.memoryBytes > 0
463
+ ? options.memoryBytes
464
+ : defaultMemoryBytes();
465
+ // Only where this store STARTS. It is not kept, so it cannot come back as a
466
+ // cap on the revision the way `#capacity` did.
467
+ const openingCeiling = Math.max(MIN_RESIDENT_PIECES, Math.floor(memoryBytes / chunkLength));
468
+ this.#growthCeiling = openingCeiling;
469
+ this.#lru = new PieceLru(openingCeiling);
470
+ this.#name = options.name ?? "pieces";
471
+ // THE LAST PLACE A PIECE CAN COME FROM, handed in as two plain functions.
472
+ // Where those bytes are, and what a file is, is not this store's business:
473
+ // it holds pieces, and these say whether one can be had elsewhere and how.
474
+ this.#readElsewhere = typeof options.readPieceElsewhere === "function"
475
+ ? options.readPieceElsewhere
476
+ : null;
477
+ this.#isElsewhere = typeof options.isPieceElsewhere === "function"
478
+ ? options.isPieceElsewhere
479
+ : null;
480
+ // Plain data the layer above needs to answer those two, and which this
481
+ // store is handed anyway: where each file of the torrent begins and how
482
+ // long the whole of it is.
483
+ this.#files = Array.isArray(options.files) ? options.files : [];
484
+ this.#torrentLength = totalLength;
485
+ // `options.disk` exists so a test can hold a write open or make one fail on
486
+ // purpose. Four of the defects fixed here live in what happens when the
487
+ // disk tier does not answer immediately or at all, and none of them is
488
+ // reachable from outside without saying so.
489
+ this.#disk = options.disk ?? new PieceDiskStore({
490
+ directory: options.path ?? ".",
491
+ name: `${this.#name}.pieces`,
492
+ chunkLength,
493
+ // What it may hold is settled by the same revision that settles memory,
494
+ // within a minute of the store existing. Until then it is unbounded, which
495
+ // is what it has always been — the difference is that it now stops.
496
+ allowanceBytes: null,
497
+ // Where the live readers stand, so what goes first is decided by them and
498
+ // not by which piece happened to be touched longest ago.
499
+ readHeads: () => this.#lru.readHeads()
500
+ });
501
+ liveStores.add(this);
502
+ }
503
+
504
+ stats() {
505
+ const resident = this.#buffers.size;
506
+ const residentBytes = resident * this.#chunkLength;
507
+ // Last piece may be short but stats historically use chunkLength.
508
+ return {
509
+ name: this.#name,
510
+ resident,
511
+ capacity: this.#growthCeiling,
512
+ residentBytes,
513
+ allocatedSlots: this.#blocksAllocated,
514
+ // What the process HOLDS, which with a pool is the blocks that exist —
515
+ // not the pieces in them. Holding and using are different quantities and
516
+ // the difference is the point of the reading.
517
+ committedBytes: this.#blocksAllocated * this.#chunkLength,
518
+ budgetBytes: this.#growthCeiling * this.#chunkLength,
519
+ pinned: this.#lru.pinnedCount,
520
+ // Slots claimed and not yet filled. Reported because a reservation that
521
+ // is never returned is invisible until the store cannot admit anything,
522
+ // and by then the reason is long gone. At rest this is zero.
523
+ outstanding: this.#outstandingPieces,
524
+ // How long since ANYTHING in this store moved — a write finishing, a
525
+ // piece admitted, a pin released. A claim gives up after
526
+ // `PINNED_WAIT_MS` of exactly this, so it is the figure that says whether
527
+ // a refusal was the store being busy or the store being stuck, and until
528
+ // 2026-09-11 nothing printed it: the field had 152 refusals in 104
529
+ // seconds and no way to tell which.
530
+ stillMs: this.#lastProgressAt > 0 ? Date.now() - this.#lastProgressAt : 0,
531
+ spilled: this.#disk.size,
532
+ // What the spill file ACTUALLY weighs, piece by piece, rather than the
533
+ // piece count times a full piece length. The last piece of a torrent is
534
+ // short, and until 2026-09-10 nothing here counted disk at all the
535
+ // figure was a multiplication, and the thing it stood for had no ceiling.
536
+ spilledBytes: this.#disk.bytes,
537
+ spillAllowanceBytes: this.#disk.allowanceBytes,
538
+ spillEvictions: this.#disk.stats().evictions,
539
+ // What the readers between them are asking this store to keep, against
540
+ // what it may hold. A union wider than the capacity cannot be held
541
+ // however the eviction is ordered, and that is the difference between a
542
+ // policy to fix and arithmetic to accept (roadmap item 9).
543
+ demand: this.#lru.demand(),
544
+ // What the process actually holds for this store, which is not the same
545
+ // as what it is using: blocks are kept for re-use. The difference is the
546
+ // spare, and it is the whole of the question whether consumption only
547
+ // grows (roadmap item 2).
548
+ blocksAllocated: this.#blocksAllocated,
549
+ blocksFree: this.#freeBlocks.length,
550
+ blocksDisplaced: this.#counters.blocksDisplaced,
551
+ blocksInUse: this.#blocksInUse(),
552
+ blocksInFlight: this.#blocksInFlight(),
553
+ blocksBeyondCeiling: this.#counters.blocksBeyondCeiling,
554
+ blockBytes: this.#blocksAllocated * this.#chunkLength,
555
+ reuseGapMs: this.#reuseGapCeilingMs(),
556
+ revivalAgeMedianMs: median(this.#revivalAges),
557
+ revivalAgeSamples: this.#revivalAges.length,
558
+ revivedWithinFiveSeconds: this.#revivalAges.filter((age) => age <= 5_000).length,
559
+ ...this.#counters
560
+ };
561
+ }
562
+
563
+ /**
564
+ * Whether the machine's share of memory is smaller than one reader's window.
565
+ *
566
+ * The store holds the window anyway refusing would leave the read it is
567
+ * serving unable to finish, which is worse but it is the honest measure of
568
+ * "this machine cannot take any more", and it is measured rather than
569
+ * guessed: it is the last revision's own comparison of what the machine
570
+ * allowed against what the widest reader declared.
571
+ */
572
+ get isBeyondTheMachine() {
573
+ return this.#beyondTheMachine;
574
+ }
575
+
576
+ /** What this store holds right now, in bytes. */
577
+ get residentBytes() {
578
+ return this.#buffers.size * this.#chunkLength;
579
+ }
580
+
581
+ /** What this store's spilled pieces weigh on disk. */
582
+ get spilledBytes() {
583
+ return this.#disk.bytes;
584
+ }
585
+
586
+ /**
587
+ * Say how much disk this store's spilled pieces may take.
588
+ *
589
+ * The counterpart of `reviseGrowthCeiling`, and settled by the same pass: the
590
+ * two tiers of one store are two readings of one machine.
591
+ *
592
+ * @param {number | null} allowedBytes
593
+ * @returns {{ name: string, allowanceBytes: number | null, bytes: number }}
594
+ */
595
+ reviseSpillCeiling(allowedBytes) {
596
+ // THE OTHER RULE, and it does not wait for the disk to be short. A piece
597
+ // behind every read head has been read and will not be read again unless
598
+ // somebody seeks back, and a seek back re-downloads itthe same bargain
599
+ // this tier makes whenever it drops a piece for room. Without it the spill
600
+ // is bounded only by a share of free space, which on a roomy host is tens of
601
+ // gigabytes against a measured growth of 14 400 MB in one viewing: the
602
+ // ceiling never binds and nothing is ever removed until the torrent goes.
603
+ const behind = this.#disk.forgetBehind(this.#lru.readHeads());
604
+ return {
605
+ name: this.#name,
606
+ allowanceBytes: this.#disk.reviseAllowance(allowedBytes),
607
+ bytes: this.#disk.bytes,
608
+ behind
609
+ };
610
+ }
611
+
612
+ /**
613
+ * What this store is asking to be allowed to hold, in bytes.
614
+ *
615
+ * The union of its readers' declared windowswhat they have said they will
616
+ * need never below the widest single window, because a store that cannot
617
+ * hold one reader's window cannot complete that reader's read at all: every
618
+ * resident piece ends up pinned, the read returns zero bytes and ffmpeg takes
619
+ * that for the end of the file (field 2026-08-15, roadmap item 9).
620
+ *
621
+ * With no reader declaring anything there is no demand to speak of, so the
622
+ * store asks for what the machine allows and the first revision after a read
623
+ * begins brings it down to what that read needs.
624
+ */
625
+ get wantedBytes() {
626
+ const demand = this.#lru.demand();
627
+ if (demand.readers > 0) {
628
+ this.#widestSeenPieces = Math.max(this.#widestSeenPieces, demand.widestPieces);
629
+ const pieces = Math.max(MIN_RESIDENT_PIECES, demand.unionPieces, demand.widestPieces);
630
+ // Plus room to absorb what arrives while a write is finishing. Asking for
631
+ // exactly what the readers want leaves no free place ever, so every
632
+ // arrival evicts one of them — measured 2026-09-02: `6 reader(s) want 23
633
+ // piece(s) of 23 the store may hold`, and 233 evictions in the minute
634
+ // that followed.
635
+ return (pieces + this.slackPieces()) * this.#chunkLength;
636
+ }
637
+ // WITH NO READER, THE FLOOR IS ONE READER'S WINDOW the widest this store
638
+ // has actually been asked for, which is measured rather than chosen, and
639
+ // `MIN_RESIDENT_PIECES` only until it has been asked for anything.
640
+ //
641
+ // It used to fall to the minimum the moment the last reader went, and the
642
+ // allowance is re-derived once a minute (`STORE_REPORT_INTERVAL_MS`) while
643
+ // a claim gives up after five seconds. A reader arriving into that minute
644
+ // met a store of two or three blocks: field 2026-09-11, the viewer switched
645
+ // to another file of the same torrent and the store was at
646
+ // `0/3 (0MB of 12MB allowed)` with the machine offering 4.3 GB.
647
+ //
648
+ // Holding one window's worth between readers is not waste: it is what the
649
+ // next read will ask for within seconds, and the pieces in it are the ones
650
+ // that reader left off at. A store that has never been read keeps nothing
651
+ // either its pieces are arriving for a reader on the way, and they have
652
+ // the disk.
653
+ return (Math.max(MIN_RESIDENT_PIECES, this.#widestSeenPieces) + this.slackPieces()) * this.#chunkLength;
654
+ }
655
+
656
+ reviseGrowthCeiling(allowedBytes) {
657
+ // No cap at what the machine could spare when this store was CREATED.
658
+ // `#capacity` was computed once in the constructor and used as an upper
659
+ // bound here, so the allowance could only ever fall: a torrent opened while
660
+ // the machine was full kept a small allowance for its whole life, however
661
+ // much memory was freed afterwards (roadmap item 2, 2026-09-02).
662
+ const wanted = Math.floor(Number(allowedBytes) / this.#chunkLength);
663
+ // Never below what the live readers together hold, even when the machine's
664
+ // share says less. A store that cannot hold what its readers are pinning
665
+ // cannot complete any of their reads at all: every resident piece ends up
666
+ // pinned, a read returns zero bytes and ffmpeg takes that for the end of
667
+ // the file, which killed every encoder on that file in the field on
668
+ // 2026-08-15 (one reader) and again on 2026-09-07 (three readers of one
669
+ // file at once — picture, sound and the edge-warming read — where this
670
+ // floor was still computed from only the widest one of them, `wantedBytes`
671
+ // above already asks for the union and got it right; this is the same
672
+ // union, used as the floor instead of only as the ask). Exceeding the share
673
+ // is the lesser failure, and the line below says when it happens.
674
+ const demand = this.#lru.demand();
675
+ this.#growthCeiling = Math.max(
676
+ MIN_RESIDENT_PIECES,
677
+ demand.readers > 0 ? demand.unionPieces : MIN_RESIDENT_PIECES,
678
+ Number.isFinite(wanted) ? wanted : MIN_RESIDENT_PIECES
679
+ );
680
+ const belowAWindow = demand.readers > 0
681
+ && Number.isFinite(wanted)
682
+ && wanted < demand.unionPieces;
683
+ this.#beyondTheMachine = belowAWindow;
684
+ // The LRU is told too. It was constructed with the store's original
685
+ // capacity and never revised, so `isFull()` answered against a number that
686
+ // had not been the limit for some time — dormant only because nothing calls
687
+ // it, which is a trap for whoever calls it next.
688
+ this.#lru.setCapacity(this.#growthCeiling);
689
+ // With per-piece buffers memory CAN be given back immediately, unlike the
690
+ // old growable pool. Eagerly evict excess to honour the new ceiling.
691
+ let evicted = 0;
692
+ while (this.#buffers.size > this.#growthCeiling) {
693
+ const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
694
+ if (victim === null) {
695
+ break;
696
+ }
697
+ const victimBuffer = this.#buffers.get(victim);
698
+ if (victimBuffer === undefined) {
699
+ this.#lru.remove(victim);
700
+ continue;
701
+ }
702
+ this.#buffers.delete(victim);
703
+ this.#lru.remove(victim);
704
+ evicted += 1;
705
+ this.#counters.evictedOnRevise += 1;
706
+ this.#noteEviction(protectionYielded, distance);
707
+ // Nobody awaits this spill, so its failure has to end here. Rethrowing
708
+ // made it an unhandled rejection, and an unhandled rejection in the
709
+ // torrent worker ends the thread — a second way to lose the torrent
710
+ // client, on top of the one that already loses it.
711
+ void this.#spill(victim, victimBuffer).catch(() => {
712
+ this.#counters.spillFailures += 1;
713
+ });
714
+ }
715
+ // Blocks the store is no longer using and has waited long enough to give
716
+ // up. The allowance falling is the moment to ask, because that is when the
717
+ // machine has been shown to need the memory.
718
+ const releasedBlocks = this.sweepFreeBlocks();
719
+ return {
720
+ name: this.#name,
721
+ ceilingBytes: this.#growthCeiling * this.#chunkLength,
722
+ committedBytes: this.#blocksAllocated * this.#chunkLength,
723
+ evicted,
724
+ releasedBlocks,
725
+ belowAWindow
726
+ };
727
+ }
728
+
729
+ get chunkLength() {
730
+ return this.#chunkLength;
731
+ }
732
+
733
+ get capacity() {
734
+ return this.#growthCeiling;
735
+ }
736
+
737
+ get residentCount() {
738
+ return this.#buffers.size;
739
+ }
740
+
741
+ get spilledCount() {
742
+ return this.#disk.size;
743
+ }
744
+
745
+ #lengthOf(index) {
746
+ return index === this.#lastChunkIndex ? this.#lastChunkLength : this.#chunkLength;
747
+ }
748
+
749
+ /**
750
+ * Where a resident piece sits, or `null` if not resident.
751
+ * Returns the piece's own SharedArrayBuffer and the intra-piece range.
752
+ * @param {number} index
753
+ * @returns {{ buffer: SharedArrayBuffer, offset: number, length: number } | null}
754
+ */
755
+ locate(index) {
756
+ const buffer = this.#buffers.get(index);
757
+ if (buffer === undefined) {
758
+ return null;
759
+ }
760
+ return { buffer, offset: 0, length: this.#lengthOf(index) };
761
+ }
762
+
763
+ /**
764
+ * Direct access to a piece's buffer for zero-copy consumers.
765
+ * @param {number} index
766
+ * @returns {SharedArrayBuffer | undefined}
767
+ */
768
+ getPieceBuffer(index) {
769
+ return this.#buffers.get(index);
770
+ }
771
+
772
+ pin(index) {
773
+ this.#lru.pin(index);
774
+ }
775
+
776
+ unpin(index) {
777
+ this.#lru.unpin(index);
778
+ this.#noteProgress();
779
+ }
780
+
781
+ /**
782
+ * Reserve room for one piece.
783
+ *
784
+ * @returns {Promise<() => void>} The release, which the caller MUST call in a
785
+ * `finally`. Calling it twice is harmless.
786
+ */
787
+ /**
788
+ * The same reservation, answering null instead of throwing.
789
+ *
790
+ * For callers that have somewhere else to go: an arriving piece has the disk,
791
+ * so it writes through rather than failing. Keeping the throwing form for
792
+ * callers that genuinely have no alternative is what makes the difference
793
+ * visible at the call site rather than in a catch.
794
+ *
795
+ * @returns {Promise<(() => void) | null>}
796
+ */
797
+ async #claimSlotOrNull() {
798
+ try {
799
+ return await this.#claimSlot();
800
+ } catch (error) {
801
+ if (this.#closed) {
802
+ throw error;
803
+ }
804
+ this.#counters.admittedWithoutSlot += 1;
805
+ return null;
806
+ }
807
+ }
808
+
809
+ async #claimSlot() {
810
+ // How long THIS claim has been trying, kept here and not on the store.
811
+ // It was a field, `#pinnedWaitStartedAt`, shared by the two waits inside
812
+ // `#claimSlotOnce` the one for the disk and the one for a piece that may
813
+ // be evicted and each of them zeroed it on giving up, which restarted the
814
+ // other's clock. Measured 2026-09-03: the claim cycled for ever, five
815
+ // seconds per side, `grewWaitingForDisk` and `waitedForPins` both climbing
816
+ // once every five seconds while `blockedByPins` stayed at 0 — the refusal
817
+ // was unreachable. A claim's patience belongs to the claim; with several
818
+ // claimants a shared field is wrong anyway, since one caller giving up
819
+ // would reset the wait of every other.
820
+ const waitingSince = Date.now();
821
+ for (;;) {
822
+ if (this.#closed) {
823
+ throw new Error("Piece store is closed.");
824
+ }
825
+ const isReserved = await this.#claimSlotOnce(waitingSince);
826
+ if (isReserved) {
827
+ let released = false;
828
+ return () => {
829
+ if (released) {
830
+ return;
831
+ }
832
+ released = true;
833
+ this.#outstandingPieces -= 1;
834
+ this.#noteProgress();
835
+ };
836
+ }
837
+ await this.#waitForSlot();
838
+ }
839
+ }
840
+
841
+ /**
842
+ * Sleep until something moves, or until the retry interval, whichever first.
843
+ *
844
+ * One handler, idempotent, and its timer is cleared when it is woken. The
845
+ * earlier version attached a fresh pair of handlers to EVERY pending spill on
846
+ * every attempt and left a timer running each time, so a claim that could not
847
+ * be satisfied allocated in proportion to attempts times pending spills. A
848
+ * settling spill now wakes the store itself, which is where that belongs.
849
+ *
850
+ * @returns {Promise<void>}
851
+ */
852
+ #waitForSlot() {
853
+ return new Promise((resolve) => {
854
+ let settled = false;
855
+ /** @type {ReturnType<typeof setTimeout> | null} */
856
+ let retry = null;
857
+ const finish = () => {
858
+ if (settled) {
859
+ return;
860
+ }
861
+ settled = true;
862
+ if (retry !== null) {
863
+ clearTimeout(retry);
864
+ }
865
+ resolve();
866
+ };
867
+ this.#waiters.push(finish);
868
+ retry = setTimeout(finish, CLAIM_RETRY_MS);
869
+ retry.unref?.();
870
+ });
871
+ }
872
+
873
+ #registerPiece(index, buffer) {
874
+ // A piece may already be here. Both paths that register one look first and
875
+ // then await `put` waits for a slot, `#revive` waits for the disk — and
876
+ // in that gap another caller can register the same index. Overwriting the
877
+ // entry used to drop the previous block on the floor: its memory was not
878
+ // returned to the pool and the pool's own count was never decremented, so
879
+ // the count climbed past the ceiling for ever and the pool degenerated into
880
+ // allocating a fresh block per piece. Field 2026-09-02: a store holding
881
+ // THREE pieces reported 812 MB committed against 68 MB allowed, 739 blocks
882
+ // allocated and 676 still alive, and the process was killed at 4.37 GB.
883
+ const displaced = this.#buffers.get(index);
884
+ this.#buffers.set(index, buffer);
885
+ if (displaced !== undefined && displaced !== buffer) {
886
+ this.#counters.blocksDisplaced += 1;
887
+ this.#returnBlock(displaced);
888
+ }
889
+ this.#lru.touch(index);
890
+ this.#noteProgress();
891
+ }
892
+
893
+ /**
894
+ * Write a piece out and account for it, from the one place that does it.
895
+ *
896
+ * @param {number} index
897
+ * @param {SharedArrayBuffer} buffer
898
+ * @returns {Promise<void>}
899
+ */
900
+ #spill(index, buffer) {
901
+ // The disk may already hold these very bytes. `#revive` reads a piece back
902
+ // into memory and leaves the copy on disk, and only `put` removes it — so a
903
+ // piece that was revived and not re-put is identical to what is already
904
+ // written, and writing it again is work for nothing. There were 7575
905
+ // revivals in one session on 2026-09-02, and every later eviction of one of
906
+ // them wrote a second time (roadmap item 66: 14.4 GB written in a single
907
+ // viewing).
908
+ if (this.#disk.has(index)) {
909
+ this.#counters.spills += 1;
910
+ this.#counters.spillsSkipped += 1;
911
+ this.#spilledAt.set(index, Date.now());
912
+ this.#returnBlock(buffer);
913
+ this.#noteProgress();
914
+ return Promise.resolve();
915
+ }
916
+
917
+ const bytes = Buffer.from(buffer, 0, this.#lengthOf(index));
918
+ const startedAt = Date.now();
919
+ const spill = this.#disk.write(index, bytes).then(
920
+ () => {
921
+ this.#noteWriteDuration(Date.now() - startedAt);
922
+ this.#counters.spills += 1;
923
+ this.#spilledAt.set(index, Date.now());
924
+ this.#evicting.delete(index);
925
+ // Only now. The write reads out of this block, so a block handed to
926
+ // another piece before the write finished would put that piece's bytes
927
+ // into this piece's place in the file.
928
+ this.#returnBlock(buffer);
929
+ this.#noteProgress();
930
+ },
931
+ (error) => {
932
+ this.#evicting.delete(index);
933
+ // The block is no longer holding anything either way; keeping it out of
934
+ // the pool because the write failed would lose it for good.
935
+ this.#returnBlock(buffer);
936
+ this.#noteProgress();
937
+ throw error;
938
+ }
939
+ );
940
+ this.#evicting.set(index, spill);
941
+ return spill;
942
+ }
943
+
944
+ /** Something actually moved: wake whoever is waiting and restart the clock. */
945
+ #noteProgress() {
946
+ this.#lastProgressAt = Date.now();
947
+ this.#wake();
948
+ }
949
+
950
+ /**
951
+ * Record how long one write to disk took.
952
+ *
953
+ * @param {number} durationMs
954
+ * @returns {void}
955
+ */
956
+ #noteWriteDuration(durationMs) {
957
+ this.#writeDurations.push(Math.max(0, durationMs));
958
+ if (this.#writeDurations.length > WRITE_DURATION_SAMPLES) {
959
+ this.#writeDurations.shift();
960
+ }
961
+ }
962
+
963
+ /** Record that a piece arrived, for the arrival rate. */
964
+ #noteArrival() {
965
+ const now = Date.now();
966
+ this.#admittedAt.push(now);
967
+ while (this.#admittedAt.length > ARRIVAL_SAMPLES
968
+ || (this.#admittedAt.length > 0 && now - this.#admittedAt[0] > ARRIVAL_WINDOW_MS)) {
969
+ this.#admittedAt.shift();
970
+ }
971
+ }
972
+
973
+ /**
974
+ * How many pieces the store needs room for beyond what the readers ask for.
975
+ *
976
+ * Measured, not chosen: the pieces that arrive while one write to disk is
977
+ * finishing. Without this room every arrival must evict something, and each
978
+ * eviction holds its block until its write completes — so a disk slower than
979
+ * the swarm turns every admission into one more block held. On 2026-09-02
980
+ * that was 233 evictions against 119 completed writes in a minute, and 203
981
+ * blocks held with three pieces resident.
982
+ *
983
+ * Zero until both quantities have been seen, because a slack invented before
984
+ * anything is measured is a chosen number, and this store has been bitten by
985
+ * those.
986
+ *
987
+ * @returns {number} Pieces.
988
+ */
989
+ slackPieces() {
990
+ if (this.#writeDurations.length === 0 || this.#admittedAt.length < 2) {
991
+ return 0;
992
+ }
993
+ const sorted = [...this.#writeDurations].sort((left, right) => left - right);
994
+ const writeMs = sorted[Math.floor(sorted.length / 2)];
995
+ const spanMs = this.#admittedAt[this.#admittedAt.length - 1] - this.#admittedAt[0];
996
+ if (!(spanMs > 0)) {
997
+ return 0;
998
+ }
999
+ const perMs = (this.#admittedAt.length - 1) / spanMs;
1000
+ return Math.ceil(perMs * writeMs);
1001
+ }
1002
+
1003
+ /**
1004
+ * Blocks that are not free: resident pieces, blocks being written out, and
1005
+ * blocks taken but not yet registered.
1006
+ *
1007
+ * This is what the ceiling has to bound, and until 2026-09-02 it bounded
1008
+ * resident pieces instead. The difference is exactly the memory that goes
1009
+ * missing from the count: a piece being spilled leaves `#buffers` the moment
1010
+ * the eviction begins, while its block stays held until the write it feeds
1011
+ * has finished.
1012
+ *
1013
+ * @returns {number}
1014
+ */
1015
+ #blocksInUse() {
1016
+ return this.#blocksAllocated - this.#freeBlocks.length;
1017
+ }
1018
+
1019
+ /**
1020
+ * Blocks held by writes that have not finished.
1021
+ *
1022
+ * @returns {number}
1023
+ */
1024
+ #blocksInFlight() {
1025
+ return Math.max(0, this.#blocksInUse() - this.#buffers.size);
1026
+ }
1027
+
1028
+ /**
1029
+ * Whether admitting one more piece would need something evicted first.
1030
+ *
1031
+ * Reservations count: a slot claimed and not yet filled is as taken as a
1032
+ * resident piece.
1033
+ *
1034
+ * @returns {boolean}
1035
+ */
1036
+ #isFullNow() {
1037
+ return this.#blocksInUse() + this.#outstandingPieces >= this.#growthCeiling;
1038
+ }
1039
+
1040
+ /**
1041
+ * Write an arriving piece straight to disk, without it ever occupying memory.
1042
+ *
1043
+ * Registered in `#evicting` like a spill, so a `get` for this index waits for
1044
+ * the write instead of finding the piece on neither tier. Deliberately NOT
1045
+ * recorded in `#spilledAt`: that clock measures how long an EVICTED piece
1046
+ * stayed away, and a piece that was never resident has no such age.
1047
+ *
1048
+ * @param {number} index
1049
+ * @param {Uint8Array} bytes
1050
+ * @returns {Promise<void>}
1051
+ */
1052
+ #writeThrough(index, bytes) {
1053
+ // Copied, not viewed. `PieceDiskStore.write` opens the file before it reads the
1054
+ // bytes, so a view onto the caller's buffer could be written to in between
1055
+ // and the file would get the wrong data. The spill path may pass a view
1056
+ // because that memory is ours; this buffer belongs to the torrent client.
1057
+ // It costs nothing extra: the piece was being copied into a shared buffer
1058
+ // on this path before, and now it is copied here instead.
1059
+ const copy = Buffer.from(bytes.subarray(0, Math.min(bytes.length, this.#lengthOf(index))));
1060
+ const write = this.#disk.write(index, copy).then(
1061
+ () => {
1062
+ this.#evicting.delete(index);
1063
+ this.#noteProgress();
1064
+ },
1065
+ (error) => {
1066
+ this.#evicting.delete(index);
1067
+ this.#noteProgress();
1068
+ throw error;
1069
+ }
1070
+ );
1071
+ this.#evicting.set(index, write);
1072
+ return write;
1073
+ }
1074
+
1075
+ /**
1076
+ * Record how long a piece stayed on disk before it was wanted again.
1077
+ *
1078
+ * A piece that comes back seconds after it left was evicted from a working
1079
+ * set that does not fit, and the write and the read were both waste. Kept as
1080
+ * a bounded window of ages because the figure wanted is a median, not a
1081
+ * history.
1082
+ *
1083
+ * @param {number} index
1084
+ * @returns {void}
1085
+ */
1086
+ #noteRevival(index) {
1087
+ const spilledAt = this.#spilledAt.get(index);
1088
+ if (spilledAt === undefined) {
1089
+ return;
1090
+ }
1091
+ this.#spilledAt.delete(index);
1092
+ this.#revivalAges.push(Date.now() - spilledAt);
1093
+ if (this.#revivalAges.length > REVIVAL_AGE_SAMPLES) {
1094
+ this.#revivalAges.shift();
1095
+ }
1096
+ }
1097
+
1098
+ /**
1099
+ * Record what an eviction had to take.
1100
+ *
1101
+ * @param {boolean} protectionYielded - The victim was inside a window a
1102
+ * reader had declared, and was taken anyway because nothing else was free.
1103
+ * @param {number} distance - Pieces from the nearest declared window, -1 when
1104
+ * no reader declared one.
1105
+ * @returns {void}
1106
+ */
1107
+ #noteEviction(protectionYielded, distance) {
1108
+ if (protectionYielded) {
1109
+ this.#counters.evictedProtected += 1;
1110
+ }
1111
+ if (distance >= 0) {
1112
+ this.#counters.evictedDistanceSum += distance;
1113
+ this.#counters.evictedWithDistance += 1;
1114
+ }
1115
+ }
1116
+
1117
+ /**
1118
+ * One piece, from wherever else it can be had.
1119
+ *
1120
+ * @param {number} index
1121
+ * @returns {Promise<Buffer | null>}
1122
+ */
1123
+ async #fromWholeFiles(index) {
1124
+ return this.#readElsewhere
1125
+ ? this.#readElsewhere({
1126
+ index,
1127
+ pieceLength: this.#chunkLength,
1128
+ length: this.#torrentLength,
1129
+ files: this.#files
1130
+ })
1131
+ : null;
1132
+ }
1133
+
1134
+ /**
1135
+ * Whether a spilled piece is now a duplicate of bytes held elsewhere.
1136
+ *
1137
+ * @param {number} index
1138
+ * @returns {boolean}
1139
+ */
1140
+ isInWholeFiles(index) {
1141
+ return this.#isElsewhere
1142
+ ? this.#isElsewhere({
1143
+ index,
1144
+ pieceLength: this.#chunkLength,
1145
+ length: this.#torrentLength,
1146
+ files: this.#files
1147
+ }) === true
1148
+ : false;
1149
+ }
1150
+
1151
+ /**
1152
+ * Drop spilled pieces that are now duplicates of bytes held elsewhere.
1153
+ *
1154
+ * A film assembled into a file is on the disk twice until this runs: once as
1155
+ * the file and once as the pieces it was built from. Field 2026-09-11, one
1156
+ * episode: 1417 MB of segments beside 1424 MB of spilled pieces. Nothing is
1157
+ * lost by dropping the second — a read that wants one of those pieces is
1158
+ * answered from the file.
1159
+ *
1160
+ * @returns {number} How many were dropped.
1161
+ */
1162
+ dropDuplicatesHeldElsewhere() {
1163
+ if (!this.#isElsewhere) {
1164
+ return 0;
1165
+ }
1166
+ let dropped = 0;
1167
+ for (const index of this.#disk.indexes()) {
1168
+ if (this.#buffers.has(index) || this.#evicting.has(index)) {
1169
+ continue;
1170
+ }
1171
+ if (this.isInWholeFiles(index)) {
1172
+ this.#disk.forget(index);
1173
+ dropped += 1;
1174
+ }
1175
+ }
1176
+ return dropped;
1177
+ }
1178
+
1179
+ #wake() {
1180
+ const waiting = this.#waiters;
1181
+ this.#waiters = [];
1182
+ for (const resolve of waiting) {
1183
+ resolve();
1184
+ }
1185
+ }
1186
+
1187
+ /**
1188
+ * One attempt at a reservation.
1189
+ *
1190
+ * @param {number} waitingSince - When the claim this attempt belongs to began
1191
+ * trying. Both waits below are measured from the later of it and the last
1192
+ * time the store moved, so neither can restart the other's clock see
1193
+ * `#claimSlot`.
1194
+ * @returns {Promise<boolean>} Whether a slot was reserved.
1195
+ */
1196
+ async #claimSlotOnce(waitingSince) {
1197
+ // Reserve before suspension so concurrent callers see the reservation.
1198
+ if (this.#blocksInUse() + this.#outstandingPieces < this.#growthCeiling) {
1199
+ this.#outstandingPieces += 1;
1200
+ return true;
1201
+ }
1202
+ const stillFor = () => Date.now() - Math.max(waitingSince, this.#lastProgressAt);
1203
+
1204
+ // Full, and evicting would make it worse rather than better. A piece being
1205
+ // written out has already left `#buffers` while its block is still held —
1206
+ // the write reads from that block so evicting another one converts a
1207
+ // resident block into an in-flight block and takes a fresh block for the
1208
+ // arrival: the memory in use goes UP by one per admission for as long as
1209
+ // the disk is behind. Field 2026-09-02: 233 evictions against 119 completed
1210
+ // writes in a minute, 203 blocks held with three pieces resident, and the
1211
+ // process killed at 4.37 GB.
1212
+ //
1213
+ // So when the disk is what the store is waiting for, it waits. A completing
1214
+ // write calls `#noteProgress`, which wakes whoever is here.
1215
+ // THE SAME QUANTITY THE GRANT ABOVE TESTS. It used to ask whether
1216
+ // `blocksInUse` alone had reached the ceiling, while what reaches the
1217
+ // ceiling is `blocksInUse + outstanding` — so a store held at its ceiling
1218
+ // by reservations fell past this branch and into the eviction below, which
1219
+ // has nothing to evict when nothing is resident. Field 2026-09-11:
1220
+ // `blocks=2 (0 spare)` with `outstanding=2` against a ceiling of 3, two
1221
+ // writes in flight each of which would have returned a block, and the claim
1222
+ // threw rather than waiting the moment out.
1223
+ if (this.#blocksInFlight() > 0 && this.#blocksInUse() + this.#outstandingPieces >= this.#growthCeiling) {
1224
+ if (stillFor() < PINNED_WAIT_MS) {
1225
+ this.#counters.waitedForDisk += 1;
1226
+ return false;
1227
+ }
1228
+ // The disk has stopped answering. Falling through to eviction is the
1229
+ // lesser failure: it grows memory, and the line above says by how much,
1230
+ // where refusing would fail the read outright. The clock is NOT restarted
1231
+ // here: the wait that follows asks the same question of the same claim,
1232
+ // and zeroing it was half of the loop described in `#claimSlot`.
1233
+ this.#counters.grewWaitingForDisk += 1;
1234
+ }
1235
+
1236
+ const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
1237
+ if (victim === null) {
1238
+ // Nothing may leave. Wait while the store is still MOVING — a spill
1239
+ // completing, a piece admitted, a pin released — and give up when it has
1240
+ // not moved for PINNED_WAIT_MS, whatever is nominally in flight. The old
1241
+ // rule asked whether anything was in flight rather than whether anything
1242
+ // had happened, which is why one lost reservation could hold a read here
1243
+ // for ever.
1244
+ if (stillFor() < PINNED_WAIT_MS) {
1245
+ this.#counters.waitedForPins += 1;
1246
+ return false;
1247
+ }
1248
+ this.#counters.blockedByPins += 1;
1249
+ // SAY WHICH STATE REFUSED, with the numbers it was read from. The old
1250
+ // text named one state — every resident piece pinned — and the field case
1251
+ // of 2026-09-11 was a different one: `resident=0 pinned=0`, nothing to
1252
+ // evict because nothing was in memory at all, the ceiling held by
1253
+ // reservations and by two writes on their way to disk. A message that
1254
+ // names a state that did not exist costs a day of reading the wrong code.
1255
+ throw new Error(
1256
+ `No block can be had for ${PINNED_WAIT_MS}ms: ` +
1257
+ `${this.#buffers.size} resident (${this.#lru.pinnedCount} pinned, ` +
1258
+ `${this.#lru.protectedCount} range(s) declared), ` +
1259
+ `${this.#blocksInUse()} block(s) in use of ${this.#growthCeiling} allowed, ` +
1260
+ `${this.#blocksInFlight()} on their way to disk, ` +
1261
+ `${this.#outstandingPieces} reservation(s) outstanding.`
1262
+ );
1263
+ }
1264
+
1265
+ const victimBuffer = this.#buffers.get(victim);
1266
+ if (victimBuffer === undefined) {
1267
+ // Should not happen: LRU says resident but buffer missing.
1268
+ this.#lru.remove(victim);
1269
+ return false;
1270
+ }
1271
+
1272
+ // Claim atomically before await.
1273
+ this.#buffers.delete(victim);
1274
+ this.#lru.remove(victim);
1275
+ this.#outstandingPieces += 1;
1276
+ this.#noteEviction(protectionYielded, distance);
1277
+
1278
+ try {
1279
+ await this.#spill(victim, victimBuffer);
1280
+ } catch (error) {
1281
+ // The caller never received a release for this reservation, so it is
1282
+ // given back here rather than left outstanding for ever.
1283
+ this.#outstandingPieces -= 1;
1284
+ this.#noteProgress();
1285
+ throw error;
1286
+ }
1287
+ // Outstanding stays +1 for the caller; the slot for the new piece is now free.
1288
+ return true;
1289
+ }
1290
+
1291
+ /**
1292
+ * Bring a spilled piece back into memory, once, however many callers ask.
1293
+ *
1294
+ * @param {number} index
1295
+ * @returns {Promise<SharedArrayBuffer | null>} `null` when the piece is on
1296
+ * neither tier.
1297
+ */
1298
+ async #revive(index) {
1299
+ const spill = this.#evicting.get(index);
1300
+ if (spill) {
1301
+ await spill.catch(() => undefined);
1302
+ }
1303
+
1304
+ if (!this.#disk.has(index)) {
1305
+ // Not spilled, but the file it belongs to may be here whole — which is
1306
+ // the ordinary case once a film has been assembled and its spilled copy
1307
+ // dropped as the duplicate it had become.
1308
+ const whole = await this.#fromWholeFiles(index);
1309
+ if (!whole) {
1310
+ return null;
1311
+ }
1312
+ this.#counters.fromWholeFile += 1;
1313
+ const release = await this.#claimSlotOrNull();
1314
+ if (release === null) {
1315
+ // No block to put it in. The caller gets the bytes anyway; what it
1316
+ // loses is only that the next read pays for this one again.
1317
+ return whole;
1318
+ }
1319
+ try {
1320
+ return this.#registerPiece(index, this.#copyIntoNewBuffer(index, whole));
1321
+ } finally {
1322
+ release();
1323
+ }
1324
+ }
1325
+
1326
+ const release = await this.#claimSlot();
1327
+ try {
1328
+ // Another caller may have brought it back while this one waited for a
1329
+ // slot. Registering a second buffer for the same piece would leave
1330
+ // whoever holds the first reading memory nothing evicts.
1331
+ const already = this.#buffers.get(index);
1332
+ if (already !== undefined) {
1333
+ this.#lru.touch(index);
1334
+ this.#counters.fromMemory += 1;
1335
+ return already;
1336
+ }
1337
+ const target = this.#takeBlock();
1338
+ try {
1339
+ // Only this piece's own length: the block is a full piece long and the
1340
+ // last piece of a file is shorter, so reading the whole block would ask
1341
+ // the file for bytes past its end.
1342
+ await this.#disk.read(index, Buffer.from(target, 0, this.#lengthOf(index)));
1343
+ } catch (error) {
1344
+ this.#returnBlock(target);
1345
+ throw error;
1346
+ }
1347
+ this.#registerPiece(index, target);
1348
+ this.#counters.fromDisk += 1;
1349
+ this.#counters.revivals += 1;
1350
+ this.#noteRevival(index);
1351
+ return target;
1352
+ } finally {
1353
+ release();
1354
+ }
1355
+ }
1356
+
1357
+ /**
1358
+ * A block to hold one piece: the most recently freed one, or a new one.
1359
+ *
1360
+ * Every block is a full piece long, whatever piece will live in it. The last
1361
+ * piece of a file is shorter, and it occupies a full block with only its own
1362
+ * bytes meaningful `#lengthOf` is what decides how much is ever read out.
1363
+ * Uniform blocks are what makes them interchangeable at all.
1364
+ *
1365
+ * Most recently freed first, deliberately: a few blocks then carry the whole
1366
+ * of a busy store's traffic and the rest age out of use, which is what makes
1367
+ * {@link SharedPieceStore#sweepFreeBlocks} able to tell a spare block from a
1368
+ * working one.
1369
+ *
1370
+ * @returns {SharedArrayBuffer}
1371
+ */
1372
+ #takeBlock() {
1373
+ const spare = this.#freeBlocks.pop();
1374
+ if (spare !== undefined) {
1375
+ this.#noteReuseGap(Date.now() - spare.freedAt);
1376
+ return spare.buffer;
1377
+ }
1378
+ // Nothing spare and the pool is already as large as it is allowed to be.
1379
+ // This cannot happen while the accounting is sound: a block is taken only
1380
+ // after a slot has been claimed, and slots are exactly what the ceiling
1381
+ // counts. It is recorded rather than hidden because when it does happen the
1382
+ // pool grows without bound, and every block it then allocates is used once
1383
+ // and thrown to a collector that has no reason to run — the heap stays at
1384
+ // 50 MB of 2240 while the process reaches four gigabytes.
1385
+ // Strictly greater: reaching the ceiling exactly is what a full store looks
1386
+ // like, and a slot has just been claimed for this block. Being ALREADY past
1387
+ // it and allocating anyway is the state that runs away.
1388
+ if (this.#blocksAllocated > this.#growthCeiling) {
1389
+ this.#counters.blocksBeyondCeiling += 1;
1390
+ }
1391
+ this.#blocksAllocated += 1;
1392
+ return this.#watchForCollection(new SharedArrayBuffer(this.#chunkLength));
1393
+ }
1394
+
1395
+ /**
1396
+ * Put a block back for re-use, or give it up.
1397
+ *
1398
+ * Given up when the allowance has fallen below the number of blocks that
1399
+ * exist: keeping it would hold memory the machine has just been shown to
1400
+ * need. Otherwise it waits in the free list for the next piece.
1401
+ *
1402
+ * @param {SharedArrayBuffer | undefined} buffer
1403
+ * @returns {void}
1404
+ */
1405
+ #returnBlock(buffer) {
1406
+ if (buffer === undefined) {
1407
+ return;
1408
+ }
1409
+ if (this.#closed || this.#blocksAllocated > this.#growthCeiling) {
1410
+ // Never below zero: `close` gives up every block at once, and a spill
1411
+ // that was already in flight resolves afterwards and arrives here.
1412
+ if (this.#blocksAllocated > 0) {
1413
+ this.#blocksAllocated -= 1;
1414
+ this.#counters.blocksReleased += 1;
1415
+ }
1416
+ return;
1417
+ }
1418
+ this.#freeBlocks.push({ buffer, freedAt: Date.now() });
1419
+ }
1420
+
1421
+ /**
1422
+ * Record how long a block waited to be used again.
1423
+ *
1424
+ * @param {number} gapMs
1425
+ * @returns {void}
1426
+ */
1427
+ #noteReuseGap(gapMs) {
1428
+ this.#reuseGaps.push(Math.max(0, gapMs));
1429
+ if (this.#reuseGaps.length > REUSE_GAP_SAMPLES) {
1430
+ this.#reuseGaps.shift();
1431
+ }
1432
+ }
1433
+
1434
+ /**
1435
+ * The longest a block has recently waited before being wanted again, or null
1436
+ * when no block has yet been re-used.
1437
+ *
1438
+ * This is the store's own working rhythm, measured rather than chosen: while
1439
+ * a film is being watched a block is taken again within milliseconds, because
1440
+ * one is taken for every piece that arrives. A block that has been sitting
1441
+ * longer than the longest of those waits is not part of the work.
1442
+ *
1443
+ * @returns {number | null}
1444
+ */
1445
+ #reuseGapCeilingMs() {
1446
+ if (this.#reuseGaps.length === 0) {
1447
+ return null;
1448
+ }
1449
+ return Math.max(...this.#reuseGaps);
1450
+ }
1451
+
1452
+ /**
1453
+ * Give up blocks that have sat unused longer than this store's own working
1454
+ * rhythm.
1455
+ *
1456
+ * The case it is for: a torrent whose peers have gone. Its readers are still
1457
+ * attached, so nothing removes the torrent — the pool's idle timer needs a
1458
+ * refcount of zero and never starts. Its allowance falls to what those
1459
+ * readers declared, the pieces beyond it are written out, and their blocks
1460
+ * would otherwise wait in the free list for peers that may not return.
1461
+ *
1462
+ * @param {number} [now]
1463
+ * @returns {number} Blocks given up.
1464
+ */
1465
+ sweepFreeBlocks(now = Date.now()) {
1466
+ const ceiling = this.#reuseGapCeilingMs();
1467
+ if (ceiling === null) {
1468
+ return 0;
1469
+ }
1470
+ const keeping = [];
1471
+ let released = 0;
1472
+ for (const spare of this.#freeBlocks) {
1473
+ if (now - spare.freedAt <= ceiling) {
1474
+ keeping.push(spare);
1475
+ continue;
1476
+ }
1477
+ this.#blocksAllocated -= 1;
1478
+ this.#counters.blocksReleased += 1;
1479
+ released += 1;
1480
+ }
1481
+ this.#freeBlocks = keeping;
1482
+ return released;
1483
+ }
1484
+
1485
+ /**
1486
+ * Count this buffer as one this thread will have to let go of, and notice
1487
+ * when the collector takes it. See {@link pieceBufferCollection}.
1488
+ *
1489
+ * @param {SharedArrayBuffer} buffer
1490
+ * @returns {SharedArrayBuffer} The same buffer.
1491
+ */
1492
+ #watchForCollection(buffer) {
1493
+ released.count += 1;
1494
+ collector?.register(buffer, null);
1495
+ return buffer;
1496
+ }
1497
+
1498
+ /**
1499
+ * A fresh buffer holding this piece's bytes.
1500
+ *
1501
+ * @param {number} index
1502
+ * @param {Uint8Array} bytes
1503
+ * @returns {SharedArrayBuffer}
1504
+ */
1505
+ #copyIntoNewBuffer(index, bytes) {
1506
+ const length = this.#lengthOf(index);
1507
+ const block = this.#takeBlock();
1508
+ const view = Buffer.from(block, 0, length);
1509
+ if (bytes.copy) {
1510
+ bytes.copy(view, 0, 0, length);
1511
+ } else {
1512
+ view.set(bytes.subarray(0, length), 0);
1513
+ }
1514
+ return block;
1515
+ }
1516
+
1517
+ /**
1518
+ * Drop the disk copy of a piece that memory now holds — after any spill of
1519
+ * that same piece has finished.
1520
+ *
1521
+ * `PieceDiskStore.write` records the index when it COMPLETES, so forgetting while a
1522
+ * spill of that index is still running let the completing write put it back,
1523
+ * and a later read then returned the stale bytes.
1524
+ *
1525
+ * @param {number} index
1526
+ * @returns {Promise<void>}
1527
+ */
1528
+ async #forgetOnDisk(index) {
1529
+ const spill = this.#evicting.get(index);
1530
+ if (spill) {
1531
+ await spill.catch(() => undefined);
1532
+ }
1533
+ this.#disk.forget(index);
1534
+ this.#spilledAt.delete(index);
1535
+ }
1536
+
1537
+ put(index, bytes, callback = () => undefined) {
1538
+ if (this.#closed) {
1539
+ queueMicrotask(() => callback(new Error("Piece store is closed.")));
1540
+ return;
1541
+ }
1542
+
1543
+ const write = async () => {
1544
+ // Already resident: the buffer is replaced, not added, so no slot is
1545
+ // needed and none is claimed. A fresh buffer rather than a write into the
1546
+ // old one, so a reader holding the old reference cannot see a torn write.
1547
+ if (this.#buffers.has(index)) {
1548
+ const previous = this.#buffers.get(index);
1549
+ // A fresh block rather than a write into the old one, so a reader
1550
+ // holding the old reference cannot see a torn write.
1551
+ this.#buffers.set(index, this.#copyIntoNewBuffer(index, bytes));
1552
+ this.#lru.touch(index);
1553
+ // And the old block goes back for re-use only if nobody is reading it.
1554
+ // A pinned piece has a view onto its memory somewhere; that block is
1555
+ // given up instead, and the pool allocates another when it needs one.
1556
+ if (this.#lru.isPinned(index)) {
1557
+ if (this.#blocksAllocated > 0) {
1558
+ this.#blocksAllocated -= 1;
1559
+ this.#counters.blocksReleased += 1;
1560
+ }
1561
+ } else {
1562
+ this.#returnBlock(previous);
1563
+ }
1564
+ await this.#forgetOnDisk(index);
1565
+ this.#noteProgress();
1566
+ return;
1567
+ }
1568
+
1569
+ this.#noteArrival();
1570
+ const isDeclared = this.#lru.wants(index);
1571
+ if (isDeclared) {
1572
+ this.#counters.admittedInsideWindow += 1;
1573
+ } else {
1574
+ this.#counters.admittedOutsideWindow += 1;
1575
+ }
1576
+
1577
+ // A piece wanted LESS than the one it would displace goes straight to
1578
+ // disk instead of being admitted.
1579
+ //
1580
+ // The same comparison eviction makes, in the same order, from the other
1581
+ // end: the priority map's level first, and the distance to a read head
1582
+ // only between pieces the map wants equally. Answering the two from
1583
+ // different quantities would let the store admit a piece by one rule and
1584
+ // evict it again by the other in the same second.
1585
+ //
1586
+ // Two cases, and the second was missing until 2026-09-02. The first: the
1587
+ // arrival is in nobody's zone at all. The second: it IS in a zone, but
1588
+ // one the map wants less than the zone holding the piece the store would
1589
+ // have to evict for it. The field session had six readers whose windows
1590
+ // covered the whole file, so the first case never applied and `0 of those
1591
+ // went straight to disk` while the store spilled 233 pieces in a minute.
1592
+ //
1593
+ // Only when SOMETHING is stated: before that there is no basis for
1594
+ // calling one piece more wanted than another.
1595
+ const isWorseThanTheVictim = () => {
1596
+ const victim = this.#lru.nextVictim();
1597
+ if (victim.index === null) {
1598
+ return false;
1599
+ }
1600
+ const arrivingWant = this.#lru.wantAt(index);
1601
+ if (arrivingWant !== victim.want) {
1602
+ return arrivingWant > victim.want;
1603
+ }
1604
+ const arriving = this.#lru.waitFor(index);
1605
+ return arriving >= 0 && victim.wait >= 0 && arriving > victim.wait;
1606
+ };
1607
+ if (this.#lru.protectedCount > 0 && this.#isFullNow()
1608
+ && (!isDeclared || isWorseThanTheVictim())) {
1609
+ this.#counters.admittedToDisk += 1;
1610
+ await this.#writeThrough(index, bytes);
1611
+ this.#noteProgress();
1612
+ return;
1613
+ }
1614
+
1615
+ // MEMORY IS NEVER A REASON TO REFUSE A PIECE. The piece is verified and
1616
+ // the disk will take it; failing here fails the torrent client's own
1617
+ // write, and the client answers that by destroying the torrent — field
1618
+ // 2026-09-11, `WebTorrent client error: Every resident piece is pinned`,
1619
+ // after which every read of that torrent answered `File 1 not found` for
1620
+ // the life of the process and the viewer could not open anything.
1621
+ //
1622
+ // The branch above already writes through when the store is full and the
1623
+ // arrival is wanted less than what it would displace. It cannot fire
1624
+ // where nothing is declared (`protectedCount > 0`), which is exactly the
1625
+ // state a store between readers is in — and that state is where the
1626
+ // refusal happened.
1627
+ const release = await this.#claimSlotOrNull();
1628
+ if (release === null) {
1629
+ this.#counters.admittedToDisk += 1;
1630
+ await this.#writeThrough(index, bytes);
1631
+ this.#noteProgress();
1632
+ return;
1633
+ }
1634
+ try {
1635
+ this.#registerPiece(index, this.#copyIntoNewBuffer(index, bytes));
1636
+ await this.#forgetOnDisk(index);
1637
+ } finally {
1638
+ release();
1639
+ }
1640
+ };
1641
+
1642
+ write().then(() => callback(null), (error) => callback(error));
1643
+ }
1644
+
1645
+ get(index, options, callback) {
1646
+ if (typeof options === "function") {
1647
+ return this.get(index, undefined, options);
1648
+ }
1649
+ const done = callback ?? (() => undefined);
1650
+ if (this.#closed) {
1651
+ queueMicrotask(() => done(new Error("Piece store is closed.")));
1652
+ return;
1653
+ }
1654
+
1655
+ const pieceLength = this.#lengthOf(index);
1656
+ const offset = options?.offset ?? 0;
1657
+ const length = options?.length ?? pieceLength - offset;
1658
+
1659
+ const fetch = async () => {
1660
+ const buffer = this.#buffers.get(index);
1661
+ if (buffer !== undefined) {
1662
+ this.#lru.touch(index);
1663
+ this.#counters.fromMemory += 1;
1664
+ return Buffer.from(Buffer.from(buffer, offset, length));
1665
+ }
1666
+
1667
+ // NOT revived into memory. This entry point is the torrent client's: it
1668
+ // reads to answer a peer, and a peer asks for 16 KB while a piece here is
1669
+ // megabytes. Reviving would take a whole block for bytes nobody is going
1670
+ // to read again — and it is the ONE read that can be answered without a
1671
+ // block at all, since the caller is handed its own copy either way.
1672
+ //
1673
+ // Field 2026-09-11, and this is the whole reason the store could not
1674
+ // serve anybody: an upload capped at 512 KB/s produced 63 416 reads of
1675
+ // which 78.4 % missed memory, 49 696 pieces revived whole, and every one
1676
+ // of those revivals competed for a ceiling of three blocks. Claiming a
1677
+ // block for an upload is also how this path reached `#claimSlot`, whose
1678
+ // failure the torrent client turns into a destroyed torrent.
1679
+ // A spill that is still being written owns the only copy there is, so
1680
+ // wait for it exactly as `#revive` does before asking the disk.
1681
+ const spill = this.#evicting.get(index);
1682
+ if (spill) {
1683
+ await spill.catch(() => undefined);
1684
+ }
1685
+ const resident = this.#buffers.get(index);
1686
+ if (resident !== undefined) {
1687
+ this.#lru.touch(index);
1688
+ this.#counters.fromMemory += 1;
1689
+ return Buffer.from(Buffer.from(resident, offset, length));
1690
+ }
1691
+ if (this.#disk.has(index)) {
1692
+ const want = Math.max(0, Math.min(length, this.#lengthOf(index) - offset));
1693
+ const target = Buffer.allocUnsafe(want);
1694
+ await this.#disk.read(index, target, offset);
1695
+ this.#counters.fromDisk += 1;
1696
+ return target;
1697
+ }
1698
+ const whole = await this.#fromWholeFiles(index);
1699
+ if (whole) {
1700
+ this.#counters.fromWholeFile += 1;
1701
+ return Buffer.from(whole.subarray(offset, offset + length));
1702
+ }
1703
+ throw new Error(`Piece ${index} is not in the store.`);
1704
+ };
1705
+
1706
+ fetch().then((bytes) => done(null, bytes), (error) => done(error));
1707
+ }
1708
+
1709
+ /**
1710
+ * State a range of pieces and how much they are wanted. The number is the
1711
+ * priority map's own, and it is what eviction compares — see
1712
+ * {@link PieceLru#protect}.
1713
+ *
1714
+ * @param {string|number} readerId
1715
+ * @param {number} from
1716
+ * @param {number} to
1717
+ * @param {number} [urgency]
1718
+ * @returns {void}
1719
+ */
1720
+ protectRange(readerId, from, to, urgency) {
1721
+ this.#lru.protect(readerId, from, to, urgency);
1722
+ // A READER DECLARES ITSELF IN A MOMENT; the allowance was re-derived once a
1723
+ // minute. Between the two a read met whatever the store had shrunk to while
1724
+ // nobody was reading, and a claim gives up after five seconds — twelve
1725
+ // times sooner than the store could have grown (field 2026-09-11).
1726
+ //
1727
+ // DELIBERATELY NOT raising the ceiling here. A reader declaring a window
1728
+ // wider than the store may hold is a shortage to absorb, not an instruction
1729
+ // to take more memory: with several viewers on several films the unions add
1730
+ // up across stores, and each store's floor already wins over the machine's
1731
+ // share at the next revision. What the shortage must not do is fail a read,
1732
+ // and that is answered where it arises — no path in this store refuses for
1733
+ // want of memory any more.
1734
+ }
1735
+
1736
+ protectedRanges() {
1737
+ return this.#lru.protectedRanges();
1738
+ }
1739
+
1740
+ releaseProtection(readerId) {
1741
+ this.#lru.unprotect(readerId);
1742
+ }
1743
+
1744
+ warmRange(from, to, limit = Math.max(1, Math.floor(this.#growthCeiling / 4))) {
1745
+ if (this.#closed || !Number.isInteger(from) || !Number.isInteger(to)) {
1746
+ return 0;
1747
+ }
1748
+ let started = 0;
1749
+ for (let index = from; index <= to && started < limit; index += 1) {
1750
+ if (this.#buffers.has(index) || !this.#disk.has(index)) {
1751
+ continue;
1752
+ }
1753
+ started += 1;
1754
+ void this.reside(index).catch(() => undefined);
1755
+ }
1756
+ return started;
1757
+ }
1758
+
1759
+ async reside(index) {
1760
+ if (this.#closed) {
1761
+ throw new Error("Piece store is closed.");
1762
+ }
1763
+
1764
+ const buffer = this.#buffers.get(index);
1765
+ if (buffer !== undefined) {
1766
+ this.#lru.touch(index);
1767
+ this.#counters.fromMemory += 1;
1768
+ return this.locate(index);
1769
+ }
1770
+
1771
+ const revived = await this.#revive(index);
1772
+ if (revived === null) {
1773
+ return null;
1774
+ }
1775
+ return { buffer: revived, offset: 0, length: this.#lengthOf(index) };
1776
+ }
1777
+
1778
+ close(callback = () => undefined) {
1779
+ this.#closed = true;
1780
+ liveStores.delete(this);
1781
+ this.#buffers.clear();
1782
+ this.#spilledAt.clear();
1783
+ this.#counters.blocksReleased += this.#blocksAllocated;
1784
+ this.#blocksAllocated = 0;
1785
+ this.#freeBlocks = [];
1786
+ // Whoever is waiting for a slot is woken and finds the store closed, which
1787
+ // is an error they can report. Left asleep they simply never returned.
1788
+ this.#wake();
1789
+ this.#disk.close().then(() => callback(null), (error) => callback(error));
1790
+ }
1791
+
1792
+ destroy(callback = () => undefined) {
1793
+ this.#closed = true;
1794
+ liveStores.delete(this);
1795
+ this.#buffers.clear();
1796
+ this.#spilledAt.clear();
1797
+ this.#counters.blocksReleased += this.#blocksAllocated;
1798
+ this.#blocksAllocated = 0;
1799
+ this.#freeBlocks = [];
1800
+ this.#wake();
1801
+ this.#disk.destroy().then(() => callback(null), (error) => callback(error));
1802
+ }
1803
+ }