imagegen-bridge-runtime 0.1.0

Provider orchestration and durable state for Imagegen Bridge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
//! Durable `SQLite` job state with conservative crash recovery.

use std::path::Path;

use imagegen_bridge_core::{
    BridgeError, ErrorCode, ImageJob, ImageJobProgress, ImageJobStatus, ImageJobSummary,
    ImageRequest, ImageResponse,
};
use sha2::{Digest as _, Sha256};
use tokio_rusqlite::{
    Connection, params,
    rusqlite::{
        OptionalExtension as _, TransactionBehavior, params_from_iter, types::Value as SqlValue,
    },
};

const CURRENT_MIGRATION: u32 = 3;
const ACTIVE_RESULT_RESERVE_BYTES: u64 = 256 * 1024;

/// Result of atomically submitting a durable job.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SqliteJobSubmission {
    /// Canonical durable job selected by the submission identity.
    pub job: ImageJob,
    /// Whether this call inserted and must schedule the job.
    pub created: bool,
}

/// Visibility constraint applied before durable history pagination.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ImageJobVisibility {
    /// Ordinary non-hidden history only.
    #[default]
    Active,
    /// Soft-deleted history only.
    Hidden,
    /// Both active and hidden history.
    All,
}

/// Server-side durable history filters applied before cursor pagination.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImageJobListFilter {
    /// Exclusive newest-first `(created,id)` cursor.
    pub before: Option<(u64, String)>,
    /// Maximum rows returned.
    pub limit: usize,
    /// Visibility selection.
    pub visibility: ImageJobVisibility,
    /// Optional lifecycle status.
    pub status: Option<ImageJobStatus>,
    /// Optional favorite state.
    pub favorite: Option<bool>,
    /// Optional case-insensitive literal prompt substring.
    pub search: Option<String>,
}

/// Read-only status of the durable job database schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SqliteJobSchemaStatus {
    /// Whether the database and migration table exist.
    pub initialized: bool,
    /// Highest applied migration.
    pub version: Option<u32>,
    /// Migration expected by this build.
    pub current_version: u32,
}

/// Redaction-safe aggregate state for the durable job database.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct SqliteJobStatistics {
    /// Total retained job rows, including soft-deleted history.
    pub total: u64,
    /// Jobs accepted but not yet claimed.
    pub queued: u64,
    /// Jobs currently recorded as running.
    pub running: u64,
    /// Successfully completed jobs.
    pub succeeded: u64,
    /// Jobs completed with a structured failure.
    pub failed: u64,
    /// Jobs cancelled before or during execution.
    pub cancelled: u64,
    /// Jobs conservatively marked after uncertain shutdown completion.
    pub interrupted: u64,
    /// Soft-deleted history rows.
    pub hidden: u64,
    /// Main `SQLite` database pages multiplied by page size, excluding WAL files.
    pub database_bytes: u64,
    /// Logical job-row bytes used for admission and retention accounting.
    pub logical_bytes: u64,
}

/// Inspects job storage without creating or migrating it.
pub async fn inspect_sqlite_job_schema(path: &Path) -> Result<SqliteJobSchemaStatus, BridgeError> {
    let metadata = match tokio::fs::symlink_metadata(path).await {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Ok(SqliteJobSchemaStatus {
                initialized: false,
                version: None,
                current_version: CURRENT_MIGRATION,
            });
        }
        Err(_) => return Err(job_error("could not inspect job database")),
    };
    if !metadata.file_type().is_file() {
        return Err(job_error("job database must be a regular file"));
    }
    let flags = tokio_rusqlite::rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY;
    let connection = Connection::open_with_flags(path, flags)
        .await
        .map_err(|_| job_error("could not open job database read-only"))?;
    let version = connection
        .call(|connection| {
            let exists: bool = connection.query_row(
                "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='job_schema_migrations')",
                [],
                |row| row.get(0),
            )?;
            if !exists {
                return Ok(None);
            }
            connection.query_row(
                "SELECT MAX(version) FROM job_schema_migrations",
                [],
                |row| row.get(0),
            )
        })
        .await
        .map_err(|_| job_error("could not inspect job database schema"))?;
    connection
        .close()
        .await
        .map_err(|_| job_error("could not close job database"))?;
    Ok(SqliteJobSchemaStatus {
        initialized: version.is_some(),
        version,
        current_version: CURRENT_MIGRATION,
    })
}

/// Durable job state used by the HTTP job manager and history index.
pub struct SqliteImageJobStore {
    connection: Connection,
}

enum CreateOutcome {
    Created(String),
    Replay(String),
    Conflict,
    Full,
}

impl std::fmt::Debug for SqliteImageJobStore {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SqliteImageJobStore")
            .finish_non_exhaustive()
    }
}

