Skip to content

A full-featured download manager.

fix(session): cancel finalize recovery when tasks are deleted (#2524)

Dr_rOot6abe17ef86c9
diff --git a/docs/plugin-hook-runtime.md b/docs/plugin-hook-runtime.md
index cc9743cb..1c405cec 100644
--- a/docs/plugin-hook-runtime.md
+++ b/docs/plugin-hook-runtime.md
@@ -610,6 +610,17 @@ and records cleanup quarantine. It fsyncs affected directories, records
quarantined), releases the mutation lease, and then removes or retains the
journal as the quarantine policy requires. Cleanup is idempotent.
+Task deletion removes `cleaned` journals in the same transaction as the task.
+Unfinished journals enter a terminal `quarantined` state with reason
+`task-deleted`; their original plan and artifact identities remain available
+because a rollback or private path may contain the only surviving copy of user
+data. These records cannot be recovered, retried, or reopened by a late recovery
+error, and do not count as pending finalization. Opening the database applies
+the same policy to orphaned journals left by older builds before either host
+starts recovery. This cancellation does not access or mutate files; normal
+task-removal file policy still applies. Independent post deliveries and their
+quota accounting survive task deletion as specified in section 11.
+
### 10.3 Compensation and crash recovery
If target staging or installation fails, the source is restored from the
diff --git a/docs/plugin-hook-runtime.zh-CN.md b/docs/plugin-hook-runtime.zh-CN.md
index f2b92edd..e18448c4 100644
--- a/docs/plugin-hook-runtime.zh-CN.md
+++ b/docs/plugin-hook-runtime.zh-CN.md
@@ -542,6 +542,14 @@ quarantine。随后 fsync 受影响目录;只有全部已知清理完成(或
quarantine)才记录 `cleaned`,释放 mutation lease,并按 quarantine policy
删除或保留 journal。清理操作必须幂等。
+删除任务时,在同一事务中删除其 `cleaned` journal。未完成的 journal 转为
+`quarantined`,原因设为 `task-deleted`,作为不可恢复的取消状态;原始 plan 和
+文件身份信息继续保留,因为 rollback 或 private path 中可能是用户数据的唯一
+剩余副本。这些记录不再恢复、重试或计入待最终化状态,迟到的恢复错误也不能
+重新启用它们。打开数据库时,在 Desktop 或 Server 启动恢复之前,对旧版本
+遗留的孤儿 journal 执行相同处理。取消操作不访问或修改文件,任务删除原有的
+文件处理策略仍然适用。独立的 post delivery 及其配额账本按第 11 节约定保留。
+
### 10.3 补偿与崩溃恢复
Target staging 或安装失败时,Motrix 在必要时从 rollback path 恢复 source,
diff --git a/e2e/finalize-journal-deletion.spec.ts b/e2e/finalize-journal-deletion.spec.ts
new file mode 100644
index 00000000..83f72ac1
--- /dev/null
+++ b/e2e/finalize-journal-deletion.spec.ts
@@ -0,0 +1,166 @@
+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 { AppNotification } from '@shared/types/notification'
+import type { DownloadTask } from '@shared/types/task'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
+
+const taskIds = ['finalize-single', 'finalize-bulk', 'finalize-cleaned']
+
+function seedFailedTasks(userDataDir: string) {
+ const db = new DatabaseSync(path.join(userDataDir, 'motrix.db'))
+ try {
+ for (const id of [...taskIds, 'finalize-legacy-orphan']) {
+ const saveDir = path.join(userDataDir, 'downloads')
+ const target = path.join(saveDir, `${id}.bin`)
+ const source = `${target}.motrix`
+ const phase = id === 'finalize-cleaned' ? 'cleaned' : 'prepared'
+ const identity = {
+ kind: 'file',
+ size: 1,
+ sha256: 'a'.repeat(64),
+ platformFileId: `file-${id}`,
+ }
+ const record = {
+ journalId: `journal-${id}`,
+ phase,
+ plan: {
+ planId: `journal-${id}`,
+ taskId: id,
+ saveDir,
+ sourcePath: source,
+ targetPath: target,
+ sourceIdentity: identity,
+ metadataOps: [],
+ contributors: [],
+ },
+ }
+ db.prepare(`INSERT INTO plugin_finalize_journals (
+ plan_id, task_id, phase, plan_json, source_identity_json, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, 1000, 1000)`).run(
+ record.journalId,
+ id,
+ phase,
+ JSON.stringify(record),
+ JSON.stringify(identity)
+ )
+ if (id === 'finalize-legacy-orphan') continue
+ db.prepare(`INSERT INTO tasks (
+ motrix_id, name, task_type, created_at, updated_at,
+ save_dir, final_path, final_name, agg_status
+ ) VALUES (?, ?, 'http', 1000, 1000, ?, ?, ?, 'error')`).run(
+ id,
+ id,
+ saveDir,
+ target,
+ `${id}.bin`
+ )
+ db.prepare(`INSERT INTO task_instances (
+ instance_id, motrix_id, phase, status, disk_path, created_at, updated_at
+ ) VALUES (?, ?, 'http_download', 'error', ?, 1000, 1000)`).run(
+ `instance-${id}`,
+ id,
+ source
+ )
+ }
+ } finally {
+ db.close()
+ }
+}
+
+async function tasks(page: Page): Promise<DownloadTask[]> {
+ return page.evaluate(
+ (channel) => window.motrix.invoke(channel),
+ Queries.ListTasks
+ ) as Promise<DownloadTask[]>
+}
+
+async function taskNotifications(page: Page) {
+ const notifications = (await page.evaluate(
+ (channel) => window.motrix.invoke(channel),
+ Queries.ListNotifications
+ )) as AppNotification[]
+ return notifications.filter(
+ (notification) =>
+ notification.taskId && taskIds.includes(notification.taskId)
+ )
+}
+
+test('removed and cleared failed finalizations stay cancelled through two app restarts', async ({
+ userDataDir,
+ rpcPort,
+}) => {
+ test.setTimeout(120_000)
+ let app: ElectronApplication | undefined
+ try {
+ app = await launchMotrix({ userDataDir, rpcPort })
+ await waitForEngineReady(await app.firstWindow())
+ await app.close()
+ app = undefined
+ seedFailedTasks(userDataDir)
+
+ app = await launchMotrix({ userDataDir, rpcPort })
+ let page = await app.firstWindow()
+ await waitForEngineReady(page)
+ await expect
+ .poll(async () => (await tasks(page)).map((task) => task.id).sort())
+ .toEqual([...taskIds].sort())
+ const notifications = await taskNotifications(page)
+ await page.evaluate(
+ ({ channel, taskId }) =>
+ window.motrix.invoke(channel, {
+ taskId,
+ deleteWithFiles: false,
+ }),
+ { channel: Commands.RemoveTask, taskId: taskIds[0] }
+ )
+ await page.evaluate(
+ ({ channel, taskIds }) => window.motrix.invoke(channel, taskIds),
+ {
+ channel: Commands.ClearStoppedTasks,
+ taskIds: taskIds.slice(1),
+ }
+ )
+ await expect.poll(() => tasks(page)).toEqual([])
+ await app.close()
+ app = undefined
+
+ for (let restart = 0; restart < 2; restart++) {
+ app = await launchMotrix({ userDataDir, rpcPort })
+ page = await app.firstWindow()
+ await waitForEngineReady(page)
+ expect(await tasks(page)).toEqual([])
+ expect(await taskNotifications(page)).toEqual(notifications)
+ await app.close()
+ app = undefined
+ const db = new DatabaseSync(path.join(userDataDir, 'motrix.db'))
+ try {
+ const journals = db
+ .prepare(`SELECT task_id, phase, quarantine_reason
+ FROM plugin_finalize_journals ORDER BY task_id`)
+ .all()
+ expect(journals).toEqual(
+ ['finalize-bulk', 'finalize-legacy-orphan', 'finalize-single'].map(
+ (taskId) => ({
+ task_id: taskId,
+ phase: 'quarantined',
+ quarantine_reason: 'task-deleted',
+ })
+ )
+ )
+ expect(db.prepare('SELECT motrix_id FROM tasks').all()).toEqual([])
+ } finally {
+ db.close()
+ }
+ }
+ } finally {
+ await app?.close().catch(() => {})
+ }
+})
diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.ts
index 43558bd6..d949924c 100644
--- a/src/core/session/durable-finalize-runtime.ts
+++ b/src/core/session/durable-finalize-runtime.ts
@@ -29,6 +29,7 @@ import type { PostDeliveryAdmission } from '@core/plugin/post/delivery-types'
import type { DownloadTask } from '@shared/types/task'
import type { TaskOccurrence } from '@shared/types/task-occurrence'
import type Database from 'better-sqlite3'
+import { TASK_DELETED_FINALIZE_REASON } from './finalize-journal-lifecycle'
import { SqliteFinalizeJournalRepository } from './finalize-journal-repository'
import type { SessionManager } from './session-manager'
@@ -362,9 +363,10 @@ export class DurableFinalizeRuntime {
return (
this.options.db
.prepare(
- "SELECT 1 FROM plugin_finalize_journals WHERE task_id=? AND phase <> 'cleaned'"
+ `SELECT 1 FROM plugin_finalize_journals
+ WHERE task_id=? AND phase <> 'cleaned' AND quarantine_reason IS NOT ?`
)
- .get(taskId) !== undefined
+ .get(taskId, TASK_DELETED_FINALIZE_REASON) !== undefined
)
}
diff --git a/src/core/session/finalize-journal-deletion.integration.test.ts b/src/core/session/finalize-journal-deletion.integration.test.ts
new file mode 100644
index 00000000..69db7933
--- /dev/null
+++ b/src/core/session/finalize-journal-deletion.integration.test.ts
@@ -0,0 +1,437 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity/task-activity-service'
+import type { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'
+import type { EngineAdapter } from '@core/engine/engine-adapter'
+import type {
+ FinalizeArtifactOperations,
+ FinalizeJournalPhase,
+ FinalizeJournalRecord,
+} from '@core/plugin/finalize/finalize-committer'
+import { materializePostDeliveries } from '@core/plugin/post/delivery-materializer'
+import { TaskManager } from '@core/task/task-manager'
+import { TaskRecoveryServiceImpl } from '@core/task/task-recovery-service'
+import { TaskStatus, TransitionPhase } from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { DurableFinalizeRuntime } from './durable-finalize-runtime'
+import { TASK_DELETED_FINALIZE_REASON } from './finalize-journal-lifecycle'
+import { SqliteFinalizeJournalRepository } from './finalize-journal-repository'
+import { MotrixDatabase } from './motrix-database'
+import { SessionManager } from './session-manager'
+
+type Phase = FinalizeJournalPhase | 'quarantined'
+const phases: Phase[] = [
+ 'prepared',
+ 'target_staged',
+ 'source_preserved',
+ 'target_installed',
+ 'db_committed',
+ 'cleaned',
+ 'quarantined',
+]
+
+describe('task deletion and durable finalize recovery', () => {
+ const roots: string[] = []
+ const databases = new Set<MotrixDatabase>()
+
+ afterEach(async () => {
+ vi.restoreAllMocks()
+ for (const db of databases) db.close()
+ databases.clear()
+ await Promise.all(
+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))
+ )
+ })
+
+ async function fixture() {
+ const root = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-finalize-delete-')
+ )
+ roots.push(root)
+ const filename = path.join(root, 'motrix.db')
+ const open = () => {
+ const db = new MotrixDatabase(filename)
+ databases.add(db)
+ db.init()
+ const tasks = new TaskManager()
+ const rpc = {
+ tellActive: vi.fn(async () => []),
+ tellWaiting: vi.fn(async () => []),
+ tellStopped: vi.fn(async () => []),
+ } as unknown as Aria2RpcClient
+ const session = new SessionManager(tasks, rpc, db, {} as EngineAdapter)
+ const fs = {
+ identity: vi.fn(async () => null),
+ sameFilesystem: vi.fn(async () => false),
+ materializePrivate: vi.fn(),
+ makeDurable: vi.fn(),
+ moveNoReplace: vi.fn(),
+ removeKnown: vi.fn(),
+ } satisfies FinalizeArtifactOperations
+ const runtime = new DurableFinalizeRuntime({
+ db: db.database,
+ session,
+ fs,
+ })
+ const journals = new SqliteFinalizeJournalRepository(db.database, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ return { db, tasks, session, runtime, journals, fs }
+ }
+ return { root, open, ...open() }
+ }
+
+ function close(db: MotrixDatabase) {
+ db.close()
+ databases.delete(db)
+ }
+
+ async function seed(
+ f: Awaited<ReturnType<typeof fixture>>,
+ id: string,
+ phase: Phase
+ ) {
+ const sourcePath = path.join(f.root, `${id}.motrix`)
+ const targetPath = path.join(f.root, id)
+ const task = makeDownloadTask({
+ id,
+ engineTaskId: '',
+ status: TaskStatus.Error,
+ transitionPhase: TransitionPhase.Renaming,
+ name: id,
+ saveDir: f.root,
+ diskPath: sourcePath,
+ finalPath: targetPath,
+ filename: id,
+ finalName: id,
+ createdAt: 1_000,
+ updatedAt: 1_000,
+ })
+ await f.session.persistTask(task)
+ const record: FinalizeJournalRecord = {
+ journalId: `plan-${id}`,
+ phase: phase === 'quarantined' ? 'prepared' : phase,
+ plan: {
+ planId: `plan-${id}`,
+ taskId: id,
+ saveDir: f.root,
+ sourcePath,
+ targetPath,
+ sourceIdentity: {
+ kind: 'file',
+ size: 1,
+ sha256: 'a'.repeat(64),
+ platformFileId: `file-${id}`,
+ },
+ metadataOps: [],
+ contributors: [],
+ },
+ rollbackPath: path.join(f.root, `${id}.rollback`),
+ privateTargetPath: path.join(f.root, `${id}.private`),
+ }
+ // Preserve real checkpoint bytes, including the original phase and paths,
+ // even when the database phase changes to a terminal cancellation.
+ f.db.database
+ .prepare(
+ `INSERT INTO plugin_finalize_journals (
+ plan_id, task_id, phase, plan_json, source_identity_json,
+ quarantine_reason, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, 1000, 1000)`
+ )
+ .run(
+ record.journalId,
+ id,
+ phase,
+ JSON.stringify(record),
+ JSON.stringify(record.plan.sourceIdentity),
+ phase === 'quarantined' ? 'compensation failed after rename' : null
+ )
+ return { task, record }
+ }
+
+ function rawJournal(db: MotrixDatabase, id: string) {
+ return db.database
+ .prepare('SELECT * FROM plugin_finalize_journals WHERE task_id=?')
+ .get(id)
+ }
+
+ function postState(db: MotrixDatabase) {
+ return {
+ deliveries: db.database
+ .prepare('SELECT * FROM plugin_post_deliveries')
+ .all(),
+ ledger: db.database
+ .prepare('SELECT * FROM plugin_post_quota_ledger')
+ .all(),
+ }
+ }
+
+ for (const deletion of ['single', 'bulk'] as const) {
+ it.each(phases)(
+ `${deletion} deletion stops %s recovery across restarts`,
+ async (phase) => {
+ const f = await fixture()
+ const { record } = await seed(f, 'deleted', phase)
+ const paths = [
+ record.plan.sourcePath,
+ record.plan.targetPath,
+ record.rollbackPath!,
+ record.privateTargetPath!,
+ ]
+ for (const file of paths) await writeFile(file, `preserve:${file}`)
+ f.db.durablePostDeliveries.admitMany([postAdmission('deleted')])
+ const posts = postState(f.db)
+ const before = rawJournal(f.db, 'deleted') as Record<string, unknown>
+
+ if (deletion === 'single') f.db.deleteTask('deleted')
+ else f.db.deleteTasks(['deleted', 'deleted'])
+
+ expect(f.db.getTask('deleted')).toBeNull()
+ expect(await f.runtime.hasPendingFinalization('deleted')).toBe(false)
+ expect(postState(f.db)).toEqual(posts)
+ if (phase === 'cleaned') {
+ expect(rawJournal(f.db, 'deleted')).toBeUndefined()
+ } else {
+ expect(rawJournal(f.db, 'deleted')).toEqual({
+ ...before,
+ phase: 'quarantined',
+ quarantine_reason: TASK_DELETED_FINALIZE_REASON,
+ updated_at: expect.any(Number),
+ })
+ }
+ close(f.db)
+
+ // Both hosts open MotrixDatabase before filesystem/session recovery.
+ // Exercise that order twice, using a real SQLite file and empty engine.
+ for (let restart = 0; restart < 2; restart++) {
+ const current = f.open()
+ await current.runtime.recoverAll()
+ await current.session.restore()
+ const finalizeTask = vi.fn()
+ const persist = vi.fn()
+ const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+ const recovery = new TaskRecoveryServiceImpl({
+ taskManager: { getAll: () => current.tasks.getAll(), persist },
+ adapter: { listActiveAndWaiting: vi.fn(async () => []) },
+ fs: {
+ pathExists: vi.fn(),
+ renameAtomic: vi.fn(),
+ removePathRecursive: vi.fn(),
+ },
+ activityRecorder: NOOP_TASK_ACTIVITY_RECORDER,
+ finalizeTask,
+ hasPendingFinalization: (id) =>
+ current.runtime.hasPendingFinalization(id),
+ log,
+ })
+ expect(await recovery.recoverOnStartup()).toMatchObject({
+ totalScanned: 0,
+ errors: [],
+ warnings: [],
+ })
+ expect(current.tasks.getAll()).toEqual([])
+ expect(current.db.getAllTasks()).toEqual([])
+ expect(await current.runtime.hasPendingFinalization('deleted')).toBe(
+ false
+ )
+ expect(await current.journals.listRecoverable()).toEqual([])
+ expect(await current.journals.listRecoverable('deleted')).toEqual([])
+ for (const operation of Object.values(current.fs))
+ expect(operation).not.toHaveBeenCalled()
+ expect(finalizeTask).not.toHaveBeenCalled()
+ expect(persist).not.toHaveBeenCalled()
+ expect(log.error).not.toHaveBeenCalled()
+ expect(postState(current.db)).toEqual(posts)
+ close(current.db)
+ }
+ for (const file of paths)
+ expect(await readFile(file, 'utf8')).toBe(`preserve:${file}`)
+ }
+ )
+
+ it(`${deletion} deletion rolls journal changes back with a failed parent delete`, async () => {
+ const f = await fixture()
+ await seed(f, 'unfinished', 'source_preserved')
+ await seed(f, 'finished', 'cleaned')
+ const before = f.db.database
+ .prepare('SELECT * FROM plugin_finalize_journals ORDER BY task_id')
+ .all()
+ f.db.database.exec(`CREATE TRIGGER reject_task_delete BEFORE DELETE ON tasks
+ WHEN OLD.motrix_id='${deletion === 'single' ? 'unfinished' : 'finished'}'
+ BEGIN SELECT RAISE(ABORT, 'delete failed'); END`)
+ expect(() =>
+ deletion === 'single'
+ ? f.db.deleteTask('unfinished')
+ : f.db.deleteTasks(['unfinished', 'finished'])
+ ).toThrow('delete failed')
+ expect(f.db.getAllTasks()).toHaveLength(2)
+ expect(
+ f.db.database
+ .prepare('SELECT * FROM plugin_finalize_journals ORDER BY task_id')
+ .all()
+ ).toEqual(before)
+ expect(await f.runtime.hasPendingFinalization('unfinished')).toBe(true)
+ })
+
+ it(`${deletion} deletion preserves journals owned by other tasks`, async () => {
+ const f = await fixture()
+ await seed(f, 'removed-pending', 'prepared')
+ await seed(f, 'removed-cleaned', 'cleaned')
+ await seed(f, 'kept-pending', 'prepared')
+ await seed(f, 'kept-cleaned', 'cleaned')
+ const pending = rawJournal(f.db, 'kept-pending')
+ const cleaned = rawJournal(f.db, 'kept-cleaned')
+ if (deletion === 'single') {
+ f.db.deleteTask('removed-pending')
+ f.db.deleteTask('removed-cleaned')
+ } else {
+ f.db.deleteTasks(['removed-pending', 'removed-cleaned'])
+ }
+ expect(rawJournal(f.db, 'removed-cleaned')).toBeUndefined()
+ expect(await f.runtime.hasPendingFinalization('removed-pending')).toBe(
+ false
+ )
+ expect(rawJournal(f.db, 'kept-pending')).toEqual(pending)
+ expect(rawJournal(f.db, 'kept-cleaned')).toEqual(cleaned)
+ expect(await f.runtime.hasPendingFinalization('kept-pending')).toBe(true)
+ expect(
+ f.db
+ .getAllTasks()
+ .map((pair) => pair.task.motrixId)
+ .sort()
+ ).toEqual(['kept-cleaned', 'kept-pending'])
+ })
+ }
+
+ it('repairs legacy orphans, preserves live owners and malformed evidence, and is idempotent', async () => {
+ const f = await fixture()
+ for (const phase of phases) await seed(f, phase, phase)
+ await seed(f, 'live', 'prepared')
+ await seed(f, 'malformed', 'prepared')
+ f.db.database
+ .prepare(
+ "UPDATE plugin_finalize_journals SET plan_json='{}' WHERE task_id='malformed'"
+ )
+ .run()
+ const live = rawJournal(f.db, 'live')
+ // Simulate a database written by a version that omitted journal cleanup.
+ f.db.database.prepare("DELETE FROM tasks WHERE motrix_id <> 'live'").run()
+ close(f.db)
+ const current = f.open()
+ expect(rawJournal(current.db, 'cleaned')).toBeUndefined()
+ for (const phase of phases.filter((phase) => phase !== 'cleaned')) {
+ expect(rawJournal(current.db, phase)).toMatchObject({
+ phase: 'quarantined',
+ quarantine_reason: TASK_DELETED_FINALIZE_REASON,
+ })
+ expect(await current.runtime.hasPendingFinalization(phase)).toBe(false)
+ }
+ expect(rawJournal(current.db, 'malformed')).toMatchObject({
+ plan_json: '{}',
+ quarantine_reason: TASK_DELETED_FINALIZE_REASON,
+ })
+ expect(rawJournal(current.db, 'live')).toEqual(live)
+ expect(await current.runtime.hasPendingFinalization('live')).toBe(true)
+ expect(
+ (await current.journals.listRecoverable()).map((row) => row.plan.taskId)
+ ).toEqual(['live'])
+ const repaired = current.db.database
+ .prepare('SELECT * FROM plugin_finalize_journals ORDER BY task_id')
+ .all()
+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 10_000)
+ current.db.init()
+ expect(
+ current.db.database
+ .prepare('SELECT * FROM plugin_finalize_journals ORDER BY task_id')
+ .all()
+ ).toEqual(repaired)
+ })
+
+ it('does not let a late recovery error reopen a deleted task journal', async () => {
+ const f = await fixture()
+ const { record } = await seed(f, 'deleted', 'prepared')
+ f.db.deleteTask('deleted')
+ const cancelled = rawJournal(f.db, 'deleted')
+ await f.journals.quarantine(
+ record.journalId,
+ 'compensation failed after rename'
+ )
+ expect(rawJournal(f.db, 'deleted')).toEqual(cancelled)
+ expect(await f.journals.listRecoverable()).toEqual([])
+ await expect(
+ f.journals.advance(record.journalId, 'cleaned')
+ ).rejects.toThrow('quarantined')
+ await expect(f.journals.prepare(record)).rejects.toThrow(
+ 'unfinished finalize journal'
+ )
+ })
+
+ it('keeps independent post delivery claimable after deleting its task', async () => {
+ const f = await fixture()
+ await seed(f, 'deleted', 'quarantined')
+ f.db.durablePostDeliveries.admitMany([postAdmission('deleted')])
+ f.db.deleteTask('deleted')
+ const claim = await f.db.durablePostDeliveries.claimNextForPlugin({
+ pluginId: 'plugin.example',
+ now: 1_000,
+ leaseToken: 'lease',
+ leaseExpiresAt: 2_000,
+ maxAttempts: 12,
+ maxActiveAgeMs: 86_400_000,
+ })
+ expect(claim).toMatchObject({ taskId: 'deleted', status: 'delivering' })
+ })
+})
+
+function postAdmission(taskId: string) {
+ return materializePostDeliveries({
+ event: {
+ schemaVersion: 1,
+ occurrenceId: `occ-${taskId}`,
+ taskId,
+ occurredAt: 1_000,
+ payload: {
+ filePath: '/downloads/output.bin',
+ task: {
+ schemaVersion: 1,
+ id: taskId,
+ name: 'output.bin',
+ type: 'http',
+ kind: 'direct',
+ status: 'completed',
+ filePath: '/downloads/output.bin',
+ saveDir: '/downloads',
+ filename: 'output.bin',
+ progress: 100,
+ totalBytes: 1,
+ downloadedBytes: 1,
+ uploadedBytes: 0,
+ sizeWhenDone: 1,
+ fileCount: 1,
+ createdAt: 1_000,
+ updatedAt: 1_000,
+ finishedAt: 1_000,
+ category: null,
+ infoHash: null,
+ error: null,
+ },
+ },
+ },
+ candidates: [
+ {
+ hook: 'afterComplete',
+ executable: {
+ pluginId: 'plugin.example',
+ version: '1.0.0',
+ digest: 'a'.repeat(64),
+ },
+ createdGeneration: 1,
+ requiredPermissions: [],
+ createdEffectivePermissions: [],
+ },
+ ],
+ createdAt: 1_000,
+ })[0]
+}
diff --git a/src/core/session/finalize-journal-lifecycle.ts b/src/core/session/finalize-journal-lifecycle.ts
new file mode 100644
index 00000000..63ed7471
--- /dev/null
+++ b/src/core/session/finalize-journal-lifecycle.ts
@@ -0,0 +1,51 @@
+import type Database from 'better-sqlite3'
+
+export const TASK_DELETED_FINALIZE_REASON = 'task-deleted'
+
+/** Deleting a task revokes recovery authority without discarding unknown bytes. */
+export class FinalizeJournalLifecycle {
+ private readonly deleteCleaned: Database.Statement
+ private readonly cancelUnfinished: Database.Statement
+
+ constructor(private readonly db: Database.Database) {
+ this.deleteCleaned = db.prepare(
+ "DELETE FROM plugin_finalize_journals WHERE task_id=? AND phase='cleaned'"
+ )
+ this.cancelUnfinished = db.prepare(
+ `UPDATE plugin_finalize_journals
+ SET phase='quarantined', quarantine_reason=?, updated_at=?
+ WHERE task_id=? AND phase <> 'cleaned' AND quarantine_reason IS NOT ?`
+ )
+ }
+
+ /** Must commit or roll back together with the parent deletion. */
+ cancelTask(taskId: string): void {
+ if (!this.db.inTransaction)
+ throw new Error('finalize cancellation requires the task transaction')
+ this.deleteCleaned.run(taskId)
+ // Keep the original plan, phase checkpoint and artifact identities. A
+ // rollback/private path may hold the only surviving copy of user data.
+ // This quarantine is terminal: neither recovery nor retry may reopen it.
+ this.cancelUnfinished.run(
+ TASK_DELETED_FINALIZE_REASON,
+ Date.now(),
+ taskId,
+ TASK_DELETED_FINALIZE_REASON
+ )
+ }
+
+ /** Repair journals left by older builds before either shell starts recovery. */
+ cancelOrphans(): void {
+ this.db.transaction(() => {
+ const orphans = this.db
+ .prepare(
+ `SELECT task_id FROM plugin_finalize_journals AS journal
+ WHERE quarantine_reason IS NOT ? AND NOT EXISTS (
+ SELECT 1 FROM tasks WHERE motrix_id=journal.task_id
+ )`
+ )
+ .all(TASK_DELETED_FINALIZE_REASON) as { task_id: string }[]
+ for (const orphan of orphans) this.cancelTask(orphan.task_id)
+ })()
+ }
+}
diff --git a/src/core/session/finalize-journal-repository.ts b/src/core/session/finalize-journal-repository.ts
index d3018e16..e879ceee 100644
--- a/src/core/session/finalize-journal-repository.ts
+++ b/src/core/session/finalize-journal-repository.ts
@@ -21,6 +21,7 @@ import {
} from '@core/plugin/finalize/reserved-identity'
import type Database from 'better-sqlite3'
import { z } from 'zod'
+import { TASK_DELETED_FINALIZE_REASON } from './finalize-journal-lifecycle'
interface RawFinalizeJournal {
plan_id: string
@@ -238,9 +239,14 @@ export class SqliteFinalizeJournalRepository
.prepare(
`UPDATE plugin_finalize_journals
SET phase='quarantined', quarantine_reason=?, updated_at=?
- WHERE plan_id=? AND phase <> 'cleaned'`
+ WHERE plan_id=? AND phase <> 'cleaned' AND quarantine_reason IS NOT ?`
)
- .run(boundedReason, Math.max(1, this.now()), journalId).changes
+ .run(
+ boundedReason,
+ Math.max(1, this.now()),
+ journalId,
+ TASK_DELETED_FINALIZE_REASON
+ ).changes
if (changed === 0) {
const row = this.readRaw(journalId)
if (!row) throw new Error('finalize journal does not exist')
@@ -255,9 +261,14 @@ export class SqliteFinalizeJournalRepository
.prepare(
`SELECT * FROM plugin_finalize_journals
WHERE phase <> 'cleaned' AND (? IS NULL OR task_id=?)
+ AND quarantine_reason IS NOT ?
ORDER BY created_at, plan_id`
)
- .all(taskId ?? null, taskId ?? null) as RawFinalizeJournal[]
+ .all(
+ taskId ?? null,
+ taskId ?? null,
+ TASK_DELETED_FINALIZE_REASON
+ ) as RawFinalizeJournal[]
const records: FinalizeJournalRecord[] = []
for (const row of rows) {
try {
diff --git a/src/core/session/motrix-database.ts b/src/core/session/motrix-database.ts
index 42258c73..47ae0fcf 100644
--- a/src/core/session/motrix-database.ts
+++ b/src/core/session/motrix-database.ts
@@ -37,6 +37,7 @@ import type {
import type BetterSqlite3 from 'better-sqlite3'
import Database from 'better-sqlite3'
import { z } from 'zod'
+import { FinalizeJournalLifecycle } from './finalize-journal-lifecycle'
import { migrate } from './migrations'
import { SqlitePostDeliveryRepository } from './post-delivery-repository'
@@ -238,6 +239,7 @@ export class MotrixDatabase {
// keeps it fail-safe: a stale-or-missing entry forces a write, never a skip.
private readonly lastPersistedSig = new Map<string, string>()
private postDeliveryRepository?: SqlitePostDeliveryRepository
+ private finalizeJournalLifecycle!: FinalizeJournalLifecycle
// ── task-level statements ─────────────────────────────
private stmtUpsertTask!: BetterSqlite3.Statement
private stmtGetAllTasks!: BetterSqlite3.Statement
@@ -292,6 +294,8 @@ export class MotrixDatabase {
init(): void {
migrate(this.db)
ensureMetadataSchema(this.db)
+ this.finalizeJournalLifecycle = new FinalizeJournalLifecycle(this.db)
+ this.finalizeJournalLifecycle.cancelOrphans()
this.prepareStatements()
this.postDeliveryRepository = new SqlitePostDeliveryRepository(this.db)
}
@@ -699,7 +703,10 @@ export class MotrixDatabase {
// gets the same explicit delete for the same reason — its rows carry
// no FK either. The notifications DISPLAY rows are deliberately left
// alone: they are user-facing history and must survive task deletion.
+ // Finalize recovery loses its authority with the task. Post-Hook delivery
+ // snapshots and their quota ledger deliberately survive (runtime §11).
this.db.transaction(() => {
+ this.finalizeJournalLifecycle.cancelTask(motrixId)
this.stmtDeleteFiles.run(motrixId)
this.stmtDeleteTaskOccurrences.run(motrixId)
this.stmtDeleteNotificationLedgerForTask.run(motrixId)
@@ -719,6 +726,7 @@ export class MotrixDatabase {
this.db.transaction(() => {
for (const motrixId of ids) {
+ this.finalizeJournalLifecycle.cancelTask(motrixId)
// FOREIGN KEY ON DELETE CASCADE removes task_instances. task_files,
// task_occurrences, and notification_occurrences have no such FK,
// so all three are deleted explicitly, in the same transaction as