Skip to content

A full-featured download manager.

fix(session): persist an empty engine gid as NULL (#2386)

Muhammad Saad Khalidd260f6c0b74c
diff --git a/src/core/session/migrations/index.ts b/src/core/session/migrations/index.ts
index 76510607..144f3b0e 100644
--- a/src/core/session/migrations/index.ts
+++ b/src/core/session/migrations/index.ts
@@ -12,6 +12,7 @@ import { V5_TASK_SCHEMA_OBJECTS, v5 } from './v5'
import { V6_SCHEMA_OBJECTS, v6 } from './v6'
import { V7_SCHEMA_OBJECTS, v7 } from './v7'
import { V8_SCHEMA_OBJECTS, v8 } from './v8'
+import { v9 } from './v9'
interface Migration {
version: number
@@ -27,8 +28,11 @@ interface Migration {
// durable plugin finalize journals plus post-delivery and quota state. v5
// persists the user-selected save directory independently of engine paths and
// repairs stale instance statuses beneath terminal tasks. v6 adds independent
-// seeding-time counters without inventing pre-upgrade history.
-const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5, v6, v7, v8]
+// seeding-time counters without inventing pre-upgrade history. v7 persists
+// task tracker state, v8 adds the legacy-import ledger, and v9 clears the
+// empty-string `task_instances.gid` rows that previously poisoned the global
+// UNIQUE(gid) index.
+const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5, v6, v7, v8, v9]
const HIGHEST_KNOWN_VERSION = MIGRATIONS.reduce(
(max, m) => (m.version > max ? m.version : max),
diff --git a/src/core/session/migrations/v1.test.ts b/src/core/session/migrations/v1.test.ts
index ccd4deca..8040a6d5 100644
--- a/src/core/session/migrations/v1.test.ts
+++ b/src/core/session/migrations/v1.test.ts
@@ -468,7 +468,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {
version INTEGER PRIMARY KEY,
applied_at INTEGER NOT NULL
);
- INSERT INTO schema_version (version, applied_at) VALUES (9, 0);
+ INSERT INTO schema_version (version, applied_at) VALUES (10, 0);
CREATE TABLE task_metadata (motrix_id TEXT PRIMARY KEY);
`)
@@ -524,7 +524,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {
const rows = db
.prepare('SELECT version FROM schema_version ORDER BY version')
.all() as Array<{ version: number }>
- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9])
db.close()
})
@@ -543,7 +543,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {
// Inspector Activity persistence, and v4 adds durable Hook delivery and
// finalize journals. V5 repairs terminal instances and v6 tracks seeding time.
// All apply on a fresh DB.
- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9])
const tables = db
.prepare("SELECT name FROM sqlite_master WHERE type='table'")
diff --git a/src/core/session/migrations/v3.test.ts b/src/core/session/migrations/v3.test.ts
index ef344006..a4d8ceb8 100644
--- a/src/core/session/migrations/v3.test.ts
+++ b/src/core/session/migrations/v3.test.ts
@@ -110,7 +110,7 @@ describe('migration v3 compatibility', () => {
const db = openMemory()
migrate(db)
- expect(readVersion(db)).toBe(8)
+ expect(readVersion(db)).toBe(9)
const names = db
.prepare(
`SELECT name FROM sqlite_master
@@ -166,7 +166,7 @@ describe('migration v3 compatibility', () => {
const reopened = new Database(dbPath)
reopened.pragma('foreign_keys = ON')
- expect(readVersion(reopened)).toBe(8)
+ expect(readVersion(reopened)).toBe(9)
expect(
reopened
.prepare("SELECT motrix_id FROM tasks WHERE motrix_id = 'survivor'")
@@ -207,7 +207,7 @@ describe('migration v3 compatibility', () => {
})()
expect(() => migrate(db)).not.toThrow()
- expect(readVersion(db)).toBe(8)
+ expect(readVersion(db)).toBe(9)
db.close()
})
diff --git a/src/core/session/migrations/v4.test.ts b/src/core/session/migrations/v4.test.ts
index 20797f85..6329eff2 100644
--- a/src/core/session/migrations/v4.test.ts
+++ b/src/core/session/migrations/v4.test.ts
@@ -40,7 +40,7 @@ describe('migration v4', () => {
const db = openMemory()
migrate(db)
- expect(readVersion(db)).toBe(8)
+ expect(readVersion(db)).toBe(9)
const rows = db
.prepare(
`SELECT name FROM sqlite_master
@@ -68,7 +68,7 @@ describe('migration v4', () => {
migrate(db)
- expect(readVersion(db)).toBe(8)
+ expect(readVersion(db)).toBe(9)
expect(
db.prepare("SELECT name FROM tasks WHERE motrix_id = 'survivor'").get()
).toEqual({ name: 'fixture' })
diff --git a/src/core/session/migrations/v5.test.ts b/src/core/session/migrations/v5.test.ts
index 0f532255..af7ebce6 100644
--- a/src/core/session/migrations/v5.test.ts
+++ b/src/core/session/migrations/v5.test.ts
@@ -111,7 +111,7 @@ describe('task recovery migration v5', () => {
expect(db.prepare('SELECT total_changes() AS count').get()).toEqual(changes)
expect(
db.prepare('SELECT version FROM schema_version ORDER BY version').all()
- ).toEqual([1, 2, 3, 4, 5, 6, 7, 8].map((version) => ({ version })))
+ ).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9].map((version) => ({ version })))
db.close()
})
})
diff --git a/src/core/session/migrations/v9.test.ts b/src/core/session/migrations/v9.test.ts
new file mode 100644
index 00000000..c26a7f01
--- /dev/null
+++ b/src/core/session/migrations/v9.test.ts
@@ -0,0 +1,67 @@
+import Database from 'better-sqlite3'
+import { describe, expect, it } from 'vitest'
+import { migrate } from '.'
+import { v1 } from './v1'
+import { v2 } from './v2'
+import { v3 } from './v3'
+import { v4 } from './v4'
+import { v5 } from './v5'
+import { v6 } from './v6'
+import { v7 } from './v7'
+import { v8 } from './v8'
+import { v9 } from './v9'
+
+describe('empty-gid repair migration v9', () => {
+ it('clears legacy empty-string task_instances.gid rows to NULL', () => {
+ const db = new Database(':memory:')
+ db.pragma('foreign_keys = ON')
+ db.exec(`CREATE TABLE schema_version (
+ version INTEGER PRIMARY KEY,
+ applied_at INTEGER NOT NULL
+ )`)
+ for (const migration of [v1, v2, v3, v4, v5, v6, v7, v8]) {
+ migration.up(db)
+ db.prepare('INSERT INTO schema_version VALUES (?, 1)').run(
+ migration.version
+ )
+ }
+ db.exec(
+ "INSERT INTO tasks (motrix_id,name,task_type,created_at,updated_at) VALUES ('t1','one','http',1,1)"
+ )
+ // The poisoned row: an empty string occupies the global UNIQUE(gid) slot.
+ db.exec(
+ `INSERT INTO task_instances (
+ instance_id,motrix_id,gid,phase,status,progress,total_bytes,
+ downloaded_bytes,uploaded_bytes,disk_path,transition_phase,uris,
+ uri_hash,payload,created_at,updated_at
+ ) VALUES ('seg:t1','t1','','hls_segment','completed',0,0,0,0,'','idle','[]',null,'{}',1,1)`
+ )
+
+ migrate(db)
+
+ const row = db
+ .prepare("SELECT gid FROM task_instances WHERE instance_id='seg:t1'")
+ .get() as { gid: string | null }
+ expect(row.gid).toBeNull()
+ // The freed slot means other empty-gid rows can now be inserted.
+ expect(() =>
+ db
+ .prepare(
+ `INSERT INTO task_instances (
+ instance_id,motrix_id,gid,phase,status,progress,total_bytes,
+ downloaded_bytes,uploaded_bytes,disk_path,transition_phase,uris,
+ uri_hash,payload,created_at,updated_at
+ ) VALUES ('seg:t1b','t1','','ffmpeg_mux','completed',0,0,0,0,'','idle','[]',null,'{}',1,1)`
+ )
+ .run()
+ ).not.toThrow()
+ // v9 is data-only: the chain records it, so a second migrate() is a noop.
+ expect(
+ db.prepare('SELECT MAX(version) AS v FROM schema_version').get()
+ ).toEqual({ v: 9 })
+ expect(() => migrate(db)).not.toThrow()
+ expect(() => v9.up(db)).not.toThrow()
+ expect(db.prepare('PRAGMA foreign_key_check').all()).toEqual([])
+ db.close()
+ })
+})
diff --git a/src/core/session/migrations/v9.ts b/src/core/session/migrations/v9.ts
new file mode 100644
index 00000000..f92ec077
--- /dev/null
+++ b/src/core/session/migrations/v9.ts
@@ -0,0 +1,26 @@
+import type Database from 'better-sqlite3'
+
+/**
+ * v9 repairs the `task_instances.gid` "empty string" defect.
+ *
+ * `gid` is a globally UNIQUE, nullable column: the absence of an engine gid is
+ * represented by NULL. Older writers (a synthesized primary instance copying
+ * an empty `task.engineTaskId`, and any in-memory instance carrying `''`)
+ * stored the empty string instead. Because SQLite treats `''` as an ordinary
+ * value, the first such row permanently occupied the single `''` slot in the
+ * UNIQUE index, so every later task with an empty-gid instance (HLS segment,
+ * mux, subtitle, …) failed to persist with
+ * `SQLITE_CONSTRAINT_UNIQUE: task_instances.gid`, taking the whole
+ * `saveTasksBatch` transaction — and thus the task's durability — down with it.
+ *
+ * The forward fix normalizes `'' -> NULL` at the persistence boundary
+ * (`MotrixDatabase.serializeInstance`) and on read (`mapInstanceRow`). This
+ * migration clears the rows already on disk so the poisoned slot is freed
+ * immediately rather than only once the owning task is next written.
+ */
+export const v9 = {
+ version: 9,
+ up(db: Database.Database): void {
+ db.prepare("UPDATE task_instances SET gid = NULL WHERE gid = ''").run()
+ },
+}
diff --git a/src/core/session/motrix-database.test.ts b/src/core/session/motrix-database.test.ts
index f2b65544..3341009d 100644
--- a/src/core/session/motrix-database.test.ts
+++ b/src/core/session/motrix-database.test.ts
@@ -169,6 +169,89 @@ describe('saveTaskWithInstances + getAllTasks (Plan A v1 schema)', () => {
db.close()
})
+ it('persists empty-string instance gids as NULL so no-gid instances never collide', () => {
+ const db = new MotrixDatabase(':memory:')
+ db.init()
+
+ // Two independent tasks, each carrying a no-engine-gid instance passed as
+ // '' (the shape the HLS/mux and synthesized-primary writers produced).
+ // `gid` is globally UNIQUE and only tolerates multiple NULLs, so '' must be
+ // normalized before the insert or the second task fails to persist with
+ // SQLITE_CONSTRAINT_UNIQUE.
+ db.saveTaskWithInstances({
+ task: makeTaskRow('m-empty-a', TaskKind.Hls),
+ instances: [
+ makeInstanceRow('seg-a', 'm-empty-a', '', TaskInstancePhase.HlsSegment),
+ ],
+ })
+
+ expect(() =>
+ db.saveTaskWithInstances({
+ task: makeTaskRow('m-empty-b', TaskKind.Hls),
+ instances: [
+ makeInstanceRow(
+ 'seg-b',
+ 'm-empty-b',
+ '',
+ TaskInstancePhase.HlsSegment
+ ),
+ ],
+ })
+ ).not.toThrow()
+
+ const rawEmpty = db
+ .getRawForTesting()
+ .prepare("SELECT COUNT(*) AS c FROM task_instances WHERE gid = ''")
+ .get() as { c: number }
+ expect(rawEmpty.c).toBe(0)
+ expect(
+ db
+ .getAllTasks()
+ .flatMap((t) => t.instances)
+ .map((i) => i.gid)
+ ).toEqual([null, null])
+
+ db.close()
+ })
+
+ it('heals a legacy empty-string gid row to NULL on read and rewrite', () => {
+ const db = new MotrixDatabase(':memory:')
+ db.init()
+ db.saveTaskWithInstances({
+ task: makeTaskRow('m-legacy', TaskKind.Hls),
+ instances: [
+ makeInstanceRow(
+ 'seg-legacy',
+ 'm-legacy',
+ null,
+ TaskInstancePhase.HlsSegment
+ ),
+ ],
+ })
+ // Simulate a row persisted before the normalization existed.
+ db.getRawForTesting()
+ .prepare(
+ "UPDATE task_instances SET gid = '' WHERE motrix_id = 'm-legacy'"
+ )
+ .run()
+
+ const loaded = db.getAllTasks()
+ expect(loaded[0].instances[0].gid).toBeNull()
+
+ // Re-writing the healed task clears the on-disk empty string as well.
+ db.saveTaskWithInstances({
+ task: loaded[0].task,
+ instances: loaded[0].instances,
+ })
+ const rawEmpty = db
+ .getRawForTesting()
+ .prepare("SELECT COUNT(*) AS c FROM task_instances WHERE gid = ''")
+ .get() as { c: number }
+ expect(rawEmpty.c).toBe(0)
+
+ db.close()
+ })
+
it('replaceInstances atomically swaps a task instance set', () => {
const db = new MotrixDatabase(':memory:')
db.init()
diff --git a/src/core/session/motrix-database.ts b/src/core/session/motrix-database.ts
index 34ca85da..42258c73 100644
--- a/src/core/session/motrix-database.ts
+++ b/src/core/session/motrix-database.ts
@@ -1355,7 +1355,12 @@ export class MotrixDatabase {
return {
instanceId: i.instanceId,
motrixId: i.motrixId,
- gid: i.gid,
+ // `gid` is globally UNIQUE and nullable: "no engine gid" MUST be NULL.
+ // An empty string is a real value to SQLite, so it would occupy the one
+ // '' slot for the whole table and make every other empty-gid instance
+ // (HLS segment/mux/etc.) fail to persist with SQLITE_CONSTRAINT_UNIQUE.
+ // Normalize '' — and any other falsy gid — to NULL at the boundary.
+ gid: i.gid ? i.gid : null,
phase: i.phase,
status: i.status,
progress: i.progress,
@@ -1500,7 +1505,11 @@ function mapInstanceRow(row: RawInstanceRow): TaskInstanceRow {
return {
instanceId: row.instance_id,
motrixId: row.motrix_id,
- gid: row.gid,
+ // Heal legacy rows written before the '' -> NULL normalization: a stored
+ // empty string means "no engine gid" and must surface as NULL in memory,
+ // otherwise it round-trips back into the UNIQUE(gid) column and re-poisons
+ // every later write. See serializeInstance.
+ gid: row.gid === '' ? null : row.gid,
phase: toInstancePhase(row.phase),
status: toTaskStatus(row.status),
progress: row.progress,
diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.ts
index f6450c4a..062d9928 100644
--- a/src/core/session/session-manager.ts
+++ b/src/core/session/session-manager.ts
@@ -2035,7 +2035,9 @@ function synthesizePrimaryInstance(
return {
instanceId: `synth:${task.id}`,
motrixId: task.id,
- gid: task.engineTaskId,
+ // task.engineTaskId defaults to '' (see makeDownloadTask); an empty engine
+ // gid must persist as NULL, not '' — see MotrixDatabase.serializeInstance.
+ gid: task.engineTaskId || null,
phase: isBtLike
? TaskInstancePhase.BtDownload
: TaskInstancePhase.HttpDownload,