impl SqliteImageJobStore {
    /// Opens storage and applies idempotent migrations.
    pub async fn open(path: &Path) -> Result<Self, BridgeError> {
        match tokio::fs::symlink_metadata(path).await {
            Ok(metadata) if metadata.file_type().is_file() => {}
            Ok(_) => return Err(job_error("job database must be a regular file")),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(_) => return Err(job_error("could not inspect job database")),
        }
        let connection = Connection::open(path)
            .await
            .map_err(|_| job_error("could not open job database"))?;
        connection
            .call(|connection| {
                connection.execute_batch(
                    "PRAGMA journal_mode=WAL;
                     PRAGMA synchronous=FULL;
                     PRAGMA busy_timeout=5000;
                     PRAGMA foreign_keys=ON;
                     CREATE TABLE IF NOT EXISTS job_schema_migrations (
                       version INTEGER PRIMARY KEY,
                       applied_at INTEGER NOT NULL
                     );
                     CREATE TABLE IF NOT EXISTS image_jobs (
                       id TEXT PRIMARY KEY,
                       status TEXT NOT NULL CHECK(status IN ('queued','running','succeeded','failed','cancelled','interrupted')),
                       created_at INTEGER NOT NULL,
                       updated_at INTEGER NOT NULL,
                       started_at INTEGER,
                       completed_at INTEGER,
                       request_json TEXT NOT NULL,
                       prompt_search TEXT NOT NULL DEFAULT '',
                       progress_stage TEXT,
                       partial_images INTEGER NOT NULL DEFAULT 0,
                       response_json TEXT,
                       error_json TEXT,
                       cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1)),
                       favorite INTEGER NOT NULL DEFAULT 0 CHECK(favorite IN (0,1)),
                       deleted_at INTEGER
                     );
                     CREATE INDEX IF NOT EXISTS image_jobs_created_idx
                       ON image_jobs(created_at DESC, id DESC);
                     CREATE INDEX IF NOT EXISTS image_jobs_status_idx
                       ON image_jobs(status, created_at);
                     INSERT OR IGNORE INTO job_schema_migrations(version, applied_at)
                       VALUES (1, unixepoch());",
                )?;
                let transaction = connection.transaction()?;
                let has_prompt_search = transaction
                    .prepare("PRAGMA table_info(image_jobs)")?
                    .query_map([], |row| row.get::<_, String>(1))?
                    .collect::<Result<Vec<_>, _>>()?
                    .iter()
                    .any(|name| name == "prompt_search");
                if !has_prompt_search {
                    transaction.execute_batch(
                        "ALTER TABLE image_jobs ADD COLUMN prompt_search TEXT NOT NULL DEFAULT '';",
                    )?;
                }
                let prompts = {
                    let mut statement = transaction.prepare(
                        "SELECT id, COALESCE(json_extract(request_json, '$.prompt'), '')
                         FROM image_jobs WHERE prompt_search='' AND json_valid(request_json)",
                    )?;
                    statement
                        .query_map([], |row| {
                            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                        })?
                        .collect::<Result<Vec<_>, _>>()?
                };
                for (id, prompt) in prompts {
                    transaction.execute(
                        "UPDATE image_jobs SET prompt_search=?2 WHERE id=?1",
                        params![id, prompt.to_lowercase()],
                    )?;
                }
                transaction.execute_batch(
                    "CREATE INDEX IF NOT EXISTS image_jobs_history_idx
                       ON image_jobs(deleted_at, favorite, created_at DESC, id DESC);
                     INSERT OR IGNORE INTO job_schema_migrations(version, applied_at)
                       VALUES (2, unixepoch());",
                )?;
                let columns = transaction
                    .prepare("PRAGMA table_info(image_jobs)")?
                    .query_map([], |row| row.get::<_, String>(1))?
                    .collect::<Result<Vec<_>, _>>()?;
                if !columns.iter().any(|name| name == "auth_scope") {
                    transaction.execute_batch(
                        "ALTER TABLE image_jobs ADD COLUMN auth_scope TEXT NOT NULL
                           DEFAULT 'legacy-unowned';",
                    )?;
                }
                if !columns.iter().any(|name| name == "submission_key_hash") {
                    transaction.execute_batch(
                        "ALTER TABLE image_jobs ADD COLUMN submission_key_hash TEXT;",
                    )?;
                }
                if !columns.iter().any(|name| name == "request_fingerprint") {
                    transaction.execute_batch(
                        "ALTER TABLE image_jobs ADD COLUMN request_fingerprint TEXT;",
                    )?;
                }
                transaction.execute_batch(
                    "CREATE INDEX IF NOT EXISTS image_jobs_scope_history_idx
                       ON image_jobs(auth_scope, deleted_at, favorite, created_at DESC, id DESC);
                     CREATE UNIQUE INDEX IF NOT EXISTS image_jobs_submission_idx
                       ON image_jobs(auth_scope, submission_key_hash)
                       WHERE submission_key_hash IS NOT NULL;
                     INSERT OR IGNORE INTO job_schema_migrations(version, applied_at)
                       VALUES (3, unixepoch());",
                )?;
                transaction.commit()?;
                Ok::<(), tokio_rusqlite::rusqlite::Error>(())
            })
            .await
            .map_err(|_| job_error("could not migrate job database"))?;
        Ok(Self { connection })
    }

    /// Closes the `SQLite` worker after pending calls finish.
    pub async fn close(self) -> Result<(), BridgeError> {
        self.connection
            .close()
            .await
            .map_err(|_| job_error("could not close job database"))
    }

    /// Inserts a queued request if bounded pending capacity remains.
    pub async fn create(
        &self,
        auth_scope: &str,
        id: &str,
        request: &ImageRequest,
        now: u64,
        max_pending: usize,
        max_database_bytes: u64,
    ) -> Result<SqliteJobSubmission, BridgeError> {
        validate_auth_scope(auth_scope)?;
        let mut persisted_request = request.clone();
        persisted_request.idempotency_key = None;
        let request_json = serde_json::to_string(&persisted_request)
            .map_err(|_| job_error("could not encode job request"))?;
        let prompt_search = request.prompt.to_lowercase();
        if let Some(key) = request.idempotency_key.as_deref() {
            validate_submission_key(key)?;
        }
        let submission_key_hash = request
            .idempotency_key
            .as_deref()
            .map(|key| base16ct::lower::encode_string(&Sha256::digest(key.as_bytes())));
        let request_fingerprint = submission_key_hash
            .as_ref()
            .map(|_| durable_request_fingerprint(request))
            .transpose()?;
        let auth_scope = auth_scope.to_owned();
        let lookup_scope = auth_scope.clone();
        let id = id.to_owned();
        let now = to_i64(now)?;
        let max_pending = i64::try_from(max_pending).unwrap_or(i64::MAX);
        let max_database_bytes = i64::try_from(max_database_bytes).unwrap_or(i64::MAX);
        let new_job_bytes = logical_new_job_bytes(
            &id,
            &auth_scope,
            &request_json,
            &prompt_search,
            submission_key_hash.as_deref(),
            request_fingerprint.as_deref(),
        )?;
        let outcome = self
            .connection
            .call(move |connection| {
                let transaction =
                    connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
                if let Some(key_hash) = submission_key_hash.as_deref() {
                    let existing: Option<(String, String)> = transaction
                        .query_row(
                            "SELECT id,request_fingerprint FROM image_jobs
                             WHERE auth_scope=?1 AND submission_key_hash=?2",
                            params![auth_scope, key_hash],
                            |row| Ok((row.get(0)?, row.get(1)?)),
                        )
                        .optional()?;
                    if let Some((existing_id, existing_fingerprint)) = existing {
                        return Ok(
                            if request_fingerprint.as_deref() == Some(existing_fingerprint.as_str())
                            {
                                CreateOutcome::Replay(existing_id)
                            } else {
                                CreateOutcome::Conflict
                            },
                        );
                    }
                }
                let pending: i64 = transaction.query_row(
                    "SELECT COUNT(*) FROM image_jobs WHERE status = 'queued'",
                    [],
                    |row| row.get(0),
                )?;
                if pending >= max_pending {
                    return Ok(CreateOutcome::Full);
                }
                let logical_bytes: i64 =
                    transaction.query_row(logical_bytes_query(), [], |row| row.get(0))?;
                if logical_bytes.saturating_add(new_job_bytes) > max_database_bytes {
                    return Ok(CreateOutcome::Full);
                }
                transaction.execute(
                    "INSERT INTO image_jobs(
                       id,status,created_at,updated_at,request_json,prompt_search,auth_scope,
                       submission_key_hash,request_fingerprint
                     ) VALUES (?1,'queued',?2,?2,?3,?4,?5,?6,?7)",
                    params![
                        id,
                        now,
                        request_json,
                        prompt_search,
                        auth_scope,
                        submission_key_hash,
                        request_fingerprint
                    ],
                )?;
                transaction.commit()?;
                Ok::<_, tokio_rusqlite::rusqlite::Error>(CreateOutcome::Created(id))
            })
            .await
            .map_err(|_| job_error("could not submit durable job"))?;
        let (lookup_id, created) = match outcome {
            CreateOutcome::Created(id) => (id, true),
            CreateOutcome::Replay(id) => (id, false),
            CreateOutcome::Conflict => {
                return Err(BridgeError::new(
                    ErrorCode::IdempotencyConflict,
                    "idempotency key was already used for a different request",
                ));
            }
            CreateOutcome::Full => {
                return Err(
                    BridgeError::new(ErrorCode::Overloaded, "durable job queue is full")
                        .retryable(true),
                );
            }
        };
        Ok(SqliteJobSubmission {
            job: self.get(lookup_scope.as_str(), lookup_id.as_str()).await?,
            created,
        })
    }

    /// Returns bounded aggregate counters without request, prompt, or path data.
    pub async fn statistics(&self) -> Result<SqliteJobStatistics, BridgeError> {
        self.connection
            .call(|connection| {
                let counts: (i64, i64, i64, i64, i64, i64, i64, i64) = connection.query_row(
                    "SELECT COUNT(*),
                            COALESCE(SUM(status='queued'),0),
                            COALESCE(SUM(status='running'),0),
                            COALESCE(SUM(status='succeeded'),0),
                            COALESCE(SUM(status='failed'),0),
                            COALESCE(SUM(status='cancelled'),0),
                            COALESCE(SUM(status='interrupted'),0),
                            COALESCE(SUM(deleted_at IS NOT NULL),0)
                     FROM image_jobs",
                    [],
                    |row| {
                        Ok((
                            row.get(0)?,
                            row.get(1)?,
                            row.get(2)?,
                            row.get(3)?,
                            row.get(4)?,
                            row.get(5)?,
                            row.get(6)?,
                            row.get(7)?,
                        ))
                    },
                )?;
                let logical_bytes: i64 =
                    connection.query_row(logical_bytes_query(), [], |row| row.get(0))?;
                let page_count: i64 =
                    connection.query_row("PRAGMA page_count", [], |row| row.get(0))?;
                let page_size: i64 =
                    connection.query_row("PRAGMA page_size", [], |row| row.get(0))?;
                Ok::<_, tokio_rusqlite::rusqlite::Error>((
                    counts,
                    logical_bytes,
                    page_count,
                    page_size,
                ))
            })
            .await
            .map_err(|_| job_error("could not inspect job database statistics"))
            .and_then(|(counts, logical_bytes, page_count, page_size)| {
                let convert = |value: i64| {
                    u64::try_from(value)
                        .map_err(|_| job_error("job database returned invalid statistics"))
                };
                Ok(SqliteJobStatistics {
                    total: convert(counts.0)?,
                    queued: convert(counts.1)?,
                    running: convert(counts.2)?,
                    succeeded: convert(counts.3)?,
                    failed: convert(counts.4)?,
                    cancelled: convert(counts.5)?,
                    interrupted: convert(counts.6)?,
                    hidden: convert(counts.7)?,
                    database_bytes: convert(page_count)?.saturating_mul(convert(page_size)?),
                    logical_bytes: convert(logical_bytes)?,
                })
            })
    }

    /// Marks previously running jobs interrupted without retrying paid work.
    pub async fn recover_interrupted(&self, now: u64) -> Result<usize, BridgeError> {
        let now = to_i64(now)?;
        let error = serde_json::to_string(
            &BridgeError::new(
                ErrorCode::Cancelled,
                "bridge stopped while provider completion was uncertain",
            )
            .with_detail("recovery", "inspect_history_before_retrying"),
        )
        .map_err(|_| job_error("could not encode interruption error"))?;
        self.connection
            .call(move |connection| {
                connection.execute(
                    "UPDATE image_jobs
                     SET status='interrupted', updated_at=?1, completed_at=?1, error_json=?2
                     WHERE status='running'",
                    params![now, error],
                )
            })
            .await
            .map_err(|_| job_error("could not recover interrupted jobs"))
    }

    /// Returns oldest-first queued identities across ownership scopes for crash recovery.
    pub async fn queued_identities(
        &self,
        limit: usize,
    ) -> Result<Vec<(String, String)>, BridgeError> {
        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
        self.connection
            .call(move |connection| {
                let mut statement = connection.prepare(
                    "SELECT auth_scope,id FROM image_jobs
                     WHERE status='queued'
                     ORDER BY created_at ASC,id ASC LIMIT ?1",
                )?;
                statement
                    .query_map([limit], |row| Ok((row.get(0)?, row.get(1)?)))?
                    .collect::<Result<Vec<_>, _>>()
            })
            .await
            .map_err(|_| job_error("could not list queued durable jobs"))
    }

    /// Atomically claims one queued job for execution.
    pub async fn claim(&self, auth_scope: &str, id: &str, now: u64) -> Result<bool, BridgeError> {
        validate_auth_scope(auth_scope)?;
        let auth_scope = auth_scope.to_owned();
        let id = id.to_owned();
        let now = to_i64(now)?;
        self.connection
            .call(move |connection| {
                connection.execute(
                    "UPDATE image_jobs
                     SET status='running', started_at=?2, updated_at=?2, progress_stage='starting'
                     WHERE id=?1 AND auth_scope=?3 AND status='queued' AND cancel_requested=0",
                    params![id, now, auth_scope],
                )
            })
            .await
            .map(|changed| changed == 1)
            .map_err(|_| job_error("could not claim durable job"))
    }

    /// Stores only the latest safe progress label and partial count.
    pub async fn progress(
        &self,
        auth_scope: &str,
        id: &str,
        stage: &str,
        partial_images: u32,
        now: u64,
    ) -> Result<(), BridgeError> {
        validate_auth_scope(auth_scope)?;
        if stage.is_empty()
            || stage.len() > 64
            || !stage
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
        {
            return Err(job_error("job progress stage is invalid"));
        }
        let id = id.to_owned();
        let auth_scope = auth_scope.to_owned();
        let stage = stage.to_owned();
        let partial_images = i64::from(partial_images);
        let now = to_i64(now)?;
        self.connection
            .call(move |connection| {
                connection.execute(
                    "UPDATE image_jobs
                     SET progress_stage=?2, partial_images=?3, updated_at=?4
                     WHERE id=?1 AND auth_scope=?5 AND status='running'",
                    params![id, stage, partial_images, now, auth_scope],
                )?;
                Ok::<(), tokio_rusqlite::rusqlite::Error>(())
            })
            .await
            .map_err(|_| job_error("could not update durable job progress"))
    }

    /// Stores a verified terminal result.
    pub async fn succeed(
        &self,
        auth_scope: &str,
        id: &str,
        response: &ImageResponse,
        now: u64,
    ) -> Result<(), BridgeError> {
        let encoded = serde_json::to_string(response)
            .map_err(|_| job_error("could not encode job result"))?;
        if encoded.len() > usize::try_from(ACTIVE_RESULT_RESERVE_BYTES).unwrap_or(usize::MAX) {
            return Err(BridgeError::new(
                ErrorCode::Artifact,
                "durable job result metadata exceeds the storage reserve",
            ));
        }
        self.finish(
            auth_scope,
            id,
            ImageJobStatus::Succeeded,
            Some(encoded),
            None,
            now,
        )
        .await
    }

    /// Stores a structured terminal error or cancellation.
    pub async fn fail(
        &self,
        auth_scope: &str,
        id: &str,
        status: ImageJobStatus,
        error: &BridgeError,
        now: u64,
    ) -> Result<(), BridgeError> {
        if !matches!(
            status,
            ImageJobStatus::Failed | ImageJobStatus::Cancelled | ImageJobStatus::Interrupted
        ) {
            return Err(job_error("invalid terminal job failure status"));
        }
        let mut encoded =
            serde_json::to_string(error).map_err(|_| job_error("could not encode job error"))?;
        if encoded.len() > usize::try_from(ACTIVE_RESULT_RESERVE_BYTES).unwrap_or(usize::MAX) {
            encoded = serde_json::to_string(&BridgeError::new(
                ErrorCode::Internal,
                "durable job failed with oversized error metadata",
            ))
            .map_err(|_| job_error("could not encode bounded job error"))?;
        }
        self.finish(auth_scope, id, status, None, Some(encoded), now)
            .await
    }

    async fn finish(
        &self,
        auth_scope: &str,
        id: &str,
        status: ImageJobStatus,
        response: Option<String>,
        error: Option<String>,
        now: u64,
    ) -> Result<(), BridgeError> {
        validate_auth_scope(auth_scope)?;
        let auth_scope = auth_scope.to_owned();
        let id = id.to_owned();
        let status = status_name(status).to_owned();
        let now = to_i64(now)?;
        self.connection
            .call(move |connection| {
                let changed = connection.execute(
                    "UPDATE image_jobs
                     SET status=?2, updated_at=?3, completed_at=?3, progress_stage='completed',
                         response_json=?4, error_json=?5
                     WHERE id=?1 AND auth_scope=?6 AND status='running'",
                    params![id, status, now, response, error, auth_scope],
                )?;
                if changed != 1 {
                    return Err(tokio_rusqlite::rusqlite::Error::QueryReturnedNoRows);
                }
                Ok::<(), tokio_rusqlite::rusqlite::Error>(())
            })
            .await
            .map_err(|_| job_error("could not finish durable job"))
    }

    /// Durably requests cancellation and immediately cancels queued work.
    pub async fn request_cancel(
        &self,
        auth_scope: &str,
        id: &str,
        now: u64,
    ) -> Result<ImageJob, BridgeError> {
        validate_auth_scope(auth_scope)?;
        let auth_scope = auth_scope.to_owned();
        let lookup_scope = auth_scope.clone();
        let id = id.to_owned();
        let lookup_id = id.clone();
        let now = to_i64(now)?;
        self.connection
            .call(move |connection| {
                let transaction = connection.transaction()?;
                let status: Option<String> = transaction
                    .query_row(
                        "SELECT status FROM image_jobs WHERE id=?1 AND auth_scope=?2",
                        params![id, auth_scope],
                        |row| row.get(0),
                    )
                    .optional()?;
                match status.as_deref() {
                    Some("queued") => {
                        transaction.execute(
                            "UPDATE image_jobs SET status='cancelled', cancel_requested=1,
                             updated_at=?2, completed_at=?2, progress_stage='completed'
                             WHERE id=?1 AND auth_scope=?3",
                            params![id, now, auth_scope],
                        )?;
                    }
                    Some("running") => {
                        transaction.execute(
                            "UPDATE image_jobs SET cancel_requested=1, updated_at=?2
                             WHERE id=?1 AND auth_scope=?3",
                            params![id, now, auth_scope],
                        )?;
                    }
                    Some(_) => {}
                    None => return Err(tokio_rusqlite::rusqlite::Error::QueryReturnedNoRows),
                }
                transaction.commit()?;
                Ok::<(), tokio_rusqlite::rusqlite::Error>(())
            })
            .await
            .map_err(|_| not_found())?;
        self.get(lookup_scope.as_str(), lookup_id.as_str()).await
    }

    /// Returns one complete job record.
    pub async fn get(&self, auth_scope: &str, id: &str) -> Result<ImageJob, BridgeError> {
        validate_auth_scope(auth_scope)?;
        let auth_scope = auth_scope.to_owned();
        let id = id.to_owned();
        let row = self
            .connection
            .call(move |connection| {
                connection
                    .query_row(
                        "SELECT id,status,created_at,updated_at,started_at,completed_at,
                                request_json,progress_stage,partial_images,response_json,error_json,
                                cancel_requested,favorite,deleted_at
                         FROM image_jobs WHERE id=?1 AND auth_scope=?2",
                        params![id, auth_scope],
                        read_job_row,
                    )
                    .optional()
            })
            .await
            .map_err(|_| job_error("could not read durable job"))?
            .ok_or_else(not_found)?;
        decode_job(row)
    }

    /// Lists newest-first summaries using a stable `(created,id)` cursor.
    pub async fn list(
        &self,
        auth_scope: &str,
        filter: ImageJobListFilter,
    ) -> Result<Vec<ImageJobSummary>, BridgeError> {
        validate_auth_scope(auth_scope)?;
        let auth_scope = auth_scope.to_owned();
        let before_created = filter
            .before
            .as_ref()
            .map(|(created, _)| to_i64(*created))
            .transpose()?;
        let before_id = filter.before.map(|(_, id)| id);
        let limit = i64::try_from(filter.limit).unwrap_or(i64::MAX);
        let status = filter.status.map(status_name).map(str::to_owned);
        let search = filter
            .search
            .map(|value| literal_like_pattern(&value.to_lowercase()));
        let visibility = filter.visibility;
        let favorite = filter.favorite;
        let rows = self
            .connection
            .call(move |connection| {
                let mut predicates = vec!["auth_scope=?"];
                let mut parameters = vec![SqlValue::Text(auth_scope)];
                match visibility {
                    ImageJobVisibility::Active => predicates.push("deleted_at IS NULL"),
                    ImageJobVisibility::Hidden => predicates.push("deleted_at IS NOT NULL"),
                    ImageJobVisibility::All => {}
                }
                if let Some(status) = status {
                    predicates.push("status=?");
                    parameters.push(SqlValue::Text(status));
                }
                if let Some(favorite) = favorite {
                    predicates.push("favorite=?");
                    parameters.push(SqlValue::Integer(i64::from(favorite)));
                }
                if let Some(search) = search {
                    predicates.push("prompt_search LIKE ? ESCAPE '\\'");
                    parameters.push(SqlValue::Text(search));
                }
                if let (Some(created), Some(id)) = (before_created, before_id) {
                    predicates.push("(created_at < ? OR (created_at=? AND id < ?))");
                    parameters.push(SqlValue::Integer(created));
                    parameters.push(SqlValue::Integer(created));
                    parameters.push(SqlValue::Text(id));
                }
                let condition = if predicates.is_empty() {
                    "1".to_owned()
                } else {
                    predicates.join(" AND ")
                };
                let query = format!(
                    "SELECT id,status,created_at,updated_at,started_at,completed_at,
                            progress_stage,partial_images,favorite,deleted_at
                     FROM image_jobs WHERE {condition}
                     ORDER BY created_at DESC, id DESC LIMIT ?"
                );
                parameters.push(SqlValue::Integer(limit));
                let mut statement = connection.prepare(&query)?;
                statement
                    .query_map(params_from_iter(parameters), read_summary)?
                    .collect::<Result<Vec<_>, _>>()
            })
            .await
            .map_err(|_| job_error("could not list durable jobs"))?;
        rows.into_iter().map(decode_summary).collect()
    }

    /// Updates favorite and soft-delete gallery state without removing job evidence.
    pub async fn update_history(
        &self,
        auth_scope: &str,
        id: &str,
        favorite: Option<bool>,
        deleted: Option<bool>,
        now: u64,
    ) -> Result<ImageJob, BridgeError> {
        validate_auth_scope(auth_scope)?;
        if favorite.is_none() && deleted.is_none() {
            return Err(BridgeError::new(
                ErrorCode::InvalidRequest,
                "history update must change favorite or deleted state",
            ));
        }
        let existing = self.get(auth_scope, id).await?;
        if deleted.is_some() && !existing.summary.status.terminal() {
            return Err(BridgeError::new(
                ErrorCode::InvalidRequest,
                "only terminal jobs can be deleted from history",
            )
            .with_detail("field", "deleted"));
        }
        let id = id.to_owned();
        let auth_scope = auth_scope.to_owned();
        let lookup_scope = auth_scope.clone();
        let lookup_id = id.clone();
        let now = to_i64(now)?;
        self.connection
            .call(move |connection| {
                let changed = connection.execute(
                    "UPDATE image_jobs
                     SET favorite=COALESCE(?2,favorite),
                         deleted_at=CASE WHEN ?3 IS NULL THEN deleted_at
                                         WHEN ?3 THEN ?4 ELSE NULL END,
                         updated_at=?4
                     WHERE id=?1 AND auth_scope=?5",
                    params![id, favorite, deleted, now, auth_scope],
                )?;
                if changed != 1 {
                    return Err(tokio_rusqlite::rusqlite::Error::QueryReturnedNoRows);
                }
                Ok::<(), tokio_rusqlite::rusqlite::Error>(())
            })
            .await
            .map_err(|_| job_error("could not update durable job history"))?;
        self.get(&lookup_scope, &lookup_id).await
    }

    /// Removes terminal records outside time/count retention bounds.
    pub async fn prune(
        &self,
        now: u64,
        retention_secs: u64,
        max_retained: usize,
        max_retained_bytes: u64,
    ) -> Result<usize, BridgeError> {
        let cutoff = to_i64(now.saturating_sub(retention_secs))?;
        let maximum = i64::try_from(max_retained).unwrap_or(i64::MAX);
        let maximum_bytes = i64::try_from(max_retained_bytes).unwrap_or(i64::MAX);
        self.connection
            .call(move |connection| {
                let transaction = connection.transaction()?;
                let expired = transaction.execute(
                    "DELETE FROM image_jobs
                     WHERE status IN ('succeeded','failed','cancelled','interrupted')
                       AND favorite=0
                       AND completed_at <= ?1",
                    [cutoff],
                )?;
                let excess = transaction.execute(
                    "WITH retained AS (
                       SELECT id,
                         ROW_NUMBER() OVER (ORDER BY created_at DESC,id DESC) AS ordinal,
                         SUM(
                           length(CAST(id AS BLOB)) + length(CAST(auth_scope AS BLOB))
                           + length(CAST(request_json AS BLOB))
                           + length(CAST(prompt_search AS BLOB))
                           + length(CAST(COALESCE(submission_key_hash,'') AS BLOB))
                           + length(CAST(COALESCE(request_fingerprint,'') AS BLOB))
                           + length(CAST(COALESCE(response_json,'') AS BLOB))
                           + length(CAST(COALESCE(error_json,'') AS BLOB)) + 128
                         ) OVER (ORDER BY created_at DESC,id DESC) AS cumulative_bytes
                       FROM image_jobs
                       WHERE status IN ('succeeded','failed','cancelled','interrupted')
                         AND favorite=0
                     )
                     DELETE FROM image_jobs WHERE id IN (
                       SELECT id FROM retained WHERE ordinal > ?1 OR cumulative_bytes > ?2
                     )",
                    params![maximum, maximum_bytes],
                )?;
                transaction.commit()?;
                Ok::<usize, tokio_rusqlite::rusqlite::Error>(expired + excess)
            })
            .await
            .map_err(|_| job_error("could not prune durable jobs"))
    }
}

