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