Skip to content

A full-featured download manager.

fix(task): prevent completed rpc downloads from restarting (#2075)

Dr_rOot58ac857e197c
diff --git a/e2e/completed-rpc-recovery.spec.ts b/e2e/completed-rpc-recovery.spec.ts
new file mode 100644
index 00000000..5a268a52
--- /dev/null
+++ b/e2e/completed-rpc-recovery.spec.ts
@@ -0,0 +1,130 @@
+import { access, readFile, unlink } from 'node:fs/promises'
+import path from 'node:path'
+import type { ElectronApplication, Page } from '@playwright/test'
+import { Queries } from '../src/shared/protocol/queries'
+import type { DownloadTask } from '../src/shared/types/task'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
+import { startHttpFixture } from './fixtures/http-server'
+
+async function readTasks(page: Page): Promise<DownloadTask[]> {
+ return page.evaluate(async (channel) => {
+ const api = (
+ window as unknown as {
+ motrix: { invoke: (channel: string) => Promise<DownloadTask[]> }
+ }
+ ).motrix
+ return api.invoke(channel)
+ }, Queries.ListTasks)
+}
+
+test('completed raw RPC download stays deleted after restart and a new same-URL task stays independent', async ({
+ userDataDir,
+ rpcPort,
+}) => {
+ const fixture = await startHttpFixture({ size: 1024 })
+ let app: ElectronApplication | undefined
+ try {
+ app = await launchMotrix({ userDataDir, rpcPort })
+ let page = await app.firstWindow()
+ await page.waitForLoadState('domcontentloaded')
+ await waitForEngineReady(page)
+ const settings = JSON.parse(
+ await readFile(path.join(userDataDir, 'settings.json'), 'utf8')
+ ) as { engine: { rpcSecret: string } }
+ const rpc = async <T>(
+ method: string,
+ params: unknown[] = []
+ ): Promise<T> => {
+ const response = await fetch(`http://127.0.0.1:${rpcPort}/jsonrpc`, {
+ method: 'POST',
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'completed-rpc-recovery',
+ method: `aria2.${method}`,
+ params: [`token:${settings.engine.rpcSecret}`, ...params],
+ }),
+ })
+ const reply = (await response.json()) as {
+ result: T
+ error?: { message: string }
+ }
+ if (reply.error) throw new Error(reply.error.message)
+ return reply.result
+ }
+ const gid = await rpc<string>('addUri', [[fixture.fileUrl]])
+ await expect
+ .poll(
+ async () =>
+ (await readTasks(page)).find((task) => task.engineTaskId === gid)
+ ?.status
+ )
+ .toBe('completed')
+ const before = (await readTasks(page)).find(
+ (task) => task.engineTaskId === gid
+ )!
+ expect(before.diskPath).toBe(before.finalPath)
+ expect(await fixture.verifyFile(before.finalPath)).toBe(true)
+ await expect
+ .poll(async () =>
+ rpc('tellStatus', [gid]).then(
+ () => false,
+ (error: Error) => /not found/i.test(error.message)
+ )
+ )
+ .toBe(true)
+ await unlink(before.finalPath)
+ await app.close()
+ app = undefined
+ fixture.resetRequests()
+
+ app = await launchMotrix({ userDataDir, rpcPort })
+ page = await app.firstWindow()
+ await page.waitForLoadState('domcontentloaded')
+ await waitForEngineReady(page)
+ await expect
+ .poll(
+ async () =>
+ (await readTasks(page)).find((task) => task.id === before.id)?.status
+ )
+ .toBe('completed')
+ const restored = (await readTasks(page)).find(
+ (task) => task.id === before.id
+ )
+ expect(restored?.finishedAt).toBe(before.finishedAt)
+ expect(restored?.downloadedBytes).toBe(fixture.fileSize)
+ await expect(rpc('tellStatus', [gid])).rejects.toThrow(/not found/i)
+ expect(fixture.requests()).toHaveLength(0)
+ await expect(access(before.finalPath)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+
+ const freshGid = await rpc<string>('addUri', [
+ [fixture.fileUrl],
+ { out: 'independent.bin' },
+ ])
+ expect(freshGid).not.toBe(gid)
+ await expect
+ .poll(
+ async () =>
+ (await readTasks(page)).find((task) => task.engineTaskId === freshGid)
+ ?.status
+ )
+ .toBe('completed')
+ expect(
+ (await readTasks(page)).find((task) => task.id === before.id)?.finishedAt
+ ).toBe(before.finishedAt)
+ expect(
+ await fixture.verifyFile(
+ path.join(userDataDir, 'downloads', 'independent.bin')
+ )
+ ).toBe(true)
+ } finally {
+ await app?.close().catch(() => {})
+ await fixture.close()
+ }
+})
diff --git a/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts b/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts
new file mode 100644
index 00000000..fb8bc72d
--- /dev/null
+++ b/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts
@@ -0,0 +1,198 @@
+// @vitest-environment node
+import { access, mkdtemp, rm, unlink } from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { MotrixDatabase } from '@core/session/motrix-database'
+import { SessionManager } from '@core/session/session-manager'
+import { CompletedEngineTaskCleanup } from '@core/task/completed-engine-task-cleanup'
+import { TaskManager } from '@core/task/task-manager'
+import { TaskStatus } from '@shared/types/task'
+import {
+ type Aria2Handle,
+ bundledAria2Exists,
+ canBindLoopbackTcp,
+ connectAdapter,
+ spawnAria2ForTest,
+} from '@test-utils/aria2'
+import { describe, expect, it, vi } from 'vitest'
+import { CompletedTaskStartupGuard } from './completed-task-startup-guard'
+
+describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
+ 'completed RPC lifecycle with real aria2',
+ () => {
+ it.each([false, true])(
+ 'blocks old completed rows before requests, preserves run intent and accepts fresh work (sqlite=%s)',
+ async (sqlite) => {
+ const root = await mkdtemp(
+ path.join(tmpdir(), 'motrix-completed-real-')
+ )
+ const counts = new Map<string, number>()
+ const server = createServer((req, res) => {
+ const route = req.url ?? '/'
+ counts.set(route, (counts.get(route) ?? 0) + 1)
+ if (route.startsWith('/slow')) {
+ res.writeHead(200, { 'content-length': 1000000 })
+ res.write(Buffer.alloc(128))
+ } else res.end('completed fixture')
+ })
+ let handle: Aria2Handle | undefined
+ let wired!: Awaited<ReturnType<typeof connectAdapter>>
+ let database: MotrixDatabase | undefined
+ try {
+ await new Promise<void>((resolve) =>
+ server.listen(0, '127.0.0.1', resolve)
+ )
+ const address = server.address()
+ if (!address || typeof address === 'string')
+ throw new Error('missing fixture port')
+ const base = `http://127.0.0.1:${address.port}`
+ const session = path.join(root, 'aria2.session')
+ const args = [
+ `--save-session=${session}`,
+ '--force-save=true',
+ '--pause=false',
+ ...(sqlite
+ ? [
+ '--enable-sqlite3-persistence=true',
+ `--sqlite3-db-path=${root}/aria2.db`,
+ ]
+ : []),
+ ]
+ handle = await spawnAria2ForTest({ baseDir: root, extraArgs: args })
+ wired = await connectAdapter(handle)
+ const done = await wired.rpc.addUri([`${base}/done.bin`])
+ await vi.waitFor(
+ async () =>
+ expect((await wired.rpc.tellStatus(done)).status).toBe(
+ 'complete'
+ ),
+ { timeout: 10000 }
+ )
+ const run = await wired.rpc.addUri([`${base}/slow-running.bin`])
+ const paused = await wired.rpc.addUri([`${base}/slow-paused.bin`], {
+ pause: 'true',
+ })
+ await vi.waitFor(
+ async () =>
+ expect((await wired.rpc.tellStatus(run)).status).toBe('active'),
+ { timeout: 10000 }
+ )
+ await wired.rpc.saveSession()
+ wired.disconnect()
+ await handle.kill()
+ await unlink(path.join(root, 'done.bin'))
+ const requestsBefore = counts.get('/done.bin')
+ const restartArgs = sqlite
+ ? args
+ : [...args, `--input-file=${session}`]
+ const guard = new CompletedTaskStartupGuard({
+ completedGids: () => new Set([done]),
+ get rpc() {
+ return wired.rpc
+ },
+ removeResult: (gid) => wired.adapter.removeDownloadResult(gid),
+ })
+ const prepared = await guard.prepare(restartArgs)
+ expect(prepared).not.toBeNull()
+ handle = await spawnAria2ForTest({
+ baseDir: root,
+ extraArgs: prepared!.args,
+ })
+ wired = await connectAdapter(handle)
+ expect((await wired.rpc.tellStatus(done)).status).toBe('paused')
+ await prepared!.reconcile(() => false)
+ await vi.waitFor(
+ async () =>
+ expect((await wired.rpc.tellStatus(run)).status).toBe('active'),
+ { timeout: 10000 }
+ )
+ expect((await wired.rpc.tellStatus(paused)).status).toBe('paused')
+ expect(counts.get('/done.bin')).toBe(requestsBefore)
+ await expect(
+ access(path.join(root, 'done.bin'))
+ ).rejects.toMatchObject({ code: 'ENOENT' })
+
+ const fresh = await wired.rpc.addUri([`${base}/fresh.bin`])
+ await vi.waitFor(
+ async () =>
+ expect((await wired.rpc.tellStatus(fresh)).status).toBe(
+ 'complete'
+ ),
+ { timeout: 10000 }
+ )
+ const taskManager = new TaskManager()
+ database = new MotrixDatabase(path.join(root, 'motrix.db'))
+ database.init()
+ const sessionManager = new SessionManager(
+ taskManager,
+ wired.rpc,
+ database,
+ wired.adapter
+ )
+ const persist = vi.fn(
+ sessionManager.persistTaskWithOccurrence.bind(sessionManager)
+ )
+ const cleanup = new CompletedEngineTaskCleanup({
+ taskManager,
+ adapter: wired.adapter,
+ mintTaskId: () => 'fresh-task',
+ persist,
+ adopt: async (_task, write) => write(),
+ publish: () => {},
+ dispatch: async () => {},
+ runTaskMutation: async (_ids, operation) => operation(),
+ log: { warn: vi.fn() },
+ })
+ await cleanup.observe((await wired.adapter.getTaskStatus(fresh))!)
+ expect(taskManager.getById('fresh-task')?.status).toBe(
+ TaskStatus.Completed
+ )
+ expect(persist).toHaveBeenCalledOnce()
+ expect(database.getTask('fresh-task')).toMatchObject({
+ task: {
+ aggStatus: TaskStatus.Completed,
+ totalBytes: 17,
+ downloadedBytes: 17,
+ },
+ instances: [
+ { gid: fresh, status: TaskStatus.Completed, downloadedBytes: 17 },
+ ],
+ })
+ expect(sessionManager.getCompletedDirectEngineTaskIds()).toEqual(
+ new Set([fresh])
+ )
+ await expect(wired.rpc.tellStatus(fresh)).rejects.toThrow(
+ /not found/i
+ )
+ await cleanup.stopAndDrain()
+ await wired.rpc.saveSession()
+ wired.disconnect()
+ await handle.kill()
+ await unlink(path.join(root, 'fresh.bin'))
+ handle = await spawnAria2ForTest({
+ baseDir: root,
+ extraArgs: restartArgs,
+ })
+ wired = await connectAdapter(handle)
+ await expect(wired.rpc.tellStatus(fresh)).rejects.toThrow(
+ /not found/i
+ )
+ expect(counts.get('/fresh.bin')).toBe(1)
+ await expect(
+ access(path.join(root, 'fresh.bin'))
+ ).rejects.toMatchObject({ code: 'ENOENT' })
+ wired.disconnect()
+ } finally {
+ wired?.disconnect()
+ await handle?.kill()
+ database?.close()
+ server.closeAllConnections()
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ await rm(root, { recursive: true, force: true })
+ }
+ },
+ 45000
+ )
+ }
+)
diff --git a/src/core/engine/aria2/completed-task-startup-guard.test.ts b/src/core/engine/aria2/completed-task-startup-guard.test.ts
new file mode 100644
index 00000000..72953ea3
--- /dev/null
+++ b/src/core/engine/aria2/completed-task-startup-guard.test.ts
@@ -0,0 +1,168 @@
+// @vitest-environment node
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import Database from 'better-sqlite3'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ CompletedTaskStartupGuard,
+ parseSessionRunIntent,
+} from './completed-task-startup-guard'
+
+const DONE = '1111111111111111'
+const RUN = '2222222222222222'
+const PAUSED = '3333333333333333'
+const entry = (gid: string, paused = false) =>
+ `http://127.0.0.1/file\n gid=${gid}\n${paused ? ' pause=true\n' : ''}`
+const folders: string[] = []
+
+async function setup(sqlite = false) {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'completed-startup-'))
+ folders.push(dir)
+ const session = path.join(dir, 'aria2.session')
+ const source = sqlite ? path.join(dir, 'aria2.db') : session
+ const content = entry(DONE) + entry(RUN) + entry(PAUSED, true)
+ if (sqlite) {
+ const db = new Database(source)
+ db.exec(
+ 'CREATE TABLE task(gid TEXT, state TEXT, serialized TEXT, queue_position INTEGER)'
+ )
+ for (const [index, gid] of [DONE, RUN, PAUSED].entries())
+ db.prepare('INSERT INTO task VALUES (?, ?, ?, ?)').run(
+ gid,
+ gid === PAUSED ? 'paused' : 'waiting',
+ entry(gid, gid === PAUSED),
+ index
+ )
+ db.close()
+ } else await writeFile(source, content)
+ const rpc = {
+ tellStatus: vi.fn(async (_gid: string) => ({ status: 'paused' }) as never),
+ forceRemove: vi.fn(async (gid: string) => gid),
+ unpause: vi.fn(async (gid: string) => gid),
+ changeGlobalOption: vi.fn(async () => 'OK' as const),
+ }
+ const removeResult = vi.fn(async (_gid: string) => {})
+ const completedGids = () => new Set([DONE])
+ const guard = new CompletedTaskStartupGuard({
+ completedGids,
+ rpc,
+ removeResult,
+ })
+ const args = [
+ `--save-session=${session}`,
+ '--pause=false',
+ ...(sqlite
+ ? ['--enable-sqlite3-persistence=true', `--sqlite3-db-path=${source}`]
+ : [`--input-file=${source}`]),
+ ]
+ return {
+ source,
+ args,
+ rpc,
+ removeResult,
+ guard,
+ journal: `${session}.completed-recovery.json`,
+ }
+}
+
+afterEach(async () => {
+ await Promise.all(
+ folders.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))
+ )
+})
+
+describe('CompletedTaskStartupGuard', () => {
+ it.each([false, true])(
+ 'purges completed rows before resuming only originally running tasks (sqlite=%s)',
+ async (sqlite) => {
+ const h = await setup(sqlite)
+ const prepared = await h.guard.prepare(h.args)
+ expect(prepared?.args).toContain('--pause=true')
+ expect(prepared?.args).not.toContain('--pause=false')
+ const journal = JSON.parse(await readFile(h.journal, 'utf8'))
+ expect(journal.resume).toEqual([DONE, RUN])
+ await prepared?.reconcile(() => false)
+ expect(h.removeResult).toHaveBeenCalledWith(DONE)
+ expect(h.rpc.unpause).toHaveBeenCalledExactlyOnceWith(RUN)
+ expect(h.removeResult.mock.invocationCallOrder[0]).toBeLessThan(
+ h.rpc.unpause.mock.invocationCallOrder[0]!
+ )
+ await expect(readFile(h.journal)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ }
+ )
+
+ it('does not pause ordinary startup without a matching completed session GID', async () => {
+ const h = await setup()
+ // Unrelated custom input must not be rejected when no barrier is needed.
+ await writeFile(
+ h.source,
+ `${entry(RUN)} pause=false\nhttp://example.test/no-gid\n`
+ )
+ expect(await h.guard.prepare(h.args)).toBeNull()
+ })
+
+ it('preserves original run intent after a crash in a paused startup', async () => {
+ const h = await setup()
+ await h.guard.prepare(h.args)
+ // The interrupted engine saved every temporarily held task as paused.
+ await writeFile(
+ h.source,
+ entry(DONE, true) + entry(RUN, true) + entry(PAUSED, true)
+ )
+ const again = await h.guard.prepare(h.args)
+ await again?.reconcile(() => false)
+ expect(h.rpc.unpause).toHaveBeenCalledExactlyOnceWith(RUN)
+ })
+
+ it('keeps all tasks held and retains recovery intent if purge fails', async () => {
+ const h = await setup()
+ h.removeResult.mockRejectedValue(new Error('database busy'))
+ const prepared = await h.guard.prepare(h.args)
+ await expect(prepared?.reconcile(() => false)).rejects.toThrow(
+ 'database busy'
+ )
+ expect(h.rpc.unpause).not.toHaveBeenCalled()
+ expect(JSON.parse(await readFile(h.journal, 'utf8')).resume).toEqual([
+ DONE,
+ RUN,
+ ])
+ })
+
+ it('does not resume or discard the journal during shutdown', async () => {
+ const h = await setup()
+ const prepared = await h.guard.prepare(h.args)
+ await prepared?.reconcile(() => true)
+ expect(h.rpc.unpause).not.toHaveBeenCalled()
+ expect(await readFile(h.journal, 'utf8')).toContain(RUN)
+ })
+
+ it('fails closed if a pending journal would cross to a different session', async () => {
+ const h = await setup()
+ await h.guard.prepare(h.args)
+ await expect(
+ h.guard.prepare(
+ h.args.map((arg) =>
+ arg.startsWith('--input-file=') ? `${arg}.other` : arg
+ )
+ )
+ ).rejects.toThrow('different engine session')
+ })
+
+ it('rejects an explicit per-task pause=false which would bypass the barrier', () => {
+ expect(() => parseSessionRunIntent(`${entry(DONE)} pause=false\n`)).toThrow(
+ 'pause barrier'
+ )
+ })
+
+ it('rejects missing or duplicate GIDs without logging URL-bearing input', () => {
+ expect(() => parseSessionRunIntent('http://secret.example/file\n')).toThrow(
+ 'Ambiguous engine session identity'
+ )
+ expect(() => parseSessionRunIntent(entry(DONE) + entry(DONE))).toThrow(
+ 'Ambiguous engine session identity'
+ )
+ })
+})
diff --git a/src/core/engine/aria2/completed-task-startup-guard.ts b/src/core/engine/aria2/completed-task-startup-guard.ts
new file mode 100644
index 00000000..8c7ded65
--- /dev/null
+++ b/src/core/engine/aria2/completed-task-startup-guard.ts
@@ -0,0 +1,244 @@
+import { access, readFile, unlink } from 'node:fs/promises'
+import path from 'node:path'
+import Database from 'better-sqlite3'
+import writeFileAtomic from 'write-file-atomic'
+import { z } from 'zod'
+import type { Aria2RpcClient } from './aria2-rpc-client'
+import { isNotFoundError } from './error-utils'
+
+const gidSchema = z.string().regex(/^[0-9a-f]{16}$/)
+const journalSchema = z
+ .object({
+ version: z.literal(1),
+ source: z.string(),
+ resume: z.array(gidSchema),
+ })
+ .strict()
+
+export interface PreparedEngineStartup {
+ args: string[]
+ reconcile: (isStopping: () => boolean) => Promise<void>
+}
+
+export interface EngineStartupGuard {
+ prepare(args: readonly string[]): Promise<PreparedEngineStartup | null>
+}
+
+function argument(args: readonly string[], name: string): string | undefined {
+ return args
+ .findLast((value) => value.startsWith(`--${name}=`))
+ ?.slice(name.length + 3)
+}
+
+function missing(error: unknown): boolean {
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
+}
+
+/** Reads only identity and original run intent; never exports URL/options. */
+export function parseSessionRunIntent(text: string): Map<string, boolean> {
+ const result = new Map<string, boolean>()
+ let inEntry = false
+ let gid: string | undefined
+ let paused = false
+ const finish = () => {
+ if (!inEntry) return
+ if (!gid || result.has(gid))
+ throw new Error(
+ 'Ambiguous engine session identity during completed-task recovery'
+ )
+ result.set(gid, !paused)
+ }
+ for (const line of text.split(/\r?\n/)) {
+ if (!line.trim() || line.trimStart().startsWith('#')) continue
+ if (!/^\s/.test(line)) {
+ finish()
+ inEntry = true
+ gid = undefined
+ paused = false
+ continue
+ }
+ const option = line.trim()
+ if (option.startsWith('gid=')) {
+ const parsed = gidSchema.safeParse(option.slice(4))
+ if (!parsed.success || gid)
+ throw new Error(
+ 'Invalid engine session identity during completed-task recovery'
+ )
+ gid = parsed.data
+ }
+ if (option.startsWith('pause=')) {
+ // An explicit false overrides --pause=true while loading the session.
+ // Our serializer omits false. Fail closed for unsupported custom input.
+ if (option !== 'pause=true')
+ throw new Error('Engine session overrides the startup pause barrier')
+ paused = true
+ }
+ }
+ finish()
+ return result
+}
+
+async function readRunIntent(
+ source: string,
+ sqlite: boolean,
+ needsGuard: (gids: readonly string[]) => boolean
+): Promise<Map<string, boolean>> {
+ if (!sqlite) {
+ try {
+ const text = await readFile(source, 'utf8')
+ const gids = [...text.matchAll(/^\s+gid=([0-9a-f]{16})\s*$/gm)].map(
+ (match) => match[1]
+ )
+ return needsGuard(gids) ? parseSessionRunIntent(text) : new Map()
+ } catch (error) {
+ if (missing(error)) return new Map()
+ throw error
+ }
+ }
+ // The supervisor has already checked that its managed RPC port is unused.
+ // Read through SQLite (including WAL), never edit another engine's tables.
+ try {
+ await access(source)
+ } catch (error) {
+ if (missing(error)) return new Map()
+ throw error
+ }
+ const db = new Database(source, { readonly: true, fileMustExist: true })
+ try {
+ if (
+ !db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='task'"
+ )
+ .get()
+ )
+ return new Map()
+ const rows = db
+ .prepare(
+ 'SELECT gid, state, serialized FROM task ORDER BY queue_position'
+ )
+ .all() as Array<{ gid: string; state: string; serialized: string }>
+ if (!needsGuard(rows.map((row) => row.gid))) return new Map()
+ const result = new Map<string, boolean>()
+ for (const row of rows) {
+ const parsed = parseSessionRunIntent(row.serialized)
+ if (
+ parsed.size !== 1 ||
+ !parsed.has(row.gid) ||
+ !['waiting', 'paused'].includes(row.state) ||
+ result.has(row.gid)
+ ) {
+ throw new Error('Unsupported persisted engine run intent')
+ }
+ result.set(
+ row.gid,
+ row.state !== 'paused' && parsed.get(row.gid) === true
+ )
+ }
+ return result
+ } finally {
+ db.close()
+ }
+}
+
+/**
+ * A targeted startup barrier for durable completed GIDs. Other downloads keep
+ * the engine's original run intent, including engine-only and paused tasks.
+ * A small durable journal preserves that intent if a paused boot is interrupted.
+ */
+export class CompletedTaskStartupGuard implements EngineStartupGuard {
+ constructor(
+ private readonly deps: {
+ completedGids: () => ReadonlySet<string>
+ rpc: Pick<
+ Aria2RpcClient,
+ 'tellStatus' | 'forceRemove' | 'unpause' | 'changeGlobalOption'
+ >
+ removeResult: (gid: string) => Promise<void>
+ }
+ ) {}
+
+ async prepare(
+ args: readonly string[]
+ ): Promise<PreparedEngineStartup | null> {
+ const sessionPath = argument(args, 'save-session')
+ if (!sessionPath) return null
+ const sqlite = argument(args, 'enable-sqlite3-persistence') === 'true'
+ const sourcePath = sqlite
+ ? argument(args, 'sqlite3-db-path')
+ : argument(args, 'input-file')
+ if (!sourcePath) return null
+ const source = path.resolve(sourcePath)
+ const journalPath = `${sessionPath}.completed-recovery.json`
+ let previous: z.infer<typeof journalSchema> | null = null
+ try {
+ previous = journalSchema.parse(
+ JSON.parse(await readFile(journalPath, 'utf8'))
+ )
+ if (previous.source !== source)
+ throw new Error(
+ 'Completed-task recovery journal belongs to a different engine session'
+ )
+ } catch (error) {
+ if (!missing(error)) throw error
+ }
+ const completed = this.deps.completedGids()
+ if (!previous && completed.size === 0) return null
+ const intent = await readRunIntent(
+ source,
+ sqlite,
+ (gids) => previous !== null || gids.some((gid) => completed.has(gid))
+ )
+ const targets = [...intent.keys()].filter((gid) => completed.has(gid))
+ if (!previous && targets.length === 0) return null
+ const resume = previous
+ ? previous.resume.filter((gid) => intent.has(gid))
+ : [...intent].filter(([, run]) => run).map(([gid]) => gid)
+ await writeFileAtomic(
+ journalPath,
+ JSON.stringify({ version: 1, source, resume }),
+ { mode: 0o600 }
+ )
+
+ return {
+ args: [
+ ...args.filter((value) => !value.startsWith('--pause=')),
+ '--pause=true',
+ ],
+ reconcile: async (isStopping) => {
+ for (const gid of targets) {
+ if (isStopping()) return
+ let state: string | undefined
+ try {
+ state = (await this.deps.rpc.tellStatus(gid)).status
+ } catch (error) {
+ if (!isNotFoundError(error)) throw error
+ }
+ if (state && !['complete', 'error', 'removed'].includes(state)) {
+ try {
+ await this.deps.rpc.forceRemove(gid)
+ } catch (error) {
+ if (!isNotFoundError(error)) throw error
+ }
+ }
+ await this.deps.removeResult(gid)
+ }
+ // Do not release any remaining task if even one required purge failed.
+ if (isStopping()) return
+ await this.deps.rpc.changeGlobalOption({ pause: 'false' })
+ const completedNow = this.deps.completedGids()
+ for (const gid of resume) {
+ if (isStopping()) return
+ if (completedNow.has(gid)) continue
+ try {
+ if ((await this.deps.rpc.tellStatus(gid)).status === 'paused')
+ await this.deps.rpc.unpause(gid)
+ } catch (error) {
+ if (!isNotFoundError(error)) throw error
+ }
+ }
+ if (!isStopping()) await unlink(journalPath)
+ },
+ }
+ }
+}
diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.ts
index 97f2e638..0ddec8de 100644
--- a/src/core/engine/engine-supervisor.test.ts
+++ b/src/core/engine/engine-supervisor.test.ts
@@ -219,6 +219,45 @@ describe('EngineSupervisor', () => {
})
describe('start — happy path', () => {
+ it('prepares the startup guard before spawning and reconciles before Ready', async () => {
+ const reconcile = vi.fn(async () => {
+ expect(rpcClient.connect).toHaveBeenCalledOnce()
+ expect(supervisor.getState()).not.toBe(EngineState.Ready)
+ })
+ const prepare = vi.fn(async () => {
+ expect(processManager.spawn).not.toHaveBeenCalled()
+ return { args: ['--pause=true'], reconcile }
+ })
+ supervisor.setStartupGuard({ prepare })
+ await supervisor.start('/usr/bin/aria2c')
+ expect(processManager.spawn).toHaveBeenCalledWith(
+ '/usr/bin/aria2c',
+ ['--pause=true'],
+ undefined
+ )
+ expect(reconcile).toHaveBeenCalledOnce()
+ expect(supervisor.getState()).toBe(EngineState.Ready)
+ })
+
+ it('does not publish Ready when mandatory completed-task cleanup fails', async () => {
+ const ready = vi.fn()
+ eventBus.on(Events.EngineStateChanged, (state) => {
+ if (state === EngineState.Ready) ready()
+ })
+ supervisor.setStartupGuard({
+ prepare: async () => ({
+ args: ['--pause=true'],
+ reconcile: async () => {
+ throw new Error('completed task purge failed')
+ },
+ }),
+ })
+ await supervisor.start('/usr/bin/aria2c')
+ expect(ready).not.toHaveBeenCalled()
+ expect(supervisor.getState()).toBe(EngineState.Failed)
+ expect(supervisor.getLastError()).toContain('completed task purge failed')
+ })
+
it('runs startup maintenance after RPC connect and before publishing Ready', async () => {
const readyObserved = vi.fn()
eventBus.on(Events.EngineStateChanged, (state) => {
diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.ts
index 7789dbd6..4a82968d 100644
--- a/src/core/engine/engine-supervisor.ts
+++ b/src/core/engine/engine-supervisor.ts
@@ -36,6 +36,7 @@ import type { Aria2RpcClient } from './aria2/aria2-rpc-client'
import { isSqliteCorruptionDiagnostic } from './aria2/aria2-sqlite-recovery'
import type { Aria2TrustStore } from './aria2/aria2-trust-store'
import { recommend } from './aria2/aria2-tuning'
+import type { EngineStartupGuard } from './aria2/completed-task-startup-guard'
import {
isMotrixFork,
STANDARD_ARIA2_CONNECTION_LIMIT,
@@ -110,6 +111,7 @@ export class EngineSupervisor {
private sqliteFallbackAttempted = false
private restartPromise: Promise<void> | null = null
private preReadyMaintenance: (() => Promise<void>) | null = null
+ private startupGuard: EngineStartupGuard | null = null
constructor(
private eventBus: EventBus,
@@ -195,6 +197,11 @@ export class EngineSupervisor {
this.getEffectiveLimits = fn
}
+ /** Required reconciliation runs under a paused startup, before Ready. */
+ setStartupGuard(guard: EngineStartupGuard): void {
+ this.startupGuard = guard
+ }
+
/** Register best-effort engine maintenance that runs after RPC connects but before Ready. */
setPreReadyMaintenance(maintenance: () => Promise<void>): void {
this.preReadyMaintenance = maintenance
@@ -522,7 +529,11 @@ export class EngineSupervisor {
// Step 4: Spawn process (abort if stop() was called during earlier awaits)
if (this.stopping) return
phase = 'spawn'
- await this.processManager.spawn(this.binaryPath, args, processEnv)
+ const guardedStartup = await this.startupGuard?.prepare(args)
+ if (this.stopping) return
+ const startArgs = guardedStartup?.args ?? args
+ this.lastStartArgs = startArgs
+ await this.processManager.spawn(this.binaryPath, startArgs, processEnv)
// Step 5: Connect RPC
if (this.stopping) {
@@ -536,6 +547,14 @@ export class EngineSupervisor {
await this.processManager.gracefulStop()
return
}
+ // Unlike best-effort maintenance, failure here must stop the paused
+ // process. Otherwise a known completed GID can recreate deleted files.
+ await guardedStartup?.reconcile(() => this.stopping)
+ if (this.stopping) {
+ this.rpcClient.disconnect()
+ await this.processManager.gracefulStop()
+ return
+ }
if (this.preReadyMaintenance) {
try {
await this.preReadyMaintenance()
diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.ts
index ca46db4c..b404c5a3 100644
--- a/src/core/session/session-manager.test.ts
+++ b/src/core/session/session-manager.test.ts
@@ -22,6 +22,7 @@ import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'
import { clearStoppedTasks } from '../task/actions/clear-stopped-tasks'
import { stopSeedingTask } from '../task/actions/stop-seeding-task'
import { TaskManager } from '../task/task-manager'
+import { computeUriHash } from './content-key'
import type {
MotrixDatabase,
TaskFileRow,
@@ -3794,6 +3795,92 @@ describe('restore() with task_instances (Plan A Task 7)', () => {
expect(adapter.createDownload).not.toHaveBeenCalled()
})
+ it.each(['active', 'waiting', 'paused', 'complete', 'error'] as const)(
+ 'preserves completed RPC history instead of merging a resurrected %s GID',
+ async (status) => {
+ const taskManager = new TaskManager()
+ const db = createMockDb()
+ const raw = createRawStatus({ status })
+ const rpc = createMockRpc({ activeTasks: [raw] })
+ const adapter = createMockAdapter()
+ seedAsPair(db, {
+ motrixId: 'done-rpc',
+ gid: raw.gid,
+ status: TaskStatus.Completed,
+ diskPath: '/tmp/test-file.zip',
+ finalPath: '/tmp/test-file.zip',
+ finishedAt: 4242,
+ totalBytes: 1000,
+ downloadedBytes: 1000,
+ })
+ await new SessionManager(taskManager, rpc, db, adapter).restore()
+ expect(taskManager.getById('done-rpc')).toMatchObject({
+ status: TaskStatus.Completed,
+ finishedAt: 4242,
+ downloadedBytes: 1000,
+ })
+ expect(adapter.removeDownloadResult).toHaveBeenCalledWith(raw.gid)
+ expect(adapter.forceRemoveTask).toHaveBeenCalledTimes(
+ status === 'complete' || status === 'error' ? 0 : 1
+ )
+ expect(adapter.createDownload).not.toHaveBeenCalled()
+ expect(db.persistTaskWithOccurrence).not.toHaveBeenCalled()
+ }
+ )
+
+ it('keeps a new GID with the same URI independent of completed RPC history', async () => {
+ const taskManager = new TaskManager()
+ const db = createMockDb()
+ const raw = createRawStatus({ gid: 'new-independent-gid' })
+ const rpc = createMockRpc({ activeTasks: [raw] })
+ const adapter = createMockAdapter()
+ const uris = ['http://example.com/file.zip']
+ seedAsPair(db, {
+ motrixId: 'done-rpc',
+ gid: 'old-gid',
+ status: TaskStatus.Completed,
+ diskPath: '/tmp/test-file.zip',
+ finalPath: '/tmp/test-file.zip',
+ uris,
+ uriHash: computeUriHash(uris),
+ finishedAt: 4242,
+ })
+ await new SessionManager(taskManager, rpc, db, adapter).restore()
+ expect(taskManager.getById('done-rpc')).toMatchObject({
+ engineTaskId: 'old-gid',
+ status: TaskStatus.Completed,
+ finishedAt: 4242,
+ })
+ expect(taskManager.getByEngineTaskId(raw.gid)).toMatchObject({
+ status: TaskStatus.Downloading,
+ })
+ expect(taskManager.getByEngineTaskId(raw.gid)?.id).not.toBe('done-rpc')
+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()
+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()
+ })
+
+ it('durably adopts a task completed before startup listeners attached, then schedules cleanup', async () => {
+ const taskManager = new TaskManager()
+ const db = createMockDb()
+ const raw = createRawStatus({ status: 'complete', completedLength: '1000' })
+ const rpc = createMockRpc()
+ vi.mocked(rpc.tellStopped).mockResolvedValue([raw])
+ const adapter = createMockAdapter()
+ const observer = vi.fn(async (snapshot: DownloadTask) => {
+ const task = taskManager.getByEngineTaskId(snapshot.engineTaskId)!
+ expect(db.getTask(task.id)?.task.aggStatus).toBe(TaskStatus.Completed)
+ expect(db.persistTaskWithOccurrence).toHaveBeenCalledOnce()
+ })
+ await new SessionManager(taskManager, rpc, db, adapter).restore(
+ undefined,
+ observer
+ )
+ expect(observer).toHaveBeenCalledOnce()
+ expect(taskManager.getByEngineTaskId(raw.gid)?.status).toBe(
+ TaskStatus.Completed
+ )
+ })
+
it.each(Object.values(TaskType))(
'save/restore retains terminal metadata and canonical type %s',
async (taskType) => {
diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.ts
index 34b7efc0..e5feda4e 100644
--- a/src/core/session/session-manager.ts
+++ b/src/core/session/session-manager.ts
@@ -48,6 +48,7 @@ import {
terminalFieldsFromRow,
} from '../task/apply-terminal-transition'
import { shouldPrioritizeBtPreviewPiecesFromMetadata } from '../task/bt-storage-layout'
+import { isCompletedDirectOutput } from '../task/completed-direct-task-policy'
import {
canMirrorAria2MetadataHeaders,
type DirectResourceProxyOptionsProvider,
@@ -598,7 +599,21 @@ export class SessionManager {
return { task: taskRow, instances }
}
- async restore(assertProxyCurrent?: () => void): Promise<void> {
+ getCompletedDirectEngineTaskIds(): ReadonlySet<string> {
+ const result = new Set<string>()
+ for (const pair of this.db.getAllTasks()) {
+ if (pair.task.aggStatus !== TaskStatus.Completed) continue
+ const task = taskRowToDownloadTask(pair.task, pair.instances)
+ if (isCompletedDirectOutput(task) && task.engineTaskId)
+ result.add(task.engineTaskId)
+ }
+ return result
+ }
+
+ async restore(
+ assertProxyCurrent?: () => void,
+ observeCompletedTask?: (snapshot: DownloadTask) => Promise<unknown>
+ ): Promise<void> {
// aria2 is the source of truth for engine lifecycle. motrix.db is a
// metadata sidecar tracking task identity and the relationship between
// a task and its instances. The loop is driven by aria2: every live
@@ -682,6 +697,13 @@ export class SessionManager {
// lets N evictions overlap each other and the later passes instead of
// serializing 2×N RPC round-trips inline.
const evictions: Promise<void>[] = []
+ const retireCompleted = (raw: Aria2RawStatus): Promise<void> =>
+ observeCompletedTask
+ ? observeCompletedTask(translateRawToTask(raw)).then(() => {})
+ : this.evictEngineRow(
+ raw,
+ 'restore: failed to evict completed direct task'
+ )
// Pass 1 — drive from aria2 rows.
for (const aria2 of aria2Tasks) {
@@ -743,7 +765,17 @@ export class SessionManager {
hit.instance.gid !== null &&
hit.instance.gid !== aria2.gid &&
aria2GidSet.has(hit.instance.gid)
- if (!consumedMotrixIds.has(hit.motrixId) && !hasDifferentLiveGid) {
+ const candidate = byMotrixId.get(hit.motrixId)
+ const completedDirect =
+ candidate &&
+ isCompletedDirectOutput(
+ taskRowToDownloadTask(candidate.task, candidate.instances)
+ )
+ if (
+ !completedDirect &&
+ !consumedMotrixIds.has(hit.motrixId) &&
+ !hasDifferentLiveGid
+ ) {
parent = byMotrixId.get(hit.motrixId)
matchedInstance = hit.instance
}
@@ -781,6 +813,17 @@ export class SessionManager {
}
continue
}
+ // Completed direct output is durable history. Only exact GID ownership
+ // authorizes retiring an engine row; URI matches can be a new download.
+ if (direct) {
+ const completed = taskRowToDownloadTask(parent.task, parent.instances)
+ if (isCompletedDirectOutput(completed)) {
+ this.taskManager.set(completed.id, completed)
+ consumedMotrixIds.add(parent.task.motrixId)
+ evictions.push(retireCompleted(aria2))
+ continue
+ }
+ }
const task = this.mergeTaskFromPair(parent, matchedInstance, aria2)
// Merging a persisted non-terminal task with aria2's stopped row can
// settle it into Completed/Error. That is a real terminal transition
@@ -799,9 +842,28 @@ export class SessionManager {
}
this.taskManager.set(task.id, task)
consumedMotrixIds.add(parent.task.motrixId)
+ if (isCompletedDirectOutput(task)) {
+ evictions.push(retireCompleted(aria2))
+ }
} else {
const task = this.adoptTask(aria2)
+ // A tiny engine-only download can finish before Ready and before the
+ // notification listeners attach. Commit its history/outbox now; a
+ // stopped GID will not appear in subsequent active/waiting polls.
+ if (isCompletedDirectOutput(task)) {
+ await this.persistRecoveredTerminalOccurrence(
+ task,
+ buildTerminalOccurrence(
+ terminalSnapshotFromTask(task),
+ TaskStatus.Queued,
+ 'engine'
+ )
+ )
+ }
this.taskManager.set(task.id, task)
+ if (isCompletedDirectOutput(task)) {
+ evictions.push(retireCompleted(aria2))
+ }
}
}
diff --git a/src/core/task/completed-direct-task-policy.ts b/src/core/task/completed-direct-task-policy.ts
new file mode 100644
index 00000000..75608b45
--- /dev/null
+++ b/src/core/task/completed-direct-task-policy.ts
@@ -0,0 +1,30 @@
+import {
+ type DownloadTask,
+ TaskInstancePhase,
+ TaskKind,
+ TaskStatus,
+ TaskType,
+ TransitionPhase,
+} from '@shared/types/task'
+
+/** Final-path RPC downloads need no rename, but still need durable retirement. */
+export function isDirectFinalOutput(task: DownloadTask): boolean {
+ return (
+ task.kind === TaskKind.Direct &&
+ (task.type === TaskType.Http || task.type === TaskType.Ftp) &&
+ task.diskPath.length > 0 &&
+ task.diskPath === task.finalPath &&
+ task.transitionPhase === TransitionPhase.Idle &&
+ task.status !== TaskStatus.Finalizing &&
+ task.instances.every(
+ (instance) =>
+ instance.phase === TaskInstancePhase.HttpDownload &&
+ (instance.gid === null || instance.gid === task.engineTaskId) &&
+ instance.transitionPhase === TransitionPhase.Idle
+ )
+ )
+}
+
+export function isCompletedDirectOutput(task: DownloadTask): boolean {
+ return task.status === TaskStatus.Completed && isDirectFinalOutput(task)
+}
diff --git a/src/core/task/completed-engine-task-cleanup.test.ts b/src/core/task/completed-engine-task-cleanup.test.ts
new file mode 100644
index 00000000..49e7747b
--- /dev/null
+++ b/src/core/task/completed-engine-task-cleanup.test.ts
@@ -0,0 +1,211 @@
+import {
+ TaskKind,
+ TaskStatus,
+ TaskType,
+ TransitionPhase,
+} from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { CompletedEngineTaskCleanup } from './completed-engine-task-cleanup'
+import { TaskManager } from './task-manager'
+
+const output = (overrides = {}) =>
+ makeDownloadTask({
+ diskPath: '/downloads/file.zip',
+ finalPath: '/downloads/file.zip',
+ status: TaskStatus.Completed,
+ finishedAt: 1234,
+ totalBytes: 100,
+ downloadedBytes: 100,
+ ...overrides,
+ })
+
+function harness(initial = true) {
+ const taskManager = new TaskManager()
+ if (initial)
+ taskManager.set(
+ 'task-1',
+ output({ status: TaskStatus.Downloading, finishedAt: null })
+ )
+ const order: string[] = []
+ const deps = {
+ taskManager,
+ mintTaskId: () => 'adopted-task',
+ persist: vi.fn(async () => {
+ order.push('persist')
+ }),
+ adopt: vi.fn(async (_task: unknown, persist: () => Promise<void>) => {
+ await persist()
+ }),
+ publish: vi.fn(() => {
+ order.push('publish')
+ }),
+ dispatch: vi.fn(async () => {
+ order.push('dispatch')
+ }),
+ prepareFiles: vi.fn(async () => {
+ order.push('files')
+ }),
+ adapter: {
+ forceRemoveTask: vi.fn(async () => {
+ order.push('stop')
+ }),
+ removeDownloadResult: vi.fn(async () => {
+ order.push('purge')
+ }),
+ },
+ runTaskMutation: async <T>(_ids: readonly string[], fn: () => Promise<T>) =>
+ fn(),
+ log: { warn: vi.fn() },
+ }
+ return { ...deps, order, cleanup: new CompletedEngineTaskCleanup(deps) }
+}
+
+afterEach(() => vi.useRealTimers())
+
+describe('CompletedEngineTaskCleanup', () => {
+ it('persists final-path completion and files before purging the engine', async () => {
+ const h = harness()
+ expect(await h.cleanup.observe(output())).toBe(true)
+ expect(h.order).toEqual([
+ 'persist',
+ 'publish',
+ 'dispatch',
+ 'files',
+ 'purge',
+ ])
+ expect(h.persist).toHaveBeenCalledWith(
+ expect.objectContaining({ status: TaskStatus.Completed, progress: 1 }),
+ expect.objectContaining({ toStatus: TaskStatus.Completed })
+ )
+ expect(h.taskManager.getById('task-1')?.finishedAt).toBe(1234)
+ await h.cleanup.stopAndDrain()
+ })
+
+ it('adopts a tiny download first observed complete before cleaning it', async () => {
+ const h = harness(false)
+ await h.cleanup.observe(output())
+ expect(h.adopt).toHaveBeenCalledOnce()
+ expect(h.taskManager.getById('adopted-task')?.status).toBe(
+ TaskStatus.Completed
+ )
+ expect(h.adapter.removeDownloadResult).toHaveBeenCalledWith('gid-1')
+ await h.cleanup.stopAndDrain()
+ })
+
+ it('retries a failed durable completion without another engine notification', async () => {
+ vi.useFakeTimers()
+ const h = harness()
+ h.persist.mockRejectedValueOnce(new Error('database busy'))
+ await h.cleanup.observe(output())
+ expect(h.taskManager.getById('task-1')?.status).toBe(TaskStatus.Downloading)
+ expect(h.taskManager.getById('task-1')?.instances[0]?.status).not.toBe(
+ TaskStatus.Completed
+ )
+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.taskManager.getById('task-1')?.status).toBe(TaskStatus.Completed)
+ expect(h.adapter.removeDownloadResult).toHaveBeenCalledOnce()
+ await h.cleanup.stopAndDrain()
+ })
+
+ it('coalesces concurrent completion snapshots while persistence is pending', async () => {
+ const h = harness(false)
+ let release!: () => void
+ h.persist.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve
+ })
+ )
+ const first = h.cleanup.observe(output())
+ const second = h.cleanup.observe(output({ finishedAt: 9999 }))
+ release()
+ await Promise.all([first, second])
+ expect(h.persist).toHaveBeenCalledOnce()
+ expect(h.adopt).toHaveBeenCalledOnce()
+ expect(h.dispatch).toHaveBeenCalledOnce()
+ expect(h.adapter.removeDownloadResult).toHaveBeenCalledOnce()
+ expect(h.taskManager.getById('adopted-task')?.finishedAt).toBe(1234)
+ await h.cleanup.stopAndDrain()
+ })
+
+ it('retries failed cleanup without changing the completion or notifying twice', async () => {
+ vi.useFakeTimers()
+ const h = harness()
+ h.adapter.removeDownloadResult.mockRejectedValueOnce(
+ new Error('RPC offline')
+ )
+ await h.cleanup.observe(output())
+ await vi.advanceTimersByTimeAsync(1000)
+ await h.cleanup.observe(output({ finishedAt: 9999 }))
+ expect(h.adapter.removeDownloadResult).toHaveBeenCalledTimes(2)
+ expect(h.persist).toHaveBeenCalledOnce()
+ expect(h.dispatch).toHaveBeenCalledOnce()
+ expect(h.taskManager.getById('task-1')?.finishedAt).toBe(1234)
+ await h.cleanup.stopAndDrain()
+ })
+
+ it('stops a resurrected exact GID while preserving completed history', async () => {
+ const h = harness()
+ h.taskManager.set('task-1', output())
+ await h.cleanup.observe(
+ output({
+ status: TaskStatus.Downloading,
+ finishedAt: null,
+ downloadedBytes: 1,
+ })
+ )
+ expect(h.order).toEqual(['files', 'stop', 'purge'])
+ expect(h.taskManager.getById('task-1')?.downloadedBytes).toBe(100)
+ expect(h.persist).not.toHaveBeenCalled()
+ expect(h.dispatch).not.toHaveBeenCalled()
+ await h.cleanup.stopAndDrain()
+ })
+
+ it('does not purge a replacement task after a failed cleanup', async () => {
+ vi.useFakeTimers()
+ const h = harness()
+ h.adapter.removeDownloadResult.mockRejectedValueOnce(new Error('busy'))
+ await h.cleanup.observe(output())
+ h.taskManager.set(
+ 'task-1',
+ output({ engineTaskId: 'new-gid', status: TaskStatus.Downloading })
+ )
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.adapter.removeDownloadResult).toHaveBeenCalledTimes(1)
+ await h.cleanup.stopAndDrain()
+ })
+
+ it.each([
+ { diskPath: '/downloads/file.zip.motrix' },
+ { transitionPhase: TransitionPhase.Renaming },
+ { kind: TaskKind.Hls },
+ { type: TaskType.Bt },
+ { type: TaskType.Magnet },
+ { diskPath: '', finalPath: '' },
+ ])(
+ 'leaves application-owned finalization and other workflows alone: %o',
+ async (overrides) => {
+ const h = harness()
+ h.taskManager.set(
+ 'task-1',
+ output({ status: TaskStatus.Downloading, ...overrides })
+ )
+ expect(await h.cleanup.observe(output(overrides))).toBe(false)
+ expect(h.persist).not.toHaveBeenCalled()
+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()
+ await h.cleanup.stopAndDrain()
+ }
+ )
+
+ it('cancels scheduled retries when stopping', async () => {
+ vi.useFakeTimers()
+ const h = harness()
+ h.persist.mockRejectedValue(new Error('busy'))
+ await h.cleanup.observe(output())
+ await h.cleanup.stopAndDrain()
+ await vi.advanceTimersByTimeAsync(60000)
+ expect(h.persist).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/core/task/completed-engine-task-cleanup.ts b/src/core/task/completed-engine-task-cleanup.ts
new file mode 100644
index 00000000..d821bf3f
--- /dev/null
+++ b/src/core/task/completed-engine-task-cleanup.ts
@@ -0,0 +1,248 @@
+import type { EngineAdapter } from '@core/engine/engine-adapter'
+import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import type { TaskOccurrence } from '@shared/types/task-occurrence'
+import {
+ buildTerminalOccurrence,
+ terminalSnapshotFromTask,
+} from './actions/shared'
+import {
+ isCompletedDirectOutput,
+ isDirectFinalOutput,
+} from './completed-direct-task-policy'
+import { mergeEngineTask } from './merge-engine-task'
+import { syncTerminalInstanceStatus } from './task-instance'
+import type { TaskManager } from './task-manager'
+
+interface CleanupDeps {
+ taskManager: Pick<
+ TaskManager,
+ 'getById' | 'getByEngineTaskId' | 'set' | 'isEngineTaskIdRetired'
+ >
+ adapter: Pick<EngineAdapter, 'forceRemoveTask' | 'removeDownloadResult'>
+ mintTaskId: () => string
+ persist: (
+ task: DownloadTask,
+ occurrence: TaskOccurrence | null
+ ) => Promise<void>
+ adopt: (task: DownloadTask, persist: () => Promise<void>) => Promise<void>
+ publish: () => void
+ dispatch: (occurrence: TaskOccurrence) => Promise<void>
+ prepareFiles?: (task: DownloadTask) => Promise<void>
+ runTaskMutation: <T>(
+ ids: readonly string[],
+ operation: () => Promise<T>
+ ) => Promise<T>
+ log: { warn(context: Record<string, unknown>, message: string): void }
+}
+
+interface PendingCompletion {
+ snapshot: DownloadTask
+ ownerId: string
+ adopted: boolean
+ attempts: number
+ retryAt: number
+}
+
+function completeMetrics(task: DownloadTask): void {
+ task.totalBytes = Math.max(task.totalBytes, task.downloadedBytes)
+ task.downloadedBytes = task.totalBytes
+ task.sizeWhenDone = task.totalBytes
+ task.progress = 1
+ syncTerminalInstanceStatus(task, TaskStatus.Completed)
+ for (const instance of task.instances) {
+ instance.totalBytes = task.totalBytes
+ instance.downloadedBytes = task.downloadedBytes
+ instance.progress = 100
+ }
+}
+
+/**
+ * Owns final-path completion from a notified snapshot through durable history
+ * and engine cleanup. Failed terminal snapshots are retained for targeted
+ * retries: active/waiting polling cannot rediscover an already stopped GID.
+ * Persisted Completed rows remain the crash-recovery source of truth.
+ */
+export class CompletedEngineTaskCleanup {
+ private readonly pending = new Map<string, PendingCompletion>()
+ private readonly inFlight = new Map<string, Promise<void>>()
+ private readonly cleaned = new Map<string, string>()
+ private timer: ReturnType<typeof setTimeout> | null = null
+ private stopped = false
+
+ constructor(private readonly deps: CleanupDeps) {}
+
+ async observe(snapshot: DownloadTask): Promise<boolean> {
+ const gid = snapshot.engineTaskId
+ const owner = this.deps.taskManager.getByEngineTaskId(gid)
+ if (!gid || !isDirectFinalOutput(owner ?? snapshot)) return false
+ if (
+ !isCompletedDirectOutput(owner ?? snapshot) &&
+ snapshot.status !== TaskStatus.Completed
+ )
+ return false
+ // Other terminal outcomes and recovery quarantines retain their owners.
+ if (
+ owner?.status === TaskStatus.Error ||
+ owner?.status === TaskStatus.Removed
+ )
+ return false
+ if (this.stopped || this.deps.taskManager.isEngineTaskIdRetired(gid))
+ return true
+
+ const completionKey = owner ? `${owner.id}:${owner.finishedAt}` : ''
+ if (
+ snapshot.status === TaskStatus.Completed &&
+ completionKey &&
+ this.cleaned.get(gid) === completionKey
+ )
+ return true
+ const previous = this.pending.get(gid)
+ this.pending.set(gid, {
+ snapshot: structuredClone(snapshot),
+ ownerId: owner?.id ?? previous?.ownerId ?? this.deps.mintTaskId(),
+ adopted: owner !== undefined || previous?.adopted === true,
+ attempts: previous?.attempts ?? 0,
+ retryAt: 0,
+ })
+ await this.run(gid)
+ return true
+ }
+
+ async stopAndDrain(): Promise<void> {
+ this.stopped = true
+ if (this.timer !== null) clearTimeout(this.timer)
+ this.timer = null
+ await Promise.allSettled([...this.inFlight.values()])
+ this.pending.clear()
+ }
+
+ private run(gid: string): Promise<void> {
+ const existing = this.inFlight.get(gid)
+ if (existing) return existing
+ const operation = this.processPending(gid).finally(() => {
+ this.inFlight.delete(gid)
+ this.scheduleRetry()
+ })
+ this.inFlight.set(gid, operation)
+ return operation
+ }
+
+ private async processPending(gid: string): Promise<void> {
+ while (!this.stopped) {
+ const pending = this.pending.get(gid)
+ if (!pending) return
+ try {
+ await this.complete(gid, pending)
+ if (this.pending.get(gid) === pending) this.pending.delete(gid)
+ } catch (err) {
+ pending.attempts++
+ pending.retryAt =
+ Date.now() +
+ Math.min(1000 * 2 ** Math.min(pending.attempts - 1, 5), 30000)
+ this.deps.log.warn(
+ { err, gid, taskId: pending.ownerId },
+ 'completed engine task cleanup deferred'
+ )
+ return
+ }
+ }
+ }
+
+ private async complete(
+ gid: string,
+ pending: PendingCompletion
+ ): Promise<void> {
+ if (this.deps.taskManager.isEngineTaskIdRetired(gid)) return
+ if (!pending.adopted) {
+ const existing = this.deps.taskManager.getByEngineTaskId(gid)
+ if (existing) {
+ pending.ownerId = existing.id
+ pending.adopted = true
+ } else {
+ const task = structuredClone(pending.snapshot)
+ task.id = pending.ownerId
+ for (const instance of task.instances) instance.motrixId = task.id
+ completeMetrics(task)
+ const occurrence = buildTerminalOccurrence(
+ terminalSnapshotFromTask(task),
+ TaskStatus.Queued,
+ 'engine'
+ )
+ await this.deps.adopt(task, () => this.deps.persist(task, occurrence))
+ this.deps.taskManager.set(task.id, task)
+ pending.adopted = true
+ this.deps.publish()
+ if (occurrence) await this.deps.dispatch(occurrence)
+ }
+ }
+
+ await this.deps.runTaskMutation([pending.ownerId], async () => {
+ const current = this.deps.taskManager.getById(pending.ownerId)
+ if (
+ !current ||
+ current.engineTaskId !== gid ||
+ !isDirectFinalOutput(current)
+ )
+ return
+ if (
+ current.status === TaskStatus.Error ||
+ current.status === TaskStatus.Removed
+ )
+ return
+ let completed = current
+ if (!isCompletedDirectOutput(current)) {
+ if (pending.snapshot.status !== TaskStatus.Completed) return
+ completed = structuredClone(mergeEngineTask(current, pending.snapshot))
+ completeMetrics(completed)
+ const occurrence = buildTerminalOccurrence(
+ terminalSnapshotFromTask(completed),
+ current.status,
+ 'engine'
+ )
+ await this.deps.persist(completed, occurrence)
+ this.deps.taskManager.set(completed.id, completed)
+ this.deps.publish()
+ if (occurrence) await this.deps.dispatch(occurrence)
+ }
+ const key = `${completed.id}:${completed.finishedAt}`
+ if (
+ pending.snapshot.status === TaskStatus.Completed &&
+ this.cleaned.get(gid) === key
+ )
+ return
+ await this.deps.prepareFiles?.(completed)
+ if (
+ ![TaskStatus.Completed, TaskStatus.Error, TaskStatus.Removed].includes(
+ pending.snapshot.status
+ )
+ ) {
+ await this.deps.adapter.forceRemoveTask(gid)
+ }
+ await this.deps.adapter.removeDownloadResult(gid)
+ this.cleaned.set(gid, key)
+ // Cache only avoids redundant RPCs; eviction never weakens durable history.
+ if (this.cleaned.size > 4096) {
+ const oldest = this.cleaned.keys().next().value
+ if (oldest !== undefined) this.cleaned.delete(oldest)
+ }
+ })
+ }
+
+ private scheduleRetry(): void {
+ if (this.stopped || this.timer !== null || this.pending.size === 0) return
+ const waiting = [...this.pending].filter(([gid]) => !this.inFlight.has(gid))
+ if (waiting.length === 0) return
+ const next = Math.min(...waiting.map(([, entry]) => entry.retryAt))
+ this.timer = setTimeout(
+ () => {
+ this.timer = null
+ for (const [gid, entry] of this.pending) {
+ if (entry.retryAt <= Date.now()) void this.run(gid)
+ }
+ this.scheduleRetry()
+ },
+ Math.max(1, next - Date.now())
+ )
+ this.timer.unref?.()
+ }
+}
diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.ts
index 6643d438..5f2849d1 100644
--- a/src/core/task/merge-engine-task.ts
+++ b/src/core/task/merge-engine-task.ts
@@ -1,6 +1,7 @@
import type { DownloadTask } from '@shared/types/task'
import { TransitionPhase } from '@shared/types/task'
import { applyTerminalTransition } from './apply-terminal-transition'
+import { isCompletedDirectOutput } from './completed-direct-task-policy'
import { nonZeroMerge } from './non-zero-merge'
/**
@@ -15,6 +16,14 @@ export function mergeEngineTask(
engineTask: DownloadTask,
now = Date.now()
): DownloadTask {
+ // Engine session replay and delayed notifications cannot reopen durable
+ // direct history. Explicit re-add changes ownership/state before merging.
+ if (
+ existing.engineTaskId === engineTask.engineTaskId &&
+ isCompletedDirectOutput(existing)
+ ) {
+ return existing
+ }
const protected_ = nonZeroMerge(existing, engineTask)
// progress is a derived value, not an independent field. Recomputing
// from the already-protected mirror keeps progress consistent with
diff --git a/src/core/task/should-skip-engine-completion-finalize.ts b/src/core/task/should-skip-engine-completion-finalize.ts
index 293af9ae..ead6af7c 100644
--- a/src/core/task/should-skip-engine-completion-finalize.ts
+++ b/src/core/task/should-skip-engine-completion-finalize.ts
@@ -8,11 +8,9 @@ import { TaskStatus, TransitionPhase } from '@shared/types/task'
* Startup recovery invokes finalize directly after inspecting the filesystem,
* so quarantined/non-idle tasks remain recoverable without event re-entry.
*
- * The poll-vs-notify race where a poll tick commits a task straight to
- * Completed/Error before this notification-driven path observes the same
- * engine-completion event is unreachable today (polling has no tellStopped
- * path). `diskPath === finalPath` already covers an already-terminal,
- * already-renamed task, so no separate terminal-status clause is needed.
+ * A final-path RPC task also passes this guard. Its terminal persistence and
+ * engine retirement belong to CompletedEngineTaskCleanup, independently of
+ * whether this notification needs to initiate a rename.
*/
export function shouldSkipEngineCompletionFinalize(
task: DownloadTask
diff --git a/src/main/index.ts b/src/main/index.ts
index 1992779b..b27090c6 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -8,6 +8,7 @@ import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'
import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'
import { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'
import { Aria2TrustStore } from '@core/engine/aria2/aria2-trust-store'
+import { CompletedTaskStartupGuard } from '@core/engine/aria2/completed-task-startup-guard'
import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'
import { createDnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'
import { JsonRpcProtocol } from '@core/engine/aria2/json-rpc-protocol'
@@ -85,6 +86,7 @@ import {
import { removeTask } from '@core/task/actions/remove-task'
import { commitPolledTerminalTransition } from '@core/task/actions/shared'
import { countActiveDownloads } from '@core/task/active-downloads'
+import { CompletedEngineTaskCleanup } from '@core/task/completed-engine-task-cleanup'
import { handleCreateTask } from '@core/task/create-task-handler'
import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'
import { FileCleanupServiceImpl } from '@core/task/file-cleanup-service'
@@ -419,6 +421,7 @@ let supervisor: EngineSupervisor
let proxyBridge: ProxyBridgeManager
let speedLimitController: SpeedLimitController
let sessionManager: SessionManager
+let completedEngineTaskCleanup: CompletedEngineTaskCleanup
let pollingScheduler: PollingScheduler
let aria2Adapter: Aria2Adapter
// Constructed in Phase 2 below (F4); see that construction site's comment
@@ -504,6 +507,9 @@ function performCleanup(): Promise<void> {
await ingressClose
const cancellationDrain = Promise.all([
safely('polling', () => pollingScheduler?.stopAndDrain()),
+ safely('completed-engine-tasks', () =>
+ completedEngineTaskCleanup?.stopAndDrain()
+ ),
// The bridge owns long-lived HLS/DASH/mux jobs. Closing it cancels media
// work and drains accepted bridge handlers.
safely('bridge', () => bridgeManager?.stop()),
@@ -725,6 +731,7 @@ async function handlePolledTasks(
rawTasks: Aria2RawStatus[],
source: PollingTaskUpdateSource
): Promise<void> {
+ if (supervisor.getState() !== EngineState.Ready) return
let dirty = false
for (const raw of rawTasks) {
if (shouldSkipForPendingMagnetMetadata(raw, magnetTracker)) {
@@ -755,6 +762,10 @@ async function handlePolledTasks(
}
const translated = translateRawToTask(raw)
+ if (await completedEngineTaskCleanup?.observe(translated)) {
+ dirty = true
+ continue
+ }
const existing = taskManager.getByEngineTaskId(raw.gid)
if (existing) {
const merged = mergeEngineTask(existing, translated)
@@ -1213,7 +1224,9 @@ async function startEngineAndRestore(
try {
await appliedDownloadProxyPolicy.runWithSnapshot(
async (_snapshot, lease) => {
- await sessionManager.restore(lease.assertCurrent)
+ await sessionManager.restore(lease.assertCurrent, (snapshot) =>
+ completedEngineTaskCleanup.observe(snapshot)
+ )
await sessionManager.recoverLegacyTaskLost(lease.assertCurrent)
}
)
@@ -1897,6 +1910,28 @@ async function initializeMainProcess(): Promise<void> {
: null
}
)
+ completedEngineTaskCleanup = new CompletedEngineTaskCleanup({
+ taskManager,
+ adapter,
+ mintTaskId: newTaskId,
+ persist: persistTaskWithOccurrence,
+ adopt: (task, persist) =>
+ activeTaskInspectorActivityRuntime.parentTaskCreated(task, persist),
+ publish: publishTaskUpdateNow,
+ dispatch: (occurrence) => occurrenceDispatcher.dispatch(occurrence),
+ prepareFiles: (task) =>
+ syncTaskFilesIfIncomplete(task.id, task.engineTaskId),
+ runTaskMutation: (ids, operation) =>
+ activeTaskInspectorActivityRuntime.runTaskMutation(ids, operation),
+ log,
+ })
+ supervisor.setStartupGuard(
+ new CompletedTaskStartupGuard({
+ completedGids: () => sessionManager.getCompletedDirectEngineTaskIds(),
+ rpc: rpcClient,
+ removeResult: (gid) => adapter.removeDownloadResult(gid),
+ })
+ )
supervisor.setPreReadyMaintenance(() =>
sessionManager.purgeEphemeralMediaRows()
)
diff --git a/src/server/index.ts b/src/server/index.ts
index c59f3573..63a82311 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -18,6 +18,7 @@ import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'
import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'
import { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'
import { Aria2TrustStore } from '@core/engine/aria2/aria2-trust-store'
+import { CompletedTaskStartupGuard } from '@core/engine/aria2/completed-task-startup-guard'
import { createDnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'
import { JsonRpcProtocol } from '@core/engine/aria2/json-rpc-protocol'
import {
@@ -89,6 +90,7 @@ import {
} from '@core/task/actions/finalize-task'
import { removeTask } from '@core/task/actions/remove-task'
import { commitPolledTerminalTransition } from '@core/task/actions/shared'
+import { CompletedEngineTaskCleanup } from '@core/task/completed-engine-task-cleanup'
import { handleCreateTask } from '@core/task/create-task-handler'
import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'
import { FileCleanupServiceImpl } from '@core/task/file-cleanup-service'
@@ -681,6 +683,13 @@ async function main() {
: null
}
)
+ supervisor.setStartupGuard(
+ new CompletedTaskStartupGuard({
+ completedGids: () => sessionManager.getCompletedDirectEngineTaskIds(),
+ rpc: rpcClient,
+ removeResult: (gid) => adapter.removeDownloadResult(gid),
+ })
+ )
shutdownActions.drainSession = () => sessionManager.stopAndDrain()
const persistTask = createServerPersistTask(taskManager, sessionManager)
let pluginHookRuntime: PluginHookRuntime | undefined
@@ -831,11 +840,26 @@ async function main() {
proxyBridge
)
+ const completedEngineTaskCleanup = new CompletedEngineTaskCleanup({
+ taskManager,
+ adapter,
+ mintTaskId: newTaskId,
+ persist: persistTaskWithOccurrence,
+ adopt: (task, persist) =>
+ taskInspectorActivityRuntime.parentTaskCreated(task, persist),
+ publish: publishTaskUpdateNow,
+ dispatch: (occurrence) => occurrenceDispatcher.dispatch(occurrence),
+ runTaskMutation: (ids, operation) =>
+ taskInspectorActivityRuntime.runTaskMutation(ids, operation),
+ log,
+ })
+
// ─── Polling ──────────────────────────────────────────────────
async function handlePolledTasks(
rawTasks: Aria2RawStatus[],
source: PollingTaskUpdateSource
): Promise<void> {
+ if (supervisor.getState() !== EngineState.Ready) return
let dirty = false
for (const raw of rawTasks) {
if (shouldSkipForPendingMagnetMetadata(raw, magnetTracker)) {
@@ -849,6 +873,10 @@ async function main() {
}
const translated = translateRawToTask(raw)
+ if (await completedEngineTaskCleanup.observe(translated)) {
+ dirty = true
+ continue
+ }
const existing = taskManager.getByEngineTaskId(raw.gid)
if (existing) {
const merged = mergeEngineTask(existing, translated)
@@ -937,7 +965,12 @@ async function main() {
},
handlePolledTasks
)
- shutdownActions.stopPolling = () => pollingScheduler.stopAndDrain()
+ shutdownActions.stopPolling = async () => {
+ await Promise.all([
+ pollingScheduler.stopAndDrain(),
+ completedEngineTaskCleanup.stopAndDrain(),
+ ])
+ }
// ─── Task lifecycle helpers ───────────────────────────────────
const finalNamePicker = new FinalNamePickerImpl({
@@ -1434,7 +1467,9 @@ async function main() {
await appliedDownloadProxyPolicy.runWithSnapshot(
async (_snapshot, lease) => {
- await sessionManager.restore(lease.assertCurrent)
+ await sessionManager.restore(lease.assertCurrent, (snapshot) =>
+ completedEngineTaskCleanup.observe(snapshot)
+ )
await sessionManager.recoverLegacyTaskLost(lease.assertCurrent)
}
)