struct JobRow {
    id: String,
    status: String,
    created: i64,
    updated: i64,
    started: Option<i64>,
    completed: Option<i64>,
    request: String,
    progress_stage: Option<String>,
    partial_images: i64,
    response: Option<String>,
    error: Option<String>,
    cancel_requested: bool,
    favorite: bool,
    deleted: Option<i64>,
}

struct SummaryRow {
    id: String,
    status: String,
    created: i64,
    updated: i64,
    started: Option<i64>,
    completed: Option<i64>,
    progress_stage: Option<String>,
    partial_images: i64,
    favorite: bool,
    deleted: Option<i64>,
}

fn read_job_row(
    row: &tokio_rusqlite::rusqlite::Row<'_>,
) -> tokio_rusqlite::rusqlite::Result<JobRow> {
    Ok(JobRow {
        id: row.get(0)?,
        status: row.get(1)?,
        created: row.get(2)?,
        updated: row.get(3)?,
        started: row.get(4)?,
        completed: row.get(5)?,
        request: row.get(6)?,
        progress_stage: row.get(7)?,
        partial_images: row.get(8)?,
        response: row.get(9)?,
        error: row.get(10)?,
        cancel_requested: row.get(11)?,
        favorite: row.get(12)?,
        deleted: row.get(13)?,
    })
}

