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 | class ComicVineOnlineSource(OnlineSource):
"""Wraps simyan for the ComicVine API."""
name: ClassVar[str] = "comicvine"
metadata_source: ClassVar[MetadataSources] = MetadataSources.COMICVINE_API
metadata_format: ClassVar[MetadataFormats] = MetadataFormats.COMICVINE_API
@override
def is_configured(self) -> bool:
"""ComicVine requires an api_key."""
return bool(self._credentials.key)
@override
@staticmethod
def classify_retry_exception(exc: BaseException) -> RetryCategory | None:
"""
Classify simyan's exceptions.
simyan encodes the failure in its class hierarchy (ServiceError >
AuthenticationError on HTTP 401 and Comic Vine body status 100,
RateLimitError on HTTP 429/420 and body status 107), so the two
cases worth retrying differently arrive already typed. The
remaining ServiceErrors need `_classify_service_error`.
RateLimitError and AuthenticationError both subclass
ServiceError, so they must be tested before it.
"""
from simyan.errors import AuthenticationError, RateLimitError, ServiceError
if isinstance(exc, RateLimitError): # 429/420 or body 107; msg may be None
return RetryCategory.RATE_LIMIT
if isinstance(exc, AuthenticationError): # HTTP 401 or body status 100
return RetryCategory.AUTH
if isinstance(exc, ServiceError):
return _classify_service_error(exc)
return None
def _get_session(self) -> Comicvine:
"""
Return the process-wide simyan client shared by this credential set.
Sources are rebuilt per file (`_build_active_online_sources` in
comicbox/box/online_lookup.py), so memoizing on `self` alone gave
every file of a batch its own client — a fresh HTTPS connection
pool, response-cache handle and ratelimit-bucket handle per
comic. Memoizing by (api_key, base_url) at module scope lets
every file, and every thread in `Runner._run_parallel`'s pool,
reuse one. See `_session_cache` for the first-build-wins
contract.
"""
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_rate_limit_overrides()
self._client = self._get_or_build_shared_session()
return self._client
def _session_config_signature(self) -> tuple:
"""Return the per-instance settings a built client bakes in."""
cache = self._settings.cache
return (cache.mode, cache.dir, cache.ttl)
def _get_or_build_shared_session(self) -> Comicvine:
key = (self._credentials.key or "", self._credentials.url or "")
signature = self._session_config_signature()
with _session_cache_lock:
entry = _session_cache.get(key)
if entry is None:
client = self._build_session()
_session_cache[key] = (client, signature)
return client
client, 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 simyan "
"client; this instance's differing cache settings "
f"{signature} are ignored in favor of the client's "
f"{built_signature}",
)
return client
def _new_client(self, cache_expiry: Any) -> Comicvine:
from simyan.comicvine import Comicvine
# Both paths are always passed explicitly — simyan's defaults land
# in ~/.cache/simyan, outside comicbox's cache dir.
kwargs: dict[str, Any] = {
"api_key": self._credentials.key,
"user_agent": user_agent(),
"cache_path": self.cache_db_path(),
"cache_expiry": cache_expiry,
"ratelimit_path": self.cache_db_path("rate_limit"),
}
if self._credentials.url:
kwargs["base_url"] = self._credentials.url
return Comicvine(**kwargs)
def _build_session(self) -> Comicvine:
resolved = self._resolve_response_cache() # REFRESH unlinks in here
client = self._new_client(self._cache_expiry(resolved))
if resolved is not None:
self._maintain_cache(client, self.cache_db_path())
return client
@override
def probe(self) -> Mapping[str, Mapping[str, Any]] | None:
"""
Verify the key with one one-row ``list_origins`` request.
Origins have their own hourly bucket, which tagging never touches,
so the probe costs no tagging budget. The request still goes through
that shared bucket file, so it counts.
"""
from requests_cache import DO_NOT_CACHE
_refuse_spent_pool(self._settings, _PROBE_POOL)
client = self._new_client(DO_NOT_CACHE)
try:
self._record_api_call("list_origins")
client.list_origins(params={"limit": "1"}, max_results=1)
finally:
close_client(client)
return shared_client_rate_limit_status(self._settings)
# -- reading lists ----------------------------------------------------
# One attempt each through the shared client, and no retry: a
# reading-list fetch reports a failure to its caller, and an hour's
# wait for a spent pool is refused before the request, not slept.
def story_arc(self, arc_id: int) -> StoryArc:
"""Fetch a story arc: its name, dates and its issues' ids."""
_refuse_spent_pool(self._settings, _STORY_ARC_POOL)
self._record_api_call("get_story_arc")
return self._get_session().get_story_arc(arc_id)
def issues_by_id(self, ids: Sequence[int]) -> list[BasicIssue]:
"""List the issues with these ids, one call for each 100."""
_refuse_spent_pool(self._settings, _ISSUES_POOL)
self._record_api_call("list_issues")
return self._get_session().list_issues(_id_filter(ids), max_results=len(ids))
def volumes_by_id(self, ids: Sequence[int]) -> list[BasicVolume]:
"""List the volumes with these ids, one call for each 100."""
_refuse_spent_pool(self._settings, _VOLUMES_POOL)
self._record_api_call("list_volumes")
return self._get_session().list_volumes(_id_filter(ids), max_results=len(ids))
@staticmethod
def _cache_expiry(resolved: tuple[Path, timedelta] | None) -> Any:
"""
Map comicbox's resolved cache mode/ttl onto simyan's `cache_expiry`.
`DO_NOT_CACHE` is the whole of CacheMode.OFF: simyan no longer
passes `cache_control`, so a response's own cache headers cannot
re-derive an expiry and get themselves written anyway, and
requests_cache counts "disabled by expiration" against reads and
writes alike. Under simyan 3.x this needed a private reach-in to
set `session.settings.disabled`.
A zero ttl means "keep forever" rather than "expire instantly" —
`NEVER_EXPIRE`, since OFF already covers not caching.
"""
from requests_cache import DO_NOT_CACHE, NEVER_EXPIRE
if resolved is None: # CacheMode.OFF
return DO_NOT_CACHE
_, ttl = resolved
return ttl if ttl.total_seconds() > 0 else NEVER_EXPIRE
def _warn_ignored_rate_limit_overrides(self) -> None:
from comicbox.config.online.settings import resolve_rate_limit
limits = resolve_rate_limit(self._settings, self.name)
if limits.per_second is not None or limits.per_hour is not None:
# Sources are rebuilt per file; warn_once keeps this at one
# line per process instead of one per file in a batch run.
warn_once(
f"{self.name}:rate-limit-override",
f"online {self.name}: rate_limit.per_second/per_hour "
"overrides are ignored — simyan manages ComicVine "
"rates internally (1/sec, 200/hr)",
)
def _maintain_cache(self, client: Comicvine, cache_path: Path) -> None:
"""
Purge expired rows, drop the v2 table, and vacuum if bloated.
requests_cache never deletes expired rows on its own (simyan v2's
cache did, on open) — without the purge the freelist-based vacuum
trigger would rarely fire and the cache would grow unbounded.
Runs once per process per cache file.
"""
from comicbox.formats.base.online.vacuum import vacuum_if_bloated
if not cache_path.exists():
return
with _maintenance_lock:
if str(cache_path) in _maintained_cache_paths:
return
_maintained_cache_paths.add(str(cache_path))
try:
# The session and its cache are private simyan surface (typed
# Any accordingly); degrade to "no purge" on a rename.
cache: Any = client._session.cache # noqa: SLF001
# vacuum=False: requests_cache's SQLite backend would otherwise
# rewrite the whole file on every purge; vacuum_if_bloated below
# only does so when the freelist justifies it.
cache.delete(expired=True, vacuum=False)
except Exception as exc:
logger.debug(f"online {self.name}: cache purge skipped: {exc}")
_drop_v2_cache_table(cache_path)
vacuum_if_bloated(cache_path)
@with_retry()
def get(self, issue_id: int) -> dict[str, Any]:
"""
Fetch one ComicVine issue by id; return its model dump.
CV's issue endpoint does NOT include the publisher inline —
`Issue.volume` is a bare `GenericEntry`. We chase one extra
request to ``get_volume(volume.id)`` to pull
``Volume.publisher`` and inject it under a top-level ``publisher``
key for the transform to pick up. simyan's response cache is
URL-keyed, so this is "+1 API call per unique volume" rather
than per issue — successive issues from the same volume are free.
``Volume.aliases``, start year, issue count and description ride
along on that same fetch and are injected onto the volume block for
the transform to read as series detail.
"""
session = self._get_session()
self._record_api_call("get_issue")
issue = session.get_issue(issue_id)
dump: dict[str, Any] = issue.model_dump(mode="json")
# `issue.volume` is a GenericEntry with id; fetch the full volume
# to get its publisher. Best-effort — log and continue on failure.
volume_id = (issue.volume.id if issue.volume else None) or (
(dump.get("volume") or {}).get("id")
)
if volume_id is not None:
self._enrich_from_volume(session, dump, int(volume_id))
return dump
def _enrich_from_volume(
self, session: Any, dump: dict[str, Any], volume_id: int
) -> None:
"""
Inject the volume's publisher and series detail into an issue dump.
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:
volume = self._get_volume_with_retry(session, volume_id)
except OnlineLookupAbortedError:
raise
except Exception as exc:
logger.warning(
f"online {self.name}: get_volume({volume_id}) failed; "
f"publisher and series detail will be missing from this issue: {exc}"
)
return
if volume.publisher is not None:
dump["publisher"] = volume.publisher.model_dump(mode="json")
if not isinstance(volume_dump := dump.get("volume"), dict):
return
detail = {
"aliases": volume.aliases,
"start_year": volume.start_year,
"issue_count": volume.issue_count,
# `summary` is simyan's name for CV's short `deck`.
"description": volume.description or volume.summary,
}
volume_dump.update({key: value for key, value in detail.items() if value})
# Limit how many candidate volumes to expand into issue queries; each
# volume → one extra `list_issues` API call under CV's 1/sec rate limit.
_MAX_VOLUMES_PER_SEARCH: ClassVar[int] = 20
# ComicVine `Images` field names from smallest to largest.
# `thumbnail` is sufficient for pHash; the rest are fallbacks for
# records where a particular size is missing.
_COVER_URL_PREFERENCE: ClassVar[tuple[str, ...]] = (
"thumbnail",
"small_url",
"medium_url",
"screen_url",
"super_url",
"original_url",
)
# The same field names largest first, for the display-only full-size
# url. `small_url` and `thumbnail` are deliberately absent: a record
# carrying only those tiers has nothing genuinely larger to show, and
# `cover_url_full` stays None rather than repeating the thumbnail.
_COVER_URL_FULL_PREFERENCE: ClassVar[tuple[str, ...]] = (
"original_url",
"super_url",
"screen_url",
"medium_url",
)
@staticmethod
def _pick_cover_url(image: Any, preference: tuple[str, ...]) -> str | None:
"""Return the first url present on ``image``, in ``preference`` order."""
if image is None:
return None
for attr in preference:
url = getattr(image, attr, None)
if url:
return str(url)
return None
def _to_candidate(
self,
basic_issue: Any,
volume: _VolumeFacts = _NO_VOLUME_FACTS,
) -> Candidate:
"""
Map simyan's `BasicIssue` to a Candidate.
``volume.name`` overrides the series field when supplied — the
two-step search has already resolved the volume so we use its
canonical name even if `basic_issue.volume.name` is sparse.
``volume.alt_series`` carries the volume's aliases so the matcher
can score a localized or variant title against the profile.
"""
bi_volume = basic_issue.volume
series = volume.name or (bi_volume.name if bi_volume else "") or ""
cover_year = basic_issue.cover_date.year if basic_issue.cover_date else None
image = basic_issue.image
cover_url = self._pick_cover_url(image, self._COVER_URL_PREFERENCE)
site_url = str(basic_issue.site_url) if basic_issue.site_url else ""
summary = CandidateSummary(
series=series,
issue=basic_issue.number or "",
year=cover_year,
publisher=None, # BasicIssue from search doesn't include publisher
page_count=None,
cover_url=cover_url,
variant_label=None,
alt_series=volume.alt_series,
# Free: the six Images variants ride in the search response
# comicbox already paid for.
cover_url_full=self._pick_cover_url(image, self._COVER_URL_FULL_PREFERENCE),
series_start_year=volume.start_year,
series_publisher=volume.publisher,
series_issue_count=volume.issue_count,
# Also free: no `field_list` is sent, so every issue row
# carries its title and deck.
issue_title=_display_text(getattr(basic_issue, "name", None)),
issue_summary=_display_text(
strip_html(getattr(basic_issue, "summary", None))
),
)
return Candidate(
source=self.name,
issue_id=basic_issue.id,
summary=summary,
url=site_url,
# ComicVine doesn't expose a precomputed pHash; matcher will
# download and hash on demand if needed.
precomputed_cover_hash=None,
# CV's volume.id — propagated for calibration diagnostics
# (lets us tell "variant cover of same volume" apart from
# "wrong volume with the same name" when two candidates tie).
volume_id=bi_volume.id if bi_volume else None,
)
# Cover-date window applied around `profile.year` when filtering
# CV's per-volume issue lookup. ±2 years gives the year-only matcher
# a small slop budget without admitting wholly-wrong-volume matches
# that score well on every other signal.
_COVER_DATE_WINDOW_YEARS: ClassVar[int] = 2
# Maximum number of years a comic may pre-date its volume's start_year
# before we treat the volume as causally impossible and skip the
# per-volume issue lookup. A 1987 Wardens issue with profile.year=1987
# cannot have been published in a reprint volume that started in 2008;
# any candidate from that volume is a reprint with cover_date=1987
# preserved from the original, score-identical to the original on
# every signal the matcher reads. Skip-and-save-budget is cleaner
# than admitting the candidate and hoping a tiebreaker resolves it.
#
# The slop=1 matches `s_year`'s diff=1 tolerance — we accept "started
# the year after the comic's cover date" cases (off-by-one cover
# dating across publisher fiscal year boundaries) without keeping
# outright impossible volumes.
_VOLUME_START_YEAR_SLOP: ClassVar[int] = 1
@with_retry()
def _get_volume_with_retry(self, session: Any, volume_id: int) -> Any:
"""
Per-call retry wrapper around `session.get_volume`.
This is the supplementary publisher-lookup call in `get()`. The
outer `get()` is itself `@with_retry()`-decorated but its inner
`try/except` swallows rate-limit errors as "best effort" —
meaning under -j N contention every transient rate-limit on
get_volume silently drops the publisher field. Wrapping the
call here lets rate-limit hits replay transparently; the outer
except only catches terminal failures (404, retries exhausted).
"""
self._record_api_call("get_volume")
return session.get_volume(volume_id)
def _discover_volumes(
self, session: Any, profile: ComicProfile, max_volumes: int
) -> list[Any]:
"""
Union-of-narrow-and-fuzzy volume discovery.
Always runs both:
- Fuzzy `session.search_volumes(query)` — CV's text-relevance
ranking. Surfaces canonical / popular volumes.
- Narrow `session.list_volumes(name+start_year filter)` — only
when profile.year is set. Surfaces the specific year's volume
for Pattern A cases (reissues, trade collections, facsimiles)
where CV's relevance buries the year-anchored volume below
older canonical runs.
Results are dedup'd by volume_id (fuzzy order preserved first;
narrow's new entries appended). Both halves are independently
capped at ``max_volumes``; the union is capped at
``2 * max_volumes``.
Replaces the 2026-05-17 narrow-then-fuzzy approach which lost
previously-correct fuzzy candidates whenever the narrow filter
returned a wrong volume. Union preserves fuzzy's candidates so
the matcher still scores them; narrow's contribution is purely
additive.
"""
# Fuzzy always runs (preserves today's behaviour as a floor).
try:
fuzzy = self._volume_search_with_retry(session, profile.series, max_volumes)
except Exception as exc:
logger.warning(f"online {self.name}: volume search failed: {exc}")
raise
if profile.year is None:
return fuzzy
try:
narrow = self._volume_filter_search_with_retry(
session, profile.series, profile.year, max_volumes
)
except OnlineLookupAbortedError:
# An abort ends the whole lookup; it is not a source-side
# failure to degrade past. Mirrors OnlineSource.lookup_issue.
raise
except Exception as exc:
logger.info(
f"online {self.name}: volume filter-search failed "
f"({exc}); proceeding with fuzzy-only candidates"
)
return fuzzy
if not narrow:
return fuzzy
# Dedup union, fuzzy first to preserve relevance ordering for
# already-good cases. Narrow's new entries appended.
fuzzy_ids = {v.id for v in fuzzy}
narrow_only = [v for v in narrow if v.id not in fuzzy_ids]
if narrow_only:
logger.debug(
f"online {self.name}: narrow filter added "
f"{len(narrow_only)} volume(s) to fuzzy's {len(fuzzy)} "
f"for series={profile.series!r} start_year={profile.year}"
)
return fuzzy + narrow_only
@with_retry()
def _volume_search_with_retry(
self, session: Any, query: str, max_results: int
) -> list[Any]:
"""
Per-call retry wrapper around `session.search_volumes(...)`.
Mirrors the Metron `_series_list_with_retry` fix from the same
2026-05-15-stress-100 audit pass: the volume-search call was
un-retried, so under -j N contention a single rate-limit hit
would drop the entire fixture's candidate set instead of
retrying transparently.
"""
self._record_api_call("search_volumes")
return session.search_volumes(query=query, max_results=max_results)
@with_retry()
def _volume_filter_search_with_retry(
self, session: Any, query: str, start_year: int, max_results: int
) -> list[Any]:
"""
Narrow volume search via `list_volumes` server-side filter.
Uses CV's `/volumes` endpoint with `name:<query>,start_year:<year>`
filter — different code path from the fuzzy `/search` endpoint.
Always paired with fuzzy via ``_discover_volumes``; never used
as a replacement. See that method's docstring + the failure
history in
``tasks/online-tagging/research-notes/cv-top-5-search-relevance.md``.
"""
self._record_api_call("filter_volumes")
# CV's filter syntax: `field1:value1,field2:value2`. Commas and
# colons in the query would break the parser. Strip them — they're
# rare in series names and won't affect icontains matching.
safe_query = query.replace(",", " ").replace(":", " ").strip()
return session.list_volumes(
params={"filter": f"name:{safe_query},start_year:{start_year}"},
max_results=max_results,
)
@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.
One ``list_issues`` call filtered by ``volume:`` + ``issue_number:``.
Returns None without a request when there is no issue number: a
bare ``volume:`` filter lists the whole volume and the first row
would win. The base class's ``lookup_issue`` wrapper owns the
failure semantics (plan §3.10).
"""
number = strip_issue_leading_zeros(issue_number)
if not number:
return None
session = self._get_session()
candidates = self._list_issues_by_volume(session, volume_id, number)
if not candidates:
return None
# First-result-wins on variant collisions; same approach as Metron.
return candidates[0]
@with_retry()
def _list_issues_by_volume(
self,
session: Any,
volume_id: int,
issue_number: str | None,
volume: _VolumeFacts = _NO_VOLUME_FACTS,
*,
year: int | None = None,
) -> list[Candidate]:
"""
Run a single ``list_issues`` call constrained by volume id.
Used both by the fast path (`--series-id comicvine:<id>`) and by
each iteration of the discovery two-step. ``volume`` carries what
the discovery step's volume row knew onto the returned
candidates' summary; the fast path has no row.
``year``, when supplied, narrows results to a ±_COVER_DATE_WINDOW_YEARS
window around it via CV's ``cover_date:Y0-01-01|Y1-12-31``
filter syntax. Cover-date drift is rarely more than ±1 year so a
2-year slop is generous; this prevents wrong-volume picks (e.g.
a 1986 series matching a 2005 collected edition with the same
issue number) from polluting the candidate set in the first place.
Decorated with ``@with_retry()`` so a rate-limit hit on this
single call waits out the rate-limit backoff schedule and replays
just the failed call. The outer ``search`` loop catches and continues
on the FINAL failure after retries are exhausted, so transient
rate-limit hits inside the loop no longer silently drop the
per-volume issue data.
"""
self._record_api_call("list_issues")
issue_filter = [f"volume:{volume_id}"]
if issue_number:
issue_filter.append(f"issue_number:{issue_number}")
if year is not None:
window = self._COVER_DATE_WINDOW_YEARS
issue_filter.append(
f"cover_date:{year - window}-01-01|{year + window}-12-31"
)
issues = session.list_issues(params={"filter": ",".join(issue_filter)})
return [self._to_candidate(i, volume) for i in issues]
def _volume_predates_comic(
self, vol_start_year: int | None, comic_year: int | None
) -> bool:
"""
Return True when the volume started so far after the comic to be impossible.
Used to skip per-volume issue queries for volumes whose `start_year`
is later than the comic year + slop. Reprint volumes (which copy the
original's cover_date onto their issues) are score-identical to
the original on every signal the matcher reads — the only thing
that distinguishes them is their volume start_year, and the
matcher doesn't see that. Filtering at search time avoids both
wrong-volume picks and the wasted `list_issues` call.
Returns False (i.e. keep the volume) when either input is None —
we'd rather over-include than drop the right answer on missing
data.
"""
if vol_start_year is None or comic_year is None:
return False
return vol_start_year > comic_year + self._VOLUME_START_YEAR_SLOP
@override
def search(self, profile: ComicProfile) -> list[Candidate]:
"""
Search ComicVine for candidate issues matching the profile.
ComicVine's ``list_issues`` filter has no series/volume-name field —
its `name:` filter matches the *issue's* title, which is rarely
useful. So we do the canonical two-step:
1. Full-text-search for volumes matching the series name. (The
``list_volumes`` filter `name:` is strict and trips on
punctuation: "GI Joe" vs "G.I. Joe". Full-text search is
more permissive.)
2. For each volume, ``list_issues`` filtered by ``volume:VOL_ID``
and ``issue_number:N`` → candidate issues for that volume.
``--series-id comicvine:<id>`` short-circuits step 1 and runs
only step 2 against the supplied volume id.
Volumes whose ``start_year`` is *later* than ``profile.year + 1``
(causally impossible — a reprint volume started in 2008 cannot
contain the original 1987 issue) are dropped before step 2;
otherwise ``start_year`` is NOT used as a filter, since a comic
dated 2020 can legitimately be issue #100 of a series that
started in 1963. ``profile.year`` is also used as a per-issue
``cover_date`` window (±2 years) inside step 2, to keep
wrong-volume candidates with the same issue number out of the
candidate set entirely. If that year filter returns empty (CV
has issues with missing cover_date), we retry once without it.
"""
session = self._get_session()
issue_number = strip_issue_leading_zeros(profile.issue)
year = profile.year
# Fast path: --series-id comicvine:<id> skips the volume search and
# goes straight to a single list_issues call constrained by that
# volume id, saving the discovery API call.
explicit_sid = self._settings.lookup.series_ids.get(self.name)
if explicit_sid is not None:
try:
return self._list_with_year_retry(
session, explicit_sid, issue_number, year=year
)
except Exception as exc:
logger.warning(
f"online {self.name}: issue-list for volume {explicit_sid} "
f"failed: {exc}"
)
raise
if not profile.series:
logger.debug(
f"online {self.name}: no series in profile; cannot search CV "
"(use --id comicvine:<id> for direct lookup, or "
"--series-id comicvine:<id>)"
)
return []
# Phase D: `minimal` effort caps the volume-search breadth more
# aggressively than the class default (20 → 5). Cuts the per-volume
# `list_issues` fan-out further at scale; the pre-filter already
# drops obvious mismatches but the long tail of weakly-matching
# volumes adds up across thousands of comics.
max_volumes = self._effort_max_results(self._MAX_VOLUMES_PER_SEARCH)
volumes = self._discover_volumes(session, profile, max_volumes)
if not volumes:
logger.info(
f"online {self.name}: no volumes match series {profile.series!r}"
)
return []
self._log_discovery_sample(
volumes,
lambda v: f"{v.name} ({v.id})",
noun="volumes",
query=f"series={profile.series!r}",
)
# Pre-call filter threshold from the resolved effort. The values
# are calibrated and live in `series_filter.threshold_for`: at the
# `balanced` default the filter drops obvious mismatches before
# they cost a call, and `thorough` turns it off.
name_threshold = self._effort_name_threshold()
budget = self._new_search_budget()
candidates: list[Candidate] = []
for vol in volumes:
candidates.extend(
self._candidates_for_volume(
session,
vol,
profile=profile,
issue_number=issue_number,
year=year,
name_threshold=name_threshold,
budget=budget,
)
)
if budget.dropped:
# Never truncate silently: a short candidate list has to be
# distinguishable from a thin one upstream.
logger.info(
f"online {self.name}: {budget.exhausted_reason()} after "
f"{budget.spent} issue-list call(s) for "
f"series={profile.series!r}; {budget.dropped} volume(s) "
"not queried. Use `--effort thorough` (config key "
"`online.tuning.effort`) to search them all."
)
return candidates
def _new_search_budget(self) -> _SearchBudget:
"""Resolve this search's pre-call fan-out limits from the effort knob."""
from comicbox.config.online.settings import resolve_effort
max_calls = max_calls_for(resolve_effort(self._settings, self.name))
deadline = None if max_calls is None else time.monotonic() + _SEARCH_DEADLINE_S
return _SearchBudget(max_calls=max_calls, deadline=deadline)
def _candidates_for_volume(
self,
session: Any,
vol: Any,
*,
profile: ComicProfile,
issue_number: str | None,
year: int | None,
name_threshold: float,
budget: _SearchBudget | None = None,
) -> list[Candidate]:
"""
Apply pre-call filters and (if kept) fetch the volume's matching issues.
Pre-filters in order: start_year causality (skip volumes that
started after the comic), then series-name fuzzy match (skip
volumes whose name diverges from `profile.series` past the
effort threshold), then the per-search call/deadline budget.
The name filters log at debug level so calibration runs can audit
drops; the budget's drops are counted and reported once by the
caller. The actual `list_issues` call only fires for volumes that
survive every gate.
The volume's aliases are read off the already-fetched search
result — no extra API call — and both widen the name gate and
ride onto the candidates for the matcher's series signal. Its
start year, publisher and issue count ride along for display.
"""
vol_start = getattr(vol, "start_year", None)
if self._volume_predates_comic(vol_start, year):
logger.debug(
f"online {self.name}: skipping volume {vol.id} "
f"({vol.name!r}, start_year={vol_start}); comic "
f"year={year} predates the volume — issue cannot "
f"originate here."
)
return []
alt_series = tuple(split_aliases(getattr(vol, "aliases", None)))
if not should_keep_volume_name(
profile.series, vol.name, name_threshold, alt_names=alt_series
):
logger.debug(
f"online {self.name}: skipping volume {vol.id} "
f"({vol.name!r}); name dissimilar to "
f"profile.series={profile.series!r} (threshold="
f"{name_threshold:.2f}, effort pre-filter)."
)
return []
if budget is not None and not budget.take():
return []
try:
return self._list_with_year_retry(
session,
vol.id,
issue_number,
_VolumeFacts.from_volume(vol, alt_series),
year=year,
budget=budget,
)
except OnlineLookupAbortedError:
# An abort ends the whole lookup; it is not a source-side
# failure to degrade past. Mirrors OnlineSource.lookup_issue.
raise
except Exception as exc:
logger.warning(
f"online {self.name}: issue-list for volume {vol.id} "
f"({vol.name!r}) failed: {exc}"
)
return []
def _list_with_year_retry(
self,
session: Any,
volume_id: int,
issue_number: str | None,
volume: _VolumeFacts = _NO_VOLUME_FACTS,
*,
year: int | None,
budget: _SearchBudget | None = None,
) -> list[Candidate]:
"""
Per-volume issue lookup with a year-window filter and one fallback.
Tries `cover_date:Y±2` first (cuts out wrong-volume candidates).
If that returns empty AND a year was supplied, retries without
the year filter — cover_date can be missing on CV issues, and
we'd rather see *something* and let the matcher score it than
wrongly drop the right answer.
That fallback is a second rate-limited call, so it claims from
the same per-search budget the first one did. This is why the
budget is counted in CALLS rather than in volumes: a volume can
cost one or two.
"""
candidates = self._list_issues_by_volume(
session, volume_id, issue_number, volume, year=year
)
if candidates or year is None:
return candidates
if budget is not None and not budget.take():
return candidates
return self._list_issues_by_volume(
session, volume_id, issue_number, volume, year=None
)
|