A full-featured download manager.
fix(engine): isolate unrecoverable magnet sessions on startup (#2486)
Dr_rOotd6e0df4cdc7e
diff --git a/e2e/engine-session-recovery.spec.ts b/e2e/engine-session-recovery.spec.tsnew file mode 100644index 00000000..99cf7594--- /dev/null+++ b/e2e/engine-session-recovery.spec.ts@@ -0,0 +1,134 @@+import { createHash } from 'node:crypto'+import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'+import path from 'node:path'+import { DatabaseSync } from 'node:sqlite'+import type { ElectronApplication, Page } from '@playwright/test'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import type { DownloadTask } from '@shared/types/task'+import {+ expect,+ launchMotrix,+ test,+ waitForEngineReady,+} from './fixtures/electron-app'++async function readTasks(page: Page): Promise<DownloadTask[]> {+ return page.evaluate(+ (channel) => window.motrix.invoke(channel),+ Queries.ListTasks+ ) as Promise<DownloadTask[]>+}++test('a missing magnet directory cannot block startup and its failed task remains removable', async ({+ userDataDir,+ rpcPort,+}) => {+ test.setTimeout(120_000)+ let app: ElectronApplication | undefined+ const infoHash = 'a'.repeat(40)+ const childGid = '2222222222222222'+ const missingDir = path.join(userDataDir, 'deleted-torrent')+ try {+ const retainedFile = path.join(userDataDir, 'downloads', 'retained.txt')+ await mkdir(path.dirname(retainedFile), { recursive: true })+ await writeFile(retainedFile, 'unrelated download')+ app = await launchMotrix({ userDataDir, rpcPort })+ let page = await app.firstWindow()+ await waitForEngineReady(page)+ const settings = JSON.parse(+ await readFile(path.join(userDataDir, 'settings.json'), 'utf8')+ ) as { engine: { rpcSecret: string } }+ const rpc = async (+ method: string,+ params: unknown[] = []+ ): Promise<unknown> => {+ const response = await fetch(`http://127.0.0.1:${rpcPort}/jsonrpc`, {+ method: 'POST',+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'session-recovery',+ method: `aria2.${method}`,+ params: [`token:${settings.engine.rpcSecret}`, ...params],+ }),+ })+ const reply = (await response.json()) as {+ result: unknown+ error?: { message: string }+ }+ if (reply.error) throw new Error(reply.error.message)+ return reply.result+ }+ const healthyGid = (await rpc('addUri', [+ ['http://127.0.0.1:1/healthy.bin'],+ { pause: 'true' },+ ])) as string+ await rpc('saveSession')+ await app.close()+ app = undefined++ // Use the real engine's schema and an orphaned metadata ancestor, as can+ // remain after an earlier cleanup. The child serializes the ancestor GID.+ const db = new DatabaseSync(path.join(userDataDir, 'aria2.db'))+ try {+ const row = db+ .prepare('SELECT * FROM task WHERE gid = ?')+ .get(healthyGid)!+ const serialized = `magnet:?xt=urn:btih:${infoHash}\n gid=1111111111111111\n dir=${missingDir}\n pause=true\n`+ Object.assign(row, {+ gid: childGid,+ state: 'paused',+ serialized,+ queue_position: 1,+ digest: createHash('sha1').update(serialized).update('paused').digest(),+ })+ const columns = Object.keys(row)+ db.prepare(+ `INSERT INTO task (${columns.join(',')}) VALUES (${columns.map(() => '?').join(',')})`+ ).run(...Object.values(row))+ } finally {+ db.close()+ }+ await mkdir(missingDir)+ await rm(missingDir, { recursive: true })++ for (let boot = 0; boot < 2; boot++) {+ app = await launchMotrix({ userDataDir, rpcPort })+ page = await app.firstWindow()+ await waitForEngineReady(page)+ await expect+ .poll(+ async () =>+ (await readTasks(page)).find(+ (task) => task.engineTaskId === childGid+ )?.status+ )+ .toBe('error')+ const tasks = await readTasks(page)+ expect(tasks).toHaveLength(2)+ expect(+ tasks.find((task) => task.engineTaskId === healthyGid)?.status+ ).toBe('paused')+ const failed = tasks.find((task) => task.engineTaskId === childGid)!+ expect(failed.errorDetailKey).toBe('task.error.detail.filesMissing')+ await expect(access(missingDir)).rejects.toMatchObject({ code: 'ENOENT' })+ if (boot === 1) {+ await page.evaluate(+ ({ channel, taskId }) =>+ window.motrix.invoke(channel, { taskId, deleteWithFiles: true }),+ { channel: Commands.RemoveTask, taskId: failed.id }+ )+ await expect+ .poll(async () =>+ (await readTasks(page)).map((task) => task.engineTaskId)+ )+ .toEqual([healthyGid])+ expect(await readFile(retainedFile, 'utf8')).toBe('unrelated download')+ }+ await app.close()+ app = undefined+ }+ } finally {+ await app?.close().catch(() => {})+ }+})diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts b/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.tsindex e8af04b2..3d729242 100644--- a/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts+++ b/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts@@ -1,12 +1,21 @@// @vitest-environment nodeimport { createHash } from 'node:crypto'import { once } from 'node:events'-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'import { createServer as createHttpServer } from 'node:http'import { type AddressInfo, createServer } from 'node:net'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 { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'+import { TaskManager } from '@core/task/task-manager'+import {+ makeDownloadTask,+ TaskKind,+ TaskStatus,+ TaskType,+} from '@shared/types/task'import {type Aria2Handle,bundledAria2Exists,@@ -63,9 +72,16 @@ function snapshot(file: string) {describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())('session recovery with the released aria2 binary',() => {- it.each(['SIGTERM', 'SIGKILL'] as const)(- 'resumes the original payload through two restarts after %s',+ it.each([+ 'SIGTERM',+ 'SIGKILL',+ 'missing-metadata',+ 'deleted-directory',+ ] as const)(+ 'recovers the persisted session through two restarts after %s',async (signal) => {+ const damaged =+ signal === 'missing-metadata' || signal === 'deleted-directory'const root = await mkdtemp(path.join(tmpdir(), 'motrix-magnet-restart-'))@@ -113,7 +129,7 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(await once(tracker, 'listening')const trackerUrl = `http://127.0.0.1:${(tracker.address() as AddressInfo).port}/announce`const torrent = encode({ announce: trackerUrl, info })- const dbPath = path.join(downloadDir, 'aria2.db')+ const dbPath = path.join(root, 'aria2.db')const common = ['--enable-dht6=false','--bt-enable-lpd=false',@@ -127,11 +143,11 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(...common,'--enable-sqlite3-persistence=true',`--sqlite3-db-path=${dbPath}`,- `--save-session=${downloadDir}/aria2.session`,+ `--save-session=${root}/aria2.session`,'--save-session-interval=1','--auto-save-interval=1','--max-download-limit=64K',- '--seed-time=0',+ `--seed-time=${damaged ? 60 : 0}`,`--listen-port=${await availablePort()}`,]let seed: Aria2Handle | undefined@@ -189,6 +205,27 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(},{ timeout: 20000, interval: 100 })+ let healthyGid = ''+ if (damaged) {+ await downloader.rpc.changeOption(payloadGid, {+ 'max-download-limit': '0',+ })+ await vi.waitFor(+ async () => {+ const task = await downloader!.rpc.tellStatus(payloadGid)+ expect(task.completedLength).toBe(String(payload.length))+ expect(task.seeder).toBe('true')+ },+ { timeout: 20000, interval: 100 }+ )+ healthyGid = await downloader.rpc.addUri(+ [`${trackerUrl}/healthy.bin`],+ {+ pause: 'true',+ dir: seedDir,+ }+ )+ }if (signal === 'SIGTERM') {await downloader.rpc.forcePause(payloadGid)await vi.waitFor(async () =>@@ -210,6 +247,109 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(expect(before.rows.find((row) => row.gid === payloadGid)?.serialized).toContain(`gid=${metadataGid}`)+ if (damaged) {+ const appDb = new MotrixDatabase(path.join(root, 'motrix.db'))+ try {+ appDb.init()+ const cache = path.join(root, 'cached.torrent')+ await writeFile(cache, torrent)+ const session = new SessionManager(+ new TaskManager(),+ downloader.rpc,+ appDb,+ downloader.adapter+ )+ await session.persistTask(+ makeDownloadTask({+ id: 'seeding-task',+ engineTaskId: payloadGid,+ name: 'payload.bin',+ filename: 'payload.bin',+ finalName: 'payload.bin',+ type: TaskType.Magnet,+ kind: TaskKind.Bt,+ status: TaskStatus.Seeding,+ saveDir: downloadDir,+ diskPath: path.join(downloadDir, 'payload.bin'),+ finalPath: path.join(downloadDir, 'payload.bin'),+ createdAt: Date.now(),+ updatedAt: Date.now(),+ source: 'user',+ sourceMeta: null,+ instances: [],+ infoHash,+ totalBytes: payload.length,+ downloadedBytes: payload.length,+ torrentMetaPath:+ signal === 'deleted-directory' ? cache : null,+ })+ )+ if (signal === 'deleted-directory')+ await rm(downloadDir, { recursive: true })+ else await rm(path.join(downloadDir, `${infoHash}.torrent`))+ const recovery = await recoverAria2SessionIdentity(+ dbPath,+ () => true,+ session.getEngineSessionRecoveryStore()+ )+ expect(recovery?.quarantinedGids).toEqual([payloadGid])+ expect(snapshot(recovery!.backupPath).rows).toEqual(before.rows)+ expect(snapshot(dbPath).rows.map((row) => row.gid)).toEqual([+ healthyGid,+ ])+ for (let boot = 0; boot < 2; boot++) {+ expect(+ await recoverAria2SessionIdentity(+ dbPath,+ () => true,+ session.getEngineSessionRecoveryStore()+ )+ ).toBeNull()+ download = await spawnAria2ForTest({+ baseDir: root,+ port: await availablePort(),+ extraArgs: args,+ })+ downloader = await connectAdapter(download)+ const manager = new TaskManager()+ const restored = new SessionManager(+ manager,+ downloader.rpc,+ appDb,+ downloader.adapter+ )+ await restored.restore()+ expect(manager.getAll()).toHaveLength(2)+ expect(manager.getById('seeding-task')).toMatchObject({+ status: TaskStatus.Error,+ errorDetailKey:+ signal === 'deleted-directory'+ ? 'task.error.detail.filesMissing'+ : 'task.recovery.startup.torrentMetaMissing',+ })+ expect(+ (await downloader.rpc.tellWaiting(0, 100)).map(+ (row) => row.gid+ )+ ).toEqual([healthyGid])+ expect(await downloader.rpc.tellActive()).toEqual([])+ if (signal === 'deleted-directory')+ await expect(stat(downloadDir)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ else+ expect(+ await readFile(path.join(downloadDir, 'payload.bin'))+ ).toEqual(payload)+ await downloader.rpc.saveSession()+ downloader.disconnect()+ await download.kill()+ }+ } finally {+ appDb.close()+ }+ return+ }const result = await recoverAria2SessionIdentity(dbPath)expect(result?.repairedGids).toEqual([payloadGid])expect(result?.retiredMetadataGids).toEqual([metadataGid])diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.test.ts b/src/core/engine/aria2/aria2-session-identity-recovery.test.tsindex 6c1a0426..d4ee47c2 100644--- a/src/core/engine/aria2/aria2-session-identity-recovery.test.ts+++ b/src/core/engine/aria2/aria2-session-identity-recovery.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport { createHash } from 'node:crypto'import {+ mkdir,mkdtemp,readdir,readFile,@@ -13,6 +14,7 @@ import path from 'node:path'import { parseEngineTorrent as parseTorrent } from '@shared/lib/engine-torrent'import Database from 'better-sqlite3'import { afterEach, describe, expect, it, vi } from 'vitest'+import type { EngineSessionRecoveryStore } from '../engine-session-recovery'import { recoverAria2SessionIdentity } from './aria2-session-identity-recovery'const PARENT = '1111111111111111'@@ -102,6 +104,255 @@ afterEach(async () => {})describe('aria2 persisted task identity recovery', () => {+ const recoveryStore = (): EngineSessionRecoveryStore => ({+ getContext: () => ({ metadataPaths: [], retired: false }),+ quarantine: vi.fn().mockResolvedValue(undefined),+ })++ it.each([2, 3, 4, 5] as const)(+ 'quarantines missing metadata with a complete backup on schema v%s',+ async (schemaVersion) => {+ const h = await setup('waiting', schemaVersion)+ try {+ await unlink(h.metadataPath)+ const before = h.rows()+ const history = h.db.prepare('SELECT * FROM download_history').all()+ const store = recoveryStore()+ store.quarantine = vi.fn(async (tasks) => {+ expect(tasks).toMatchObject([+ {+ engineTaskId: CHILD,+ metadataTaskId: PARENT,+ reason: 'metadata-unavailable',+ },+ ])+ expect(h.rows()).toEqual(before)+ const backups = (await readdir(h.root)).filter((name) =>+ name.includes('identity-recovery-')+ )+ const backup = new Database(+ path.join(h.root, backups[0], 'aria2.db'),+ { readonly: true }+ )+ try {+ expect(+ backup.prepare('SELECT * FROM task ORDER BY queue_position').all()+ ).toEqual(before)+ expect(+ backup.prepare('SELECT * FROM task_progress').all()+ ).toHaveLength(1)+ expect(+ backup.prepare('SELECT * FROM task_cookie_context').all()+ ).toHaveLength(1)+ } finally {+ backup.close()+ }+ })+ const result = await recoverAria2SessionIdentity(+ h.file,+ () => true,+ store+ )+ expect(result?.quarantinedGids).toEqual([CHILD])+ expect(result?.repairedGids).toEqual([])+ expect(h.rows()).toEqual([before[2]])+ expect(h.db.prepare('SELECT * FROM task_progress').all()).toEqual([])+ expect(h.db.prepare('SELECT * FROM task_cookie_context').all()).toEqual(+ []+ )+ expect(h.db.prepare('SELECT * FROM download_history').all()).toEqual(+ history+ )+ expect(+ await recoverAria2SessionIdentity(h.file, () => true, store)+ ).toBeNull()+ expect(store.quarantine).toHaveBeenCalledOnce()+ } finally {+ h.db.close()+ }+ }+ )++ it('uses only hash-verified cached metadata when the download copy is missing', async () => {+ const h = await setup()+ try {+ await unlink(h.metadataPath)+ const cached = path.join(h.root, 'app-cache.torrent')+ const invalid = path.join(h.root, 'invalid.torrent')+ await writeFile(cached, h.bytes)+ await writeFile(+ invalid,+ await readFile('scripts/poc/fixtures/multi.torrent')+ )+ const store = recoveryStore()+ store.getContext = () => ({+ metadataPaths: [invalid, cached],+ retired: false,+ })+ const result = await recoverAria2SessionIdentity(+ h.file,+ () => true,+ store+ )+ expect(result?.repairedGids).toEqual([CHILD])+ expect(result?.quarantinedGids).toEqual([])+ expect(store.quarantine).not.toHaveBeenCalled()+ const row = h.db+ .prepare('SELECT bt_local_path FROM task WHERE gid = ?')+ .get(CHILD) as { bt_local_path: string }+ expect(await readFile(row.bt_local_path)).toEqual(h.bytes)+ } finally {+ h.db.close()+ }+ })++ it('repairs a healthy BT identity in the same transaction that isolates a broken task', async () => {+ const h = await setup()+ try {+ const good = '4444444444444444'+ const directory = path.join(h.root, 'healthy')+ await mkdir(directory)+ await writeFile(+ path.join(directory, path.basename(h.metadataPath)),+ h.bytes+ )+ const serialized = h+ .entry('5555555555555555', true)+ .replace(`dir=${h.root}`, `dir=${directory}`)+ h.db+ .prepare(+ 'INSERT INTO task SELECT ?, state, ?, digest, bt_local_path, updated_at, queue_position + 10 FROM task WHERE gid = ?'+ )+ .run(good, serialized, CHILD)+ h.db+ .prepare('INSERT INTO task_progress (gid, bitfield) VALUES (?, ?)')+ .run(good, Buffer.from([0xff]))+ await unlink(h.metadataPath)+ const result = await recoverAria2SessionIdentity(+ h.file,+ () => true,+ recoveryStore()+ )+ expect(result?.repairedGids).toEqual([good])+ expect(result?.quarantinedGids).toEqual([CHILD])+ expect(h.db.prepare('SELECT * FROM task_progress').all()).toEqual([+ { gid: good, bitfield: Buffer.from([0xff]) },+ ])+ const repaired = h.db+ .prepare('SELECT serialized, state FROM task WHERE gid = ?')+ .get(good) as { serialized: string; state: string }+ expect(repaired.state).toBe('paused')+ expect(repaired.serialized).toContain(`gid=${good}`)+ expect(+ await recoverAria2SessionIdentity(h.file, () => true, recoveryStore())+ ).toBeNull()+ } finally {+ h.db.close()+ }+ })++ it('does not recreate a deleted download directory even with cached metadata', async () => {+ const h = await setup()+ try {+ const missingDir = path.join(h.root, 'deleted-download')+ h.db+ .prepare('UPDATE task SET serialized = replace(serialized, ?, ?)')+ .run(`dir=${h.root}`, `dir=${missingDir}`)+ const store = recoveryStore()+ store.getContext = () => ({+ metadataPaths: [h.metadataPath],+ retired: false,+ })+ const result = await recoverAria2SessionIdentity(+ h.file,+ () => true,+ store+ )+ expect(result?.quarantinedGids).toEqual([CHILD])+ expect(store.quarantine).toHaveBeenCalledWith([+ expect.objectContaining({ reason: 'files-missing' }),+ ])+ await expect(readFile(missingDir)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ } finally {+ h.db.close()+ }+ })++ it('leaves engine rows intact if durable application quarantine fails', async () => {+ const h = await setup()+ try {+ await unlink(h.metadataPath)+ const before = h.rows()+ const store = recoveryStore()+ store.quarantine = vi+ .fn()+ .mockRejectedValue(new Error('application database full'))+ await expect(+ recoverAria2SessionIdentity(h.file, () => true, store)+ ).rejects.toThrow('application database full')+ expect(h.rows()).toEqual(before)+ } finally {+ h.db.close()+ }+ })++ it('finishes quarantine after a failed engine transaction even if metadata reappears', async () => {+ const h = await setup()+ try {+ await unlink(h.metadataPath)+ let retired = false+ const store = recoveryStore()+ store.getContext = () => ({ metadataPaths: [], retired })+ store.quarantine = vi.fn(async () => {+ retired = true+ })+ h.db.exec(+ "CREATE TRIGGER refuse_delete BEFORE DELETE ON task BEGIN SELECT RAISE(ABORT, 'injected failure'); END"+ )+ await expect(+ recoverAria2SessionIdentity(h.file, () => true, store)+ ).rejects.toThrow('injected failure')+ expect(h.rows()).toHaveLength(3)+ h.db.exec('DROP TRIGGER refuse_delete')+ await writeFile(h.metadataPath, h.bytes)+ const result = await recoverAria2SessionIdentity(+ h.file,+ () => true,+ store+ )+ expect(result?.quarantinedGids).toEqual([CHILD])+ expect(result?.repairedGids).toEqual([])+ expect(h.rows()).toHaveLength(1)+ } finally {+ h.db.close()+ }+ })++ it.each(['invalid', 'mismatched'])(+ 'quarantines %s metadata when no verified cache exists',+ async (variant) => {+ const h = await setup()+ try {+ await writeFile(+ h.metadataPath,+ variant === 'invalid'+ ? Buffer.from('broken')+ : await readFile('scripts/poc/fixtures/multi.torrent')+ )+ const result = await recoverAria2SessionIdentity(+ h.file,+ () => true,+ recoveryStore()+ )+ expect(result?.quarantinedGids).toEqual([CHILD])+ expect(h.rows()).toHaveLength(1)+ } finally {+ h.db.close()+ }+ }+ )it.each(['waiting', 'paused'])('preserves task identity, options and progress (%s)',async (state) => {diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.ts b/src/core/engine/aria2/aria2-session-identity-recovery.tsindex 2050cc04..9bed7b7f 100644--- a/src/core/engine/aria2/aria2-session-identity-recovery.ts+++ b/src/core/engine/aria2/aria2-session-identity-recovery.ts@@ -6,6 +6,10 @@ import { MAX_TORRENT_BASE64_SIZE } from '@shared/lib/torrent-meta'import Database from 'better-sqlite3'import writeFileAtomic from 'write-file-atomic'import { z } from 'zod'+import type {+ EngineSessionRecoveryStore,+ EngineSessionTaskFailure,+} from '../engine-session-recovery'const gidSchema = z.string().regex(/^[0-9a-f]{16}$/)const rowSchema = z.object({@@ -57,17 +61,51 @@ export interface SessionIdentityRecovery {backupPath: stringrepairedGids: string[]retiredMetadataGids: string[]+ quarantinedGids: string[]+}++async function readMatchingMetadata(+ metadataPath: string,+ infoHash: string+): Promise<Buffer | null> {+ let bytes: Buffer+ try {+ const metadataStat = await stat(metadataPath)+ if (+ !metadataStat.isFile() ||+ metadataStat.size > (MAX_TORRENT_BASE64_SIZE * 3) / 4+ )+ return null+ bytes = await readFile(metadataPath)+ } catch (error) {+ if (+ ['ENOENT', 'ENOTDIR'].includes(+ (error as NodeJS.ErrnoException).code ?? ''+ )+ )+ return null+ // Permission and storage failures are not evidence that a task was deleted.+ throw error+ }+ try {+ const torrent = await parseTorrent(bytes)+ return torrent.infoHash === infoHash && torrent.files?.length ? bytes : null+ } catch {+ return null+ }}/*** Repair the fork's metadata-ancestor GID serialization (schema v1–v5) before spawn.* The actual row key remains the owner of progress, cookies and app identity.* A verified local torrent replaces the magnet so aria2 recreates that exact- * payload task directly. No engine schema, setting or download data changes.+ * payload task directly. Unrecoverable tasks are backed up and retained in the+ * application before their engine rows are retired. Download data is untouched.*/export async function recoverAria2SessionIdentity(databasePath: string,- canRepair: () => boolean = () => true+ canRepair: () => boolean = () => true,+ recoveryStore?: EngineSessionRecoveryStore): Promise<SessionIdentityRecovery | null> {try {await stat(databasePath)@@ -110,6 +148,7 @@ export async function recoverAria2SessionIdentity(const retiredMetadataGids = new Set<string>()const plans: Array<{ row: Row; entry: Entry; bytes: Buffer }> = []+ const quarantined: EngineSessionTaskFailure[] = []for (const { row, entry } of candidates) {if (!['waiting', 'paused'].includes(row.state))throw failure(row.gid, 'unsupported task state')@@ -141,32 +180,62 @@ export async function recoverAria2SessionIdentity(retiredMetadataGids.add(parent.gid)}- let bytes: Buffer+ let infoHash: stringtry {const magnet = await parseTorrent(entry.source)if (!magnet.infoHash || !/^[a-f0-9]{40}$/.test(magnet.infoHash))throw new Error('invalid infohash')- const metadataPath = path.join(- entry.directory,- `${magnet.infoHash}.torrent`- )- const metadataStat = await stat(metadataPath)- if (- !metadataStat.isFile() ||- metadataStat.size > (MAX_TORRENT_BASE64_SIZE * 3) / 4- )- throw new Error('invalid metadata size')- bytes = await readFile(metadataPath)- const torrent = await parseTorrent(bytes)- if (torrent.infoHash !== magnet.infoHash || !torrent.files?.length)- throw new Error('metadata does not match magnet')+ infoHash = magnet.infoHash} catch {+ throw failure(row.gid, 'invalid magnet identity')+ }+ const task = {+ engineTaskId: row.gid,+ metadataTaskId: entry.gid,+ sourceUri: entry.source,+ saveDir: entry.directory,+ infoHash,+ }+ const context = recoveryStore?.getContext(task)+ let directoryMissing = false+ if (!context?.retired) {+ try {+ directoryMissing = !(await stat(entry.directory)).isDirectory()+ } catch (error) {+ if (+ !['ENOENT', 'ENOTDIR'].includes(+ (error as NodeJS.ErrnoException).code ?? ''+ )+ )+ throw error+ directoryMissing = true+ }+ }+ let bytes: Buffer | null = null+ if (!context?.retired && !directoryMissing) {+ const metadataPaths = new Set([+ path.join(entry.directory, `${infoHash}.torrent`),+ ...(context?.metadataPaths ?? []),+ ])+ for (const metadataPath of metadataPaths) {+ bytes = await readMatchingMetadata(metadataPath, infoHash)+ if (bytes) break+ }+ }+ if (bytes) {+ plans.push({ row, entry, bytes })+ } else if (recoveryStore) {+ quarantined.push({+ ...task,+ reason: directoryMissing ? 'files-missing' : 'metadata-unavailable',+ })+ } else {+ // Standalone callers cannot discard a task without a durable UI owner.throw failure(row.gid,'matching saved torrent metadata is unavailable; session was not changed')}- plans.push({ row, entry, bytes })}if (!canRepair())@@ -199,6 +268,12 @@ export async function recoverAria2SessionIdentity(changes.push({ row, serialized, metadataPath })}+ // Commit application errors first. A crash or engine transaction failure+ // leaves those identities retired in getContext(), so a subsequent boot+ // cannot revive them even if their metadata has since reappeared.+ if (quarantined.length && recoveryStore)+ await recoveryStore.quarantine(quarantined)+db.pragma('foreign_keys = ON')db.transaction(() => {if (@@ -236,7 +311,10 @@ export async function recoverAria2SessionIdentity(Number(schemaVersion) >= 3? db.prepare('DELETE FROM task_progress WHERE gid = ?'): null- for (const gid of retiredMetadataGids) {+ for (const gid of new Set([+ ...retiredMetadataGids,+ ...quarantined.map((task) => task.engineTaskId),+ ])) {remove.run(gid)removeProgress?.run(gid)}@@ -245,6 +323,7 @@ export async function recoverAria2SessionIdentity(backupPath,repairedGids: plans.map(({ row }) => row.gid),retiredMetadataGids: [...retiredMetadataGids],+ quarantinedGids: quarantined.map((task) => task.engineTaskId),}} finally {db.close()diff --git a/src/core/engine/engine-session-recovery.ts b/src/core/engine/engine-session-recovery.tsnew file mode 100644index 00000000..50ca375a--- /dev/null+++ b/src/core/engine/engine-session-recovery.ts@@ -0,0 +1,26 @@+/** Persisted engine identity, without engine-specific session options. */+export interface EngineSessionTask {+ engineTaskId: string+ metadataTaskId: string+ sourceUri: string+ saveDir: string+ infoHash: string+}++export type EngineSessionRecoveryReason =+ | 'metadata-unavailable'+ | 'files-missing'++export interface EngineSessionTaskFailure extends EngineSessionTask {+ reason: EngineSessionRecoveryReason+}++export interface EngineSessionRecoveryStore {+ getContext(task: EngineSessionTask): {+ metadataPaths: readonly string[]+ /** A previous quarantine must survive a crash before engine-row removal. */+ retired: boolean+ }+ /** Must durably retain user-visible failures before engine rows are removed. */+ quarantine(tasks: readonly EngineSessionTaskFailure[]): Promise<void>+}diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex 38e684b4..cfdda5ea 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -861,7 +861,8 @@ describe('EngineSupervisor', () => {await supervisor.start('/usr/bin/aria2c')expect(recoverSessionMock).toHaveBeenCalledWith('/tmp/aria2.db',- expect.any(Function)+ expect.any(Function),+ undefined)expect(recoverSessionMock.mock.invocationCallOrder.at(-1)).toBeLessThan(prepare.mock.invocationCallOrder[0]!@@ -889,6 +890,28 @@ describe('EngineSupervisor', () => {expect(supervisor.getLastError()).toBe('saved metadata unavailable')})+ it('starts after durable per-task quarantine and passes the application recovery store', async () => {+ const store = {+ getContext: vi.fn(() => ({ metadataPaths: [], retired: false })),+ quarantine: vi.fn().mockResolvedValue(undefined),+ }+ supervisor.setSessionRecoveryStore(store)+ recoverSessionMock.mockResolvedValueOnce({+ backupPath: '/backup/aria2.db',+ repairedGids: [],+ retiredMetadataGids: ['1111111111111111'],+ quarantinedGids: ['2222222222222222'],+ })+ await supervisor.start('/usr/bin/aria2c')+ expect(recoverSessionMock).toHaveBeenLastCalledWith(+ '/tmp/aria2.db',+ expect.any(Function),+ store+ )+ expect(processManager.spawn).toHaveBeenCalledOnce()+ expect(supervisor.getState()).toBe(EngineState.Ready)+ })+it('preserves only the GID conflict diagnostic when RPC fails', async () => {vi.mocked(rpcClient.connect).mockRejectedValueOnce(new Error('ECONNREFUSED')diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex 01664fa3..a97061af 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -43,6 +43,7 @@ import {STANDARD_ARIA2_CONNECTION_LIMIT,} from './aria2/feature-report'import type { DirectResourceMetadataProfile } from './engine-adapter'+import type { EngineSessionRecoveryStore } from './engine-session-recovery'import { checkPort, findAvailablePort } from './port-check'const log = getLogger('engine')@@ -88,6 +89,7 @@ function getBackoffDelay(attempt: number): number {}export class EngineSupervisor {+ private sessionRecoveryStore?: EngineSessionRecoveryStoreprivate state: EngineState = EngineState.Stoppedprivate featureReport: EngineFeatureReport | null = nullprivate getEffectiveLimits:@@ -202,6 +204,10 @@ export class EngineSupervisor {this.startupGuard = guard}+ setSessionRecoveryStore(store: EngineSessionRecoveryStore): void {+ this.sessionRecoveryStore = store+ }+/** Register best-effort engine maintenance that runs after RPC connects but before Ready. */setPreReadyMaintenance(maintenance: () => Promise<void>): void {this.preReadyMaintenance = maintenance@@ -531,10 +537,11 @@ export class EngineSupervisor {if (sqliteActive) {const recovery = await recoverAria2SessionIdentity(this.configBuilder.resolveSqliteDbPath(engineSettings),- () => !this.stopping && !this.processManager.isRunning()+ () => !this.stopping && !this.processManager.isRunning(),+ this.sessionRecoveryStore)if (recovery)- log.warn(recovery, 'repaired aria2 metadata task identities')+ log.warn(recovery, 'recovered aria2 metadata task identities')}// Step 4: Spawn process (abort if stop() was called during earlier awaits)diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex b5cab82a..aba392c6 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -532,6 +532,135 @@ describe('SessionManager', () => {vi.restoreAllMocks()})+ describe('engine session quarantine', () => {+ const failed = {+ engineTaskId: '2222222222222222',+ metadataTaskId: '1111111111111111',+ infoHash: 'a'.repeat(40),+ sourceUri: `magnet:?xt=urn:btih:${'a'.repeat(40)}`,+ saveDir: '/downloads/shared',+ reason: 'metadata-unavailable' as const,+ }++ it('retains the owned task as an error across restore without re-adding it', async () => {+ seedAsPair(db, {+ motrixId: 'owned',+ gid: failed.engineTaskId,+ infoHash: failed.infoHash,+ status: TaskStatus.Seeding,+ totalBytes: 1000,+ downloadedBytes: 1000,+ uploadedBytes: 900,+ })+ const store = session.getEngineSessionRecoveryStore()+ await store.quarantine([failed])+ expect(db.getTask('owned')?.task).toMatchObject({+ aggStatus: TaskStatus.Error,+ errorDetailKey: 'task.recovery.startup.torrentMetaMissing',+ downloadedBytes: 1000,+ })+ expect(store.getContext(failed).retired).toBe(true)+ const durable = structuredClone(db.getTask('owned'))+ await store.quarantine([failed])+ expect(db.getTask('owned')).toEqual(durable)+ await session.restore()+ await session.restore()+ expect(taskManager.getById('owned')).toMatchObject({+ status: TaskStatus.Error,+ uploadedBytes: 900,+ })+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ expect(adapter.createDownload).not.toHaveBeenCalled()+ })++ it('borrows metadata by content without retiring a different task with the same hash', async () => {+ seedAsPair(db, {+ motrixId: 'other-copy',+ gid: '3333333333333333',+ infoHash: failed.infoHash,+ torrentMetaPath: '/cache/other.torrent',+ status: TaskStatus.Paused,+ })+ const store = session.getEngineSessionRecoveryStore()+ expect(store.getContext(failed)).toEqual({+ metadataPaths: ['/cache/other.torrent'],+ retired: false,+ })+ await store.quarantine([failed])+ expect(db.getTask('other-copy')?.task.aggStatus).toBe(TaskStatus.Paused)+ const quarantined = db+ .getAllTasks()+ .find((pair) => pair.task.motrixId !== 'other-copy')!+ expect(quarantined.task).toMatchObject({+ aggStatus: TaskStatus.Error,+ finalPath: '',+ finalName: '',+ })+ expect(quarantined.instances[0]).toMatchObject({+ gid: failed.engineTaskId,+ diskPath: '',+ phase: TaskInstancePhase.BtDownload,+ })+ await store.quarantine([failed])+ expect(db.getAllTasks()).toHaveLength(2)+ db.deleteTask(quarantined.task.motrixId)+ await session.restore()+ expect(taskManager.getById(quarantined.task.motrixId)).toBeUndefined()+ })++ it('retires an owned metadata parent without reissuing its magnet on restore', async () => {+ seedAsPair(db, {+ motrixId: 'parent',+ gid: failed.metadataTaskId,+ infoHash: failed.infoHash,+ status: TaskStatus.FetchingMetadata,+ })+ const pair = db.getTask('parent')!+ pair.instances[0].phase = TaskInstancePhase.MagnetMetadataResolution+ pair.instances[0].payload = { metadataDir: '/tmp/metadata' }+ db.saveTaskWithInstances(pair)+ await session+ .getEngineSessionRecoveryStore()+ .quarantine([{ ...failed, reason: 'files-missing' }])+ await session.restore()+ expect(taskManager.getById('parent')).toMatchObject({+ status: TaskStatus.Error,+ errorDetailKey: 'task.error.detail.filesMissing',+ })+ expect(db.getAllTasks()).toHaveLength(1)+ })++ it('does not publish an error or retire an engine identity when persistence fails', async () => {+ seedAsPair(db, {+ motrixId: 'owned',+ gid: failed.engineTaskId,+ infoHash: failed.infoHash,+ status: TaskStatus.Seeding,+ })+ session.bindTerminalOccurrencePersistence(async () => {+ throw new Error('disk full')+ })+ await expect(+ session.getEngineSessionRecoveryStore().quarantine([failed])+ ).rejects.toThrow('disk full')+ expect(db.getTask('owned')?.task.aggStatus).toBe(TaskStatus.Seeding)+ expect(taskManager.getById('owned')).toBeUndefined()+ })++ it('preserves completed task history while retiring its engine identity', async () => {+ seedAsPair(db, {+ motrixId: 'done',+ gid: failed.engineTaskId,+ infoHash: failed.infoHash,+ status: TaskStatus.Completed,+ })+ const store = session.getEngineSessionRecoveryStore()+ expect(store.getContext(failed).retired).toBe(true)+ await store.quarantine([failed])+ expect(db.getTask('done')?.task.aggStatus).toBe(TaskStatus.Completed)+ })+ })+describe('save', () => {it('saves non-removed tasks to database', async () => {const task1 = createTask({diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 881d6d09..92118a9b 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -22,7 +22,9 @@ import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'import type { DownloadTask } from '@shared/types/task'import {makeDefaultBtExtension,+ makeDownloadTask,TaskInstancePhase,+ TaskKind,TaskStatus,TaskType,TransitionPhase,@@ -48,6 +50,11 @@ import type {DirectResourceMetadataProfile,EngineAdapter,} from '../engine/engine-adapter'+import type {+ EngineSessionRecoveryStore,+ EngineSessionTask,+ EngineSessionTaskFailure,+} from '../engine/engine-session-recovery'import {buildTerminalOccurrence,terminalSnapshotFromTask,@@ -659,6 +666,105 @@ export class SessionManager {return result}+ /** Bind the same pre-spawn recovery policy in both application hosts. */+ getEngineSessionRecoveryStore(): EngineSessionRecoveryStore {+ return {+ getContext: (task) => {+ const pairs = this.db.getAllTasks()+ const owners = this.sessionRecoveryOwners(task, pairs)+ return {+ retired: owners.some((pair) =>+ [TaskStatus.Error, TaskStatus.Completed].includes(+ pair.task.aggStatus+ )+ ),+ // Content identity is sufficient for metadata bytes, but never for+ // choosing which public task to retire. The engine validates hashes.+ metadataPaths: pairs.flatMap((pair) =>+ !hasLegacyImport(pair) &&+ pair.task.torrentMetaPath &&+ (owners.includes(pair) ||+ pair.task.infoHash?.toLowerCase() === task.infoHash)+ ? [pair.task.torrentMetaPath]+ : []+ ),+ }+ },+ quarantine: (tasks) => this.quarantineEngineSessionTasks(tasks),+ }+ }++ private sessionRecoveryOwners(+ task: EngineSessionTask,+ pairs = this.db.getAllTasks()+ ): TaskWithInstances[] {+ const owners = pairs.filter((pair) =>+ pair.instances.some(+ (instance) =>+ instance.gid === task.engineTaskId ||+ instance.gid === task.metadataTaskId+ )+ )+ if (+ owners.some(+ (pair) =>+ hasLegacyImport(pair) || !isTorrentLikeType(pair.task.taskType)+ )+ )+ throw new Error(+ 'Engine session recovery conflicts with a protected task identity'+ )+ return owners+ }++ private async quarantineEngineSessionTasks(+ tasks: readonly EngineSessionTaskFailure[]+ ): Promise<void> {+ for (const failed of tasks) {+ const owners = this.sessionRecoveryOwners(failed)+ const candidates = owners.length+ ? owners.map((pair) =>+ this.adoptByPair(pair, pair.instances[0]?.gid ?? '')+ )+ : [+ makeDownloadTask({+ id: newTaskId(),+ engineTaskId: failed.engineTaskId,+ name: failed.infoHash,+ filename: failed.infoHash,+ type: TaskType.Magnet,+ kind: TaskKind.Bt,+ saveDir: failed.saveDir,+ // The engine session does not prove any output file paths. Keep+ // deletion from treating a shared download directory as payload.+ diskPath: '',+ finalPath: '',+ finalName: '',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ source: 'user',+ sourceMeta: null,+ uris: [failed.sourceUri],+ infoHash: failed.infoHash,+ bt: makeDefaultBtExtension({ magnetUri: failed.sourceUri }),+ instances: [],+ }),+ ]+ for (const candidate of candidates) {+ if ([TaskStatus.Error, TaskStatus.Completed].includes(candidate.status))+ continue+ const task = await this.markRecoverErrorTask(+ candidate,+ candidate.status,+ failed.reason === 'files-missing'+ ? 'task.error.detail.filesMissing'+ : 'task.recovery.startup.torrentMetaMissing'+ )+ this.taskManager.set(task.id, task)+ }+ }+ }+async restore(assertProxyCurrent?: () => void,observeCompletedTask?: (snapshot: DownloadTask) => Promise<unknown>diff --git a/src/main/index.ts b/src/main/index.tsindex cbcfeb9f..9c3cd743 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2344,6 +2344,9 @@ async function initializeMainProcess(): Promise<void> {activeTaskInspectorActivityRuntime.runTaskMutation(ids, operation),log,})+ supervisor.setSessionRecoveryStore(+ sessionManager.getEngineSessionRecoveryStore()+ )supervisor.setStartupGuard(new CompletedTaskStartupGuard({completedGids: () => sessionManager.getCompletedDirectEngineTaskIds(),diff --git a/src/server/index.ts b/src/server/index.tsindex 9e57d19b..2d3f30b5 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -765,6 +765,9 @@ async function main() {: null})+ supervisor.setSessionRecoveryStore(+ sessionManager.getEngineSessionRecoveryStore()+ )supervisor.setStartupGuard(new CompletedTaskStartupGuard({completedGids: () => sessionManager.getCompletedDirectEngineTaskIds(),