fn read_summary(
    row: &tokio_rusqlite::rusqlite::Row<'_>,
) -> tokio_rusqlite::rusqlite::Result<SummaryRow> {
    Ok(SummaryRow {
        id: row.get(0)?,
        status: row.get(1)?,
        created: row.get(2)?,
        updated: row.get(3)?,
        started: row.get(4)?,
        completed: row.get(5)?,
        progress_stage: row.get(6)?,
        partial_images: row.get(7)?,
        favorite: row.get(8)?,
        deleted: row.get(9)?,
    })
}

fn decode_job(row: JobRow) -> Result<ImageJob, BridgeError> {
    let summary = decode_summary(SummaryRow {
        id: row.id,
        status: row.status,
        created: row.created,
        updated: row.updated,
        started: row.started,
        completed: row.completed,
        progress_stage: row.progress_stage,
        partial_images: row.partial_images,
        favorite: row.favorite,
        deleted: row.deleted,
    })?;
    Ok(ImageJob {
        summary,
        request: serde_json::from_str(&row.request)
            .map_err(|_| job_error("stored job request is invalid"))?,
        result: row
            .response
            .map(|value| serde_json::from_str(&value))
            .transpose()
            .map_err(|_| job_error("stored job result is invalid"))?,
        error: row
            .error
            .map(|value| serde_json::from_str(&value))
            .transpose()
            .map_err(|_| job_error("stored job error is invalid"))?,
        cancel_requested: row.cancel_requested,
    })
}

