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 | class MetronOnlineSource(OnlineSource):
"""Wraps mokkari for the Metron API."""
name: ClassVar[str] = "metron"
metadata_source: ClassVar[MetadataSources] = MetadataSources.METRON_API
metadata_format: ClassVar[MetadataFormats] = MetadataFormats.METRON_API
# Every send goes through this credential set's `RateGate` (see
# `paced_session`), so the retry loop must not also sleep the hint.
paces_rate_limit: ClassVar[bool] = True
@override
def is_configured(self) -> bool:
"""Metron needs an API token (key)."""
return bool(self._credentials.key)
@override
@staticmethod
def classify_retry_exception(exc: BaseException) -> RetryCategory | None:
"""Classify mokkari's exceptions; see `_classify_api_error`."""
from mokkari.exceptions import (
ApiError,
AuthenticationError,
CacheError,
RateLimiterError,
RateLimitError,
)
if isinstance(exc, RateLimitError):
return RetryCategory.RATE_LIMIT
if isinstance(exc, AuthenticationError):
# Raised only by Session.__init__ for a missing or empty token.
return RetryCategory.AUTH
if isinstance(exc, CacheError):
# Raised by Session.__init__ when the cache's get()/store() don't
# take Session's arguments: a wiring bug, never transient. The
# SqliteCache open errors are handled in `_open_cache`.
return RetryCategory.INVALID
if isinstance(exc, RateLimiterError):
# Same shape as CacheError: raised on the first request when the
# injected rate limiter lacks a protocol method. A wiring bug no
# replay fixes.
return RetryCategory.INVALID
if isinstance(exc, ApiError):
return _classify_api_error(exc)
return None
def _get_cache(self) -> SqliteCache | None:
# REFRESH empties the open cache rather than unlinking the file:
# another process (codex's librarian) may hold this WAL database
# open, and deleting the main file under it strands the -wal and
# -shm files, leaving both processes with "disk I/O error".
resolved = self._resolve_response_cache(unlink_on_refresh=False)
if resolved is None:
return None
from comicbox.config.online.settings import CacheMode
from comicbox.formats.base.online.vacuum import vacuum_if_bloated
cache_path, ttl = resolved
cache = _open_cache(cache_path, ttl)
if cache is None:
return None
if self._settings.cache.mode is CacheMode.REFRESH and claim_cache_refresh(
cache_path
):
removed = cache.clear()
logger.debug(f"refresh-cache: cleared {removed} entries from {cache_path}")
# mokkari's SqliteCache cleans up expired rows on open; reclaim the
# freed pages if the file has gotten bloated.
vacuum_if_bloated(cache_path)
return cache
def _get_session(self) -> Session:
"""
Return the process-wide mokkari client shared by this API token.
Sources are rebuilt per file (see `MetronOnlineSource.__init__` via
`OnlineSource`), so without sharing at module scope every file's
source would get its own `Session` with its own blank
`rate_limit_status` — none of them would ever see another worker's
rate-limit state. Memoizing by token lets every thread in
`Runner._run_parallel`'s pool (comicbox/run.py) that logs in with the
same token observe one shared, continuously-updated
`rate_limit_status` — and, more importantly, queue behind one
`RateGate`. Pacing is what makes sharing threads (not processes)
worthwhile: a second process would get a second gate and the two
would have to split the window between them.
"""
if self._client is None:
# Warn here rather than in _build_session so ignored-config
# warnings don't depend on winning the session-cache miss;
# warn_once keeps them at one line per process either way.
self._warn_ignored_url()
self._warn_ignored_rate_limit_overrides()
self._client = self._get_or_build_shared_session()
return self._client
def session(self) -> Session:
"""
Return the shared mokkari Session for this source's API token.
Reading lists call Metron through it, so their requests queue at
the same rate gate and fill the same response cache as tagging.
"""
return self._get_session()
@contextmanager
def refreshing_session(self) -> Generator[Session]:
"""
Get a Session that fetches from Metron past the response cache.
For a caller that knows the cached copy is stale, such as a list
found changed since it was cached. It queues at this token's rate
gate and stores what it fetches in the shared cache, replacing the
stale entries, so the next cached read is fresh too. Closed on exit.
Without a cache the shared Session already fetches everything.
"""
from comicbox.formats.metron_api.paced_session import build_paced_session
shared = self.session()
cache, gate = shared.cache, self._gate()
if cache is None or gate is None:
yield shared
return
session = build_paced_session(
gate,
api_token=self._credential_key(),
cache=_RefreshingCache(cache),
user_agent=user_agent(),
)
try:
yield session
finally:
session.close()
def _session_config_signature(self) -> tuple:
"""Return the per-instance settings a built Session bakes in."""
cache = self._settings.cache
return (cache.mode, cache.dir, cache.ttl)
def _credential_key(self) -> str:
"""Return the API token a Session and gate are shared by."""
return self._credentials.key or ""
def _get_or_build_shared_session(self) -> Session:
key = self._credential_key()
signature = self._session_config_signature()
with _session_cache_lock:
entry = _session_cache.get(key)
if entry is None:
gate = _gate_cache.get(key)
if gate is None:
gate = self._build_gate()
_gate_cache[key] = gate
session = self._build_session(gate)
_session_cache[key] = (session, signature)
return session
session, built_signature = entry
if built_signature != signature:
# First build wins (see the _session_cache comment); tell the
# user their differing cache config is not taking effect.
warn_once(
f"{self.name}:session-config-mismatch",
f"online {self.name}: reusing the existing shared mokkari "
"session; this instance's differing cache settings "
f"{signature} are ignored in favor of the session's "
f"{built_signature}",
)
return session
def _build_gate(self) -> RateGate:
"""
Build this credential set's rate gate.
``rate_limit.per_minute`` is honored here as a CEILING on the
server-reported burst limit, never a raise. That gives the knob a
real meaning again for the case it exists for: an embedder
running several processes against one Metron token has one gate
per process, and the only way to keep their sum inside the
server's window is for each to take a share.
"""
from comicbox.config.online.settings import resolve_rate_limit
limits = resolve_rate_limit(self._settings, self.name)
return RateGate(
default_limit=METRON_DEFAULT_PER_MINUTE,
config_limit=limits.per_minute,
)
def _build_session(self, gate: RateGate) -> Session:
"""
Build a mokkari Session paced by this credential set's gate.
`build_paced_session` registers the gate through mokkari's
`rate_limiter` hook and installs the telemetry observer (see
`paced_session`). The keyword set is `mokkari.api()`'s, minus
`dev_mode`, which comicbox has no setting for.
"""
from comicbox.formats.metron_api.paced_session import build_paced_session
return build_paced_session(
gate,
api_token=self._credential_key(),
cache=self._get_cache(),
user_agent=user_agent(),
)
def _gate(self) -> RateGate | None:
"""Return the shared rate gate, once a session has been built."""
with _session_cache_lock:
return _gate_cache.get(self._credential_key())
def _warn_ignored_url(self) -> None:
if self._credentials.url:
# mokkari's api() factory has no URL-override parameter (only
# dev_mode for the dev API), so --auth metron:url= can't
# actually be honored. Warn so the user notices.
warn_once(
f"{self.name}:api-url",
f"online {self.name}: --auth metron:url= is a no-op "
f"(mokkari has no base_url override); ignoring "
f"{self._credentials.url!r}",
)
def _warn_ignored_rate_limit_overrides(self) -> None:
"""
Warn about `per_day`, which still has nowhere to go.
`per_minute` is honored again — `_build_gate` takes it as a
ceiling on the burst window. `per_day` is not: Metron reports the
sustained window per user (donor tiers raise it), the gate tracks
what the server says is left, and comicbox keeps no cross-run
tally of its own to enforce a smaller daily number against.
"""
from comicbox.config.online.settings import resolve_rate_limit
limits = resolve_rate_limit(self._settings, self.name)
if limits.per_day is not None:
warn_once(
f"{self.name}:rate-limit-override",
f"online {self.name}: rate_limit.per_day is ignored — "
"Metron reports the remaining daily quota per user in its "
"response headers and comicbox paces against that. Use "
"rate_limit.per_minute to take a smaller share of the "
"burst window.",
)
@override
def probe(self) -> Mapping[str, Mapping[str, Any]] | None:
"""
Verify the credentials with one ``series_type_list`` request.
The smallest listing Metron serves. It still counts against the
burst and daily windows, which is what the returned status shows.
"""
from comicbox.formats.metron_api.paced_session import build_paced_session
session = build_paced_session(
self._build_gate(),
api_token=self._credential_key(),
cache=None,
user_agent=user_agent(),
)
try:
self._record_api_call("series_type_list")
session.series_type_list()
status = session.rate_limit_status
finally:
session.close()
return {"burst": _window(status.burst), "daily": _window(status.sustained)}
@with_retry()
def get(self, issue_id: int) -> dict[str, Any]:
"""
Fetch one Metron issue by id; return its model dump.
The issue's nested series carries no end year, status, description
or issue count, so one ``series(id)`` request adds them to the
series block. mokkari's response cache is URL-keyed, which makes
that one extra request per distinct series rather than per issue.
"""
session = self._get_session()
self._record_api_call("issue")
issue = session.issue(issue_id)
dump: dict[str, Any] = issue.model_dump(mode="json")
if isinstance(series_dump := dump.get("series"), dict):
self._enrich_from_series(session, series_dump, issue.series.id)
return dump
def _enrich_from_series(
self, session: Session, series_dump: dict[str, Any], series_id: int
) -> None:
"""
Inject the full series' detail into an issue dump's series block.
Best-effort: a source-side failure leaves the issue without them
rather than failing the fetch. An abort is not such a failure -- it
ends the whole lookup, as in `OnlineSource.lookup_issue`.
"""
try:
series = self._series_with_retry(session, series_id)
except OnlineLookupAbortedError:
raise
except Exception as exc:
logger.warning(
f"online {self.name}: series({series_id}) failed; series end "
f"year, status and summary will be missing from this issue: {exc}"
)
return
detail = series.model_dump(mode="json")
series_dump.update(
{key: value for key in _SERIES_DETAIL_KEYS if (value := detail.get(key))}
)
def _build_common_issue_filters(
self,
profile: ComicProfile,
*,
include_volume: bool,
) -> dict[str, Any]:
"""
Build filters shared by the series_id-keyed and series_name-keyed builders.
``include_volume`` is the toggle for the ``--series-id`` fast
path: passing False omits Metron's ``series_volume`` filter even
when ``profile.volume`` is set, because a user who named the
series id has been explicit and the soft volume filter would only
risk a false zero.
"""
params: dict[str, Any] = {}
# Strip leading zeros — Metron stores `number` without padding.
if number := strip_issue_leading_zeros(profile.issue):
params["number"] = number
if profile.year is not None:
params["cover_year"] = profile.year
if include_volume and profile.volume is not None:
params["series_volume"] = profile.volume
return params
def _build_issue_params(
self,
profile: ComicProfile,
series_id: int,
*,
include_volume: bool = True,
) -> dict[str, Any]:
"""
Build the `issues_list` params filtering on a resolved series id.
IMPORTANT: the FK filter param is ``series_id``, NOT ``series``.
Mokkari's docstring example (`{"series": 1}`) is misleading —
Metron's DRF backend silently ignores `series` as an unknown
filter and returns issues matched only by the remaining params
(number + cover_year), leaking thousands of unrelated 2020 #1s
when querying for AR #1 (2020). Confirmed empirically against
the live Metron API on 2026-05-13.
"""
params: dict[str, Any] = {"series_id": series_id}
params.update(
self._build_common_issue_filters(profile, include_volume=include_volume)
)
return params
def _build_issue_params_by_name(
self,
profile: ComicProfile,
*,
include_volume: bool = True,
) -> dict[str, Any]:
"""
Build the `issues_list` params filtering directly on series_name.
Confirmed against Metron's live `IssueFilter`
(`comicsdb/filters/issue.py`): `series_name` reuses the identical
`unaccent__icontains` whitespace-AND-of-terms predicate that
`series_list`'s own `name` filter applies to `Series.name` — so
this has the same recall as the old "discover series by name,
then filter issues by series id" two-step, at one call instead of
up to 21.
"""
params: dict[str, Any] = {"series_name": profile.series}
params.update(
self._build_common_issue_filters(profile, include_volume=include_volume)
)
return params
def _build_wide_issue_params_by_name(self, profile: ComicProfile) -> dict[str, Any]:
"""
Build the one wide fallback call: name + number over a 3-year window.
Metron's `cover_date_range_after` / `cover_date_range_before`
filters (server #628) let one request cover what the old cascade
spent up to five on: Y-1, Y and Y+1, with and without the volume
filter. The volume filter is dropped here rather than retried
separately — `_select_precedence_tier` reproduces the order the
old calls ran in, from rows this single call already returned.
With no year there is no range to send, and the call degrades to
exactly the old drop-volume call: name + number.
"""
params: dict[str, Any] = {"series_name": profile.series}
if number := strip_issue_leading_zeros(profile.issue):
params["number"] = number
if profile.year is not None:
params["cover_date_range_after"] = f"{profile.year - 1}-01-01"
params["cover_date_range_before"] = f"{profile.year + 1}-12-31"
return params
def _to_candidate(
self,
base_issue: Any,
*,
series_id: int | None = None,
) -> Candidate:
"""
Map a mokkari `BaseIssue` to a Candidate.
``series_id`` lets a caller that already knows the series id
(the explicit `--series-id` fast path, or the volume-scoped
`lookup_issue` fast path) supply it directly. The by-name search
path doesn't need to — since mokkari 3.28.0 / Metron server
commit 3b1e46b, `BaseIssue.series` (`BasicSeries`) carries a real
`.id`, so `_bi_series_id` recovers it from the search result
itself.
"""
bi_series = getattr(base_issue, "series", None)
cover_url = str(base_issue.image) if base_issue.image else None
summary = CandidateSummary(
series=_bi_series_name(bi_series) or "",
issue=base_issue.number,
year=base_issue.cover_date.year if base_issue.cover_date else None,
publisher=None, # BaseIssue from search omits publisher
page_count=None,
cover_url=cover_url,
variant_label=None,
volume=_bi_series_volume(bi_series),
# Metron serves one image per issue at full size, so the
# thumbnail and the full-size url are the same url -- and both
# are None when the record has no image at all.
cover_url_full=cover_url,
series_start_year=_bi_series_year_began(bi_series),
)
return Candidate(
source=self.name,
issue_id=base_issue.id,
summary=summary,
url=_issue_url(base_issue.id),
precomputed_cover_hash=getattr(base_issue, "cover_hash", None) or None,
volume_id=series_id if series_id is not None else _bi_series_id(bi_series),
)
@override
def _lookup_issue_in_volume(
self, volume_id: int, issue_number: str | None
) -> Candidate | None:
"""
Volume-scoped issue lookup; cheaper than the fuzzy search path.
Calls ``issues_list`` filtered by ``series_id`` + ``number`` — one
request, returns ≤1 result on healthy data. Returns None without
a request when there is no issue number: an unfiltered
``series_id`` query pages through the whole series and the first
row would win. The base class's ``lookup_issue`` wrapper owns the
failure semantics.
"""
number = strip_issue_leading_zeros(issue_number)
if not number:
return None
prefetched = _prefetched_issue(volume_id, number)
if prefetched is not None:
return self._to_candidate(prefetched, series_id=volume_id)
session = self._get_session()
params: dict[str, Any] = {"series_id": volume_id, "number": number}
issues = self._issues_list_with_retry(session, params)
issue_list = list(issues)
if not issue_list:
return None
# On the rare multi-result case (cover variants under one
# `number`), accept the first — caller would otherwise need to
# decide between variants which is a different problem.
return self._to_candidate(issue_list[0], series_id=volume_id)
@override
def prefetch_volume(self, volume_id: int, cluster_size: int) -> None:
"""
Pull a whole series' issue list once instead of once per comic.
With `PAGE_SIZE=100` a series is one or a few pages, so a long run
costs `1 + pages` requests to list instead of one `issues_list`
per comic. Only worth it when that is actually cheaper than the
lookups it replaces, which is what the `series(id)` call buys: its
`issue_count` says how many pages the list will take before
committing to fetching it.
The `issue(id)` detail fetch still happens per comic — `BaseIssue`
carries no credits or characters — so this takes a cluster from
about two requests per comic to about one.
Best effort throughout: anything that goes wrong leaves the
per-comic path exactly as it was.
"""
if cluster_size < _PREFETCH_MIN_CLUSTER or _has_prefetch(volume_id):
return
try:
self._prefetch_volume_issues(volume_id, cluster_size)
except OnlineLookupAbortedError:
raise
except Exception as exc:
logger.debug(
f"online {self.name}: series prefetch for volume {volume_id} "
f"failed: {exc}; falling back to per-issue lookups"
)
def _prefetch_volume_issues(self, volume_id: int, cluster_size: int) -> None:
"""Do the two-step prefetch; see `prefetch_volume` for the policy."""
session = self._get_session()
series = self._series_with_retry(session, volume_id)
issue_count = getattr(series, "issue_count", None) if series else None
if not issue_count:
return
pages = math.ceil(issue_count / _METRON_PAGE_SIZE)
# `1` for the series() call already spent, plus a page each. The
# comparison is against what the cluster would otherwise pay: one
# issues_list per comic.
if 1 + pages >= cluster_size:
logger.debug(
f"online {self.name}: not prefetching volume {volume_id} — "
f"{1 + pages} requests to list {issue_count} issues is not "
f"cheaper than {cluster_size} per-issue lookups"
)
return
issues = self._issues_list_with_retry(session, {"series_id": volume_id})
by_number: dict[str, Any] = {}
for issue in issues:
number = strip_issue_leading_zeros(getattr(issue, "number", None))
# First writer wins, mirroring `_lookup_issue_in_volume`'s
# "accept the first" rule for cover variants sharing a number.
if number and number not in by_number:
by_number[number] = issue
_store_prefetch(volume_id, by_number)
logger.info(
f"online {self.name}: prefetched {len(by_number)} issues of volume "
f"{volume_id} in {1 + pages} requests, for {cluster_size} comics"
)
@override
def enrich_prompt_candidates(
self, candidates: Sequence[Candidate]
) -> tuple[Candidate, ...]:
"""
Fetch series detail for candidates that would read identically.
Metron's issue rows carry no publication format ("Trade
Paperback", "One-Shot"), publisher or series issue count; only
`series(id)` does, at a request per series. So it is paid only
for candidates the prompt could not otherwise tell apart (same
title, different series), and only while the daily quota is
above the reserve `_may_start_cold_search` keeps. Every comic of
a series defers its own prompt; mokkari's response cache answers
the repeats.
"""
cands = tuple(candidates)
series_ids = _colliding_series_ids(cands)
if not series_ids:
return cands
gate = self._gate()
if gate is not None and not gate.allow_cold_search():
return cands
details = self._fetch_series_details(series_ids)
return tuple(_with_series_detail(c, details) for c in cands)
def _fetch_series_details(self, series_ids: Sequence[int]) -> dict[int, Any]:
"""`series(id)` per id; a failure loses only that series' detail."""
session = self._get_session()
details: dict[int, Any] = {}
for series_id in series_ids:
try:
details[series_id] = self._series_with_retry(session, series_id)
except OnlineLookupAbortedError:
raise
except Exception as exc:
logger.debug(
f"online {self.name}: series {series_id} detail for a "
f"prompt failed: {exc}"
)
return details
@with_retry(max_retries=1)
def _series_with_retry(self, session: Session, series_id: int) -> Any:
"""
Per-call retry wrapper around `session.series`.
Deliberately a tighter budget than the rest of the source. This
call only decides whether a prefetch is worth doing, adds display
detail to a prompt, or adds series detail to a fetched issue, and
all three have a working fallback, so burning the user's full
retry budget (and its 31s of backoff) on it would cost more than
it can ever save. Rate-limit errors keep their own budget, which
the gate makes free to spend.
"""
self._record_api_call("series")
return session.series(series_id)
def _search_by_explicit_series_id(
self, session: Session, profile: ComicProfile, series_id: int
) -> list[Candidate]:
"""
Single-call issue lookup against a user-supplied series id.
Not decorated with ``@with_retry()``: the API call inside
(`_issues_list_with_retry`) carries its own retry budget, and an
outer decorator would multiply budgets (8x8 attempts) by replaying
the whole lookup after the inner budget is already exhausted.
"""
# The user has been explicit about the series id; the soft volume
# filter would just risk false-zero. Trust the supplied id.
params = self._build_issue_params(profile, series_id, include_volume=False)
try:
issues = self._issues_list_with_retry(session, params)
except Exception as exc:
logger.warning(
f"online {self.name}: issue-list for series id {series_id} "
f"failed: {exc}"
)
raise
return [self._to_candidate(i, series_id=series_id) for i in issues]
@override
def search(self, profile: ComicProfile) -> list[Candidate]:
"""
Search Metron via a direct issues_list(series_name=...) call.
No series-discovery step, no per-series fan-out, and at most two
requests: the exact call, and one wide fallback when it misses.
None at all for a series name with no issue number and no year;
see `_name_search_worth_a_call`.
Not decorated with ``@with_retry()``: every API call inside is
individually retried by its leaf wrapper (`_issues_list_with_retry`),
matching the ComicVine source. An outer decorator here would
multiply retry budgets (8x8 whole-search replays of already-
exhausted inner budgets — hours of worst-case sleep).
Metron's `series_name` issue-list filter (`comicsdb/filters/issue.py`,
`IssueFilter.series_name`) reuses the identical icontains+unaccent,
whitespace-AND-of-terms predicate that `series_list`'s own `name`
filter applies — same recall as the old series_list → issues_list
two-step, at 1 call instead of up to 21. Since mokkari 3.28.0 /
Metron server commit 3b1e46b, `BaseIssue.series.id` is populated
directly on `issues_list` results, so `Candidate.volume_id` no
longer requires a separate series-discovery step to resolve
either.
``--series-id metron:<id>`` still short-circuits straight to a
single `issues_list({series_id: ...})` call — unchanged.
"""
# Owns its own lifetime: set when this search declines to run,
# cleared here so it can never be read as the next comic's answer.
self.reset_search_skip_reason()
session = self._get_session()
if not self._may_start_cold_search():
return []
explicit_sid = self._settings.lookup.series_ids.get(self.name)
if explicit_sid is not None:
return self._search_by_explicit_series_id(session, profile, explicit_sid)
if not profile.series:
logger.debug(
f"online {self.name}: no series in profile; cannot search Metron "
"(use --id metron:<id> for direct lookup, or --series-id metron:<id>)"
)
return []
if not self._name_search_worth_a_call(profile):
return []
candidates = self._search_exact(session, profile)
if candidates:
return candidates
return self._search_wide(session, profile)
def _may_start_cold_search(self) -> bool:
"""
Whether the daily quota can still afford to START a search.
Once Metron reports the sustained window down to its reserve, the
gate stops admitting discretionary work. A search only begins a
comic; the `issue(id)` fetch that follows a match is what
finishes one. Spending the last of the day on new searches would
leave a trail of comics that matched and were never written.
Returning [] reads downstream as "no candidates", so the reason is
recorded alongside it: the lookup reports a `Skipped` with
`SKIP_QUOTA_RESERVED` rather than a NO_MATCH, since this comic was
never actually looked at and should be tried again tomorrow.
"""
gate = self._gate()
if gate is None or gate.allow_cold_search():
return True
self._note_search_skipped(SKIP_QUOTA_RESERVED)
logger.info(
f"online {self.name}: daily quota nearly spent; skipping this "
"search so the remaining budget finishes comics that matched"
)
return False
def _fetch_candidates_by_name(
self,
session: Session,
profile: ComicProfile,
*,
wide: bool = False,
) -> list[Candidate]:
"""
One issues_list call filtered by series_name.
``wide`` swaps the exact filters (cover_year + series_volume) for
the fallback's three-year cover-date range and no volume. Both
shapes go through here so there is exactly one place a search
spends a request by name.
"""
params = (
self._build_wide_issue_params_by_name(profile)
if wide
else self._build_issue_params_by_name(profile)
)
issues = self._issues_list_with_retry(session, params)
return [self._to_candidate(i) for i in issues]
def _name_search_worth_a_call(self, profile: ComicProfile) -> bool:
"""
Whether anything narrows a by-name search below a whole catalog.
`series_name` is a substring match, so a name alone returns every
issue of every series whose name contains it, and mokkari follows
every `next` page. On 2026-11-17 a file named `ee.cbz` matched
8,026 rows: about 81 requests, some 2% of a day's quota, for a
prompt nobody could use. An issue number or a cover year bounds
the result. A volume does not, since most series are volume 1.
Warns rather than logging at debug: the lookup goes on to report
an ordinary empty search, which alone would read as a real miss.
"""
if strip_issue_leading_zeros(profile.issue) or profile.year is not None:
return True
logger.warning(
f"online {self.name}: series {profile.series!r} has no issue number "
"or year, so it is not searched by name. Add one, or use "
f"--series-id {self.name}:<series_id> or --id {self.name}:<issue_id>."
)
return False
def _search_exact(self, session: Session, profile: ComicProfile) -> list[Candidate]:
"""
Make the first and usually only call: name + number + year [+ volume].
Keeps the raise-on-failure contract the whole search is built on:
a hard failure here means the search failed, not that Metron has
nothing. Only a genuine empty result may fall through to the
fallback.
"""
try:
return self._fetch_candidates_by_name(session, profile)
except Exception as exc:
logger.warning(
f"online {self.name}: issue-list for series_name="
f"{profile.series!r} failed: {exc}"
)
raise
def _search_wide(self, session: Session, profile: ComicProfile) -> list[Candidate]:
"""
One wide call replacing the old five-call miss cascade.
The old shape was a year cycle (Y, then Y-1 and Y+1) run twice —
once with `series_volume` and once without — because both filters
are guesses a filename made. Cover-date drift is real (a comic
published in late 2019 can be cover-dated 2020-01) and a
filename's `Vol. N` is inconsistent (some scanners drop it, some
get it wrong), so both had to be relaxed. That cost up to six
requests to answer one question.
`cover_date_range_after` / `_before` collapse the year cycle into
one filter, and dropping `series_volume` collapses the two cycles
into one call. What the cascade's ORDER used to encode — a
volume-and-year hit beats a volume hit beats a year hit — is
reproduced from the returned rows by `_select_precedence_tier`,
so the candidate set is the one the six calls produced.
Failure here is not failure of the search: an exception is logged
and swallowed, mirroring what the per-year retries did, and an
abort is re-raised because it ends the whole lookup rather than
being a source-side failure to degrade past.
"""
if not self._wide_fallback_worth_a_call(profile):
return []
logger.info(
f"online {self.name}: 0 candidates for series_name="
f"{profile.series!r} at cover_year={profile.year}"
f"{f', series_volume={profile.volume}' if profile.volume else ''}; "
"retrying wide"
)
try:
candidates = self._fetch_candidates_by_name(session, profile, wide=True)
except OnlineLookupAbortedError:
# An abort ends the whole lookup; it is not a source-side
# failure to degrade past.
raise
except Exception as exc:
logger.warning(
f"online {self.name}: wide issue-list retry for series_name="
f"{profile.series!r} failed: {exc}"
)
return []
if profile.year is None:
# No range was sent, so there is nothing to guard and no year
# to rank by. This call IS the old drop-volume call, which
# returned every row it got.
return candidates
candidates = self._drop_out_of_range(candidates, profile.year)
return _select_precedence_tier(
candidates, year=profile.year, volume=profile.volume
)
def _wide_fallback_worth_a_call(self, profile: ComicProfile) -> bool:
"""
Whether the wide call would ask Metron anything new.
One case where it would not, and one where asking would cost far
more than the answer is worth:
- No issue number. The old cascade ran in full here, and a wide
call with only a series name paginates every issue of every
series whose name matches. A deliberate cost cut, not parity:
the matcher has nothing to pick between those rows with anyway.
- No year AND no volume. Call 1 was already name + number, so the
fallback would repeat it verbatim.
"""
if not strip_issue_leading_zeros(profile.issue):
logger.debug(
f"online {self.name}: no issue number; skipping the wide "
"retry rather than paginating a whole series"
)
return False
# With neither a year nor a volume, call 1 was already
# name + number and the fallback would repeat it verbatim.
return not (profile.year is None and profile.volume is None)
def _drop_out_of_range(
self, candidates: list[Candidate], year: int
) -> list[Candidate]:
"""
Enforce the cover-date window the server was asked for.
DRF ignores filter params it does not recognize, so a Metron that
predates server #628 — or one rolled back — answers the wide call
with every issue of the series ever published, silently. That is
not a wider search, it is a different one: the tiering below would
rank a 1987 issue against a 2020 profile. Dropping the rows the
range should already have excluded makes the guard exact, since
`cover_date` is non-null on Metron's side and on ours.
"""
allowed = (year - 1, year, year + 1)
kept = [c for c in candidates if c.summary.year in allowed]
if len(kept) != len(candidates):
warn_once(
"metron:cover-date-range-ignored",
f"online {self.name}: Metron returned issues outside the "
"requested cover-date range, so it is ignoring "
"cover_date_range_after/_before. Filtering locally; a "
"server that supports the filter would not have sent them.",
)
return kept
def _build_cover_search_params(
self, profile: ComicProfile
) -> dict[str, Any] | None:
"""
Build the filters that narrow a cover search, or None if there are none.
The issue number and cover year do most of the narrowing: a hash on
its own can't tell apart unrelated covers a few bits away. A
``--series-id`` narrows further than a year can, so it replaces the
date range rather than joining it; a file's year is often the
series' start year, which would exclude later issues.
None, so no request, without an issue number, and without either a
series id or a plausible year: a query that loose returns hundreds
of covers for nothing to rank but the hash.
"""
number = strip_issue_leading_zeros(profile.issue)
if not number:
return None
params: dict[str, Any] = {"number": number}
series_id = self._settings.lookup.series_ids.get(self.name)
if series_id is not None:
params["series_id"] = series_id
return params
year = profile.year
if year is None or year not in _COVER_YEARS:
return None
params["cover_date_range_after"] = f"{year - _COVER_YEAR_TOLERANCE}-01-01"
params["cover_date_range_before"] = f"{year + _COVER_YEAR_TOLERANCE}-12-31"
return params
@override
def can_search_by_cover(self, profile: ComicProfile) -> bool:
"""Metron can, unless the server ignored the filter earlier this run."""
return (
not _cover_search_unsupported.is_set()
and self._build_cover_search_params(profile) is not None
)
@override
def search_by_cover(
self, profile: ComicProfile, cover_hash: str
) -> list[Candidate]:
"""
One `issues_by_cover_hash` call, at the widest distance Metron allows.
Not decorated with ``@with_retry()`` for the reason `search` isn't:
`_issues_by_cover_hash_with_retry` carries the call's retry budget.
Like `search`, it declines (returns []) once the daily quota is down
to the reserve.
"""
params = self._build_cover_search_params(profile)
if params is None or not self._may_start_cold_search():
return []
session = self._get_session()
matches = self._issues_by_cover_hash_with_retry(session, cover_hash, params)
return self._drop_beyond_cover_range(matches)
def _drop_beyond_cover_range(self, matches: list[CoverMatch]) -> list[Candidate]:
"""
Keep only the rows `cover_hash_near` could have returned.
A Metron without the filter (one that predates metron#683, or a
rollback) ignores it as DRF ignores any unknown filter, and answers
with every issue matching the number and date range. That isn't a
wider search, it's a different one: a 40-bit cover would rank as a
candidate. So rows without a comparable hash, or further than the
distance asked for, are dropped, and their presence turns cover
search off for the rest of the process. The one search that found
out has already paid for the pages.
"""
from mokkari.utils import MAX_COVER_HASH_DISTANCE
kept = [
match
for match in matches
if match.distance is not None and match.distance <= MAX_COVER_HASH_DISTANCE
]
if len(kept) != len(matches):
_cover_search_unsupported.set()
warn_once(
"metron:cover-hash-near-ignored",
f"online {self.name}: Metron returned issues that "
"cover_hash_near could not have, so it is ignoring the "
"filter. Cover search is off for the rest of this run.",
)
return [self._to_candidate(match.issue) for match in kept]
@with_retry()
def _issues_by_cover_hash_with_retry(
self, session: Session, cover_hash: str, params: dict[str, Any]
) -> list[CoverMatch]:
"""Per-call retry wrapper around `issues_by_cover_hash`, one `issues_list`."""
from mokkari.utils import MAX_COVER_HASH_DISTANCE
self._record_api_call("issues_list")
return session.issues_by_cover_hash(cover_hash, MAX_COVER_HASH_DISTANCE, params)
@with_retry()
def _issues_list_with_retry(
self, session: Session, params: dict[str, Any]
) -> list[Any]:
"""
Per-call retry wrapper around `session.issues_list`.
`search()` fires at most 2 `issues_list` calls: the exact one,
and the wide fallback when it misses.
Every one of those is admitted through this credential set's
`RateGate`, so under `-j N` they queue instead of colliding
and a 429 should not happen at all. It still can — another client
on the same token, or a window we had not yet been told the shape
of — and when it does, the gate absorbs the `Retry-After` hint
and this decorator replays the single failed call rather than
spamming "issue-list … failed" warnings and dropping the data.
Because the source sets `paces_rate_limit`, the replay does not
sleep the hint a second time; it blocks at the gate.
`_record_api_call` counts one call here, but mokkari follows
`next` pages inside it, so a result set longer than one Metron
page costs more HTTP requests than the count shows. The
production filters (series, number, cover_year) keep results
well under a page.
"""
self._record_api_call("issues_list")
return session.issues_list(params=params)
|