A full-featured download manager.
fix(media): purge ephemeral aria2 segment tasks (#2041)
Dr_rOot0d2ea5a2d6e5
diff --git a/src/core/bridge-receiver/bridge-receiver.test.ts b/src/core/bridge-receiver/bridge-receiver.test.tsindex 7811d1fd..6a98dbd9 100644--- a/src/core/bridge-receiver/bridge-receiver.test.ts+++ b/src/core/bridge-receiver/bridge-receiver.test.ts@@ -16,6 +16,7 @@ import { BridgeReceiver } from './bridge-receiver'const fakeSegmentAria2: SegmentAria2 = {addUri: vi.fn(async () => 'gid-seg'),forceRemove: vi.fn(async () => {}),+ removeDownloadResult: vi.fn(async () => {}),tellStatus: vi.fn(async () => null),onComplete: vi.fn(),onError: vi.fn(),diff --git a/src/core/download/aria2-segment-client.test.ts b/src/core/download/aria2-segment-client.test.tsindex 7c637d54..a391f15f 100644--- a/src/core/download/aria2-segment-client.test.ts+++ b/src/core/download/aria2-segment-client.test.ts@@ -13,6 +13,7 @@ function makeFakeRpc() {options: Record<string, string | string[]>}[] = []const forceRemoveCalls: string[] = []+ const removeDownloadResultCalls: string[] = []const tellStatusCalls: { gid: string; keys?: string[] }[] = []let tellStatusImpl: (@@ -29,9 +30,13 @@ function makeFakeRpc() {return Promise.resolve('gid-1')}),- forceRemove: vi.fn((gid: string) => {+ forceRemoveTask: vi.fn((gid: string) => {forceRemoveCalls.push(gid)- return Promise.resolve('gid-1')+ return Promise.resolve()+ }),+ removeDownloadResult: vi.fn((gid: string) => {+ removeDownloadResultCalls.push(gid)+ return Promise.resolve()}),tellStatus: vi.fn((gid: string, keys?: string[]) => {tellStatusCalls.push({ gid, keys })@@ -56,6 +61,7 @@ function makeFakeRpc() {},addUriCalls,forceRemoveCalls,+ removeDownloadResultCalls,tellStatusCalls,}}@@ -63,7 +69,7 @@ function makeFakeRpc() {describe('Aria2SegmentClient', () => {it('fan-out: two onComplete subscribers both receive the gid', () => {const { rpc, fireComplete } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)const cb1 = vi.fn()const cb2 = vi.fn()client.onComplete(cb1)@@ -75,7 +81,7 @@ describe('Aria2SegmentClient', () => {it('fan-out: two onError subscribers both receive the gid', () => {const { rpc, fireError } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)const cb1 = vi.fn()const cb2 = vi.fn()client.onError(cb1)@@ -87,7 +93,7 @@ describe('Aria2SegmentClient', () => {it('addUri forwards uris and maps opts to string aria2 options', async () => {const { rpc, addUriCalls } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)const gid = await client.addUri(['http://example.com/seg.ts'], {dir: '/tmp/media',out: '000001.seg',@@ -107,17 +113,18 @@ describe('Aria2SegmentClient', () => {expect(options.continue).toBe('false')})- it('forceRemove forwards the gid to rpc', async () => {- const { rpc, forceRemoveCalls } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ it('forceRemove stops the gid and purges its durable result', async () => {+ const { rpc, forceRemoveCalls, removeDownloadResultCalls } = makeFakeRpc()+ const client = new Aria2SegmentClient(rpc, rpc)await client.forceRemove('gid-42')expect(forceRemoveCalls).toEqual(['gid-42'])+ expect(removeDownloadResultCalls).toEqual(['gid-42'])})// C2: isSegmentGid trackingit('isSegmentGid returns true after addUri, false before', async () => {const { rpc } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)expect(client.isSegmentGid('gid-1')).toBe(false)await client.addUri(['http://cdn/seg.ts'], { dir: '/tmp', out: 'seg.ts' })expect(client.isSegmentGid('gid-1')).toBe(true)@@ -125,7 +132,7 @@ describe('Aria2SegmentClient', () => {it('isSegmentGid returns false after forceRemove', async () => {const { rpc } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)await client.addUri(['http://cdn/seg.ts'], { dir: '/tmp', out: 'seg.ts' })expect(client.isSegmentGid('gid-1')).toBe(true)await client.forceRemove('gid-1')@@ -136,15 +143,16 @@ describe('Aria2SegmentClient', () => {let resolveRemove: () => void = () => {}const rpc = {addUri: async () => 'gid-1',- forceRemove: () =>+ forceRemoveTask: () =>new Promise<void>((r) => {resolveRemove = r}),+ removeDownloadResult: async () => {},tellStatus: async () => ({ completedLength: '0', totalLength: '0' }),onDownloadComplete: () => {},onDownloadError: () => {},}- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)await client.addUri(['http://cdn/seg.ts'], { dir: '/tmp', out: 'seg.ts' })expect(client.isSegmentGid('gid-1')).toBe(true)const p = client.forceRemove('gid-1')@@ -156,21 +164,25 @@ describe('Aria2SegmentClient', () => {expect(client.isSegmentGid('gid-1')).toBe(false)})- it('isSegmentGid returns false after a complete event fires', async () => {+ it('keeps a completed gid owned until its durable result is purged', async () => {const { rpc, fireComplete } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)await client.addUri(['http://cdn/seg.ts'], { dir: '/tmp', out: 'seg.ts' })expect(client.isSegmentGid('gid-1')).toBe(true)fireComplete('gid-1')+ expect(client.isSegmentGid('gid-1')).toBe(true)+ await client.removeDownloadResult('gid-1')expect(client.isSegmentGid('gid-1')).toBe(false)})- it('isSegmentGid returns false after an error event fires', async () => {+ it('keeps an errored gid owned until its durable result is purged', async () => {const { rpc, fireError } = makeFakeRpc()- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)await client.addUri(['http://cdn/seg.ts'], { dir: '/tmp', out: 'seg.ts' })expect(client.isSegmentGid('gid-1')).toBe(true)fireError('gid-1')+ expect(client.isSegmentGid('gid-1')).toBe(true)+ await client.removeDownloadResult('gid-1')expect(client.isSegmentGid('gid-1')).toBe(false)})@@ -182,7 +194,7 @@ describe('Aria2SegmentClient', () => {completedLength: '1024',totalLength: '4096',}))- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)const result = await client.tellStatus('gid-7')@@ -198,7 +210,7 @@ describe('Aria2SegmentClient', () => {setTellStatus(async () => {throw new Error('GID not found')})- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)const result = await client.tellStatus('gid-gone')@@ -208,7 +220,7 @@ describe('Aria2SegmentClient', () => {it('tellStatus returns null when a length field is missing / non-numeric', async () => {const { rpc, setTellStatus } = makeFakeRpc()setTellStatus(async () => ({ totalLength: '4096' }))- const client = new Aria2SegmentClient(rpc)+ const client = new Aria2SegmentClient(rpc, rpc)const result = await client.tellStatus('gid-partial')diff --git a/src/core/download/aria2-segment-client.ts b/src/core/download/aria2-segment-client.tsindex d6791615..29e70eed 100644--- a/src/core/download/aria2-segment-client.ts+++ b/src/core/download/aria2-segment-client.ts@@ -9,7 +9,6 @@ interface Aria2Rpc {uris: string[],options: Record<string, string | string[]>): Promise<string>- forceRemove(gid: string): Promise<unknown>// aria2 returns every numeric field as a string (JSON-RPC convention). We// only need the two byte counts, so pass an explicit key filter to keep the// response small. Typed structurally (not via Aria2RawStatus) so this file@@ -22,29 +21,34 @@ interface Aria2Rpc {onDownloadError(handler: (event: Aria2Event) => void): void}+interface SegmentResultLifecycle {+ forceRemoveTask(gid: string): Promise<void>+ removeDownloadResult(gid: string): Promise<void>+}+export class Aria2SegmentClient implements SegmentAria2 {private readonly rpc: Aria2Rpc+ private readonly resultLifecycle: SegmentResultLifecycleprivate readonly completeCallbacks: Array<(gid: string) => void> = []private readonly errorCallbacks: Array<(gid: string) => void> = []private readonly active = new Set<string>()- constructor(rpc: Aria2Rpc) {+ constructor(rpc: Aria2Rpc, resultLifecycle: SegmentResultLifecycle) {this.rpc = rpc+ this.resultLifecycle = resultLifecyclerpc.onDownloadComplete((event) => {- this.active.delete(event.gid)for (const cb of this.completeCallbacks) {cb(event.gid)}})rpc.onDownloadError((event) => {- this.active.delete(event.gid)for (const cb of this.errorCallbacks) {cb(event.gid)}})}- /** Returns true if this gid belongs to an active segment download. */+ /** Returns true while this gid is still owned by the segment lifecycle. */isSegmentGid(gid: string): boolean {return this.active.has(gid)}@@ -113,15 +117,35 @@ export class Aria2SegmentClient implements SegmentAria2 {}async forceRemove(gid: string): Promise<void> {- // Drop from the skip-set only AFTER aria2 has removed the download. If we- // deleted first, the 1s poll loop could observe the gid still live in- // aria2 but no longer in `active` and mint a phantom segment task — the- // "a bunch of seg tasks appear right after the mux task errors" bug. The- // dir-based suppression in the poll loop is the gid-timing-independent- // backstop; this ordering closes the window at the source.+ // Removing a live task only moves it into aria2's stopped-result store.+ // Purge that result as a second, mandatory step so SQLite persistence+ // cannot restore this ephemeral segment on the next process launch.+ let stopError: unknown+ try {+ await this.resultLifecycle.forceRemoveTask(gid)+ } catch (err) {+ stopError = err+ }+try {- await this.rpc.forceRemove(gid)- } finally {+ await this.removeDownloadResult(gid)+ } catch (purgeError) {+ if (stopError !== undefined) {+ throw new AggregateError(+ [stopError, purgeError],+ `Failed to stop and purge segment ${gid}`+ )+ }+ throw purgeError+ }+ }++ async removeDownloadResult(gid: string): Promise<void> {+ // Keep the gid in the poll-loop skip set until durable deletion succeeds.+ // If deletion fails, startup reconciliation gets another chance without+ // exposing the row as a standalone task in the meantime.+ await this.resultLifecycle.removeDownloadResult(gid)+ if (this.active.has(gid)) {this.active.delete(gid)}}diff --git a/src/core/download/segment-downloader.test.ts b/src/core/download/segment-downloader.test.tsindex 9355f125..2e432690 100644--- a/src/core/download/segment-downloader.test.ts+++ b/src/core/download/segment-downloader.test.ts@@ -51,6 +51,7 @@ function makeFakeAria2(opts?: {}) {const addUriCalls: FakeAddUriCall[] = []const forceRemoveCalls: FakeForceRemoveCall[] = []+ const removeDownloadResultCalls: string[] = []const bytes = new Map<string,{ completedLength: number; totalLength: number }@@ -70,6 +71,10 @@ function makeFakeAria2(opts?: {forceRemoveCalls.push({ gid })return Promise.resolve()},+ removeDownloadResult(gid) {+ removeDownloadResultCalls.push(gid)+ return Promise.resolve()+ },tellStatus(gid) {return Promise.resolve(bytes.get(gid) ?? null)},@@ -89,6 +94,9 @@ function makeFakeAria2(opts?: {get forceRemoveCalls() {return forceRemoveCalls},+ get removeDownloadResultCalls() {+ return removeDownloadResultCalls+ },/** Set the byte counts aria2 would report for a gid on the next poll. */setBytes(gid: string, completedLength: number, totalLength: number) {bytes.set(gid, { completedLength, totalLength })@@ -315,6 +323,12 @@ describe('SegmentDownloader', () => {await runPromise// 1 initial + 3 retries = 4 total addUri callsexpect(fake.addUriCalls).toHaveLength(4)+ expect(fake.removeDownloadResultCalls).toEqual([+ 'gid1',+ 'gid2',+ 'gid3',+ 'gid4',+ ])expect(caught).toBeInstanceOf(Error)})@@ -346,6 +360,32 @@ describe('SegmentDownloader', () => {await runPromise})+ it('purges every completed gid before the run resolves', async () => {+ const fake = makeFakeAria2()+ const dl = new SegmentDownloader({+ aria2: fake.aria2,+ tmpDir: TMP,+ pollScheduler: neverSchedule,+ })+ const runPromise = dl.run(+ makePlan({+ segments: [+ { url: 'https://cdn.example/seg0.ts' },+ { url: 'https://cdn.example/seg1.ts' },+ ],+ }),+ {},+ () => {}+ )+ await new Promise((resolve) => setImmediate(resolve))++ fake.fireComplete('gid1')+ fake.fireComplete('gid2')+ await runPromise++ expect(fake.removeDownloadResultCalls).toEqual(['gid1', 'gid2'])+ })+it('(g) resolves partPaths in index order with initPath separate', async () => {const fake = makeFakeAria2()const dl = new SegmentDownloader({@@ -651,13 +691,13 @@ describe('SegmentDownloader', () => {await new Promise((resolve) => setImmediate(resolve))// Cancel while addUri promise is still pending- await dl.cancel()+ const cancelPromise = dl.cancel()// Now resolve the addUri promise — the gid should be forceRemovedif (delayPromises.resolve) {delayPromises.resolve()}- await new Promise((resolve) => setImmediate(resolve))+ await cancelPromise// Verify: the returned gid was forceRemoved, not added to activeGids/activeJobsexpect(fake.forceRemoveCalls).toHaveLength(1)diff --git a/src/core/download/segment-downloader.ts b/src/core/download/segment-downloader.tsindex fe01ca2b..80814a8f 100644--- a/src/core/download/segment-downloader.ts+++ b/src/core/download/segment-downloader.ts@@ -22,6 +22,8 @@ export interface SegmentAria2 {}): Promise<string>forceRemove(gid: string): Promise<void>+ /** Purge a terminal segment from aria2's stopped result and durable store. */+ removeDownloadResult(gid: string): Promise<void>/*** Register a single callback to receive completion notifications.* Important: onComplete and onError register a SINGLE callback each.@@ -146,6 +148,10 @@ export class SegmentDownloader {private readonly activeJobs = new Map<string, Job>()/** Set of all gids currently in-flight (submitted but not yet complete/error). */private readonly activeGids = new Set<string>()+ /** Terminal gids whose durable result deletion has not settled yet. */+ private readonly settlingGids = new Set<string>()+ /** Async add/terminal-cleanup operations that cancel() must drain. */+ private readonly pendingOperations = new Set<Promise<void>>()private rejectRun: ((err: Error) => void) | null = null/** Flag to guard against cancel-during-retry race: set when cancel() is called. */@@ -185,6 +191,30 @@ export class SegmentDownloader {}}+ private trackOperation(operation: Promise<void>): void {+ this.pendingOperations.add(operation)+ void operation.finally(() => {+ this.pendingOperations.delete(operation)+ })+ }++ private async purgeResult(gid: string): Promise<void> {+ try {+ await this.aria2.removeDownloadResult(gid)+ } catch (firstError) {+ try {+ // A live/stale classification race can make the first terminal purge+ // fail. forceRemove performs stop + a second durable purge attempt.+ await this.aria2.forceRemove(gid)+ } catch (retryError) {+ throw new AggregateError(+ [firstError, retryError],+ `Failed to purge segment ${gid}`+ )+ }+ }+ }+// -------------------------------------------------------------------------// Public API// -------------------------------------------------------------------------@@ -194,8 +224,11 @@ export class SegmentDownloader {headers: Record<string, string>,onProgress: (p: SegmentProgress) => void): Promise<{ initPath?: string; partPaths: string[] }> {+ this.cancelled = false+ this.rejectRun = nullthis.activeJobs.clear()this.activeGids.clear()+ this.settlingGids.clear()// Build a flat ordered job list: [init?, seg0, seg1, ...]const jobs: Job[] = []@@ -241,11 +274,6 @@ export class SegmentDownloader {// and a poll that transiently returns null keeps the prior value instead of// dropping bytes.let finishedBytes = 0- // Size lookups for segments that completed before any poll recorded them —- // awaited before the run resolves so the FINAL total is accurate even when- // the poll's first tick never landed (e.g. a fast single-segment stream).- const pendingSizes: Promise<void>[] = []-return new Promise<{ initPath?: string; partPaths: string[] }>((resolve, reject) => {if (total === 0) {@@ -255,6 +283,12 @@ export class SegmentDownloader {this.rejectRun = reject+ const fail = (err: Error) => {+ this.stopPolling()+ this.rejectRun = null+ reject(err)+ }+const report = () => {let activeCompleted = 0let activeTotal = 0@@ -292,13 +326,10 @@ export class SegmentDownloader {const resolveWhenDone = () => {if (completed !== total) return- // Await any in-flight size lookups so the final report is accurate- // before the run resolves (the coordinator reads the final bytes).- void Promise.all(pendingSizes).then(() => {- this.stopPolling()- report()- resolve(buildResult())- })+ this.stopPolling()+ this.rejectRun = null+ report()+ resolve(buildResult())}// Register callbacks once@@ -307,32 +338,29 @@ export class SegmentDownloader {if (!job) returnthis.activeJobs.delete(gid)this.activeGids.delete(gid)- completed++-- const ls = lastSeen.get(gid)- if (ls) {- // Size known from a prior poll: move it to finished synchronously so- // the running total stays continuous (no dip as the gid leaves).- lastSeen.delete(gid)- addFinished(ls.total)- } else {- // Completed before any poll recorded its size — it contributed 0 to- // every prior report, so learning its size now only ADDS (never- // shrinks). aria2 keeps a completed download queryable until- // removeDownloadResult, so a final tellStatus still returns it.- report()- pendingSizes.push(- this.aria2- .tellStatus(gid)- .catch(() => null)- .then((s) => {- if (s) addFinished(s.totalLength)- })- )- }+ this.settlingGids.add(gid)+ const operation = (async () => {+ const ls = lastSeen.get(gid)+ if (ls) {+ // Size known from a prior poll: move it to finished before the+ // gid leaves the active set so the running total never dips.+ lastSeen.delete(gid)+ addFinished(ls.total)+ } else {+ // Query before purging: terminal downloads remain queryable only+ // until removeDownloadResult succeeds.+ const status = await this.aria2.tellStatus(gid).catch(() => null)+ if (status) addFinished(status.totalLength)+ }- releaseSlot()- resolveWhenDone()+ await this.purgeResult(gid)+ this.settlingGids.delete(gid)+ completed+++ report()+ releaseSlot()+ resolveWhenDone()+ })().catch((err: Error) => fail(err))+ this.trackOperation(operation)})this.aria2.onError((gid) => {@@ -340,20 +368,28 @@ export class SegmentDownloader {if (!job) returnthis.activeJobs.delete(gid)this.activeGids.delete(gid)+ this.settlingGids.add(gid)// A retry restarts this segment from zero; drop its cached bytes so// the active sum reflects only live in-flight segments.lastSeen.delete(gid)-- if (job.retriesLeft > 0) {- // Re-submit with one fewer retry remaining- job.retriesLeft--- submitJob(job)- } else {- this.stopPolling()- reject(- new Error(`Segment download failed permanently: ${job.outPath}`)- )- }+ const operation = (async () => {+ await this.purgeResult(gid)+ this.settlingGids.delete(gid)+ running--++ if (this.cancelled) return+ if (job.retriesLeft > 0) {+ // Re-submit only after the failed durable row is gone. This also+ // keeps the semaphore count stable across retries.+ job.retriesLeft--+ submitJob(job)+ } else {+ fail(+ new Error(`Segment download failed permanently: ${job.outPath}`)+ )+ }+ })().catch((err: Error) => fail(err))+ this.trackOperation(operation)})// ── Byte poll ────────────────────────────────────────────────────@@ -395,27 +431,36 @@ export class SegmentDownloader {}running++const partHeaders = buildHeaders(job.part, headers)- this.aria2- .addUri([job.part.url], {- dir: this.tmpDir,- out: path.basename(job.outPath),- header: partHeaders.length > 0 ? partHeaders : undefined,- 'max-tries': MAX_TRIES,- 'retry-wait': RETRY_WAIT,- })- .then((gid) => {- if (this.cancelled) {- void this.aria2.forceRemove(gid)- return- }- this.activeJobs.set(gid, job)- this.activeGids.add(gid)- })- .catch((err: Error) => {+ const operation = (async () => {+ let gid: string+ try {+ gid = await this.aria2.addUri([job.part.url], {+ dir: this.tmpDir,+ out: path.basename(job.outPath),+ header: partHeaders.length > 0 ? partHeaders : undefined,+ 'max-tries': MAX_TRIES,+ 'retry-wait': RETRY_WAIT,+ })+ } catch (err) {+ running--+ if (!this.cancelled) fail(err as Error)+ return+ }++ if (this.cancelled) {running--- this.stopPolling()- reject(err)- })+ await this.aria2.forceRemove(gid)+ return+ }+ this.activeJobs.set(gid, job)+ this.activeGids.add(gid)+ })().catch((err: Error) => {+ // At this point addUri succeeded and cancellation owns the gid.+ // Keep run() cancelled; cancel() drains this rejected operation and+ // startup reconciliation retries any rare durable-delete failure.+ if (!this.cancelled) fail(err)+ })+ this.trackOperation(operation)}const releaseSlot = () => {@@ -440,13 +485,20 @@ export class SegmentDownloader {async cancel(): Promise<void> {this.cancelled = truethis.stopPolling()- const gids = [...this.activeGids]- this.activeGids.clear()- this.activeJobs.clear()- await Promise.allSettled(gids.map((g) => this.aria2.forceRemove(g)))+ const gids = [...new Set([...this.activeGids, ...this.settlingGids])]if (this.rejectRun) {this.rejectRun(new Error('SegmentDownloader: cancelled'))this.rejectRun = null}+ await Promise.allSettled(gids.map((g) => this.aria2.forceRemove(g)))+ // addUri can resolve after cancellation and return a gid that was not in+ // the snapshot above. Its tracked continuation force-removes that gid;+ // drain it before cancellation is considered complete.+ while (this.pendingOperations.size > 0) {+ await Promise.allSettled([...this.pendingOperations])+ }+ this.activeGids.clear()+ this.settlingGids.clear()+ this.activeJobs.clear()}}diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex cbdd3d7b..97f2e638 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -219,6 +219,26 @@ describe('EngineSupervisor', () => {})describe('start — happy path', () => {+ it('runs startup maintenance after RPC connect and before publishing Ready', async () => {+ const readyObserved = vi.fn()+ eventBus.on(Events.EngineStateChanged, (state) => {+ if (state === EngineState.Ready) readyObserved()+ })+ const maintenance = vi.fn(async () => {+ expect(rpcClient.connect).toHaveBeenCalledOnce()+ expect(readyObserved).not.toHaveBeenCalled()+ })+ supervisor.setPreReadyMaintenance(maintenance)++ await supervisor.start('/usr/bin/aria2c')++ expect(maintenance).toHaveBeenCalledOnce()+ expect(readyObserved).toHaveBeenCalledOnce()+ expect(maintenance.mock.invocationCallOrder[0]).toBeLessThan(+ readyObserved.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER+ )+ })+it('resolves the download proxy before building aria2 arguments', async () => {const resolved = {allProxy: 'http://127.0.0.1:43123',diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex dd043b7c..7789dbd6 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -109,6 +109,7 @@ export class EngineSupervisor {private sqliteFallbackActive = falseprivate sqliteFallbackAttempted = falseprivate restartPromise: Promise<void> | null = null+ private preReadyMaintenance: (() => Promise<void>) | null = nullconstructor(private eventBus: EventBus,@@ -194,6 +195,11 @@ export class EngineSupervisor {this.getEffectiveLimits = fn}+ /** Register best-effort engine maintenance that runs after RPC connects but before Ready. */+ setPreReadyMaintenance(maintenance: () => Promise<void>): void {+ this.preReadyMaintenance = maintenance+ }+/*** HOT-update the aria2 speed limits via `aria2.changeGlobalOption`. No-op* when the engine is not Ready (cold start picks up limits via `buildArgs`).@@ -530,6 +536,20 @@ export class EngineSupervisor {await this.processManager.gracefulStop()return}+ if (this.preReadyMaintenance) {+ try {+ await this.preReadyMaintenance()+ } catch (error) {+ // Startup reconciliation also runs after Ready. Maintenance narrows+ // the visibility/resume window but must not make aria2 unavailable.+ log.warn({ err: error }, 'pre-ready engine maintenance failed')+ }+ if (this.stopping) {+ this.rpcClient.disconnect()+ await this.processManager.gracefulStop()+ return+ }+ }// Raw JSON-RPC clients commonly omit per-task options. Seed the global// template so their new HTTP/FTP tasks retain aria2's historical Motrix// resume behavior. Motrix-owned recovery still overrides `continue`diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 6498249d..ca46db4c 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -1009,7 +1009,7 @@ describe('SessionManager', () => {expect(tasks[0].id).not.toBe('gid-orphan')})- it('does NOT adopt aria2 segment downloads under mediaTmpRoot (phantom-task guard)', async () => {+ it('evicts aria2 segment downloads under mediaTmpRoot instead of adopting them', async () => {// A mux/hls/dash task's segment downloads run on the shared aria2 daemon// and persist in aria2's session. On restart aria2 restores them; without// the guard restore() would adopt each as a phantom "000000.seg" task.@@ -1037,6 +1037,62 @@ describe('SessionManager', () => {await mediaSession.restore()expect(taskManager.getAll()).toHaveLength(0)+ expect(adapter.forceRemoveTask).toHaveBeenCalledTimes(1)+ expect(adapter.forceRemoveTask).toHaveBeenCalledWith('seg-video')+ expect(adapter.removeDownloadResult).toHaveBeenCalledTimes(2)+ expect(adapter.removeDownloadResult).toHaveBeenCalledWith('seg-video')+ expect(adapter.removeDownloadResult).toHaveBeenCalledWith('seg-audio')+ })++ it('still purges a media row when force-remove races or fails', async () => {+ const mediaRoot = '/var/tmp/motrix-media'+ const mediaSession = new SessionManager(+ taskManager,+ rpc,+ db,+ adapter,+ mediaRoot+ )+ vi.mocked(adapter.forceRemoveTask).mockRejectedValueOnce(+ new Error('already terminal')+ )+ vi.mocked(rpc.tellWaiting).mockResolvedValue([+ createRawStatus({+ gid: 'seg-raced',+ status: 'waiting',+ dir: `${mediaRoot}/motrix-media-race/video`,+ }),+ ])++ await mediaSession.restore()++ expect(adapter.forceRemoveTask).toHaveBeenCalledWith('seg-raced')+ expect(adapter.removeDownloadResult).toHaveBeenCalledWith('seg-raced')+ expect(taskManager.getAll()).toHaveLength(0)+ })++ it('sweeps legacy media rows before the normal restore pass', async () => {+ const mediaRoot = '/var/tmp/motrix-media'+ const mediaSession = new SessionManager(+ taskManager,+ rpc,+ db,+ adapter,+ mediaRoot+ )+ vi.mocked(rpc.tellActive).mockResolvedValue([+ createRawStatus({+ gid: 'seg-startup',+ status: 'active',+ dir: `${mediaRoot}/motrix-media-old/video`,+ }),+ ])++ await mediaSession.purgeEphemeralMediaRows()++ expect(adapter.forceRemoveTask).toHaveBeenCalledWith('seg-startup')+ expect(adapter.removeDownloadResult).toHaveBeenCalledWith('seg-startup')+ expect(taskManager.getAll()).toHaveLength(0)})it('still adopts a normal download whose dir is outside mediaTmpRoot', async () => {diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex e9ab6d54..34b7efc0 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -1,4 +1,5 @@import fs from 'node:fs'+import path from 'node:path'import { newEngineTaskId, newTaskId } from '@core/lib/ids'import { getLogger } from '@core/logger'import type { StagedMetadataOp } from '@core/plugin/hooks/staged-effects'@@ -293,6 +294,49 @@ export class SessionManager {this.postDeliveryObservability = observability}+ /**+ * Remove media-segment rows left by older versions before the engine is+ * published as Ready. Segment downloads are implementation details of a+ * parent media task, live only in the app temp tree, and must never survive+ * an aria2 restart as standalone work.+ */+ async purgeEphemeralMediaRows(): Promise<void> {+ if (!this.mediaTmpRoot) return++ try {+ const [activeTasks, waitingTasks, stoppedTasks] = await Promise.all([+ this.rpc.tellActive(),+ fetchAll((offset, num) => this.rpc.tellWaiting(offset, num)),+ fetchAll((offset, num) => this.rpc.tellStopped(offset, num)),+ ])+ const { tasks } = await resolveCurrentAria2Rows(+ this.rpc,+ activeTasks,+ waitingTasks,+ stoppedTasks+ )+ const mediaRows = tasks.filter((row) => this.isMediaSegmentRow(row))+ await Promise.all(+ mediaRows.map((row) =>+ this.evictEngineRow(+ row,+ 'startup: failed to evict persisted media segment'+ )+ )+ )+ if (mediaRows.length > 0) {+ log.info(+ { count: mediaRows.length },+ 'startup: evicted persisted media segments'+ )+ }+ } catch (err) {+ // Full restore repeats the row-level cleanup. A transient list failure+ // must not make the whole download engine unavailable.+ log.warn({ err }, 'startup: media segment sweep failed')+ }+ }+runExclusivePersistence<T>(operation: () => T | Promise<T>): Promise<T> {if (this.stopping) {return Promise.reject(new Error('SessionManager is stopping'))@@ -641,12 +685,16 @@ export class SessionManager {// Pass 1 — drive from aria2 rows.for (const aria2 of aria2Tasks) {- // Skip media segment downloads. They run on the shared aria2 daemon for- // an hls/dash/mux task and get persisted in aria2's session; on restart- // aria2 restores them, and adopting them here surfaces phantom- // "000000.seg" tasks. They always write under mediaTmpRoot. The owning- // MediaTaskCoordinator task is restored from motrix.db separately.- if (this.mediaTmpRoot && aria2.dir.startsWith(this.mediaTmpRoot)) {+ // Media segments are ephemeral children of a coordinator task. Older+ // versions left them in aria2's durable store, so hide AND evict them;+ // skipping adoption alone made the restarted downloads invisible.+ if (this.isMediaSegmentRow(aria2)) {+ evictions.push(+ this.evictEngineRow(+ aria2,+ 'restore: failed to evict persisted media segment'+ )+ )continue}@@ -1052,24 +1100,55 @@ export class SessionManager {* Failures are logged and swallowed — restore must finish, and a row* that survives here is retried by the same shield on the next launch.*/- private async evictResurrectedErrorRow(aria2: Aria2RawStatus): Promise<void> {+ private isMediaSegmentRow(aria2: Aria2RawStatus): boolean {+ if (!this.mediaTmpRoot || !aria2.dir) return false+ const relative = path.relative(+ path.resolve(this.mediaTmpRoot),+ path.resolve(aria2.dir)+ )+ return (+ relative === '' ||+ (relative !== '..' &&+ !relative.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relative))+ )+ }++ private async evictEngineRow(+ aria2: Aria2RawStatus,+ failureMessage: string+ ): Promise<void> {const stopped =aria2.status === 'error' ||aria2.status === 'complete' ||aria2.status === 'removed'- try {- if (!stopped) {+ let stopError: unknown+ if (!stopped) {+ try {await this.adapter.forceRemoveTask(aria2.gid)+ } catch (err) {+ stopError = err}+ }+ try {+ // Always attempt the durable purge even if force-remove failed. The row+ // may have become terminal between the list snapshot and this call.await this.adapter.removeDownloadResult(aria2.gid)} catch (err) {log.warn(- { err, gid: aria2.gid, engineStatus: aria2.status },- 'restore: failed to evict resurrected errored engine row'+ { err, stopError, gid: aria2.gid, engineStatus: aria2.status },+ failureMessage)}}+ private evictResurrectedErrorRow(aria2: Aria2RawStatus): Promise<void> {+ return this.evictEngineRow(+ aria2,+ 'restore: failed to evict resurrected errored engine row'+ )+ }+private mergeTaskFromPair(pair: TaskWithInstances,matchedInstance: TaskInstanceRow | null,diff --git a/src/core/task/media-mux-e2e.test.ts b/src/core/task/media-mux-e2e.test.tsindex e6a82899..fb2ab4cc 100644--- a/src/core/task/media-mux-e2e.test.ts+++ b/src/core/task/media-mux-e2e.test.ts@@ -64,6 +64,7 @@ describe.skipIf(let baseUrl: stringlet handle: Aria2Handlelet rpc: import('../engine/aria2/aria2-rpc-client').Aria2RpcClient+ let adapter: import('../engine/aria2/aria2-adapter').Aria2Adapterlet disconnect: () => voidbeforeAll(async () => {@@ -113,6 +114,7 @@ describe.skipIf(handle = await spawnAria2ForTest({ baseDir: aria2BaseDir })const wired = await connectAdapter(handle)rpc = wired.rpc+ adapter = wired.adapterdisconnect = wired.disconnect}, 60_000)@@ -130,7 +132,7 @@ describe.skipIf(})it('downloads video+audio over aria2 and muxes to a playable mp4 (saveDir auto-created)', async () => {- const segmentClient = new Aria2SegmentClient(rpc)+ const segmentClient = new Aria2SegmentClient(rpc, adapter)const taskManager = new TaskManager()const coordinator = new MediaTaskCoordinator({taskManager,diff --git a/src/core/task/media-task-coordinator.test.ts b/src/core/task/media-task-coordinator.test.tsindex 593a1a34..aa230164 100644--- a/src/core/task/media-task-coordinator.test.ts+++ b/src/core/task/media-task-coordinator.test.ts@@ -26,6 +26,7 @@ function makeDownloaderFake(opts?: {report?: SegmentProgress[]/** Active segment gids this stream reports (Bug B). */activeGids?: string[]+ error?: Error}) {const cancelFn = vi.fn(async () => {})let rejectRun: ((err: Error) => void) | null = null@@ -36,6 +37,7 @@ function makeDownloaderFake(opts?: {_headers: unknown,onProgress: (p: SegmentProgress) => void): Promise<{ initPath?: string; partPaths: string[] }> => {+ if (opts?.error) throw opts.errorif (opts?.hang) {return new Promise<{ initPath?: string; partPaths: string[] }>((_resolve, reject) => {@@ -664,6 +666,40 @@ describe('MediaTaskCoordinator.start', () => {expect(task?.errorDetailKey).toBe('task.error.detail.muxFailed')})+ it('cancels the sibling stream when one segment downloader fails', async () => {+ const video = makeDownloaderFake({+ error: new Error('segment download failed'),+ })+ const audio = makeDownloaderFake({ hang: true })+ const streams = [video, audio]+ const { deps, taskManager } = makeDeps({+ makeDownloader: () => {+ const next = streams.shift()+ if (!next) throw new Error('unexpected downloader')+ return next as unknown as import('@core/download/segment-downloader').SegmentDownloader+ },+ mintTaskId: () => 'stream-failure-test',+ })+ const coordinator = new MediaTaskCoordinator(deps)++ await expect(+ coordinator.start({+ ...baseJob(),+ audio: {+ container: 'mpegts',+ segments: [{ url: 'https://cdn/audio.ts', index: 0 }],+ isComplete: true,+ },+ })+ ).rejects.toThrow('segment download failed')++ expect(video.cancel).toHaveBeenCalledOnce()+ expect(audio.cancel).toHaveBeenCalledOnce()+ expect(taskManager.getById('stream-failure-test')?.status).toBe(+ TaskStatus.Error+ )+ })+it('uses a stable taskId across the whole lifecycle', async () => {let id = 0const { deps, taskManager } = makeDeps({diff --git a/src/core/task/media-task-coordinator.ts b/src/core/task/media-task-coordinator.tsindex 60749963..d854d97f 100644--- a/src/core/task/media-task-coordinator.ts+++ b/src/core/task/media-task-coordinator.ts@@ -659,6 +659,16 @@ export class MediaTaskCoordinator {() => this.persistBestEffort(taskId, 'completion'))} catch (err) {+ // Promise.all rejects as soon as either stream fails. Explicitly drain+ // every coordinator-owned downloader before recording the failure or+ // cleaning/preserving its temp directory; otherwise the sibling stream+ // keeps writing invisible aria2 work after its parent task has ended.+ if (!state.cancelled) {+ await Promise.allSettled(state.downloaders.map((d) => d.cancel()))+ state.ffmpeg?.kill()+ state.ffmpeg = null+ }+// If cancel() already set mux-aborted, don't overwriteif (this.running.has(taskId) &&diff --git a/src/main/index.ts b/src/main/index.tsindex a1697724..833bb09e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1893,6 +1893,9 @@ async function initializeMainProcess(): Promise<void> {: null})+ supervisor.setPreReadyMaintenance(() =>+ sessionManager.purgeEphemeralMediaRows()+ )const pluginRuntime = await createPluginRuntime({activation: pluginActivation,registry: pluginRegistry,@@ -2334,7 +2337,7 @@ async function initializeMainProcess(): Promise<void> {(candidate) => resolveExecutable(candidate, process.env))const ff = await resolveFfmpegLocation()- const segmentAria2Client = new Aria2SegmentClient(rpcClient)+ const segmentAria2Client = new Aria2SegmentClient(rpcClient, adapter)segmentClient = segmentAria2Clientconst revealInFolder = createRevealInFolderHandler({shell,diff --git a/src/server/index.ts b/src/server/index.tsindex 7d100701..91dcb243 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1827,7 +1827,7 @@ async function main() {publishTaskUpdateNow,taskManager,activityRecorder: taskActivityService,- segmentAria2: new Aria2SegmentClient(rpcClient),+ segmentAria2: new Aria2SegmentClient(rpcClient, adapter),tmpRoot: runtimeDirectories.tempDir,persistTask,persistTaskWithOccurrence,