fn decode_summary(row: SummaryRow) -> Result<ImageJobSummary, BridgeError> {
    let partial_images = u32::try_from(row.partial_images)
        .map_err(|_| job_error("stored partial image count is invalid"))?;
    Ok(ImageJobSummary {
        id: row.id,
        status: parse_status(&row.status)?,
        created: from_i64(row.created)?,
        updated: from_i64(row.updated)?,
        started: row.started.map(from_i64).transpose()?,
        completed: row.completed.map(from_i64).transpose()?,
        progress: row.progress_stage.map(|stage| ImageJobProgress {
            stage,
            partial_images,
        }),
        favorite: row.favorite,
        deleted: row.deleted.map(from_i64).transpose()?,
    })
}

const fn status_name(status: ImageJobStatus) -> &'static str {
    match status {
        ImageJobStatus::Queued => "queued",
        ImageJobStatus::Running => "running",
        ImageJobStatus::Succeeded => "succeeded",
        ImageJobStatus::Failed => "failed",
        ImageJobStatus::Cancelled => "cancelled",
        ImageJobStatus::Interrupted => "interrupted",
    }
}

fn parse_status(value: &str) -> Result<ImageJobStatus, BridgeError> {
    match value {
        "queued" => Ok(ImageJobStatus::Queued),
        "running" => Ok(ImageJobStatus::Running),
        "succeeded" => Ok(ImageJobStatus::Succeeded),
        "failed" => Ok(ImageJobStatus::Failed),
        "cancelled" => Ok(ImageJobStatus::Cancelled),
        "interrupted" => Ok(ImageJobStatus::Interrupted),
        _ => Err(job_error("stored job status is invalid")),
    }
}

