@torrent-tv/proxy 2.87.8 → 2.87.10

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