fn to_i64(value: u64) -> Result<i64, BridgeError> {
    i64::try_from(value).map_err(|_| job_error("job timestamp is out of range"))
}

fn from_i64(value: i64) -> Result<u64, BridgeError> {
    u64::try_from(value).map_err(|_| job_error("stored job timestamp is invalid"))
}

fn literal_like_pattern(value: &str) -> String {
    let mut pattern = String::with_capacity(value.len().saturating_add(2));
    pattern.push('%');
    for character in value.chars() {
        if matches!(character, '%' | '_' | '\\') {
            pattern.push('\\');
        }
        pattern.push(character);
    }
    pattern.push('%');
    pattern
}

const fn logical_bytes_query() -> &'static str {
    "SELECT COALESCE(SUM(
       length(CAST(id AS BLOB)) + length(CAST(auth_scope AS BLOB))
       + length(CAST(request_json AS BLOB)) + length(CAST(prompt_search AS BLOB))
       + length(CAST(COALESCE(submission_key_hash,'') AS BLOB))
       + length(CAST(COALESCE(request_fingerprint,'') AS BLOB))
       + CASE WHEN status IN ('queued','running') THEN 262144 ELSE
           length(CAST(COALESCE(response_json,'') AS BLOB))
           + length(CAST(COALESCE(error_json,'') AS BLOB)) END
       + 128
     ),0) FROM image_jobs"
}

fn logical_new_job_bytes(
    id: &str,
    auth_scope: &str,
    request_json: &str,
    prompt_search: &str,
    submission_key_hash: Option<&str>,
    request_fingerprint: Option<&str>,
) -> Result<i64, BridgeError> {
    let bytes = id
        .len()
        .saturating_add(auth_scope.len())
        .saturating_add(request_json.len())
        .saturating_add(prompt_search.len())
        .saturating_add(submission_key_hash.map_or(0, str::len))
        .saturating_add(request_fingerprint.map_or(0, str::len))
        .saturating_add(usize::try_from(ACTIVE_RESULT_RESERVE_BYTES).unwrap_or(usize::MAX))
        .saturating_add(128);
    i64::try_from(bytes).map_err(|_| job_error("durable job is too large to account"))
}

fn durable_request_fingerprint(request: &ImageRequest) -> Result<String, BridgeError> {
    let mut canonical = request.clone();
    canonical.idempotency_key = None;
    canonical.timeout_ms = None;
    let encoded = serde_json::to_vec(&canonical)
        .map_err(|_| job_error("could not fingerprint durable job request"))?;
    Ok(base16ct::lower::encode_string(&Sha256::digest(encoded)))
}

fn validate_auth_scope(scope: &str) -> Result<(), BridgeError> {
    if scope.is_empty() || scope.len() > 256 || scope.chars().any(char::is_control) {
        Err(BridgeError::new(
            ErrorCode::InvalidRequest,
            "durable job authorization scope is invalid",
        ))
    } else {
        Ok(())
    }
}

fn validate_submission_key(key: &str) -> Result<(), BridgeError> {
    if key.trim().is_empty() || key.len() > 512 || key.chars().any(char::is_control) {
        Err(BridgeError::new(
            ErrorCode::InvalidRequest,
            "durable job idempotency key is invalid",
        ))
    } else {
        Ok(())
    }
}

fn not_found() -> BridgeError {
    BridgeError::new(ErrorCode::InvalidRequest, "durable job was not found")
        .with_detail("resource", "job")
}

fn job_error(message: impl Into<String>) -> BridgeError {
    BridgeError::new(ErrorCode::Internal, message)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use std::sync::Arc;

    use super::*;

    const SCOPE: &str = "test-scope";
    const MAX_BYTES: u64 = 1024 * 1024 * 1024;

    fn fixture_response(id: &str) -> ImageResponse {
        ImageResponse {
            id: id.to_owned(),
            created: 14,
            provider: "test".to_owned(),
            model: "test".to_owned(),
            requested: imagegen_bridge_core::GenerationParameters::default(),
            effective: imagegen_bridge_core::GenerationParameters::default(),
            normalizations: Vec::new(),
            attempts: Vec::new(),
            data: Vec::new(),
            failures: Vec::new(),
            revised_prompt: None,
            usage: None,
            session: None,
            timings: imagegen_bridge_core::Timings::default(),
            warnings: Vec::new(),
        }
    }

    #[tokio::test]
    async fn lifecycle_survives_reopen_and_is_cursor_stable() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("jobs.sqlite3");
        let store = SqliteImageJobStore::open(&path).await.unwrap();
        store
            .create(
                SCOPE,
                "019f-job-a",
                &ImageRequest::generate("first"),
                10,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();
        store
            .create(
                SCOPE,
                "019f-job-b",
                &ImageRequest::generate("second"),
                11,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();
        assert!(store.claim(SCOPE, "019f-job-a", 12).await.unwrap());
        store
            .progress(SCOPE, "019f-job-a", "provider", 2, 13)
            .await
            .unwrap();
        let response = fixture_response("019f-job-a");
        store
            .succeed(SCOPE, "019f-job-a", &response, 14)
            .await
            .unwrap();
        let first = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    limit: 1,
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(first[0].id, "019f-job-b");
        let second = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    before: Some((first[0].created, first[0].id.clone())),
                    limit: 2,
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(second[0].id, "019f-job-a");
        store.close().await.unwrap();

        let reopened = SqliteImageJobStore::open(&path).await.unwrap();
        let job = reopened.get(SCOPE, "019f-job-a").await.unwrap();
        assert_eq!(job.summary.status, ImageJobStatus::Succeeded);
        assert_eq!(job.summary.progress.unwrap().partial_images, 2);
        assert_eq!(job.result.unwrap().id, "019f-job-a");
    }

    #[tokio::test]
    async fn recovery_never_retries_ambiguous_running_work() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        store
            .create(
                SCOPE,
                "019f-job",
                &ImageRequest::generate("test"),
                10,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();
        store.claim(SCOPE, "019f-job", 11).await.unwrap();
        assert_eq!(store.recover_interrupted(12).await.unwrap(), 1);
        let job = store.get(SCOPE, "019f-job").await.unwrap();
        assert_eq!(job.summary.status, ImageJobStatus::Interrupted);
        assert!(!job.error.unwrap().retryable);
    }

    #[tokio::test]
    async fn queued_cancellation_is_immediate_and_durable() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        store
            .create(
                SCOPE,
                "019f-job",
                &ImageRequest::generate("test"),
                10,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();
        let job = store.request_cancel(SCOPE, "019f-job", 11).await.unwrap();
        assert_eq!(job.summary.status, ImageJobStatus::Cancelled);
        assert!(job.cancel_requested);
        assert!(!store.claim(SCOPE, "019f-job", 12).await.unwrap());

        let statistics = store.statistics().await.unwrap();
        assert_eq!(statistics.total, 1);
        assert_eq!(statistics.cancelled, 1);
        assert_eq!(statistics.queued, 0);
        assert_eq!(statistics.running, 0);
        assert_eq!(statistics.hidden, 0);
        assert!(statistics.database_bytes > 0);
    }

    #[tokio::test]
    async fn pending_capacity_rejects_without_persisting_extra_work() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        store
            .create(
                SCOPE,
                "019f-job-a",
                &ImageRequest::generate("first"),
                10,
                1,
                MAX_BYTES,
            )
            .await
            .unwrap();
        let error = store
            .create(
                SCOPE,
                "019f-job-b",
                &ImageRequest::generate("second"),
                11,
                1,
                MAX_BYTES,
            )
            .await
            .unwrap_err();
        assert_eq!(error.code, ErrorCode::Overloaded);
        assert!(error.retryable);
        assert!(store.get(SCOPE, "019f-job-b").await.is_err());
    }

    #[tokio::test]
    async fn logical_database_budget_rejects_before_persistence() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        let error = store
            .create(
                SCOPE,
                "019f-too-large",
                &ImageRequest::generate("bounded"),
                10,
                10,
                ACTIVE_RESULT_RESERVE_BYTES - 1,
            )
            .await
            .unwrap_err();
        assert_eq!(error.code, ErrorCode::Overloaded);
        assert_eq!(store.statistics().await.unwrap().total, 0);
    }

    #[tokio::test]
    async fn pruning_enforces_terminal_logical_byte_budget() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        store
            .create(
                SCOPE,
                "019f-job-a",
                &ImageRequest::generate("first retained request"),
                10,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();
        assert!(store.claim(SCOPE, "019f-job-a", 11).await.unwrap());
        store
            .succeed(SCOPE, "019f-job-a", &fixture_response("019f-job-a"), 12)
            .await
            .unwrap();
        let one_job_bytes = store.statistics().await.unwrap().logical_bytes;

        store
            .create(
                SCOPE,
                "019f-job-b",
                &ImageRequest::generate("second retained request"),
                13,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();
        assert!(store.claim(SCOPE, "019f-job-b", 14).await.unwrap());
        store
            .succeed(SCOPE, "019f-job-b", &fixture_response("019f-job-b"), 15)
            .await
            .unwrap();

        let two_job_bytes = store.statistics().await.unwrap().logical_bytes;
        let byte_budget = one_job_bytes.max(two_job_bytes.saturating_sub(one_job_bytes));
        assert_eq!(store.prune(15, 100, 10, byte_budget).await.unwrap(), 1);
        assert!(store.get(SCOPE, "019f-job-a").await.is_err());
        assert!(store.get(SCOPE, "019f-job-b").await.is_ok());
        assert!(store.statistics().await.unwrap().logical_bytes <= byte_budget);
    }

    #[tokio::test]
    async fn submission_idempotency_is_atomic_scoped_and_persistent() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("jobs.sqlite3");
        let store = SqliteImageJobStore::open(&path).await.unwrap();
        let mut request = ImageRequest::generate("same request");
        request.idempotency_key = Some("durable-key".to_owned());

        let first = store
            .create("scope-a", "019f-job-a", &request, 10, 1, MAX_BYTES)
            .await
            .unwrap();
        assert!(first.created);
        assert_eq!(first.job.summary.id, "019f-job-a");
        assert_eq!(first.job.request.idempotency_key, None);

        let replay = store
            .create("scope-a", "019f-job-b", &request, 11, 1, MAX_BYTES)
            .await
            .unwrap();
        assert!(!replay.created);
        assert_eq!(replay.job.summary.id, "019f-job-a");

        let other_scope = store
            .create("scope-b", "019f-job-c", &request, 12, 2, MAX_BYTES)
            .await
            .unwrap();
        assert!(other_scope.created);
        assert_eq!(other_scope.job.summary.id, "019f-job-c");

        let mut conflict = request.clone();
        conflict.prompt = "different request".to_owned();
        let error = store
            .create("scope-a", "019f-job-d", &conflict, 13, 2, MAX_BYTES)
            .await
            .unwrap_err();
        assert_eq!(error.code, ErrorCode::IdempotencyConflict);
        store.close().await.unwrap();

        let reopened = SqliteImageJobStore::open(&path).await.unwrap();
        let replay = reopened
            .create("scope-a", "019f-job-e", &request, 14, 1, MAX_BYTES)
            .await
            .unwrap();
        assert!(!replay.created);
        assert_eq!(replay.job.summary.id, "019f-job-a");
    }

    #[tokio::test]
    async fn caller_operations_never_cross_authorization_scopes() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        store
            .create(
                "scope-a",
                "019f-owned",
                &ImageRequest::generate("private"),
                10,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();

        assert!(store.get("scope-b", "019f-owned").await.is_err());
        assert!(
            store
                .list(
                    "scope-b",
                    ImageJobListFilter {
                        limit: 10,
                        ..ImageJobListFilter::default()
                    },
                )
                .await
                .unwrap()
                .is_empty()
        );
        assert!(
            store
                .request_cancel("scope-b", "019f-owned", 11)
                .await
                .is_err()
        );
        assert!(
            store
                .update_history("scope-b", "019f-owned", Some(true), None, 11)
                .await
                .is_err()
        );
        assert_eq!(
            store
                .get("scope-a", "019f-owned")
                .await
                .unwrap()
                .request
                .prompt,
            "private"
        );
    }

    #[tokio::test]
    async fn concurrent_identical_submissions_converge_on_one_job() {
        let directory = tempfile::tempdir().unwrap();
        let store = Arc::new(
            SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
                .await
                .unwrap(),
        );
        let mut request = ImageRequest::generate("concurrent request");
        request.idempotency_key = Some("concurrent-key".to_owned());
        let first = store.create("scope-a", "019f-first", &request, 10, 10, MAX_BYTES);
        let second = store.create("scope-a", "019f-second", &request, 10, 10, MAX_BYTES);
        let (first, second) = tokio::join!(first, second);
        let first = first.unwrap();
        let second = second.unwrap();
        assert_ne!(first.created, second.created);
        assert_eq!(first.job.summary.id, second.job.summary.id);
        assert_eq!(store.statistics().await.unwrap().total, 1);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn database_symlinks_are_rejected() {
        use std::os::unix::fs::symlink;

        let directory = tempfile::tempdir().unwrap();
        let target = directory.path().join("target.sqlite3");
        std::fs::write(&target, []).unwrap();
        let link = directory.path().join("jobs.sqlite3");
        symlink(target, &link).unwrap();
        let error = SqliteImageJobStore::open(&link).await.unwrap_err();
        assert_eq!(error.code, ErrorCode::Internal);
    }

    #[tokio::test]
    async fn history_updates_only_soft_delete_terminal_jobs() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        store
            .create(
                SCOPE,
                "019f-job",
                &ImageRequest::generate("test"),
                10,
                10,
                MAX_BYTES,
            )
            .await
            .unwrap();
        let error = store
            .update_history(SCOPE, "019f-job", None, Some(true), 11)
            .await
            .unwrap_err();
        assert_eq!(error.code, ErrorCode::InvalidRequest);
        assert!(store.claim(SCOPE, "019f-job", 12).await.unwrap());
        store
            .succeed(SCOPE, "019f-job", &fixture_response("019f-job"), 13)
            .await
            .unwrap();
        let deleted = store
            .update_history(SCOPE, "019f-job", Some(true), Some(true), 14)
            .await
            .unwrap();
        assert!(deleted.summary.favorite);
        assert_eq!(deleted.summary.deleted, Some(14));
        assert!(
            store
                .list(
                    SCOPE,
                    ImageJobListFilter {
                        limit: 10,
                        ..ImageJobListFilter::default()
                    }
                )
                .await
                .unwrap()
                .is_empty()
        );
        let restored = store
            .update_history(SCOPE, "019f-job", None, Some(false), 15)
            .await
            .unwrap();
        assert_eq!(restored.summary.deleted, None);
        assert_eq!(store.prune(100, 1, 1, MAX_BYTES).await.unwrap(), 0);
        store
            .update_history(SCOPE, "019f-job", Some(false), None, 101)
            .await
            .unwrap();
        assert_eq!(store.prune(102, 1, 1, MAX_BYTES).await.unwrap(), 1);
    }

    #[tokio::test]
    async fn history_filters_apply_before_cursor_pagination() {
        let directory = tempfile::tempdir().unwrap();
        let store = SqliteImageJobStore::open(&directory.path().join("jobs.sqlite3"))
            .await
            .unwrap();
        for (id, prompt, created) in [
            ("019f-job-a", "Red fox 100%", 10),
            ("019f-job-b", "BLUE_bird study", 11),
            ("019f-job-c", "ČERVENÁ liška", 12),
        ] {
            store
                .create(
                    SCOPE,
                    id,
                    &ImageRequest::generate(prompt),
                    created,
                    10,
                    MAX_BYTES,
                )
                .await
                .unwrap();
            assert!(store.claim(SCOPE, id, created + 1).await.unwrap());
            store
                .succeed(SCOPE, id, &fixture_response(id), created + 2)
                .await
                .unwrap();
        }
        store
            .update_history(SCOPE, "019f-job-a", Some(true), None, 20)
            .await
            .unwrap();
        store
            .update_history(SCOPE, "019f-job-b", None, Some(true), 21)
            .await
            .unwrap();

        let percent = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    limit: 10,
                    search: Some("100%".to_owned()),
                    favorite: Some(true),
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(percent.len(), 1);
        assert_eq!(percent[0].id, "019f-job-a");

        let underscore = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    limit: 10,
                    visibility: ImageJobVisibility::Hidden,
                    search: Some("blue_".to_owned()),
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(underscore.len(), 1);
        assert_eq!(underscore[0].id, "019f-job-b");

        let unicode_case = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    limit: 10,
                    search: Some("červená".to_owned()),
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(unicode_case.len(), 1);
        assert_eq!(unicode_case[0].id, "019f-job-c");

        let injection = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    limit: 10,
                    visibility: ImageJobVisibility::All,
                    search: Some("' OR 1=1 --".to_owned()),
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert!(injection.is_empty());

        let newest_favorite = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    limit: 1,
                    visibility: ImageJobVisibility::All,
                    favorite: Some(true),
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(newest_favorite[0].id, "019f-job-a");
        let after_favorite = store
            .list(
                SCOPE,
                ImageJobListFilter {
                    before: Some((newest_favorite[0].created, newest_favorite[0].id.clone())),
                    limit: 1,
                    visibility: ImageJobVisibility::All,
                    favorite: Some(true),
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert!(after_favorite.is_empty());
    }

    #[tokio::test]
    async fn version_one_database_migrates_prompt_search_without_losing_jobs() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("jobs.sqlite3");
        let connection = Connection::open(&path).await.unwrap();
        let request = serde_json::to_string(&ImageRequest::generate("legacy copper fox")).unwrap();
        connection
            .call(move |connection| {
                connection.execute_batch(
                    "CREATE TABLE job_schema_migrations (
                       version INTEGER PRIMARY KEY,
                       applied_at INTEGER NOT NULL
                     );
                     CREATE TABLE image_jobs (
                       id TEXT PRIMARY KEY,
                       status TEXT NOT NULL,
                       created_at INTEGER NOT NULL,
                       updated_at INTEGER NOT NULL,
                       started_at INTEGER,
                       completed_at INTEGER,
                       request_json TEXT NOT NULL,
                       progress_stage TEXT,
                       partial_images INTEGER NOT NULL DEFAULT 0,
                       response_json TEXT,
                       error_json TEXT,
                       cancel_requested INTEGER NOT NULL DEFAULT 0,
                       favorite INTEGER NOT NULL DEFAULT 0,
                       deleted_at INTEGER
                     );
                     INSERT INTO job_schema_migrations(version, applied_at) VALUES (1, 10);",
                )?;
                connection.execute(
                    "INSERT INTO image_jobs(id,status,created_at,updated_at,request_json)
                     VALUES ('019f-legacy','queued',10,10,?1)",
                    [request],
                )?;
                Ok::<(), tokio_rusqlite::rusqlite::Error>(())
            })
            .await
            .unwrap();
        connection.close().await.unwrap();

        let store = SqliteImageJobStore::open(&path).await.unwrap();
        let results = store
            .list(
                "legacy-unowned",
                ImageJobListFilter {
                    limit: 10,
                    search: Some("COPPER".to_owned()),
                    ..ImageJobListFilter::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id, "019f-legacy");
        let status = inspect_sqlite_job_schema(&path).await.unwrap();
        assert_eq!(status.version, Some(3));
        assert_eq!(status.current_version, 3);
        store.close().await.unwrap();

        let connection = Connection::open(&path).await.unwrap();
        connection
            .call(|connection| {
                connection.execute("UPDATE image_jobs SET prompt_search=''", [])?;
                connection.execute("DELETE FROM job_schema_migrations WHERE version=2", [])?;
                Ok::<(), tokio_rusqlite::rusqlite::Error>(())
            })
            .await
            .unwrap();
        connection.close().await.unwrap();
        let repaired = SqliteImageJobStore::open(&path).await.unwrap();
        assert_eq!(
            repaired
                .list(
                    "legacy-unowned",
                    ImageJobListFilter {
                        limit: 10,
                        search: Some("legacy copper".to_owned()),
                        ..ImageJobListFilter::default()
                    }
                )
                .await
                .unwrap()
                .len(),
            1
        );
    }
}